[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71H0HNNWPMMW8WD3R8K0KZE":3,"skill-same:01M71H0HNNWPMMW8WD3R8K0KZE":58},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":25,"linkOnly":26,"markdownContent":27,"markdownBody":28,"frontMatter":29,"refName":31,"commitSha":32,"skillDirectory":33,"forksCount":34,"repositoryHtmlUrl":35,"repositoryHomepageUrl":6,"ownerHtmlUrl":36,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":37,"install":38,"resources":51},"01M71H0HNNWPMMW8WD3R8K0KZE","portfolio-sync",null,"Sync portfolio positions from Polymarket, Kalshi, and Manifold","JSGforever\u002Fskillguard","JSGforever","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F85541948?v=4","01M71FQD3E132VMR5F4TAYX3YS","01M71FQD4DYW0XJ4XQ4YQH75Y9",2,"GPL-3.0","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__alsk1992--portfolio-sync\u002FSKILL.md",[],[18,19,20,21,22,23,24],"portfolio","portfolio sync","sync","manifold","positions","polymarket","kalshi","2026-11-10 10:12:30",false,"---\nname: portfolio-sync\ndescription: \"Sync portfolio positions from Polymarket, Kalshi, and Manifold\"\nemoji: \"📁\"\n---\n\n# Portfolio Sync Skill\n\nReal methods to fetch and sync positions from each prediction market platform.\n\n## Polymarket Position Sync\n\nPolymarket positions are held as ERC-1155 tokens on Polygon. Query on-chain balances.\n\n```python\nimport os\nimport requests\n\nWALLET = os.getenv(\"POLY_FUNDER_ADDRESS\")\nCTF_CONTRACT = \"0x4D97DCd97eC945f40cF65F87097ACe5EA0476045\"  # Conditional Token Framework\n\ndef get_polymarket_positions(token_ids: list[str]) -> dict:\n    \"\"\"\n    Get balances for specific token IDs\n\n    Args:\n        token_ids: List of token IDs to check (from market data)\n\n    Returns:\n        Dict of token_id -> balance in shares\n    \"\"\"\n    positions = {}\n\n    for token_id in token_ids:\n        token_int = int(token_id)\n\n        # ERC-1155 balanceOf call\n        data = f\"0x00fdd58e000000000000000000000000{WALLET[2:].lower()}{token_int:064x}\"\n\n        r = requests.post(\"https:\u002F\u002Fpolygon-rpc.com\u002F\", json={\n            \"jsonrpc\": \"2.0\",\n            \"method\": \"eth_call\",\n            \"params\": [{\"to\": CTF_CONTRACT, \"data\": data}, \"latest\"],\n            \"id\": 1\n        })\n\n        result = r.json().get(\"result\", \"0x0\")\n        balance = int(result, 16) \u002F 1e6  # Raw to shares\n\n        if balance > 0:\n            positions[token_id] = balance\n\n    return positions\n\n# Example: Check positions for BTC 15-min market\nbtc_tokens = [\n    \"21742633143463906290569050155826241533067272736897614950488156847949938836455\",  # YES\n    \"48331043336612883890938759509493159234755048973500640148014422747788308965745\"   # NO\n]\n\npositions = get_polymarket_positions(btc_tokens)\nfor token_id, balance in positions.items():\n    print(f\"Token {token_id[:20]}...: {balance} shares\")\n```\n\n### Get All Polymarket Positions (via Gamma API)\n\n```python\ndef get_all_polymarket_positions(wallet: str):\n    \"\"\"Get all positions for a wallet via Gamma API\"\"\"\n    url = f\"https:\u002F\u002Fgamma-api.polymarket.com\u002Fpositions?user={wallet.lower()}\"\n    r = requests.get(url)\n\n    if r.status_code != 200:\n        return []\n\n    positions = r.json()\n\n    result = []\n    for p in positions:\n        result.append({\n            \"market_id\": p.get(\"conditionId\"),\n            \"market_question\": p.get(\"title\", \"Unknown\"),\n            \"token_id\": p.get(\"tokenId\"),\n            \"outcome\": p.get(\"outcome\"),\n            \"size\": float(p.get(\"size\", 0)),\n            \"avg_price\": float(p.get(\"avgPrice\", 0)),\n            \"current_price\": float(p.get(\"currentPrice\", 0)),\n            \"pnl\": float(p.get(\"pnl\", 0)),\n            \"value\": float(p.get(\"value\", 0))\n        })\n\n    return result\n\npositions = get_all_polymarket_positions(WALLET)\nfor p in positions:\n    print(f\"{p['market_question'][:40]}\")\n    print(f\"  {p['outcome']}: {p['size']} shares @ {p['avg_price']:.2f} -> {p['current_price']:.2f}\")\n    print(f\"  PnL: ${p['pnl']:.2f}\")\n```\n\n### Get USDC Balance\n\n```python\ndef get_usdc_balance(wallet: str) -> float:\n    \"\"\"Get USDC balance on Polygon\"\"\"\n    USDC = \"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174\"  # USDC on Polygon\n\n    # ERC-20 balanceOf\n    data = f\"0x70a08231000000000000000000000000{wallet[2:].lower()}\"\n\n    r = requests.post(\"https:\u002F\u002Fpolygon-rpc.com\u002F\", json={\n        \"jsonrpc\": \"2.0\",\n        \"method\": \"eth_call\",\n        \"params\": [{\"to\": USDC, \"data\": data}, \"latest\"],\n        \"id\": 1\n    })\n\n    result = r.json().get(\"result\", \"0x0\")\n    balance = int(result, 16) \u002F 1e6  # USDC has 6 decimals\n\n    return balance\n\nusdc = get_usdc_balance(WALLET)\nprint(f\"USDC Balance: ${usdc:.2f}\")\n```\n\n## Kalshi Position Sync\n\n```python\nimport requests\nimport time\n\nBASE_URL = \"https:\u002F\u002Ftrading-api.kalshi.com\u002Ftrade-api\u002Fv2\"\n\nclass KalshiSync:\n    def __init__(self, email: str, password: str):\n        self.email = email\n        self.password = password\n        self.token = None\n        self.token_expiry = 0\n\n    def _auth(self):\n        if time.time() > self.token_expiry - 60:\n            r = requests.post(f\"{BASE_URL}\u002Flogin\", json={\n                \"email\": self.email,\n                \"password\": self.password\n            })\n            r.raise_for_status()\n            self.token = r.json()[\"token\"]\n            self.token_expiry = time.time() + 29 * 60\n\n    def _headers(self):\n        self._auth()\n        return {\"Authorization\": f\"Bearer {self.token}\"}\n\n    def get_positions(self):\n        \"\"\"Get all Kalshi positions\"\"\"\n        r = requests.get(f\"{BASE_URL}\u002Fportfolio\u002Fpositions\", headers=self._headers())\n        r.raise_for_status()\n\n        positions = []\n        for p in r.json().get(\"market_positions\", []):\n            # Get market details\n            market = requests.get(\n                f\"{BASE_URL}\u002Fmarkets\u002F{p['ticker']}\",\n                headers=self._headers()\n            ).json().get(\"market\", {})\n\n            positions.append({\n                \"market_id\": p[\"ticker\"],\n                \"market_question\": market.get(\"title\", p[\"ticker\"]),\n                \"side\": \"YES\" if p.get(\"position\", 0) > 0 else \"NO\",\n                \"size\": abs(p.get(\"position\", 0)),\n                \"avg_price\": p.get(\"average_price\", 0) \u002F 100,\n                \"current_price\": market.get(\"yes_bid\", 50) \u002F 100,\n                \"value\": abs(p.get(\"position\", 0)) * market.get(\"yes_bid\", 50) \u002F 100,\n                \"pnl\": p.get(\"realized_pnl\", 0) \u002F 100\n            })\n\n        return positions\n\n    def get_balance(self):\n        \"\"\"Get Kalshi balance\"\"\"\n        r = requests.get(f\"{BASE_URL}\u002Fportfolio\u002Fbalance\", headers=self._headers())\n        r.raise_for_status()\n        data = r.json()\n        return {\n            \"available\": data.get(\"balance\", 0) \u002F 100,\n            \"portfolio_value\": data.get(\"portfolio_value\", 0) \u002F 100\n        }\n\n# Usage\nsync = KalshiSync(os.getenv(\"KALSHI_EMAIL\"), os.getenv(\"KALSHI_PASSWORD\"))\n\npositions = sync.get_positions()\nfor p in positions:\n    print(f\"{p['market_question'][:40]}\")\n    print(f\"  {p['side']}: {p['size']} @ {p['avg_price']:.2f} -> {p['current_price']:.2f}\")\n\nbalance = sync.get_balance()\nprint(f\"\\nAvailable: ${balance['available']:.2f}\")\nprint(f\"Portfolio: ${balance['portfolio_value']:.2f}\")\n```\n\n## Manifold Position Sync\n\n```python\nimport requests\n\nAPI_URL = \"https:\u002F\u002Fapi.manifold.markets\u002Fv0\"\nAPI_KEY = os.getenv(\"MANIFOLD_API_KEY\")\n\ndef get_manifold_positions():\n    \"\"\"Get all Manifold positions\"\"\"\n    headers = {\"Authorization\": f\"Key {API_KEY}\"}\n\n    # Get user profile\n    r = requests.get(f\"{API_URL}\u002Fme\", headers=headers)\n    r.raise_for_status()\n    user = r.json()\n    user_id = user[\"id\"]\n    balance = user.get(\"balance\", 0)\n\n    # Get all bets\n    r = requests.get(f\"{API_URL}\u002Fbets\", headers=headers, params={\"userId\": user_id, \"limit\": 1000})\n    bets = r.json()\n\n    # Aggregate positions by market\n    markets = {}\n    for bet in bets:\n        if bet.get(\"isSold\") or bet.get(\"isCancelled\"):\n            continue\n\n        mid = bet[\"contractId\"]\n        if mid not in markets:\n            markets[mid] = {\n                \"yes_shares\": 0,\n                \"no_shares\": 0,\n                \"invested\": 0,\n                \"question\": bet.get(\"contractQuestion\", \"Unknown\")\n            }\n\n        if bet[\"outcome\"] == \"YES\":\n            markets[mid][\"yes_shares\"] += bet.get(\"shares\", 0)\n        else:\n            markets[mid][\"no_shares\"] += bet.get(\"shares\", 0)\n\n        markets[mid][\"invested\"] += bet[\"amount\"]\n\n    # Get current prices\n    positions = []\n    for mid, data in markets.items():\n        if data[\"yes_shares\"] == 0 and data[\"no_shares\"] == 0:\n            continue\n\n        # Fetch current market price\n        r = requests.get(f\"{API_URL}\u002Fmarket\u002F{mid}\")\n        if r.status_code == 200:\n            market = r.json()\n            prob = market.get(\"probability\", 0.5)\n\n            yes_value = data[\"yes_shares\"] * prob\n            no_value = data[\"no_shares\"] * (1 - prob)\n            total_value = yes_value + no_value\n            pnl = total_value - data[\"invested\"]\n\n            positions.append({\n                \"market_id\": mid,\n                \"market_question\": data[\"question\"],\n                \"yes_shares\": data[\"yes_shares\"],\n                \"no_shares\": data[\"no_shares\"],\n                \"invested\": data[\"invested\"],\n                \"current_value\": total_value,\n                \"probability\": prob,\n                \"pnl\": pnl,\n                \"url\": market.get(\"url\", \"\")\n            })\n\n    return positions, balance\n\npositions, balance = get_manifold_positions()\nprint(f\"Mana Balance: {balance}\")\n\nfor p in positions:\n    print(f\"\\n{p['market_question'][:50]}\")\n    print(f\"  YES: {p['yes_shares']:.1f} shares, NO: {p['no_shares']:.1f} shares\")\n    print(f\"  Value: {p['current_value']:.0f}M, PnL: {p['pnl']:+.0f}M\")\n```\n\n## Unified Portfolio Sync\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nSync portfolio from all prediction markets\n\"\"\"\n\nimport os\nfrom dataclasses import dataclass\nfrom typing import List\n\n@dataclass\nclass Position:\n    platform: str\n    market_id: str\n    market_question: str\n    side: str\n    size: float\n    avg_price: float\n    current_price: float\n    value: float\n    pnl: float\n    pnl_pct: float\n\ndef sync_all_portfolios() -> List[Position]:\n    \"\"\"Sync positions from all platforms\"\"\"\n    all_positions = []\n\n    # Polymarket\n    if os.getenv(\"POLY_FUNDER_ADDRESS\"):\n        poly_positions = get_all_polymarket_positions(os.getenv(\"POLY_FUNDER_ADDRESS\"))\n        for p in poly_positions:\n            avg = p[\"avg_price\"] or 0.01\n            pnl_pct = ((p[\"current_price\"] - avg) \u002F avg * 100) if avg > 0 else 0\n\n            all_positions.append(Position(\n                platform=\"polymarket\",\n                market_id=p[\"market_id\"],\n                market_question=p[\"market_question\"],\n                side=p[\"outcome\"],\n                size=p[\"size\"],\n                avg_price=avg,\n                current_price=p[\"current_price\"],\n                value=p[\"value\"],\n                pnl=p[\"pnl\"],\n                pnl_pct=pnl_pct\n            ))\n\n    # Kalshi\n    if os.getenv(\"KALSHI_EMAIL\"):\n        kalshi = KalshiSync(os.getenv(\"KALSHI_EMAIL\"), os.getenv(\"KALSHI_PASSWORD\"))\n        kalshi_positions = kalshi.get_positions()\n        for p in kalshi_positions:\n            avg = p[\"avg_price\"] or 0.01\n            pnl_pct = ((p[\"current_price\"] - avg) \u002F avg * 100) if avg > 0 else 0\n\n            all_positions.append(Position(\n                platform=\"kalshi\",\n                market_id=p[\"market_id\"],\n                market_question=p[\"market_question\"],\n                side=p[\"side\"],\n                size=p[\"size\"],\n                avg_price=avg,\n                current_price=p[\"current_price\"],\n                value=p[\"value\"],\n                pnl=p[\"pnl\"],\n                pnl_pct=pnl_pct\n            ))\n\n    # Manifold\n    if os.getenv(\"MANIFOLD_API_KEY\"):\n        mani_positions, _ = get_manifold_positions()\n        for p in mani_positions:\n            invested = p[\"invested\"] or 1\n            pnl_pct = (p[\"pnl\"] \u002F invested * 100) if invested > 0 else 0\n\n            # Add YES position\n            if p[\"yes_shares\"] > 0:\n                all_positions.append(Position(\n                    platform=\"manifold\",\n                    market_id=p[\"market_id\"],\n                    market_question=p[\"market_question\"],\n                    side=\"YES\",\n                    size=p[\"yes_shares\"],\n                    avg_price=0,  # Manifold doesn't track this\n                    current_price=p[\"probability\"],\n                    value=p[\"yes_shares\"] * p[\"probability\"],\n                    pnl=p[\"pnl\"] \u002F 2,  # Split PnL\n                    pnl_pct=pnl_pct\n                ))\n\n            # Add NO position\n            if p[\"no_shares\"] > 0:\n                all_positions.append(Position(\n                    platform=\"manifold\",\n                    market_id=p[\"market_id\"],\n                    market_question=p[\"market_question\"],\n                    side=\"NO\",\n                    size=p[\"no_shares\"],\n                    avg_price=0,\n                    current_price=1 - p[\"probability\"],\n                    value=p[\"no_shares\"] * (1 - p[\"probability\"]),\n                    pnl=p[\"pnl\"] \u002F 2,\n                    pnl_pct=pnl_pct\n                ))\n\n    return all_positions\n\n# Run sync\npositions = sync_all_portfolios()\n\n# Print summary\ntotal_value = sum(p.value for p in positions)\ntotal_pnl = sum(p.pnl for p in positions)\n\nprint(f\"\\n{'='*60}\")\nprint(f\"PORTFOLIO SUMMARY\")\nprint(f\"{'='*60}\")\nprint(f\"Total Value: ${total_value:.2f}\")\nprint(f\"Total PnL: ${total_pnl:+.2f}\")\nprint(f\"{'='*60}\")\n\nfor platform in [\"polymarket\", \"kalshi\", \"manifold\"]:\n    plat_positions = [p for p in positions if p.platform == platform]\n    if plat_positions:\n        plat_value = sum(p.value for p in plat_positions)\n        plat_pnl = sum(p.pnl for p in plat_positions)\n        print(f\"\\n{platform.upper()}: ${plat_value:.2f} (PnL: ${plat_pnl:+.2f})\")\n\n        for p in plat_positions:\n            print(f\"  {p.market_question[:35]}\")\n            print(f\"    {p.side}: {p.size:.1f} @ {p.avg_price:.2f} -> {p.current_price:.2f}\")\n            print(f\"    Value: ${p.value:.2f}, PnL: ${p.pnl:+.2f} ({p.pnl_pct:+.1f}%)\")\n```\n\n## Cron Job for Auto-Sync\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nRun every hour to sync positions to database\n\"\"\"\n\nimport sqlite3\nfrom datetime import datetime\n\ndef sync_to_db():\n    \"\"\"Sync all positions to SQLite\"\"\"\n    conn = sqlite3.connect(\"~\u002F.clodds\u002Fclodds.db\")\n    positions = sync_all_portfolios()\n\n    for p in positions:\n        conn.execute(\"\"\"\n            INSERT OR REPLACE INTO positions\n            (platform, market_id, market_question, side, size, avg_price, current_price, value, pnl, updated_at)\n            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n        \"\"\", (\n            p.platform, p.market_id, p.market_question, p.side,\n            p.size, p.avg_price, p.current_price, p.value, p.pnl,\n            datetime.now().isoformat()\n        ))\n\n    conn.commit()\n    conn.close()\n    print(f\"Synced {len(positions)} positions at {datetime.now()}\")\n\nif __name__ == \"__main__\":\n    sync_to_db()\n```\n\nAdd to crontab:\n```bash\n# Sync every hour\n0 * * * * cd \u002Fpath\u002Fto\u002Fclodds && python3 -c \"from skills.portfolio_sync import sync_to_db; sync_to_db()\"\n```\n","# Portfolio Sync Skill\n\nReal methods to fetch and sync positions from each prediction market platform.\n\n## Polymarket Position Sync\n\nPolymarket positions are held as ERC-1155 tokens on Polygon. Query on-chain balances.\n\n```python\nimport os\nimport requests\n\nWALLET = os.getenv(\"POLY_FUNDER_ADDRESS\")\nCTF_CONTRACT = \"0x4D97DCd97eC945f40cF65F87097ACe5EA0476045\"  # Conditional Token Framework\n\ndef get_polymarket_positions(token_ids: list[str]) -> dict:\n    \"\"\"\n    Get balances for specific token IDs\n\n    Args:\n        token_ids: List of token IDs to check (from market data)\n\n    Returns:\n        Dict of token_id -> balance in shares\n    \"\"\"\n    positions = {}\n\n    for token_id in token_ids:\n        token_int = int(token_id)\n\n        # ERC-1155 balanceOf call\n        data = f\"0x00fdd58e000000000000000000000000{WALLET[2:].lower()}{token_int:064x}\"\n\n        r = requests.post(\"https:\u002F\u002Fpolygon-rpc.com\u002F\", json={\n            \"jsonrpc\": \"2.0\",\n            \"method\": \"eth_call\",\n            \"params\": [{\"to\": CTF_CONTRACT, \"data\": data}, \"latest\"],\n            \"id\": 1\n        })\n\n        result = r.json().get(\"result\", \"0x0\")\n        balance = int(result, 16) \u002F 1e6  # Raw to shares\n\n        if balance > 0:\n            positions[token_id] = balance\n\n    return positions\n\n# Example: Check positions for BTC 15-min market\nbtc_tokens = [\n    \"21742633143463906290569050155826241533067272736897614950488156847949938836455\",  # YES\n    \"48331043336612883890938759509493159234755048973500640148014422747788308965745\"   # NO\n]\n\npositions = get_polymarket_positions(btc_tokens)\nfor token_id, balance in positions.items():\n    print(f\"Token {token_id[:20]}...: {balance} shares\")\n```\n\n### Get All Polymarket Positions (via Gamma API)\n\n```python\ndef get_all_polymarket_positions(wallet: str):\n    \"\"\"Get all positions for a wallet via Gamma API\"\"\"\n    url = f\"https:\u002F\u002Fgamma-api.polymarket.com\u002Fpositions?user={wallet.lower()}\"\n    r = requests.get(url)\n\n    if r.status_code != 200:\n        return []\n\n    positions = r.json()\n\n    result = []\n    for p in positions:\n        result.append({\n            \"market_id\": p.get(\"conditionId\"),\n            \"market_question\": p.get(\"title\", \"Unknown\"),\n            \"token_id\": p.get(\"tokenId\"),\n            \"outcome\": p.get(\"outcome\"),\n            \"size\": float(p.get(\"size\", 0)),\n            \"avg_price\": float(p.get(\"avgPrice\", 0)),\n            \"current_price\": float(p.get(\"currentPrice\", 0)),\n            \"pnl\": float(p.get(\"pnl\", 0)),\n            \"value\": float(p.get(\"value\", 0))\n        })\n\n    return result\n\npositions = get_all_polymarket_positions(WALLET)\nfor p in positions:\n    print(f\"{p['market_question'][:40]}\")\n    print(f\"  {p['outcome']}: {p['size']} shares @ {p['avg_price']:.2f} -> {p['current_price']:.2f}\")\n    print(f\"  PnL: ${p['pnl']:.2f}\")\n```\n\n### Get USDC Balance\n\n```python\ndef get_usdc_balance(wallet: str) -> float:\n    \"\"\"Get USDC balance on Polygon\"\"\"\n    USDC = \"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174\"  # USDC on Polygon\n\n    # ERC-20 balanceOf\n    data = f\"0x70a08231000000000000000000000000{wallet[2:].lower()}\"\n\n    r = requests.post(\"https:\u002F\u002Fpolygon-rpc.com\u002F\", json={\n        \"jsonrpc\": \"2.0\",\n        \"method\": \"eth_call\",\n        \"params\": [{\"to\": USDC, \"data\": data}, \"latest\"],\n        \"id\": 1\n    })\n\n    result = r.json().get(\"result\", \"0x0\")\n    balance = int(result, 16) \u002F 1e6  # USDC has 6 decimals\n\n    return balance\n\nusdc = get_usdc_balance(WALLET)\nprint(f\"USDC Balance: ${usdc:.2f}\")\n```\n\n## Kalshi Position Sync\n\n```python\nimport requests\nimport time\n\nBASE_URL = \"https:\u002F\u002Ftrading-api.kalshi.com\u002Ftrade-api\u002Fv2\"\n\nclass KalshiSync:\n    def __init__(self, email: str, password: str):\n        self.email = email\n        self.password = password\n        self.token = None\n        self.token_expiry = 0\n\n    def _auth(self):\n        if time.time() > self.token_expiry - 60:\n            r = requests.post(f\"{BASE_URL}\u002Flogin\", json={\n                \"email\": self.email,\n                \"password\": self.password\n            })\n            r.raise_for_status()\n            self.token = r.json()[\"token\"]\n            self.token_expiry = time.time() + 29 * 60\n\n    def _headers(self):\n        self._auth()\n        return {\"Authorization\": f\"Bearer {self.token}\"}\n\n    def get_positions(self):\n        \"\"\"Get all Kalshi positions\"\"\"\n        r = requests.get(f\"{BASE_URL}\u002Fportfolio\u002Fpositions\", headers=self._headers())\n        r.raise_for_status()\n\n        positions = []\n        for p in r.json().get(\"market_positions\", []):\n            # Get market details\n            market = requests.get(\n                f\"{BASE_URL}\u002Fmarkets\u002F{p['ticker']}\",\n                headers=self._headers()\n            ).json().get(\"market\", {})\n\n            positions.append({\n                \"market_id\": p[\"ticker\"],\n                \"market_question\": market.get(\"title\", p[\"ticker\"]),\n                \"side\": \"YES\" if p.get(\"position\", 0) > 0 else \"NO\",\n                \"size\": abs(p.get(\"position\", 0)),\n                \"avg_price\": p.get(\"average_price\", 0) \u002F 100,\n                \"current_price\": market.get(\"yes_bid\", 50) \u002F 100,\n                \"value\": abs(p.get(\"position\", 0)) * market.get(\"yes_bid\", 50) \u002F 100,\n                \"pnl\": p.get(\"realized_pnl\", 0) \u002F 100\n            })\n\n        return positions\n\n    def get_balance(self):\n        \"\"\"Get Kalshi balance\"\"\"\n        r = requests.get(f\"{BASE_URL}\u002Fportfolio\u002Fbalance\", headers=self._headers())\n        r.raise_for_status()\n        data = r.json()\n        return {\n            \"available\": data.get(\"balance\", 0) \u002F 100,\n            \"portfolio_value\": data.get(\"portfolio_value\", 0) \u002F 100\n        }\n\n# Usage\nsync = KalshiSync(os.getenv(\"KALSHI_EMAIL\"), os.getenv(\"KALSHI_PASSWORD\"))\n\npositions = sync.get_positions()\nfor p in positions:\n    print(f\"{p['market_question'][:40]}\")\n    print(f\"  {p['side']}: {p['size']} @ {p['avg_price']:.2f} -> {p['current_price']:.2f}\")\n\nbalance = sync.get_balance()\nprint(f\"\\nAvailable: ${balance['available']:.2f}\")\nprint(f\"Portfolio: ${balance['portfolio_value']:.2f}\")\n```\n\n## Manifold Position Sync\n\n```python\nimport requests\n\nAPI_URL = \"https:\u002F\u002Fapi.manifold.markets\u002Fv0\"\nAPI_KEY = os.getenv(\"MANIFOLD_API_KEY\")\n\ndef get_manifold_positions():\n    \"\"\"Get all Manifold positions\"\"\"\n    headers = {\"Authorization\": f\"Key {API_KEY}\"}\n\n    # Get user profile\n    r = requests.get(f\"{API_URL}\u002Fme\", headers=headers)\n    r.raise_for_status()\n    user = r.json()\n    user_id = user[\"id\"]\n    balance = user.get(\"balance\", 0)\n\n    # Get all bets\n    r = requests.get(f\"{API_URL}\u002Fbets\", headers=headers, params={\"userId\": user_id, \"limit\": 1000})\n    bets = r.json()\n\n    # Aggregate positions by market\n    markets = {}\n    for bet in bets:\n        if bet.get(\"isSold\") or bet.get(\"isCancelled\"):\n            continue\n\n        mid = bet[\"contractId\"]\n        if mid not in markets:\n            markets[mid] = {\n                \"yes_shares\": 0,\n                \"no_shares\": 0,\n                \"invested\": 0,\n                \"question\": bet.get(\"contractQuestion\", \"Unknown\")\n            }\n\n        if bet[\"outcome\"] == \"YES\":\n            markets[mid][\"yes_shares\"] += bet.get(\"shares\", 0)\n        else:\n            markets[mid][\"no_shares\"] += bet.get(\"shares\", 0)\n\n        markets[mid][\"invested\"] += bet[\"amount\"]\n\n    # Get current prices\n    positions = []\n    for mid, data in markets.items():\n        if data[\"yes_shares\"] == 0 and data[\"no_shares\"] == 0:\n            continue\n\n        # Fetch current market price\n        r = requests.get(f\"{API_URL}\u002Fmarket\u002F{mid}\")\n        if r.status_code == 200:\n            market = r.json()\n            prob = market.get(\"probability\", 0.5)\n\n            yes_value = data[\"yes_shares\"] * prob\n            no_value = data[\"no_shares\"] * (1 - prob)\n            total_value = yes_value + no_value\n            pnl = total_value - data[\"invested\"]\n\n            positions.append({\n                \"market_id\": mid,\n                \"market_question\": data[\"question\"],\n                \"yes_shares\": data[\"yes_shares\"],\n                \"no_shares\": data[\"no_shares\"],\n                \"invested\": data[\"invested\"],\n                \"current_value\": total_value,\n                \"probability\": prob,\n                \"pnl\": pnl,\n                \"url\": market.get(\"url\", \"\")\n            })\n\n    return positions, balance\n\npositions, balance = get_manifold_positions()\nprint(f\"Mana Balance: {balance}\")\n\nfor p in positions:\n    print(f\"\\n{p['market_question'][:50]}\")\n    print(f\"  YES: {p['yes_shares']:.1f} shares, NO: {p['no_shares']:.1f} shares\")\n    print(f\"  Value: {p['current_value']:.0f}M, PnL: {p['pnl']:+.0f}M\")\n```\n\n## Unified Portfolio Sync\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nSync portfolio from all prediction markets\n\"\"\"\n\nimport os\nfrom dataclasses import dataclass\nfrom typing import List\n\n@dataclass\nclass Position:\n    platform: str\n    market_id: str\n    market_question: str\n    side: str\n    size: float\n    avg_price: float\n    current_price: float\n    value: float\n    pnl: float\n    pnl_pct: float\n\ndef sync_all_portfolios() -> List[Position]:\n    \"\"\"Sync positions from all platforms\"\"\"\n    all_positions = []\n\n    # Polymarket\n    if os.getenv(\"POLY_FUNDER_ADDRESS\"):\n        poly_positions = get_all_polymarket_positions(os.getenv(\"POLY_FUNDER_ADDRESS\"))\n        for p in poly_positions:\n            avg = p[\"avg_price\"] or 0.01\n            pnl_pct = ((p[\"current_price\"] - avg) \u002F avg * 100) if avg > 0 else 0\n\n            all_positions.append(Position(\n                platform=\"polymarket\",\n                market_id=p[\"market_id\"],\n                market_question=p[\"market_question\"],\n                side=p[\"outcome\"],\n                size=p[\"size\"],\n                avg_price=avg,\n                current_price=p[\"current_price\"],\n                value=p[\"value\"],\n                pnl=p[\"pnl\"],\n                pnl_pct=pnl_pct\n            ))\n\n    # Kalshi\n    if os.getenv(\"KALSHI_EMAIL\"):\n        kalshi = KalshiSync(os.getenv(\"KALSHI_EMAIL\"), os.getenv(\"KALSHI_PASSWORD\"))\n        kalshi_positions = kalshi.get_positions()\n        for p in kalshi_positions:\n            avg = p[\"avg_price\"] or 0.01\n            pnl_pct = ((p[\"current_price\"] - avg) \u002F avg * 100) if avg > 0 else 0\n\n            all_positions.append(Position(\n                platform=\"kalshi\",\n                market_id=p[\"market_id\"],\n                market_question=p[\"market_question\"],\n                side=p[\"side\"],\n                size=p[\"size\"],\n                avg_price=avg,\n                current_price=p[\"current_price\"],\n                value=p[\"value\"],\n                pnl=p[\"pnl\"],\n                pnl_pct=pnl_pct\n            ))\n\n    # Manifold\n    if os.getenv(\"MANIFOLD_API_KEY\"):\n        mani_positions, _ = get_manifold_positions()\n        for p in mani_positions:\n            invested = p[\"invested\"] or 1\n            pnl_pct = (p[\"pnl\"] \u002F invested * 100) if invested > 0 else 0\n\n            # Add YES position\n            if p[\"yes_shares\"] > 0:\n                all_positions.append(Position(\n                    platform=\"manifold\",\n                    market_id=p[\"market_id\"],\n                    market_question=p[\"market_question\"],\n                    side=\"YES\",\n                    size=p[\"yes_shares\"],\n                    avg_price=0,  # Manifold doesn't track this\n                    current_price=p[\"probability\"],\n                    value=p[\"yes_shares\"] * p[\"probability\"],\n                    pnl=p[\"pnl\"] \u002F 2,  # Split PnL\n                    pnl_pct=pnl_pct\n                ))\n\n            # Add NO position\n            if p[\"no_shares\"] > 0:\n                all_positions.append(Position(\n                    platform=\"manifold\",\n                    market_id=p[\"market_id\"],\n                    market_question=p[\"market_question\"],\n                    side=\"NO\",\n                    size=p[\"no_shares\"],\n                    avg_price=0,\n                    current_price=1 - p[\"probability\"],\n                    value=p[\"no_shares\"] * (1 - p[\"probability\"]),\n                    pnl=p[\"pnl\"] \u002F 2,\n                    pnl_pct=pnl_pct\n                ))\n\n    return all_positions\n\n# Run sync\npositions = sync_all_portfolios()\n\n# Print summary\ntotal_value = sum(p.value for p in positions)\ntotal_pnl = sum(p.pnl for p in positions)\n\nprint(f\"\\n{'='*60}\")\nprint(f\"PORTFOLIO SUMMARY\")\nprint(f\"{'='*60}\")\nprint(f\"Total Value: ${total_value:.2f}\")\nprint(f\"Total PnL: ${total_pnl:+.2f}\")\nprint(f\"{'='*60}\")\n\nfor platform in [\"polymarket\", \"kalshi\", \"manifold\"]:\n    plat_positions = [p for p in positions if p.platform == platform]\n    if plat_positions:\n        plat_value = sum(p.value for p in plat_positions)\n        plat_pnl = sum(p.pnl for p in plat_positions)\n        print(f\"\\n{platform.upper()}: ${plat_value:.2f} (PnL: ${plat_pnl:+.2f})\")\n\n        for p in plat_positions:\n            print(f\"  {p.market_question[:35]}\")\n            print(f\"    {p.side}: {p.size:.1f} @ {p.avg_price:.2f} -> {p.current_price:.2f}\")\n            print(f\"    Value: ${p.value:.2f}, PnL: ${p.pnl:+.2f} ({p.pnl_pct:+.1f}%)\")\n```\n\n## Cron Job for Auto-Sync\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nRun every hour to sync positions to database\n\"\"\"\n\nimport sqlite3\nfrom datetime import datetime\n\ndef sync_to_db():\n    \"\"\"Sync all positions to SQLite\"\"\"\n    conn = sqlite3.connect(\"~\u002F.clodds\u002Fclodds.db\")\n    positions = sync_all_portfolios()\n\n    for p in positions:\n        conn.execute(\"\"\"\n            INSERT OR REPLACE INTO positions\n            (platform, market_id, market_question, side, size, avg_price, current_price, value, pnl, updated_at)\n            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n        \"\"\", (\n            p.platform, p.market_id, p.market_question, p.side,\n            p.size, p.avg_price, p.current_price, p.value, p.pnl,\n            datetime.now().isoformat()\n        ))\n\n    conn.commit()\n    conn.close()\n    print(f\"Synced {len(positions)} positions at {datetime.now()}\")\n\nif __name__ == \"__main__\":\n    sync_to_db()\n```\n\nAdd to crontab:\n```bash\n# Sync every hour\n0 * * * * cd \u002Fpath\u002Fto\u002Fclodds && python3 -c \"from skills.portfolio_sync import sync_to_db; sync_to_db()\"\n```\n",{"name":5,"emoji":30,"description":7},"📁","main","f2ec4b3b9133d34eeaf9b38e4b0a97e8e5705a7f","benchmarks\u002Ffinal\u002Fskills\u002Fasset1__alsk1992--portfolio-sync",0,"https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard","https:\u002F\u002Fgithub.com\u002FJSGforever","2026-08-29 18:27:56",{"source":8,"skillName":5,"commands":39,"prompt":49,"zipAvailable":50},[40,43,46],{"tool":41,"command":42},"npx","npx skills add JSGforever\u002Fskillguard --skill portfolio-sync",{"tool":44,"command":45},"bunx","bunx skills add JSGforever\u002Fskillguard --skill portfolio-sync",{"tool":47,"command":48},"pnpm","pnpm dlx skills add JSGforever\u002Fskillguard --skill portfolio-sync","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__alsk1992--portfolio-sync\u002FSKILL.md",true,[52],{"path":53,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":56,"sourceHtmlUrl":57},"index.ts","SCRIPT","脚本",3361,"https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__alsk1992--portfolio-sync\u002Findex.ts",[59,86,97,124,143,163],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":25},"01M71HY2SNXBA9Q00WZDTZQ31Z","skillguard-codex-scanner","Hybrid deterministic+LLM agent-skill security scanner. Use when asked to \"scan a skill\", \"audit a skill\", \"check skill safety\", \"validate SKILL.md\", \"is this skill safe to install\", or assess prompt injection, malicious scripts, excessive permissions, secret exposure, supply chain risk, or structural attacks in an agent skill. Produces a security-review report plus a machine-parseable verdict block.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fsrc\u002Fskillguard\u002Fstatic_scanner\u002Fskillguard-codex-scanner\u002FSKILL.md",[],[66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85],"scanner","skillguard codex scanner","skillguard","codex","chain","skill security","security-review","review report","structural","secret","prompt injection","security scanner","when","review","malicious","permissions","exposure","audit","scripts","safe",{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":90,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":25},"01M71HY0SPKTT3S27BC2HPAC5M","data-exfiltrator","Analyzes data files","MIT","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Fsmoke-one-skill\u002Fasset1__cisco-ai-defense--data-exfiltrator\u002FSKILL.md",[],[94,95,96],"data","data exfiltrator","files",{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":25},"01M71HXVS9EMN44BGDW215FZ72","real-time-collaboration-engine","Build real-time collaborative editing with WebSockets, OT\u002FCRDT conflict resolution, and presence awareness. Implements cursor tracking, optimistic updates, and offline sync. Use for collaborative editors, whiteboards, video editing. Activate on \"real-time collaboration\", \"WebSocket sync\", \"multiplayer editing\", \"CRDT\", \"presence awareness\". NOT for simple chat, request-response APIs, or single-user apps.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__curiositech--real-time-collaboration-engine\u002FSKILL.md",[],[104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123],"time","real time collaboration engine","real time collaboration","collaboration","engine","real time","Video","reliability","video editing","performance","conflict resolution","presence","access","apps","updates","Bash","activate","optimizer","react","streaming",{"skillNo":125,"name":126,"nameZh":6,"description":127,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":128,"categories":129,"keywords":130,"publishedAt":25},"01M71HXP6CTY4KFN0QVMMN0V7J","react-performance-optimizer","Optimize React apps for 60fps performance. Implements memoization, virtualization, code splitting, bundle optimization. Use for slow renders, large lists, bundle bloat. Activate on \"React performance\", \"slow render\", \"useMemo\", \"bundle size\", \"virtualization\". NOT for backend optimization, non-React frameworks, or premature optimization.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__curiositech--react-performance-optimizer\u002FSKILL.md",[],[113,131,121,122,132,133,134,135,136,137,104,138,139,117,119,140,120,123,141,142],"react performance optimizer","react performance","performance optimizer","app","nextjs","expert","re","render","2025","code","router","strategies",{"skillNo":144,"name":145,"nameZh":6,"description":146,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":147,"categories":148,"keywords":149,"publishedAt":25},"01M71HXH7QXSQB4QTDZ7SP7YXQ","llm-streaming-response-handler","Build production LLM streaming UIs with Server-Sent Events, real-time token display, cancellation, error recovery. Handles OpenAI\u002FAnthropic\u002FClaude streaming APIs. Use for chatbots, AI assistants, real-time text generation. Activate on \"LLM streaming\", \"SSE\", \"token stream\", \"chat UI\", \"real-time AI\". NOT for batch processing, non-streaming APIs, or WebSocket bidirectional chat.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__curiositech--llm-streaming-response-handler\u002FSKILL.md",[],[150,123,151,152,153,154,113,104,155,156,157,119,120,121,158,122,159,160,161,162],"llm streaming response handler","handler","error","processing","retry","chat ui","error recovery","critical","batch","display","text","server","read",{"skillNo":164,"name":165,"nameZh":6,"description":166,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":167,"categories":168,"keywords":169,"publishedAt":25},"01M71HXCB0E1YRKYW1Y8T0Y106","github-actions-pipeline-builder","Build production CI\u002FCD pipelines with GitHub Actions. Implements matrix builds, caching, deployments, testing, security scanning. Use for automated testing, deployments, release workflows. Activate on \"GitHub Actions\", \"CI\u002FCD\", \"workflow\", \"deployment pipeline\", \"automated testing\". NOT for Jenkins\u002FCircleCI, manual deployments, or non-GitHub repositories.","https:\u002F\u002Fgithub.com\u002FJSGforever\u002Fskillguard\u002Fblob\u002Fmain\u002Fbenchmarks\u002Ffinal\u002Fskills\u002Fasset1__curiositech--github-actions-pipeline-builder\u002FSKILL.md",[],[170,171,172,173,174,175,176,111,136,177,178,179,120,142,180,162,181,182,183,184],"github actions pipeline builder","actions","github actions","pipeline builder","github","builder","pipeline","testing","ci","workflows","run","release","write","edit","git"]