{"id":"87acfadc-fcdd-494f-8a0e-2f164263f6f4","entityType":"agent","slug":"clawhub-ssj124-aionmarket-trading","name":"Aionmarket Trading","canonicalUrl":"https://www.xpersona.co/agent/clawhub-ssj124-aionmarket-trading","canonicalPath":"/agent/clawhub-ssj124-aionmarket-trading","generatedAt":"2026-10-10T02:45:53.689Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T20:29:14.402Z","emptyReason":null},"description":"Core trading skill for AION Market prediction market agents. Provides agent setup, wallet binding, market search, automated pre-trade checks, risk-aware trad...","descriptionLabel":"Source description","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 2K downloads reported by the source. Last updated 10/9/2026.","installCommand":"clawhub skill install s174p432zdjmq0szb7x7pvv8zx84s03q:aionmarket-trading","sourceUrl":"https://clawhub.ai/ssj124/aionmarket-trading","homepage":"https://clawhub.ai/ssj124/skills/aionmarket-trading","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/ssj124/aionmarket-trading","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/ssj124/skills/aionmarket-trading","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":66,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Aionmarket Trading technical dossier on Xpersona with agent coverage, OPENCLEW support, and live trust metadata."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-09T20:29:14.402Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T20:29:14.402Z","emptyReason":null},"stars":null,"forks":null,"downloads":2024,"packageName":null,"latestVersion":"1.0.7","tractionLabel":"2K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T20:29:14.402Z","emptyReason":null},"lastUpdatedAt":"2026-10-09T20:29:14.402Z","lastCrawledAt":"2026-10-09T20:29:14.402Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-10T20:29:14.402Z","lastVerifiedAt":null,"highlights":[{"version":"1.0.7","createdAt":"2026-05-11T14:30:23.851Z","changelog":"- Documentation and metadata updates only—no functional or API changes. - Clarified usage, environment setup, and agent responsibilities in the skill description. - Restated requirements, principles, and constraints for safer and clearer agent integration. - Installation and setup instructions remain unchanged.","fileCount":3,"zipByteSize":12069},{"version":"1.0.6","createdAt":"2026-05-07T02:31:57.142Z","changelog":"- Updated SDK dependency from `aionmarket-sdk` to `aion-sdk` throughout documentation. - Changed documentation URLs to reflect new canonical `www.aionmarket.com` domains. - Added requirements to charge the platform trading fee after every successful order using `charge_polymarket_fee()` or `charge_kalshi_fee()`. - Now mandates that fee allowance must be pre-approved before trading (Safe AllowanceModule for Polymarket, USDC token approval for Kalshi). - Updated example installation commands, prerequisites, and environment setup instructions accordingly.","fileCount":2,"zipByteSize":10763},{"version":"1.0.5","createdAt":"2026-04-23T12:15:39.235Z","changelog":"- Updated documentation URLs to point to new production domains (`aionmarket.com` and `docs.aionmarket.com`) - No logic or API changes; documentation clarification only - Maintains previous installation and usage instructions - Ensures users reference accurate environment setup and support resources","fileCount":2,"zipByteSize":9028},{"version":"1.0.4","createdAt":"2026-04-23T11:44:05.290Z","changelog":"- Updated documentation links in metadata (`homepage` and `docs`) to new test/staging URLs. - No functional code changes; documentation and reference updates only.","fileCount":2,"zipByteSize":9036},{"version":"1.0.3","createdAt":"2026-04-23T09:08:36.771Z","changelog":"Added Kalshi venue support and settlement workflows. - Expanded prerequisites and logic to support both Polygon (Polymarket) and Solana (Kalshi) wallets. - Documented Kalshi trading flow (quote -> sign -> submit) and position management. - Updated environment variable requirements to include optional `SOLANA_PRIVATE_KEY` for Kalshi. - Clarified venue-specific constraints and default automation behaviors for Polymarket and Kalshi. - Refined installation, secret management, and API usage recommendations to reflect multi-venue support.","fileCount":2,"zipByteSize":9026},{"version":"1.0.2","createdAt":"2026-04-17T13:14:42.502Z","changelog":"- Added `tags` field to metadata for improved discovery (e.g., polymarket, trading, ai-agent). - No changes to functionality or API; documentation only.","fileCount":2,"zipByteSize":8493},{"version":"1.0.1","createdAt":"2026-04-17T08:21:48.647Z","changelog":"## Changelog for aionmarket-trading 1.0.1 - Updated environment variable instructions to clarify when and how to set `AIONMARKET_BASE_URL`. - Added warnings not to hardcode or use outdated staging URLs; reference only URLs documented in official AION Market docs. - Improved comments in the environment setup section for safer usage. - Sample `.env` section now flags the correct approach for specifying environment URLs. - No functional changes to trading logic; documentation improvements only.","fileCount":2,"zipByteSize":8167},{"version":"1.0.0","createdAt":"2026-04-17T05:48:07.586Z","changelog":"aionmarket-trading 1.0.0 - Initial release providing core trading operations for AION Market / Polymarket through the aionmarket-sdk. - Automates agent setup, wallet binding, market search, pre-trade checks, risk-aware trading, order management, position monitoring, and settlement redemption. - Enforces strict credential handling, wallet checks (balance, gas, allowance), and error management. - Separates foundational trading from strategy logic for modular agent development. - Supports environment-based configuration and automatic CLOB credential derivation from private keys. - Includes detailed instructions for installation, setup, and workflow.","fileCount":2,"zipByteSize":7820}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s174p432zdjmq0szb7x7pvv8zx84s03q:aionmarket-trading","setupComplexity":"low","setupSteps":["Install using `clawhub skill install s174p432zdjmq0szb7x7pvv8zx84s03q:aionmarket-trading` in an isolated environment before connecting it to live workloads.","No published capability contract is available yet, so validate auth and request/response behavior manually.","Review the upstream CLAWHUB listing at https://clawhub.ai/ssj124/aionmarket-trading before using production credentials."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-ssj124-aionmarket-trading/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-ssj124-aionmarket-trading/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-ssj124-aionmarket-trading/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-ssj124-aionmarket-trading/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-ssj124-aionmarket-trading/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-ssj124-aionmarket-trading/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-10T02:45:53.686Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-ssj124-aionmarket-trading/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-ssj124-aionmarket-trading/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-ssj124-aionmarket-trading/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-ssj124-aionmarket-trading/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T20:29:14.402Z","emptyReason":null},"readme":"Skill: Aionmarket Trading\n\nOwner: ssj124\n\nSummary: Core trading skill for AION Market prediction market agents. Provides agent setup, wallet binding, market search, automated pre-trade checks, risk-aware trad...\n\nTags: latest:1.0.7\n\nVersion history:\n\nv1.0.7 | 2026-05-11T14:30:23.851Z | auto\n\n- Documentation and metadata updates only—no functional or API changes.\n- Clarified usage, environment setup, and agent responsibilities in the skill description.\n- Restated requirements, principles, and constraints for safer and clearer agent integration.\n- Installation and setup instructions remain unchanged.\n\nv1.0.6 | 2026-05-07T02:31:57.142Z | auto\n\n- Updated SDK dependency from `aionmarket-sdk` to `aion-sdk` throughout documentation.\n- Changed documentation URLs to reflect new canonical `www.aionmarket.com` domains.\n- Added requirements to charge the platform trading fee after every successful order using `charge_polymarket_fee()` or `charge_kalshi_fee()`.\n- Now mandates that fee allowance must be pre-approved before trading (Safe AllowanceModule for Polymarket, USDC token approval for Kalshi).\n- Updated example installation commands, prerequisites, and environment setup instructions accordingly.\n\nv1.0.5 | 2026-04-23T12:15:39.235Z | auto\n\n- Updated documentation URLs to point to new production domains (`aionmarket.com` and `docs.aionmarket.com`)\n- No logic or API changes; documentation clarification only\n- Maintains previous installation and usage instructions\n- Ensures users reference accurate environment setup and support resources\n\nv1.0.4 | 2026-04-23T11:44:05.290Z | auto\n\n- Updated documentation links in metadata (`homepage` and `docs`) to new test/staging URLs.\n- No functional code changes; documentation and reference updates only.\n\nv1.0.3 | 2026-04-23T09:08:36.771Z | auto\n\nAdded Kalshi venue support and settlement workflows.\n\n- Expanded prerequisites and logic to support both Polygon (Polymarket) and Solana (Kalshi) wallets.\n- Documented Kalshi trading flow (quote -> sign -> submit) and position management.\n- Updated environment variable requirements to include optional `SOLANA_PRIVATE_KEY` for Kalshi.\n- Clarified venue-specific constraints and default automation behaviors for Polymarket and Kalshi.\n- Refined installation, secret management, and API usage recommendations to reflect multi-venue support.\n\nv1.0.2 | 2026-04-17T13:14:42.502Z | auto\n\n- Added `tags` field to metadata for improved discovery (e.g., polymarket, trading, ai-agent).\n- No changes to functionality or API; documentation only.\n\nv1.0.1 | 2026-04-17T08:21:48.647Z | auto\n\n## Changelog for aionmarket-trading 1.0.1\n\n- Updated environment variable instructions to clarify when and how to set `AIONMARKET_BASE_URL`.\n- Added warnings not to hardcode or use outdated staging URLs; reference only URLs documented in official AION Market docs.\n- Improved comments in the environment setup section for safer usage.\n- Sample `.env` section now flags the correct approach for specifying environment URLs.\n- No functional changes to trading logic; documentation improvements only.\n\nv1.0.0 | 2026-04-17T05:48:07.586Z | auto\n\naionmarket-trading 1.0.0\n\n- Initial release providing core trading operations for AION Market / Polymarket through the aionmarket-sdk.\n- Automates agent setup, wallet binding, market search, pre-trade checks, risk-aware trading, order management, position monitoring, and settlement redemption.\n- Enforces strict credential handling, wallet checks (balance, gas, allowance), and error management.\n- Separates foundational trading from strategy logic for modular agent development.\n- Supports environment-based configuration and automatic CLOB credential derivation from private keys.\n- Includes detailed instructions for installation, setup, and workflow.\n\nArchive index:\n\nArchive v1.0.7: 3 files, 12069 bytes\n\nFiles: skill-card.md (2704b), skill.md (29827b), _meta.json (137b)\n\nFile v1.0.7:skill.md\n\n---\nname: aionmarket-trading\ndescription: |\n  Core trading skill for AION Market prediction market agents.\n  Provides agent setup, wallet binding, market search, automated pre-trade\n  checks, risk-aware trading, order management, position monitoring, and\n  settlement workflows on Polymarket and Kalshi via the aion-sdk Python package.\n\n  Use when: an AI agent needs to register, configure wallets, search markets,\n  place or cancel trades, monitor positions, or run settlement-related flows on AION Market / Polymarket / Kalshi.\nmetadata:\n  author: \"AION Market\"\n  version: \"0.3.0\"\n  homepage: \"https://www.aionmarket.com/\"\n  docs: \"https://docs.aionmarket.com/\"\n  sdk: \"aion-sdk (PyPI)\"\n---\n\n# Skill: aionmarket-trading\n\nCore trading operations for AI agents on AION Market / Polymarket / Kalshi.\nThis skill covers the **foundational** capabilities — agent lifecycle, wallet setup,\nmarket data, order execution, and position management.\n\n> **Strategy skills** (market discovery, signal generation, automated loops) are\n> separate skills that build on top of this one.\n\n---\n\n## Scope\n\n- **Applies to:** Any AI agent that needs to trade prediction markets through AION Market\n- **Does NOT cover:** Strategy logic, autonomous market scanning loops, or signal generation (see dedicated strategy skills)\n\n---\n\n## Prerequisites — USER MUST PROVIDE\n\nBefore this skill can operate, the user **must** supply:\n\n| Secret                 | Where to set                           | Example                               |\n| ---------------------- | -------------------------------------- | ------------------------------------- |\n| **Agent API Key**      | `AIONMARKET_API_KEY` env var or `.env` | `sk_live_Ab12Cd34...`                 |\n| **Wallet Private Key** | `WALLET_PRIVATE_KEY` env var or `.env` | `0xabc123...` (64 hex chars, Polygon) |\n| **Solana Private Key** | `SOLANA_PRIVATE_KEY` env var or `.env` | `<base58-key>` (Kalshi optional)      |\n\nThe skill will:\n\n1. Derive wallet addresses from provided keys (Polygon and/or Solana)\n2. For Polymarket, call CLOB auth to derive **API Key / Secret / Passphrase** from private key signature\n3. Register Polymarket CLOB credentials with AION Market via `register_wallet_credentials()` when needed\n4. For Kalshi, use quote -> local sign -> submit flow via DFlow-backed endpoints\n5. Automatically check wallet readiness before trading: balance, gas/fees, allowance (Polymarket), and market context\n\n> **If the private key is missing, STOP and ask the user to provide it.**\n> Never guess, fabricate, or skip credential setup.\n> Store secrets in a local `.env` file (never commit to git) or export as env vars.\n\n---\n\n## Assumptions\n\n- Python 3.9+\n- `aion-sdk >= 0.1.2` installed (`pip install aion-sdk`)\n- `py-clob-client` for Polymarket order signing and credential derivation\n- Agent has been registered or will be registered as part of the flow\n- Polymarket CLOB credentials are derived automatically from private key via `py-clob-client`\n- Kalshi trading uses quote -> sign -> submit; position queries use the unified `get_current_positions(..., venue=\"kalshi\")` endpoint\n- All SDK methods return plain dicts/lists; errors raise `ApiError`\n- **`get_markets()` returns events with nested `markets[]` sub-markets** — trading fields like `conditionId`, `clobTokenIds`, `outcomePrices` live on the sub-market, not the event\n\n---\n\n## Principles\n\n1. **Always check context before trading** — call `get_market_context()` before every order\n2. **Never trade without a thesis** — every trade needs explicit reasoning\n3. **Respect risk limits** — honour `riskLimit`, `maxTradesPerDay`, `maxTradeAmount`\n4. **Fail loudly** — catch `ApiError` and surface the message; never swallow errors\n5. **Self-custody** — wallet keys belong to the user; SDK only stores encrypted CLOB credentials\n6. **Automate mechanical steps** — do not ask the user to manually confirm balance checks, gas checks, allowance checks, or approval after the private key is available\n7. **Verify execution independently** — if the wrapper response is weak, validate through the corresponding venue (Polymarket or Kalshi) before reporting failure\n\n---\n\n## Automation Defaults\n\nUnless the user explicitly overrides them, the agent should use these defaults:\n\n- default trade mode: `market`\n- default buy size: `2` USDC\n- default behavior: auto-select a valid market candidate from the requested strategy scope\n- default pre-trade workflow: derive wallet, register wallet credentials, check balance, check gas, check allowance, auto-approve if needed, then trade\n- default post-trade workflow: query recent venue-specific trades/orders (Polymarket orders or Kalshi positions/orders) if the SDK result is generic, null, or ambiguous\n\nThe agent should ask the user only for information it cannot safely infer or execute itself.\n\n---\n\n## Constraints\n\n### MUST\n\n- Set `AIONMARKET_API_KEY` before any authenticated call\n- Register Polymarket CLOB credentials before live Polymarket trading\n- Check wallet balance, gas/fees, and relevant allowance before submitting any order\n- Call `get_market_context()` before placing any trade\n- Handle `ApiError` on every SDK call\n- Save the API key returned by `register_agent()` immediately — it is shown only once\n- For Polymarket, send a full signed order object and `walletAddress` with every trade\n- For Kalshi, follow quote -> local sign -> submit and include `userPublicKey` when executing BUY flows\n- Verify downstream execution via the target venue when SDK responses are incomplete- **Charge platform trading fee after every successful order** — call `charge_polymarket_fee()` or `charge_kalshi_fee()` after trade confirmation\n- **Ensure fee allowance is pre-approved** before trading — Polymarket requires Safe AllowanceModule delegate; Kalshi requires USDC token approval on Solana\n\n### SHOULD\n\n- Use environment variables for all secrets (never hardcode)\n- Call `get_briefing()` periodically (heartbeat pattern) for risk alerts and opportunities\n- Set conservative risk limits first via `update_settings()`, then scale up\n- Cancel stale open orders promptly\n- Rotate API keys every 90 days\n- Prefer market orders for simple one-shot execution unless the user explicitly requests a limit order\n- Auto-approve required spenders when allowance is missing and gas is sufficient\n\n### AVOID\n\n- Trading without checking `warnings` from market context\n- Exceeding the agent's configured `maxTradeAmount`\n- Sharing or logging API keys, CLOB secrets, or private keys\n- Calling `cancel_all_orders()` without confirming with the user first\n- Making trades in markets the agent has not researched\n- Treating a wrapper `INTERNAL_ERROR` as final without checking whether the downstream venue actually accepted or matched the order\n\n---\n\n## Installation\n\n```bash\npip install aion-sdk py-clob-client python-dotenv\n```\n\n- `py-clob-client` — Polymarket official SDK, derives CLOB API credentials from private key\n- `python-dotenv` — loads `.env` file automatically\n\n---\n\n## Environment Setup\n\nCreate a `.env` file in your project root (add `.env` to `.gitignore`):\n\n```bash\n# .env\nAIONMARKET_API_KEY=sk_live_...\nWALLET_PRIVATE_KEY=0xabc123...your_64_hex_char_private_key\n\n# Optional — only set this when AION Market docs tell you to use\n# a non-production environment URL for your target environment.\n# Do not hardcode a staging URL copied from an old example.\n# AIONMARKET_BASE_URL=https://<documented-aionmarket-base-url>/bvapi\n```\n\nOr export directly:\n\n```bash\nexport AIONMARKET_API_KEY=\"sk_live_...\"\nexport WALLET_PRIVATE_KEY=\"0xabc123...\"\n```\n\n### Derive Wallet Address and CLOB Credentials from Private Key\n\n```python\nimport os\nfrom dotenv import load_dotenv\nfrom py_clob_client.client import ClobClient\n\nload_dotenv()  # loads .env file\n\nprivate_key = os.environ[\"WALLET_PRIVATE_KEY\"]\n\n# Use Polymarket CLOB client to derive credentials from private key\npolymarket = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,\n    chain_id=137,\n)\ncreds = polymarket.create_or_derive_api_creds()\n# creds contains: api_key, api_secret, api_passphrase\n\nwallet_address = polymarket.get_address()\nprint(f\"Wallet address: {wallet_address}\")\nprint(f\"CLOB credentials derived successfully\")\n```\n\n**Base URL resolution priority:**\n\n1. Explicit `base_url` argument in code\n2. `AIONMARKET_BASE_URL` environment variable\n3. Production default: `https://www.aionmarket.com//bvapi`\n\nUse the SDK's documented resolution order above. Do **not** hardcode a sandbox or staging URL in sample code unless that exact environment URL is the current one documented by AION Market.\n\n---\n\n## Workflow: Agent Bootstrap\n\nRun once to create an agent and bind a wallet.\n\n### Step 1 — Register Agent\n\n```python\nfrom aion_sdk import AionMarketClient\n\nclient = AionMarketClient()  # no key needed for registration\nregistration = client.register_agent(\"my-trading-bot\")\n\napi_key = registration[\"apiKeyCode\"]\nclaim_code = registration[\"claimCode\"]\nprint(f\"API Key (save now!): {api_key}\")\nprint(f\"Claim URL: {registration['claimUrl']}\")\n```\n\n> Save `apiKeyCode` immediately — it is only returned once.\n> After the API key is generated, open or click `claimUrl` and complete the claim/auth flow. Generating the key alone does **not** finish agent authentication.\n\nThe `claimUrl` returned by `register_agent()` is environment-aware and points\ndirectly to the frontend claim page (staging or production). Open it in a\nbrowser to claim and authenticate the agent.\n\nThe URL format is:\n\n```\nhttps://<FRONTEND_DOMAIN>/agents/claim?code=<CLAIM_CODE>\n```\n\nOr use `claim_preview(claim_code)` to verify the agent name before claiming.\n\n### Step 2 — Verify Agent\n\n```python\nclient = AionMarketClient(api_key=api_key)\nme = client.get_me()\nprint(f\"Agent: {me['name']}, Status: {me['status']}\")\n```\n\n### Step 3 — Derive Polymarket CLOB Credentials & Register Wallet\n\nThe private key is used to call Polymarket's auth endpoint and derive CLOB credentials automatically.\nThe user does **not** need to manually copy API Key / Secret / Passphrase from Polymarket settings.\n\n```python\nimport os\nfrom dotenv import load_dotenv\nfrom py_clob_client.client import ClobClient\n\nload_dotenv()\n\nprivate_key = os.environ[\"WALLET_PRIVATE_KEY\"]\n\n# 1. Derive CLOB credentials from private key via Polymarket\npolymarket = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,\n    chain_id=137,\n)\ncreds = polymarket.create_or_derive_api_creds()\nwallet = polymarket.get_address()\n\nprint(f\"Wallet: {wallet}\")\nprint(f\"CLOB API Key: {creds.api_key}\")\n\n# 2. Register with AION Market\ncheck = client.check_wallet_credentials(wallet)\nif not check[\"hasCredentials\"]:\n    client.register_wallet_credentials(\n        wallet_address=wallet,\n        api_key=creds.api_key,\n        api_secret=creds.api_secret,\n        api_passphrase=creds.api_passphrase,\n    )\n    print(f\"Wallet credentials registered for {wallet}\")\nelse:\n    print(f\"Wallet {wallet} already configured.\")\n```\n\n### Step 4 — Configure Risk Limits\n\n```python\nclient.update_settings(\n    max_trades_per_day=50,\n    max_trade_amount=100.0,\n    trading_paused=False,\n    auto_redeem_enabled=True,\n)\nsettings = client.get_settings()\nprint(settings)\n```\n\n### Step 5 — Kalshi Prerequisites (Optional, for Kalshi venue)\n\n- Ensure Solana wallet is available (`SOLANA_PRIVATE_KEY` / `userPublicKey`)\n- Use `kalshi_quote()` to request unsigned tx, locally sign, then call `kalshi_submit()`\n- For BUY flows, provide `userPublicKey` so KYC/geo checks can be evaluated upstream\n\n---\n\n## Workflow: Market Search & Context\n\n### Understanding Market Data Structure\n\n> **Critical:** `get_markets()` returns **events**, each containing a nested `markets[]`\n> array of **sub-markets**. Trading fields like `conditionId`, `clobTokenIds`,\n> `outcomePrices`, `negRisk`, and `orderPriceMinTickSize` live on the **sub-market**, NOT the event.\n\n```python\nimport ast\n\n# Search returns events\nevents = client.get_markets(q=\"bitcoin\", limit=10)\n\nfor event in events:\n    print(f\"Event: {event['title']}\")\n    for sub in event.get(\"markets\", []):\n        # Parse JSON strings\n        prices = ast.literal_eval(sub.get(\"outcomePrices\", '[\"0.5\",\"0.5\"]'))\n        token_ids = ast.literal_eval(sub.get(\"clobTokenIds\", '[]'))\n        print(f\"  Sub-market: {sub['question']}\")\n        print(f\"    conditionId: {sub['conditionId']}\")\n        print(f\"    YES price: {prices[0]}, NO price: {prices[1]}\")\n        print(f\"    YES token: {token_ids[0] if token_ids else 'N/A'}\")\n        print(f\"    negRisk: {sub.get('negRisk', False)}\")\n        print(f\"    tickSize: {sub.get('orderPriceMinTickSize', 0.01)}\")\n        print(f\"    minSize: {sub.get('orderMinSize', 5)}\")\n```\n\n### Get Market Context (REQUIRED before trading)\n\n```python\ncontext = client.get_market_context(\"CONDITION_ID\", user=wallet)\n\nprint(f\"Name:       {context.get('name')}\")\nprint(f\"Position:   {context.get('myPosition')}\")\nprint(f\"Risk limit: {context.get('riskLimit')}\")\nprint(f\"Warnings:   {context.get('warnings')}\")\n\nif context.get(\"warnings\"):\n    print(\"⚠️  Review warnings before proceeding!\")\n```\n\n### Automatic Pre-Trade Readiness Checks\n\nBefore signing or submitting any order, the agent should automatically verify:\n\n- wallet credentials are already registered, otherwise register them\n- collateral balance is sufficient for the intended spend\n- Polygon gas balance is sufficient if an onchain approval may be needed\n- the required spender allowance already exists for the intended order\n\nIf allowance is insufficient and gas is available, the agent should send the approval transaction automatically instead of asking the user to do it manually.\n\n---\n\n## Workflow: Trade Execution\n\n### Building a Signed Order (REQUIRED)\n\nThe `trade()` endpoint requires a **complete EIP712-signed order** from `py-clob-client`.\nPassing `\"order\": {}` will cause a credential lookup failure — the server reads\n`order.signatureType` to find your wallet credentials.\n\n```python\nimport ast\nfrom py_clob_client.client import ClobClient\nfrom py_clob_client.clob_types import ApiCreds, CreateOrderOptions, OrderArgs\n\n# 1. Initialize CLOB client with creds (derived earlier in bootstrap)\nclob = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,     # WALLET_PRIVATE_KEY\n    chain_id=137,\n    creds=ApiCreds(\n        api_key=creds.api_key,\n        api_secret=creds.api_secret,\n        api_passphrase=creds.api_passphrase,\n    ),\n)\n\n# 2. Extract trading params from sub-market (NOT event)\nsub_market = event[\"markets\"][0]  # pick the sub-market you want to trade\ncondition_id = sub_market[\"conditionId\"]\ntoken_ids = ast.literal_eval(sub_market[\"clobTokenIds\"])\nyes_token_id = token_ids[0]   # index 0 = YES, index 1 = NO\nno_token_id = token_ids[1]\nneg_risk = sub_market.get(\"negRisk\", False)\ntick_size = str(sub_market.get(\"orderPriceMinTickSize\", \"0.01\"))\nmin_size = sub_market.get(\"orderMinSize\", 5)\n\n# 3. Build signed order — MUST use CreateOrderOptions for proper signing\nsigned_order = clob.create_order(\n    OrderArgs(\n        token_id=yes_token_id,   # or no_token_id for NO side\n        price=0.55,\n        size=min_size,           # must >= orderMinSize\n        side=\"BUY\",\n    ),\n    options=CreateOrderOptions(\n        tick_size=tick_size,     # from sub-market.orderPriceMinTickSize\n        neg_risk=neg_risk,       # CRITICAL for neg-risk markets!\n    ),\n)\n\n# 4. Convert dataclass to dict for JSON serialization\norder_dict = signed_order.dict()\n```\n\n### Place a Trade\n\n```python\nresult = client.trade({\n    \"marketConditionId\": condition_id,          # hex conditionId from sub-market\n    \"marketQuestion\": sub_market[\"question\"],   # question text\n    \"outcome\": \"YES\",                           # YES or NO\n    \"orderSize\": min_size,                      # number of contracts\n    \"price\": 0.55,                              # price per contract (0-1)\n    \"isLimitOrder\": True,                       # True=limit, False=market\n    \"order\": order_dict,                        # ← FULL signed order (never {})\n    \"walletAddress\": wallet,                    # ← REQUIRED\n    \"reasoning\": \"Strategy edge explanation\",\n})\nprint(f\"Order ID: {result.get('orderId')}\")\nprint(f\"Status:   {result.get('status')}\")\n```\n\n### Default Execution Policy\n\nFor general-purpose execution, use this default policy unless the user overrides it:\n\n1. prefer `market` mode\n2. use `2` USDC as default buy size\n3. derive a marketable cap from current prices or order book when using market-order helpers\n4. ask for a price only when the user explicitly requested a limit order and did not provide one\n5. report the market snapshot and final order parameters without blocking on extra confirmation\n\n> **Common pitfalls:**\n>\n> - `\"order\": {}` → server cannot find `signatureType`, returns credential error\n> - Using event numeric ID as `marketConditionId` → use sub-market hex `conditionId`\n> - Missing `walletAddress` → \"walletAddress 不能为空\" error\n> - Not setting `neg_risk=True` for neg-risk markets → invalid signature, Polymarket rejects\n> - `orderSize` below `orderMinSize` → order rejected\n> - Insufficient USDC balance → server returns generic `INTERNAL_ERROR`\n> - Insufficient allowance → downstream exchange cannot spend collateral\n> - SDK result is empty or generic → verify recent trades and orders before reporting failure\n\n**Order types:** `GTC` (default), `FOK`, `GTD`, `FAK`\n**Sides:** `BUY`, `SELL`\n**Outcomes:** `YES`, `NO`\n\n---\n\n## Workflow: Kalshi Quote -> Sign -> Submit\n\nUse this flow for Kalshi venue execution.\n\n```python\nquote = client.kalshi_quote(\n    market_ticker=\"KX...\",\n    side=\"YES\",\n    action=\"BUY\",\n    amount=10,\n    user_public_key=\"<solana-wallet>\",\n)\n\n# Sign quote[\"unsignedTransaction\"] locally (wallet implementation specific)\nsigned_tx = \"<base64-signed-tx>\"\n\nsubmit = client.kalshi_submit(\n    market_ticker=\"KX...\",\n    side=\"YES\",\n    action=\"BUY\",\n    amount=10,\n    quote_id=quote[\"quoteId\"],\n    signed_transaction=signed_tx,\n    user_public_key=\"<solana-wallet>\",\n    in_amount=quote.get(\"inAmount\"),\n    out_amount=quote.get(\"outAmount\"),\n    min_out_amount=quote.get(\"minOutAmount\"),\n)\nprint(submit)\n\n# Unified positions endpoint for Kalshi (venue = kalshi)\nkalshi_positions = client.get_current_positions(\n    user=\"<solana-wallet>\",\n    venue=\"kalshi\",\n)\nprint(kalshi_positions)\n```\n\nKalshi currently does not expose a dedicated cancel API in this SDK. Use a SELL flow (`kalshi_quote` -> sign -> `kalshi_submit`) to reduce/exit exposure.\n\n---\n\n## Workflow: Platform Fee Charging\n\nAION Market charges a **1% platform trading fee** on every executed order. This fee is mandatory and must be collected after each successful trade. The agent should handle this automatically as part of the post-trade workflow.\n\n### Fee Structure\n\n| Venue      | Fee Rate                           | Token      | Chain   | Collection Method                          |\n| ---------- | ---------------------------------- | ---------- | ------- | ------------------------------------------ |\n| Polymarket | 1% of notional (orderSize × price) | pUSD       | Polygon | Safe AllowanceModule (auto-cron or manual) |\n| Kalshi     | 1% of order amount                 | USDC (SPL) | Solana  | Fireblocks transfer (manual trigger)       |\n\n### Fee Calculation\n\n```\nPolymarket: fee = orderSize × price × 0.01\nKalshi:     fee = orderAmount × 0.01\n```\n\nExample: An order of 100 contracts at $0.55 → notional = $55 → fee = $0.55 pUSD\n\n### Platform Fee Receiving Addresses\n\n| Venue                | Platform Wallet                                |\n| -------------------- | ---------------------------------------------- |\n| Polymarket (Polygon) | `0xeA44cAF1f893729342dC5D8903F658E8D3e2379B`   |\n| Kalshi (Solana)      | `CHMkL5utJWFFHSkHX6pwWcb8VXj5jAz5fAqqMGAyEXcX` |\n\n### Prerequisites for Fee Collection\n\n**Polymarket (pUSD on Polygon):**\n\n1. User's Safe wallet must have **AllowanceModule** enabled\n2. Platform Fireblocks address must be added as **delegate** in the AllowanceModule\n3. Sufficient **pUSD token allowance** must be configured on the module\n4. The agent should verify allowance before trading and auto-approve if gas is available\n\n**Kalshi (USDC on Solana):**\n\n1. User's Solana wallet must hold sufficient **USDC** (native SPL token)\n2. User must grant **token approval** to the platform vault address\n3. The agent should use the local private key to sign approval if not already granted\n\n### Post-Trade Fee Charging Flow\n\n#### Polymarket — Automatic + Manual Fallback\n\nPolymarket fees are collected automatically by a server-side cron job (every 3 seconds).\nHowever, the agent should verify fee status and trigger manually if needed:\n\n```python\n# After a successful trade:\nresult = client.trade({...})\norder_hash_id = result.get(\"orderId\")\n\n# Option 1: Rely on automatic cron (default — fees are charged within 3 seconds)\n# Option 2: Explicitly trigger fee charging\nif order_hash_id:\n    fee_result = client.charge_polymarket_fee(order_hash_id)\n    print(f\"Fee: ${fee_result['feeAmount']}, Status: {fee_result['status']}\")\n    # status will be 'PENDING' — Fireblocks tx takes ~10-30s to confirm\n```\n\n#### Kalshi — Must Trigger Manually\n\nKalshi fees are NOT collected automatically. The agent MUST call `charge_kalshi_fee()`\nafter a successful `kalshi_submit()`:\n\n```python\n# After successful Kalshi submit:\nsubmit_result = client.kalshi_submit(\n    market_ticker=\"KX...\",\n    side=\"YES\",\n    action=\"BUY\",\n    amount=10,\n    signed_transaction=signed_tx,\n    quote_id=quote[\"quoteId\"],\n    user_public_key=sol_wallet,\n)\n\ntx_signature = submit_result.get(\"txSignature\")\n\n# REQUIRED: Charge the 1% platform fee\nif tx_signature:\n    fee_result = client.charge_kalshi_fee(tx_signature)\n    print(f\"Fee: ${fee_result['feeAmount']}, TxId: {fee_result['transactionId']}\")\n```\n\n### Fee Charging Error Handling\n\n```python\nfrom aion_sdk import ApiError\n\ntry:\n    fee_result = client.charge_kalshi_fee(tx_signature)\nexcept ApiError as e:\n    if \"allowance\" in e.message.lower() or \"insufficient\" in e.message.lower():\n        print(\"❌ Insufficient allowance — user needs to approve more USDC\")\n    elif \"not found\" in e.message.lower():\n        print(\"❌ Order not found — verify order was submitted successfully\")\n    else:\n        print(f\"❌ Fee charging failed: {e.message}\")\n```\n\n### Agent Commission\n\nAgents that execute trades earn a **10% commission** on collected fees:\n\n- Platform collects 1% fee → agent receives 0.1% of trade notional\n- Commission is tracked automatically and available for periodic payout\n- No additional API calls are needed — commission is recorded when fee is charged\n\n---\n\n## Workflow: Order Management\n\n```python\n# List open orders\nopen_orders = client.get_open_orders()\n\n# Order history (with optional filters)\nhistory = client.get_order_history(limit=20, order_status=2)\n\n# Single order detail\ndetail = client.get_order_detail(\"ORDER_ID\")\n\n# Cancel one order\nclient.cancel_order(\"ORDER_ID\")\n\n# Cancel ALL orders (use with care)\nclient.cancel_all_orders()\n```\n\n---\n\n## Workflow: Heartbeat / Briefing\n\nCall periodically (every 30s–15min depending on strategy frequency).\n\n```python\n# wallet can be Polygon or Solana based on venue flow\nbriefing = client.get_briefing(user=wallet)\n\n# 1. Handle risk alerts first\nfor alert in briefing.get(\"riskAlerts\", []):\n    print(f\"⚠️  {alert}\")\n\n# 2. Review open orders\nopen_orders = client.get_open_orders()\nprint(f\"Open orders: {len(open_orders)}\")\n\n# 3. Scan opportunity markets\nfor opp in briefing.get(\"opportunityMarkets\", [])[:5]:\n    print(f\"Opportunity: {opp.get('id')} — {opp.get('question')}\")\n```\n\n---\n\n## Workflow: Redemption\n\nWhen a market settles, redeem winning positions:\n\n```python\nclient.redeem(market_id=\"MARKET_ID\", side=\"YES\")\n```\n\n---\n\n## Error Handling\n\n```python\nfrom aion_sdk import AionMarketClient, ApiError\n\nclient = AionMarketClient()\n\ntry:\n    result = client.get_me()\nexcept ApiError as e:\n    if e.status_code == 401:\n        print(\"❌ Invalid or missing API key\")\n    elif e.status_code == 403:\n        print(\"❌ Agent not authorized — check claim status or wallet credentials\")\n    elif e.status_code == 429:\n        print(\"⏳ Rate limited — back off and retry\")\n    else:\n        print(f\"API Error {e.code}: {e.message}\")\n```\n\nWhen trading, an `ApiError` from AION Market may still hide a successful downstream venue execution. If the response is ambiguous, query venue-specific follow-up endpoints before concluding failure (Polymarket orders/trades, or Kalshi submit/positions state).\n\n---\n\n## SDK Method Reference\n\n### Agent Management\n\n| Method                                | Description                                       |\n| ------------------------------------- | ------------------------------------------------- |\n| `register_agent(name)`                | Create agent, returns API key + claim code        |\n| `claim_preview(claim_code)`           | Preview agent info via claim code                 |\n| `get_me()`                            | Current agent profile and balances                |\n| `get_settings()`                      | Read risk control settings                        |\n| `update_settings(...)`                | Update max trades, max amount, pause, auto-redeem |\n| `get_skills(category, limit, offset)` | List available strategy skills                    |\n\n### Market Operations\n\n| Method                                                       | Description                                         |\n| ------------------------------------------------------------ | --------------------------------------------------- |\n| `get_markets(q, limit, page, venue, events_status)`          | Search markets by keyword                           |\n| `get_market(market_id, venue)`                               | Single market details                               |\n| `check_market_exists(market_id, venue)`                      | Existence check                                     |\n| `get_prices_history(token_id, ...)`                          | Historical prices for a token                       |\n| `get_briefing(venue, since, user, include_markets)`          | Heartbeat: alerts + opportunities                   |\n| `get_market_context(market_id, venue, user, my_probability)` | Pre-trade context & risk                            |\n| `get_current_positions(user, venue, ...)`                    | Unified current positions (`polymarket` / `kalshi`) |\n\n### Wallet Management\n\n| Method                                                                             | Description                      |\n| ---------------------------------------------------------------------------------- | -------------------------------- |\n| `check_wallet_credentials(wallet_address)`                                         | Check if CLOB credentials exist  |\n| `register_wallet_credentials(wallet_address, api_key, api_secret, api_passphrase)` | Store encrypted CLOB credentials |\n\n### Trading Operations\n\n| Method                                               | Description                           |\n| ---------------------------------------------------- | ------------------------------------- |\n| `trade(payload)`                                     | Place a Polymarket market/limit order |\n| `get_open_orders(venue, market_condition_id, limit)` | List unfilled orders                  |\n| `get_order_history(venue, ..., limit, offset)`       | Historical orders with filters        |\n| `get_order_detail(order_id, venue, wallet_address)`  | Single order detail                   |\n| `cancel_order(order_id, venue, wallet_address)`      | Cancel one order                      |\n| `cancel_all_orders(venue, wallet_address)`           | Cancel all open orders                |\n| `redeem(market_id, side, venue, wallet_address)`     | Redeem settled position               |\n| `kalshi_quote(...)`                                  | Build unsigned Kalshi quote tx        |\n| `kalshi_submit(...)`                                 | Submit locally signed Kalshi tx       |\n\n### Fee Charging Operations\n\n| Method                                 | Description                                          |\n| -------------------------------------- | ---------------------------------------------------- |\n| `charge_polymarket_fee(order_hash_id)` | Charge 1% fee for Polymarket order (pUSD on Polygon) |\n| `charge_kalshi_fee(kalshi_order_id)`   | Charge 1% fee for Kalshi order (USDC on Solana)      |\n\n---\n\n## Checklist: Ready to Trade\n\n- [ ] `pip install aion-sdk py-clob-client python-dotenv` installed\n- [ ] `.env` file created with `AIONMARKET_API_KEY` and `WALLET_PRIVATE_KEY` (plus `SOLANA_PRIVATE_KEY` if using Kalshi)\n- [ ] `.env` added to `.gitignore`\n- [ ] `get_me()` returns valid agent info\n- [ ] Polymarket CLOB credentials derived from private key and registered via `register_wallet_credentials()`\n- [ ] automatic balance, gas/fees, and allowance checks are part of the trading flow\n- [ ] missing allowance is auto-approved when technically possible\n- [ ] Risk limits configured via `update_settings()`\n- [ ] Heartbeat loop (`get_briefing()`) running or planned\n- [ ] Error handling wraps every SDK call with `ApiError`\n- [ ] For Kalshi: quote -> sign -> submit flow validated with `kalshi_quote()` / `kalshi_submit()`\n- [ ] ambiguous trade responses are verified against venue-specific state endpoints\n- [ ] **Fee allowance configured** — Polymarket Safe AllowanceModule delegate set; Kalshi USDC approval granted\n- [ ] **Post-trade fee charging integrated** — `charge_polymarket_fee()` or `charge_kalshi_fee()` called after every successful trade\n\n> Once all boxes are checked, the agent is ready for strategy skills to drive\n> market discovery and automated trade execution.\n\nFile v1.0.7:_meta.json\n\n{\n  \"ownerId\": \"kn75fv5d7z6aj8q78vn72zsbnn84rb61\",\n  \"slug\": \"aionmarket-trading\",\n  \"version\": \"1.0.7\",\n  \"publishedAt\": 1778509823851\n}\n\nFile v1.0.7:skill-card.md\n\n## Description:\n\nCore trading skill for AION Market prediction market agents, covering setup, wallet binding, market search, pre-trade checks, risk-aware trading, order management, position monitoring, and settlement workflows on Polymarket and Kalshi via aion-sdk.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[ssj124](https://clawhub.ai/user/ssj124)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nExternal developers and agent operators use this skill to configure AION Market trading agents, connect wallets, inspect prediction markets, submit or cancel Polymarket and Kalshi orders, monitor positions, redeem settlements, and manage post-trade fee workflows.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Real-money prediction-market automation can approve spend, place trades, charge fees, or transfer funds with too much default authority.\n\nMitigation: Use a limited wallet, set strict allowance and trade caps, pause trading until limits are configured, and require explicit confirmation for every approval, trade, and fee transfer.\n\nRisk: Wallet private keys, API keys, derived CLOB credentials, and Solana keys can expose user funds if logged, committed, or reused broadly.\n\nMitigation: Keep secrets in environment variables or an uncommitted .env file, avoid printing credentials, use pinned dependencies, and prefer a separate signer or hardware wallet for live trading.\n\nRisk: Ambiguous SDK or venue responses can cause the agent to misreport whether an order, cancellation, settlement, or fee transfer succeeded.\n\nMitigation: Verify ambiguous outcomes through venue-specific order, trade, position, or transaction state before retrying or reporting final status.\n\n## Reference(s):\n\n- [AION Market documentation](https://docs.aionmarket.com/)\n- [AION Market homepage](https://www.aionmarket.com/)\n- [ClawHub skill page](https://clawhub.ai/ssj124/skills/aionmarket-trading)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown guidance with Python and shell code blocks]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [Guides authenticated SDK calls and wallet-dependent trading workflows; it does not itself produce market predictions or strategy signals.]\n\n## Skill Version(s):\n\n1.0.7 (source: server release metadata; artifact metadata.version is 0.3.0)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nArchive v1.0.6: 2 files, 10763 bytes\n\nFiles: skill.md (30404b), _meta.json (137b)\n\nFile v1.0.6:skill.md\n\n---\nname: aionmarket-trading\ndescription: |\n  Core trading skill for AION Market prediction market agents.\n  Provides agent setup, wallet binding, market search, automated pre-trade\n  checks, risk-aware trading, order management, position monitoring, and\n  settlement workflows on Polymarket and Kalshi via the aion-sdk Python package.\n\n  Use when: an AI agent needs to register, configure wallets, search markets,\n  place or cancel trades, monitor positions, or run settlement-related flows on AION Market / Polymarket / Kalshi.\nmetadata:\n  author: \"AION Market\"\n  version: \"0.3.0\"\n  homepage: \"https://www.aionmarket.com/\"\n  docs: \"https://docs.aionmarket.com/\"\n  sdk: \"aion-sdk (PyPI)\"\n---\n\n# Skill: aionmarket-trading\n\nCore trading operations for AI agents on AION Market / Polymarket / Kalshi.\nThis skill covers the **foundational** capabilities — agent lifecycle, wallet setup,\nmarket data, order execution, and position management.\n\n> **Strategy skills** (market discovery, signal generation, automated loops) are\n> separate skills that build on top of this one.\n\n---\n\n## Scope\n\n- **Applies to:** Any AI agent that needs to trade prediction markets through AION Market\n- **Does NOT cover:** Strategy logic, autonomous market scanning loops, or signal generation (see dedicated strategy skills)\n\n---\n\n## Prerequisites — USER MUST PROVIDE\n\nBefore this skill can operate, the user **must** supply:\n\n| Secret                 | Where to set                           | Example                               |\n| ---------------------- | -------------------------------------- | ------------------------------------- |\n| **Agent API Key**      | `AIONMARKET_API_KEY` env var or `.env` | `sk_live_Ab12Cd34...`                 |\n| **Wallet Private Key** | `WALLET_PRIVATE_KEY` env var or `.env` | `0xabc123...` (64 hex chars, Polygon) |\n| **Solana Private Key** | `SOLANA_PRIVATE_KEY` env var or `.env` | `<base58-key>` (Kalshi optional)      |\n\nThe skill will:\n\n1. Derive wallet addresses from provided keys (Polygon and/or Solana)\n2. For Polymarket, call CLOB auth to derive **API Key / Secret / Passphrase** from private key signature\n3. Register Polymarket CLOB credentials with AION Market via `register_wallet_credentials()` when needed\n4. For Kalshi, use quote -> local sign -> submit flow via DFlow-backed endpoints\n5. Automatically check wallet readiness before trading: balance, gas/fees, allowance (Polymarket), and market context\n\n> **If the private key is missing, STOP and ask the user to provide it.**\n> Never guess, fabricate, or skip credential setup.\n> Store secrets in a local `.env` file (never commit to git) or export as env vars.\n\n---\n\n## Assumptions\n\n- Python 3.9+\n- `aion-sdk >= 0.1.2` installed (`pip install aion-sdk`)\n- `py-clob-client` for Polymarket order signing and credential derivation\n- Agent has been registered or will be registered as part of the flow\n- Polymarket CLOB credentials are derived automatically from private key via `py-clob-client`\n- Kalshi trading uses quote -> sign -> submit; position queries use the unified `get_current_positions(..., venue=\"kalshi\")` endpoint\n- All SDK methods return plain dicts/lists; errors raise `ApiError`\n- **`get_markets()` returns events with nested `markets[]` sub-markets** — trading fields like `conditionId`, `clobTokenIds`, `outcomePrices` live on the sub-market, not the event\n\n---\n\n## Principles\n\n1. **Always check context before trading** — call `get_market_context()` before every order\n2. **Never trade without a thesis** — every trade needs explicit reasoning\n3. **Respect risk limits** — honour `riskLimit`, `maxTradesPerDay`, `maxTradeAmount`\n4. **Fail loudly** — catch `ApiError` and surface the message; never swallow errors\n5. **Self-custody** — wallet keys belong to the user; SDK only stores encrypted CLOB credentials\n6. **Automate mechanical steps** — do not ask the user to manually confirm balance checks, gas checks, allowance checks, or approval after the private key is available\n7. **Verify execution independently** — if the wrapper response is weak, validate through the corresponding venue (Polymarket or Kalshi) before reporting failure\n\n---\n\n## Automation Defaults\n\nUnless the user explicitly overrides them, the agent should use these defaults:\n\n- default trade mode: `market`\n- default buy size: `2` USDC\n- default behavior: auto-select a valid market candidate from the requested strategy scope\n- default pre-trade workflow: derive wallet, register wallet credentials, check balance, check gas, check allowance, auto-approve if needed, then trade\n- default post-trade workflow: query recent venue-specific trades/orders (Polymarket orders or Kalshi positions/orders) if the SDK result is generic, null, or ambiguous\n\nThe agent should ask the user only for information it cannot safely infer or execute itself.\n\n---\n\n## Constraints\n\n### MUST\n\n- Set `AIONMARKET_API_KEY` before any authenticated call\n- Register Polymarket CLOB credentials before live Polymarket trading\n- Check wallet balance, gas/fees, and relevant allowance before submitting any order\n- Call `get_market_context()` before placing any trade\n- Handle `ApiError` on every SDK call\n- Save the API key returned by `register_agent()` immediately — it is shown only once\n- For Polymarket, send a full signed order object and `walletAddress` with every trade\n- For Kalshi, follow quote -> local sign -> submit and include `userPublicKey` when executing BUY flows\n- Verify downstream execution via the target venue when SDK responses are incomplete- **Charge platform trading fee after every successful order** — call `charge_polymarket_fee()` or `charge_kalshi_fee()` after trade confirmation\n- **Ensure fee allowance is pre-approved** before trading — Polymarket requires Safe AllowanceModule delegate; Kalshi requires USDC token approval on Solana\n\n### SHOULD\n\n- Use environment variables for all secrets (never hardcode)\n- Call `get_briefing()` periodically (heartbeat pattern) for risk alerts and opportunities\n- Set conservative risk limits first via `update_settings()`, then scale up\n- Cancel stale open orders promptly\n- Rotate API keys every 90 days\n- Prefer market orders for simple one-shot execution unless the user explicitly requests a limit order\n- Auto-approve required spenders when allowance is missing and gas is sufficient\n\n### AVOID\n\n- Trading without checking `warnings` from market context\n- Exceeding the agent's configured `maxTradeAmount`\n- Sharing or logging API keys, CLOB secrets, or private keys\n- Calling `cancel_all_orders()` without confirming with the user first\n- Making trades in markets the agent has not researched\n- Treating a wrapper `INTERNAL_ERROR` as final without checking whether the downstream venue actually accepted or matched the order\n\n---\n\n## Installation\n\n```bash\npip install aion-sdk py-clob-client python-dotenv\n```\n\n- `py-clob-client` — Polymarket official SDK, derives CLOB API credentials from private key\n- `python-dotenv` — loads `.env` file automatically\n\n---\n\n## Environment Setup\n\nCreate a `.env` file in your project root (add `.env` to `.gitignore`):\n\n```bash\n# .env\nAIONMARKET_API_KEY=sk_live_...\nWALLET_PRIVATE_KEY=0xabc123...your_64_hex_char_private_key\n\n# Optional — only set this when AION Market docs tell you to use\n# a non-production environment URL for your target environment.\n# Do not hardcode a staging URL copied from an old example.\n# AIONMARKET_BASE_URL=https://<documented-aionmarket-base-url>/bvapi\n```\n\nOr export directly:\n\n```bash\nexport AIONMARKET_API_KEY=\"sk_live_...\"\nexport WALLET_PRIVATE_KEY=\"0xabc123...\"\n```\n\n### Derive Wallet Address and CLOB Credentials from Private Key\n\n```python\nimport os\nfrom dotenv import load_dotenv\nfrom py_clob_client.client import ClobClient\n\nload_dotenv()  # loads .env file\n\nprivate_key = os.environ[\"WALLET_PRIVATE_KEY\"]\n\n# Use Polymarket CLOB client to derive credentials from private key\npolymarket = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,\n    chain_id=137,\n)\ncreds = polymarket.create_or_derive_api_creds()\n# creds contains: api_key, api_secret, api_passphrase\n\nwallet_address = polymarket.get_address()\nprint(f\"Wallet address: {wallet_address}\")\nprint(f\"CLOB credentials derived successfully\")\n```\n\n**Base URL resolution priority:**\n\n1. Explicit `base_url` argument in code\n2. `AIONMARKET_BASE_URL` environment variable\n3. Production default: `https://www.aionmarket.com//bvapi`\n\nUse the SDK's documented resolution order above. Do **not** hardcode a sandbox or staging URL in sample code unless that exact environment URL is the current one documented by AION Market.\n\n---\n\n## Workflow: Agent Bootstrap\n\nRun once to create an agent and bind a wallet.\n\n### Step 1 — Register Agent\n\n```python\nfrom aion_sdk import AionMarketClient\n\nclient = AionMarketClient()  # no key needed for registration\nregistration = client.register_agent(\"my-trading-bot\")\n\napi_key = registration[\"apiKeyCode\"]\nclaim_code = registration[\"claimCode\"]\nprint(f\"API Key (save now!): {api_key}\")\nprint(f\"Claim URL: {registration['claimUrl']}\")\n```\n\n> Save `apiKeyCode` immediately — it is only returned once.\n> After the API key is generated, open or click `claimUrl` and complete the claim/auth flow. Generating the key alone does **not** finish agent authentication.\n\nThe `claimUrl` returned by `register_agent()` is environment-aware and points\ndirectly to the frontend claim page (staging or production). Open it in a\nbrowser to claim and authenticate the agent.\n\nThe URL format is:\n\n```\nhttps://<FRONTEND_DOMAIN>/agents/claim?code=<CLAIM_CODE>\n```\n\nOr use `claim_preview(claim_code)` to verify the agent name before claiming.\n\n### Step 2 — Verify Agent\n\n```python\nclient = AionMarketClient(api_key=api_key)\nme = client.get_me()\nprint(f\"Agent: {me['name']}, Status: {me['status']}\")\n```\n\n### Step 3 — Derive Polymarket CLOB Credentials & Register Wallet\n\nThe private key is used to call Polymarket's auth endpoint and derive CLOB credentials automatically.\nThe user does **not** need to manually copy API Key / Secret / Passphrase from Polymarket settings.\n\n```python\nimport os\nfrom dotenv import load_dotenv\nfrom py_clob_client.client import ClobClient\n\nload_dotenv()\n\nprivate_key = os.environ[\"WALLET_PRIVATE_KEY\"]\n\n# 1. Derive CLOB credentials from private key via Polymarket\npolymarket = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,\n    chain_id=137,\n)\ncreds = polymarket.create_or_derive_api_creds()\nwallet = polymarket.get_address()\n\nprint(f\"Wallet: {wallet}\")\nprint(f\"CLOB API Key: {creds.api_key}\")\n\n# 2. Register with AION Market\ncheck = client.check_wallet_credentials(wallet)\nif not check[\"hasCredentials\"]:\n    client.register_wallet_credentials(\n        wallet_address=wallet,\n        api_key=creds.api_key,\n        api_secret=creds.api_secret,\n        api_passphrase=creds.api_passphrase,\n    )\n    print(f\"Wallet credentials registered for {wallet}\")\nelse:\n    print(f\"Wallet {wallet} already configured.\")\n```\n\n### Step 4 — Configure Risk Limits\n\n```python\nclient.update_settings(\n    max_trades_per_day=50,\n    max_trade_amount=100.0,\n    trading_paused=False,\n    auto_redeem_enabled=True,\n)\nsettings = client.get_settings()\nprint(settings)\n```\n\n### Step 5 — Kalshi Prerequisites (Optional, for Kalshi venue)\n\n- Ensure Solana wallet is available (`SOLANA_PRIVATE_KEY` / `userPublicKey`)\n- Use `kalshi_quote()` to request unsigned tx, locally sign, then call `kalshi_submit()`\n- For BUY flows, provide `userPublicKey` so KYC/geo checks can be evaluated upstream\n\n---\n\n## Workflow: Market Search & Context\n\n### Understanding Market Data Structure\n\n> **Critical:** `get_markets()` returns **events**, each containing a nested `markets[]`\n> array of **sub-markets**. Trading fields like `conditionId`, `clobTokenIds`,\n> `outcomePrices`, `negRisk`, and `orderPriceMinTickSize` live on the **sub-market**, NOT the event.\n\n```python\nimport ast\n\n# Search returns events\nevents = client.get_markets(q=\"bitcoin\", limit=10)\n\nfor event in events:\n    print(f\"Event: {event['title']}\")\n    for sub in event.get(\"markets\", []):\n        # Parse JSON strings\n        prices = ast.literal_eval(sub.get(\"outcomePrices\", '[\"0.5\",\"0.5\"]'))\n        token_ids = ast.literal_eval(sub.get(\"clobTokenIds\", '[]'))\n        print(f\"  Sub-market: {sub['question']}\")\n        print(f\"    conditionId: {sub['conditionId']}\")\n        print(f\"    YES price: {prices[0]}, NO price: {prices[1]}\")\n        print(f\"    YES token: {token_ids[0] if token_ids else 'N/A'}\")\n        print(f\"    negRisk: {sub.get('negRisk', False)}\")\n        print(f\"    tickSize: {sub.get('orderPriceMinTickSize', 0.01)}\")\n        print(f\"    minSize: {sub.get('orderMinSize', 5)}\")\n```\n\n### Get Market Context (REQUIRED before trading)\n\n```python\ncontext = client.get_market_context(\"CONDITION_ID\", user=wallet)\n\nprint(f\"Name:       {context.get('name')}\")\nprint(f\"Position:   {context.get('myPosition')}\")\nprint(f\"Risk limit: {context.get('riskLimit')}\")\nprint(f\"Warnings:   {context.get('warnings')}\")\n\nif context.get(\"warnings\"):\n    print(\"⚠️  Review warnings before proceeding!\")\n```\n\n### Automatic Pre-Trade Readiness Checks\n\nBefore signing or submitting any order, the agent should automatically verify:\n\n- wallet credentials are already registered, otherwise register them\n- collateral balance is sufficient for the intended spend\n- Polygon gas balance is sufficient if an onchain approval may be needed\n- the required spender allowance already exists for the intended order\n\nIf allowance is insufficient and gas is available, the agent should send the approval transaction automatically instead of asking the user to do it manually.\n\n---\n\n## Workflow: Trade Execution\n\n### Building a Signed Order (REQUIRED)\n\nThe `trade()` endpoint requires a **complete EIP712-signed order** from `py-clob-client`.\nPassing `\"order\": {}` will cause a credential lookup failure — the server reads\n`order.signatureType` to find your wallet credentials.\n\n```python\nimport ast\nfrom py_clob_client.client import ClobClient\nfrom py_clob_client.clob_types import ApiCreds, CreateOrderOptions, OrderArgs\n\n# 1. Initialize CLOB client with creds (derived earlier in bootstrap)\nclob = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,     # WALLET_PRIVATE_KEY\n    chain_id=137,\n    creds=ApiCreds(\n        api_key=creds.api_key,\n        api_secret=creds.api_secret,\n        api_passphrase=creds.api_passphrase,\n    ),\n)\n\n# 2. Extract trading params from sub-market (NOT event)\nsub_market = event[\"markets\"][0]  # pick the sub-market you want to trade\ncondition_id = sub_market[\"conditionId\"]\ntoken_ids = ast.literal_eval(sub_market[\"clobTokenIds\"])\nyes_token_id = token_ids[0]   # index 0 = YES, index 1 = NO\nno_token_id = token_ids[1]\nneg_risk = sub_market.get(\"negRisk\", False)\ntick_size = str(sub_market.get(\"orderPriceMinTickSize\", \"0.01\"))\nmin_size = sub_market.get(\"orderMinSize\", 5)\n\n# 3. Build signed order — MUST use CreateOrderOptions for proper signing\nsigned_order = clob.create_order(\n    OrderArgs(\n        token_id=yes_token_id,   # or no_token_id for NO side\n        price=0.55,\n        size=min_size,           # must >= orderMinSize\n        side=\"BUY\",\n    ),\n    options=CreateOrderOptions(\n        tick_size=tick_size,     # from sub-market.orderPriceMinTickSize\n        neg_risk=neg_risk,       # CRITICAL for neg-risk markets!\n    ),\n)\n\n# 4. Convert dataclass to dict for JSON serialization\norder_dict = signed_order.dict()\n```\n\n### Place a Trade\n\n```python\nresult = client.trade({\n    \"marketConditionId\": condition_id,          # hex conditionId from sub-market\n    \"marketQuestion\": sub_market[\"question\"],   # question text\n    \"outcome\": \"YES\",                           # YES or NO\n    \"orderSize\": min_size,                      # number of contracts\n    \"price\": 0.55,                              # price per contract (0-1)\n    \"isLimitOrder\": True,                       # True=limit, False=market\n    \"order\": order_dict,                        # ← FULL signed order (never {})\n    \"walletAddress\": wallet,                    # ← REQUIRED\n    \"reasoning\": \"Strategy edge explanation\",\n})\nprint(f\"Order ID: {result.get('orderId')}\")\nprint(f\"Status:   {result.get('status')}\")\n```\n\n### Default Execution Policy\n\nFor general-purpose execution, use this default policy unless the user overrides it:\n\n1. prefer `market` mode\n2. use `2` USDC as default buy size\n3. derive a marketable cap from current prices or order book when using market-order helpers\n4. ask for a price only when the user explicitly requested a limit order and did not provide one\n5. report the market snapshot and final order parameters without blocking on extra confirmation\n\n> **Common pitfalls:**\n>\n> - `\"order\": {}` → server cannot find `signatureType`, returns credential error\n> - Using event numeric ID as `marketConditionId` → use sub-market hex `conditionId`\n> - Missing `walletAddress` → \"walletAddress 不能为空\" error\n> - Not setting `neg_risk=True` for neg-risk markets → invalid signature, Polymarket rejects\n> - `orderSize` below `orderMinSize` → order rejected\n> - Insufficient USDC balance → server returns generic `INTERNAL_ERROR`\n> - Insufficient allowance → downstream exchange cannot spend collateral\n> - SDK result is empty or generic → verify recent trades and orders before reporting failure\n\n**Order types:** `GTC` (default), `FOK`, `GTD`, `FAK`\n**Sides:** `BUY`, `SELL`\n**Outcomes:** `YES`, `NO`\n\n---\n\n## Workflow: Kalshi Quote -> Sign -> Submit\n\nUse this flow for Kalshi venue execution.\n\n```python\nquote = client.kalshi_quote(\n    market_ticker=\"KX...\",\n    side=\"YES\",\n    action=\"BUY\",\n    amount=10,\n    user_public_key=\"<solana-wallet>\",\n)\n\n# Sign quote[\"unsignedTransaction\"] locally (wallet implementation specific)\nsigned_tx = \"<base64-signed-tx>\"\n\nsubmit = client.kalshi_submit(\n    market_ticker=\"KX...\",\n    side=\"YES\",\n    action=\"BUY\",\n    amount=10,\n    quote_id=quote[\"quoteId\"],\n    signed_transaction=signed_tx,\n    user_public_key=\"<solana-wallet>\",\n    in_amount=quote.get(\"inAmount\"),\n    out_amount=quote.get(\"outAmount\"),\n    min_out_amount=quote.get(\"minOutAmount\"),\n)\nprint(submit)\n\n# Unified positions endpoint for Kalshi (venue = kalshi)\nkalshi_positions = client.get_current_positions(\n    user=\"<solana-wallet>\",\n    venue=\"kalshi\",\n)\nprint(kalshi_positions)\n```\n\nKalshi currently does not expose a dedicated cancel API in this SDK. Use a SELL flow (`kalshi_quote` -> sign -> `kalshi_submit`) to reduce/exit exposure.\n\n---\n\n## Workflow: Platform Fee Charging\n\nAION Market charges a **1% platform trading fee** on every executed order. This fee is mandatory and must be collected after each successful trade. The agent should handle this automatically as part of the post-trade workflow.\n\n### Fee Structure\n\n| Venue      | Fee Rate                           | Token      | Chain   | Collection Method                          |\n| ---------- | ---------------------------------- | ---------- | ------- | ------------------------------------------ |\n| Polymarket | 1% of notional (orderSize × price) | pUSD       | Polygon | Safe AllowanceModule (auto-cron or manual) |\n| Kalshi     | 1% of order amount                 | USDC (SPL) | Solana  | Fireblocks transfer (manual trigger)       |\n\n### Fee Calculation\n\n```\nPolymarket: fee = orderSize × price × 0.01\nKalshi:     fee = orderAmount × 0.01\n```\n\nExample: An order of 100 contracts at $0.55 → notional = $55 → fee = $0.55 pUSD\n\n### Platform Fee Receiving Addresses\n\n| Venue                | Platform Wallet                                |\n| -------------------- | ---------------------------------------------- |\n| Polymarket (Polygon) | `0xeA44cAF1f893729342dC5D8903F658E8D3e2379B`   |\n| Kalshi (Solana)      | `CHMkL5utJWFFHSkHX6pwWcb8VXj5jAz5fAqqMGAyEXcX` |\n\n### Prerequisites for Fee Collection\n\n**Polymarket (pUSD on Polygon):**\n\n1. User's Safe wallet must have **AllowanceModule** enabled\n2. Platform Fireblocks address must be added as **delegate** in the AllowanceModule\n3. Sufficient **pUSD token allowance** must be configured on the module\n4. The agent should verify allowance before trading and auto-approve if gas is available\n\n**Kalshi (USDC on Solana):**\n\n1. User's Solana wallet must hold sufficient **USDC** (native SPL token)\n2. User must grant **token approval** to the platform vault address\n3. The agent should use the local private key to sign approval if not already granted\n\n### Post-Trade Fee Charging Flow\n\n#### Polymarket — Automatic + Manual Fallback\n\nPolymarket fees are collected automatically by a server-side cron job (every 3 seconds).\nHowever, the agent should verify fee status and trigger manually if needed:\n\n```python\n# After a successful trade:\nresult = client.trade({...})\norder_hash_id = result.get(\"orderId\")\n\n# Option 1: Rely on automatic cron (default — fees are charged within 3 seconds)\n# Option 2: Explicitly trigger fee charging\nif order_hash_id:\n    fee_result = client.charge_polymarket_fee(order_hash_id)\n    print(f\"Fee: ${fee_result['feeAmount']}, Status: {fee_result['status']}\")\n    # status will be 'PENDING' — Fireblocks tx takes ~10-30s to confirm\n```\n\n#### Kalshi — Must Trigger Manually\n\nKalshi fees are NOT collected automatically. The agent MUST call `charge_kalshi_fee()`\nafter a successful `kalshi_submit()`:\n\n```python\n# After successful Kalshi submit:\nsubmit_result = client.kalshi_submit(\n    market_ticker=\"KX...\",\n    side=\"YES\",\n    action=\"BUY\",\n    amount=10,\n    signed_transaction=signed_tx,\n    quote_id=quote[\"quoteId\"],\n    user_public_key=sol_wallet,\n)\n\ntx_signature = submit_result.get(\"txSignature\")\n\n# REQUIRED: Charge the 1% platform fee\nif tx_signature:\n    fee_result = client.charge_kalshi_fee(tx_signature)\n    print(f\"Fee: ${fee_result['feeAmount']}, TxId: {fee_result['transactionId']}\")\n```\n\n### Checking Fee Status\n\n```python\n# Check Polymarket fee status\nstatus = client.get_fee_status(order_hash_id, venue=\"polymarket\")\nprint(f\"Status: {status['status']}, Amount: {status['feeAmount']}\")\n# status: 'pending' | 'charged' | 'failed' | 'unknown'\n\n# Check Kalshi fee status\nstatus = client.get_fee_status(tx_signature, venue=\"kalshi\")\nprint(f\"Status: {status['status']}\")\n```\n\n### Fee Charging Error Handling\n\n```python\nfrom aion_sdk import ApiError\n\ntry:\n    fee_result = client.charge_kalshi_fee(tx_signature)\nexcept ApiError as e:\n    if \"allowance\" in e.message.lower() or \"insufficient\" in e.message.lower():\n        print(\"❌ Insufficient allowance — user needs to approve more USDC\")\n    elif \"not found\" in e.message.lower():\n        print(\"❌ Order not found — verify order was submitted successfully\")\n    else:\n        print(f\"❌ Fee charging failed: {e.message}\")\n```\n\n### Agent Commission\n\nAgents that execute trades earn a **10% commission** on collected fees:\n\n- Platform collects 1% fee → agent receives 0.1% of trade notional\n- Commission is tracked automatically and available for periodic payout\n- No additional API calls are needed — commission is recorded when fee is charged\n\n---\n\n## Workflow: Order Management\n\n```python\n# List open orders\nopen_orders = client.get_open_orders()\n\n# Order history (with optional filters)\nhistory = client.get_order_history(limit=20, order_status=2)\n\n# Single order detail\ndetail = client.get_order_detail(\"ORDER_ID\")\n\n# Cancel one order\nclient.cancel_order(\"ORDER_ID\")\n\n# Cancel ALL orders (use with care)\nclient.cancel_all_orders()\n```\n\n---\n\n## Workflow: Heartbeat / Briefing\n\nCall periodically (every 30s–15min depending on strategy frequency).\n\n```python\n# wallet can be Polygon or Solana based on venue flow\nbriefing = client.get_briefing(user=wallet)\n\n# 1. Handle risk alerts first\nfor alert in briefing.get(\"riskAlerts\", []):\n    print(f\"⚠️  {alert}\")\n\n# 2. Review open orders\nopen_orders = client.get_open_orders()\nprint(f\"Open orders: {len(open_orders)}\")\n\n# 3. Scan opportunity markets\nfor opp in briefing.get(\"opportunityMarkets\", [])[:5]:\n    print(f\"Opportunity: {opp.get('id')} — {opp.get('question')}\")\n```\n\n---\n\n## Workflow: Redemption\n\nWhen a market settles, redeem winning positions:\n\n```python\nclient.redeem(market_id=\"MARKET_ID\", side=\"YES\")\n```\n\n---\n\n## Error Handling\n\n```python\nfrom aion_sdk import AionMarketClient, ApiError\n\nclient = AionMarketClient()\n\ntry:\n    result = client.get_me()\nexcept ApiError as e:\n    if e.status_code == 401:\n        print(\"❌ Invalid or missing API key\")\n    elif e.status_code == 403:\n        print(\"❌ Agent not authorized — check claim status or wallet credentials\")\n    elif e.status_code == 429:\n        print(\"⏳ Rate limited — back off and retry\")\n    else:\n        print(f\"API Error {e.code}: {e.message}\")\n```\n\nWhen trading, an `ApiError` from AION Market may still hide a successful downstream venue execution. If the response is ambiguous, query venue-specific follow-up endpoints before concluding failure (Polymarket orders/trades, or Kalshi submit/positions state).\n\n---\n\n## SDK Method Reference\n\n### Agent Management\n\n| Method                                | Description                                       |\n| ------------------------------------- | ------------------------------------------------- |\n| `register_agent(name)`                | Create agent, returns API key + claim code        |\n| `claim_preview(claim_code)`           | Preview agent info via claim code                 |\n| `get_me()`                            | Current agent profile and balances                |\n| `get_settings()`                      | Read risk control settings                        |\n| `update_settings(...)`                | Update max trades, max amount, pause, auto-redeem |\n| `get_skills(category, limit, offset)` | List available strategy skills                    |\n\n### Market Operations\n\n| Method                                                       | Description                                         |\n| ------------------------------------------------------------ | --------------------------------------------------- |\n| `get_markets(q, limit, page, venue, events_status)`          | Search markets by keyword                           |\n| `get_market(market_id, venue)`                               | Single market details                               |\n| `check_market_exists(market_id, venue)`                      | Existence check                                     |\n| `get_prices_history(token_id, ...)`                          | Historical prices for a token                       |\n| `get_briefing(venue, since, user, include_markets)`          | Heartbeat: alerts + opportunities                   |\n| `get_market_context(market_id, venue, user, my_probability)` | Pre-trade context & risk                            |\n| `get_current_positions(user, venue, ...)`                    | Unified current positions (`polymarket` / `kalshi`) |\n\n### Wallet Management\n\n| Method                                                                             | Description                      |\n| ---------------------------------------------------------------------------------- | -------------------------------- |\n| `check_wallet_credentials(wallet_address)`                                         | Check if CLOB credentials exist  |\n| `register_wallet_credentials(wallet_address, api_key, api_secret, api_passphrase)` | Store encrypted CLOB credentials |\n\n### Trading Operations\n\n| Method                                               | Description                           |\n| ---------------------------------------------------- | ------------------------------------- |\n| `trade(payload)`                                     | Place a Polymarket market/limit order |\n| `get_open_orders(venue, market_condition_id, limit)` | List unfilled orders                  |\n| `get_order_history(venue, ..., limit, offset)`       | Historical orders with filters        |\n| `get_order_detail(order_id, venue, wallet_address)`  | Single order detail                   |\n| `cancel_order(order_id, venue, wallet_address)`      | Cancel one order                      |\n| `cancel_all_orders(venue, wallet_address)`           | Cancel all open orders                |\n| `redeem(market_id, side, venue, wallet_address)`     | Redeem settled position               |\n| `kalshi_quote(...)`                                  | Build unsigned Kalshi quote tx        |\n| `kalshi_submit(...)`                                 | Submit locally signed Kalshi tx       |\n\n### Fee Charging Operations\n\n| Method                                 | Description                                          |\n| -------------------------------------- | ---------------------------------------------------- |\n| `charge_polymarket_fee(order_hash_id)` | Charge 1% fee for Polymarket order (pUSD on Polygon) |\n| `charge_kalshi_fee(kalshi_order_id)`   | Charge 1% fee for Kalshi order (USDC on Solana)      |\n| `get_fee_status(order_id, venue)`      | Query fee charging status for an order               |\n\n---\n\n## Checklist: Ready to Trade\n\n- [ ] `pip install aion-sdk py-clob-client python-dotenv` installed\n- [ ] `.env` file created with `AIONMARKET_API_KEY` and `WALLET_PRIVATE_KEY` (plus `SOLANA_PRIVATE_KEY` if using Kalshi)\n- [ ] `.env` added to `.gitignore`\n- [ ] `get_me()` returns valid agent info\n- [ ] Polymarket CLOB credentials derived from private key and registered via `register_wallet_credentials()`\n- [ ] automatic balance, gas/fees, and allowance checks are part of the trading flow\n- [ ] missing allowance is auto-approved when technically possible\n- [ ] Risk limits configured via `update_settings()`\n- [ ] Heartbeat loop (`get_briefing()`) running or planned\n- [ ] Error handling wraps every SDK call with `ApiError`\n- [ ] For Kalshi: quote -> sign -> submit flow validated with `kalshi_quote()` / `kalshi_submit()`\n- [ ] ambiguous trade responses are verified against venue-specific state endpoints\n- [ ] **Fee allowance configured** — Polymarket Safe AllowanceModule delegate set; Kalshi USDC approval granted\n- [ ] **Post-trade fee charging integrated** — `charge_polymarket_fee()` or `charge_kalshi_fee()` called after every successful trade\n- [ ] **Fee status monitoring** — `get_fee_status()` used to verify fee collection completed\n\n> Once all boxes are checked, the agent is ready for strategy skills to drive\n> market discovery and automated trade execution.\n\nFile v1.0.6:_meta.json\n\n{\n  \"ownerId\": \"kn75fv5d7z6aj8q78vn72zsbnn84rb61\",\n  \"slug\": \"aionmarket-trading\",\n  \"version\": \"1.0.6\",\n  \"publishedAt\": 1778121117142\n}\n\nArchive v1.0.5: 2 files, 9028 bytes\n\nFiles: skill.md (24724b), _meta.json (137b)\n\nFile v1.0.5:skill.md\n\n---\nname: aionmarket-trading\ndescription: |\n  Core trading skill for AION Market prediction market agents.\n  Provides agent setup, wallet binding, market search, automated pre-trade\n  checks, risk-aware trading, order management, position monitoring, and\n  settlement workflows on Polymarket and Kalshi via the aionmarket-sdk Python package.\n\n  Use when: an AI agent needs to register, configure wallets, search markets,\n  place or cancel trades, monitor positions, or run settlement-related flows on AION Market / Polymarket / Kalshi.\nmetadata:\n  author: \"AION Market\"\n  version: \"0.3.0\"\n  homepage: \"https://aionmarket.com\"\n  docs: \"https://docs.aionmarket.com\"\n  sdk: \"aionmarket-sdk (PyPI)\"\n---\n\n# Skill: aionmarket-trading\n\nCore trading operations for AI agents on AION Market / Polymarket / Kalshi.\nThis skill covers the **foundational** capabilities — agent lifecycle, wallet setup,\nmarket data, order execution, and position management.\n\n> **Strategy skills** (market discovery, signal generation, automated loops) are\n> separate skills that build on top of this one.\n\n---\n\n## Scope\n\n- **Applies to:** Any AI agent that needs to trade prediction markets through AION Market\n- **Does NOT cover:** Strategy logic, autonomous market scanning loops, or signal generation (see dedicated strategy skills)\n\n---\n\n## Prerequisites — USER MUST PROVIDE\n\nBefore this skill can operate, the user **must** supply:\n\n| Secret                 | Where to set                           | Example                               |\n| ---------------------- | -------------------------------------- | ------------------------------------- |\n| **Agent API Key**      | `AIONMARKET_API_KEY` env var or `.env` | `sk_live_Ab12Cd34...`                 |\n| **Wallet Private Key** | `WALLET_PRIVATE_KEY` env var or `.env` | `0xabc123...` (64 hex chars, Polygon) |\n| **Solana Private Key** | `SOLANA_PRIVATE_KEY` env var or `.env` | `<base58-key>` (Kalshi optional)      |\n\nThe skill will:\n\n1. Derive wallet addresses from provided keys (Polygon and/or Solana)\n2. For Polymarket, call CLOB auth to derive **API Key / Secret / Passphrase** from private key signature\n3. Register Polymarket CLOB credentials with AION Market via `register_wallet_credentials()` when needed\n4. For Kalshi, use quote -> local sign -> submit flow via DFlow-backed endpoints\n5. Automatically check wallet readiness before trading: balance, gas/fees, allowance (Polymarket), and market context\n\n> **If the private key is missing, STOP and ask the user to provide it.**\n> Never guess, fabricate, or skip credential setup.\n> Store secrets in a local `.env` file (never commit to git) or export as env vars.\n\n---\n\n## Assumptions\n\n- Python 3.9+\n- `aionmarket-sdk >= 0.1.2` installed (`pip install aionmarket-sdk`)\n- `py-clob-client` for Polymarket order signing and credential derivation\n- Agent has been registered or will be registered as part of the flow\n- Polymarket CLOB credentials are derived automatically from private key via `py-clob-client`\n- Kalshi trading uses quote -> sign -> submit; position queries use the unified `get_current_positions(..., venue=\"kalshi\")` endpoint\n- All SDK methods return plain dicts/lists; errors raise `ApiError`\n- **`get_markets()` returns events with nested `markets[]` sub-markets** — trading fields like `conditionId`, `clobTokenIds`, `outcomePrices` live on the sub-market, not the event\n\n---\n\n## Principles\n\n1. **Always check context before trading** — call `get_market_context()` before every order\n2. **Never trade without a thesis** — every trade needs explicit reasoning\n3. **Respect risk limits** — honour `riskLimit`, `maxTradesPerDay`, `maxTradeAmount`\n4. **Fail loudly** — catch `ApiError` and surface the message; never swallow errors\n5. **Self-custody** — wallet keys belong to the user; SDK only stores encrypted CLOB credentials\n6. **Automate mechanical steps** — do not ask the user to manually confirm balance checks, gas checks, allowance checks, or approval after the private key is available\n7. **Verify execution independently** — if the wrapper response is weak, validate through the corresponding venue (Polymarket or Kalshi) before reporting failure\n\n---\n\n## Automation Defaults\n\nUnless the user explicitly overrides them, the agent should use these defaults:\n\n- default trade mode: `market`\n- default buy size: `2` USDC\n- default behavior: auto-select a valid market candidate from the requested strategy scope\n- default pre-trade workflow: derive wallet, register wallet credentials, check balance, check gas, check allowance, auto-approve if needed, then trade\n- default post-trade workflow: query recent venue-specific trades/orders (Polymarket orders or Kalshi positions/orders) if the SDK result is generic, null, or ambiguous\n\nThe agent should ask the user only for information it cannot safely infer or execute itself.\n\n---\n\n## Constraints\n\n### MUST\n\n- Set `AIONMARKET_API_KEY` before any authenticated call\n- Register Polymarket CLOB credentials before live Polymarket trading\n- Check wallet balance, gas/fees, and relevant allowance before submitting any order\n- Call `get_market_context()` before placing any trade\n- Handle `ApiError` on every SDK call\n- Save the API key returned by `register_agent()` immediately — it is shown only once\n- For Polymarket, send a full signed order object and `walletAddress` with every trade\n- For Kalshi, follow quote -> local sign -> submit and include `userPublicKey` when executing BUY flows\n- Verify downstream execution via the target venue when SDK responses are incomplete\n\n### SHOULD\n\n- Use environment variables for all secrets (never hardcode)\n- Call `get_briefing()` periodically (heartbeat pattern) for risk alerts and opportunities\n- Set conservative risk limits first via `update_settings()`, then scale up\n- Cancel stale open orders promptly\n- Rotate API keys every 90 days\n- Prefer market orders for simple one-shot execution unless the user explicitly requests a limit order\n- Auto-approve required spenders when allowance is missing and gas is sufficient\n\n### AVOID\n\n- Trading without checking `warnings` from market context\n- Exceeding the agent's configured `maxTradeAmount`\n- Sharing or logging API keys, CLOB secrets, or private keys\n- Calling `cancel_all_orders()` without confirming with the user first\n- Making trades in markets the agent has not researched\n- Treating a wrapper `INTERNAL_ERROR` as final without checking whether the downstream venue actually accepted or matched the order\n\n---\n\n## Installation\n\n```bash\npip install aionmarket-sdk py-clob-client python-dotenv\n```\n\n- `py-clob-client` — Polymarket official SDK, derives CLOB API credentials from private key\n- `python-dotenv` — loads `.env` file automatically\n\n---\n\n## Environment Setup\n\nCreate a `.env` file in your project root (add `.env` to `.gitignore`):\n\n```bash\n# .env\nAIONMARKET_API_KEY=sk_live_...\nWALLET_PRIVATE_KEY=0xabc123...your_64_hex_char_private_key\n\n# Optional — only set this when AION Market docs tell you to use\n# a non-production environment URL for your target environment.\n# Do not hardcode a staging URL copied from an old example.\n# AIONMARKET_BASE_URL=https://<documented-aionmarket-base-url>/bvapi\n```\n\nOr export directly:\n\n```bash\nexport AIONMARKET_API_KEY=\"sk_live_...\"\nexport WALLET_PRIVATE_KEY=\"0xabc123...\"\n```\n\n### Derive Wallet Address and CLOB Credentials from Private Key\n\n```python\nimport os\nfrom dotenv import load_dotenv\nfrom py_clob_client.client import ClobClient\n\nload_dotenv()  # loads .env file\n\nprivate_key = os.environ[\"WALLET_PRIVATE_KEY\"]\n\n# Use Polymarket CLOB client to derive credentials from private key\npolymarket = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,\n    chain_id=137,\n)\ncreds = polymarket.create_or_derive_api_creds()\n# creds contains: api_key, api_secret, api_passphrase\n\nwallet_address = polymarket.get_address()\nprint(f\"Wallet address: {wallet_address}\")\nprint(f\"CLOB credentials derived successfully\")\n```\n\n**Base URL resolution priority:**\n\n1. Explicit `base_url` argument in code\n2. `AIONMARKET_BASE_URL` environment variable\n3. Production default: `https://api.aionmarket.com/bvapi`\n\n\nUse the SDK's documented resolution order above. Do **not** hardcode a sandbox or staging URL in sample code unless that exact environment URL is the current one documented by AION Market.\n\n---\n\n## Workflow: Agent Bootstrap\n\nRun once to create an agent and bind a wallet.\n\n### Step 1 — Register Agent\n\n```python\nfrom aionmarket_sdk import AionMarketClient\n\nclient = AionMarketClient()  # no key needed for registration\nregistration = client.register_agent(\"my-trading-bot\")\n\napi_key = registration[\"apiKeyCode\"]\nclaim_code = registration[\"claimCode\"]\nprint(f\"API Key (save now!): {api_key}\")\nprint(f\"Claim URL: {registration['claimUrl']}\")\n```\n\n> Save `apiKeyCode` immediately — it is only returned once.\n> After the API key is generated, open or click `claimUrl` and complete the claim/auth flow. Generating the key alone does **not** finish agent authentication.\n\nThe `claimUrl` returned by `register_agent()` is environment-aware and points\ndirectly to the frontend claim page (staging or production). Open it in a\nbrowser to claim and authenticate the agent.\n\nThe URL format is:\n\n```\nhttps://<FRONTEND_DOMAIN>/agents/claim?code=<CLAIM_CODE>\n```\n\nOr use `claim_preview(claim_code)` to verify the agent name before claiming.\n\n### Step 2 — Verify Agent\n\n```python\nclient = AionMarketClient(api_key=api_key)\nme = client.get_me()\nprint(f\"Agent: {me['name']}, Status: {me['status']}\")\n```\n\n### Step 3 — Derive Polymarket CLOB Credentials & Register Wallet\n\nThe private key is used to call Polymarket's auth endpoint and derive CLOB credentials automatically.\nThe user does **not** need to manually copy API Key / Secret / Passphrase from Polymarket settings.\n\n```python\nimport os\nfrom dotenv import load_dotenv\nfrom py_clob_client.client import ClobClient\n\nload_dotenv()\n\nprivate_key = os.environ[\"WALLET_PRIVATE_KEY\"]\n\n# 1. Derive CLOB credentials from private key via Polymarket\npolymarket = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,\n    chain_id=137,\n)\ncreds = polymarket.create_or_derive_api_creds()\nwallet = polymarket.get_address()\n\nprint(f\"Wallet: {wallet}\")\nprint(f\"CLOB API Key: {creds.api_key}\")\n\n# 2. Register with AION Market\ncheck = client.check_wallet_credentials(wallet)\nif not check[\"hasCredentials\"]:\n    client.register_wallet_credentials(\n        wallet_address=wallet,\n        api_key=creds.api_key,\n        api_secret=creds.api_secret,\n        api_passphrase=creds.api_passphrase,\n    )\n    print(f\"Wallet credentials registered for {wallet}\")\nelse:\n    print(f\"Wallet {wallet} already configured.\")\n```\n\n### Step 4 — Configure Risk Limits\n\n```python\nclient.update_settings(\n    max_trades_per_day=50,\n    max_trade_amount=100.0,\n    trading_paused=False,\n    auto_redeem_enabled=True,\n)\nsettings = client.get_settings()\nprint(settings)\n```\n\n### Step 5 — Kalshi Prerequisites (Optional, for Kalshi venue)\n\n- Ensure Solana wallet is available (`SOLANA_PRIVATE_KEY` / `userPublicKey`)\n- Use `kalshi_quote()` to request unsigned tx, locally sign, then call `kalshi_submit()`\n- For BUY flows, provide `userPublicKey` so KYC/geo checks can be evaluated upstream\n\n---\n\n## Workflow: Market Search & Context\n\n### Understanding Market Data Structure\n\n> **Critical:** `get_markets()` returns **events**, each containing a nested `markets[]`\n> array of **sub-markets**. Trading fields like `conditionId`, `clobTokenIds`,\n> `outcomePrices`, `negRisk`, and `orderPriceMinTickSize` live on the **sub-market**, NOT the event.\n\n```python\nimport ast\n\n# Search returns events\nevents = client.get_markets(q=\"bitcoin\", limit=10)\n\nfor event in events:\n    print(f\"Event: {event['title']}\")\n    for sub in event.get(\"markets\", []):\n        # Parse JSON strings\n        prices = ast.literal_eval(sub.get(\"outcomePrices\", '[\"0.5\",\"0.5\"]'))\n        token_ids = ast.literal_eval(sub.get(\"clobTokenIds\", '[]'))\n        print(f\"  Sub-market: {sub['question']}\")\n        print(f\"    conditionId: {sub['conditionId']}\")\n        print(f\"    YES price: {prices[0]}, NO price: {prices[1]}\")\n        print(f\"    YES token: {token_ids[0] if token_ids else 'N/A'}\")\n        print(f\"    negRisk: {sub.get('negRisk', False)}\")\n        print(f\"    tickSize: {sub.get('orderPriceMinTickSize', 0.01)}\")\n        print(f\"    minSize: {sub.get('orderMinSize', 5)}\")\n```\n\n### Get Market Context (REQUIRED before trading)\n\n```python\ncontext = client.get_market_context(\"CONDITION_ID\", user=wallet)\n\nprint(f\"Name:       {context.get('name')}\")\nprint(f\"Position:   {context.get('myPosition')}\")\nprint(f\"Risk limit: {context.get('riskLimit')}\")\nprint(f\"Warnings:   {context.get('warnings')}\")\n\nif context.get(\"warnings\"):\n    print(\"⚠️  Review warnings before proceeding!\")\n```\n\n### Automatic Pre-Trade Readiness Checks\n\nBefore signing or submitting any order, the agent should automatically verify:\n\n- wallet credentials are already registered, otherwise register them\n- collateral balance is sufficient for the intended spend\n- Polygon gas balance is sufficient if an onchain approval may be needed\n- the required spender allowance already exists for the intended order\n\nIf allowance is insufficient and gas is available, the agent should send the approval transaction automatically instead of asking the user to do it manually.\n\n---\n\n## Workflow: Trade Execution\n\n### Building a Signed Order (REQUIRED)\n\nThe `trade()` endpoint requires a **complete EIP712-signed order** from `py-clob-client`.\nPassing `\"order\": {}` will cause a credential lookup failure — the server reads\n`order.signatureType` to find your wallet credentials.\n\n```python\nimport ast\nfrom py_clob_client.client import ClobClient\nfrom py_clob_client.clob_types import ApiCreds, CreateOrderOptions, OrderArgs\n\n# 1. Initialize CLOB client with creds (derived earlier in bootstrap)\nclob = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,     # WALLET_PRIVATE_KEY\n    chain_id=137,\n    creds=ApiCreds(\n        api_key=creds.api_key,\n        api_secret=creds.api_secret,\n        api_passphrase=creds.api_passphrase,\n    ),\n)\n\n# 2. Extract trading params from sub-market (NOT event)\nsub_market = event[\"markets\"][0]  # pick the sub-market you want to trade\ncondition_id = sub_market[\"conditionId\"]\ntoken_ids = ast.literal_eval(sub_market[\"clobTokenIds\"])\nyes_token_id = token_ids[0]   # index 0 = YES, index 1 = NO\nno_token_id = token_ids[1]\nneg_risk = sub_market.get(\"negRisk\", False)\ntick_size = str(sub_market.get(\"orderPriceMinTickSize\", \"0.01\"))\nmin_size = sub_market.get(\"orderMinSize\", 5)\n\n# 3. Build signed order — MUST use CreateOrderOptions for proper signing\nsigned_order = clob.create_order(\n    OrderArgs(\n        token_id=yes_token_id,   # or no_token_id for NO side\n        price=0.55,\n        size=min_size,           # must >= orderMinSize\n        side=\"BUY\",\n    ),\n    options=CreateOrderOptions(\n        tick_size=tick_size,     # from sub-market.orderPriceMinTickSize\n        neg_risk=neg_risk,       # CRITICAL for neg-risk markets!\n    ),\n)\n\n# 4. Convert dataclass to dict for JSON serialization\norder_dict = signed_order.dict()\n```\n\n### Place a Trade\n\n```python\nresult = client.trade({\n    \"marketConditionId\": condition_id,          # hex conditionId from sub-market\n    \"marketQuestion\": sub_market[\"question\"],   # question text\n    \"outcome\": \"YES\",                           # YES or NO\n    \"orderSize\": min_size,                      # number of contracts\n    \"price\": 0.55,                              # price per contract (0-1)\n    \"isLimitOrder\": True,                       # True=limit, False=market\n    \"order\": order_dict,                        # ← FULL signed order (never {})\n    \"walletAddress\": wallet,                    # ← REQUIRED\n    \"reasoning\": \"Strategy edge explanation\",\n})\nprint(f\"Order ID: {result.get('orderId')}\")\nprint(f\"Status:   {result.get('status')}\")\n```\n\n### Default Execution Policy\n\nFor general-purpose execution, use this default policy unless the user overrides it:\n\n1. prefer `market` mode\n2. use `2` USDC as default buy size\n3. derive a marketable cap from current prices or order book when using market-order helpers\n4. ask for a price only when the user explicitly requested a limit order and did not provide one\n5. report the market snapshot and final order parameters without blocking on extra confirmation\n\n> **Common pitfalls:**\n>\n> - `\"order\": {}` → server cannot find `signatureType`, returns credential error\n> - Using event numeric ID as `marketConditionId` → use sub-market hex `conditionId`\n> - Missing `walletAddress` → \"walletAddress 不能为空\" error\n> - Not setting `neg_risk=True` for neg-risk markets → invalid signature, Polymarket rejects\n> - `orderSize` below `orderMinSize` → order rejected\n> - Insufficient USDC balance → server returns generic `INTERNAL_ERROR`\n> - Insufficient allowance → downstream exchange cannot spend collateral\n> - SDK result is empty or generic → verify recent trades and orders before reporting failure\n\n**Order types:** `GTC` (default), `FOK`, `GTD`, `FAK`\n**Sides:** `BUY`, `SELL`\n**Outcomes:** `YES`, `NO`\n\n---\n\n## Workflow: Kalshi Quote -> Sign -> Submit\n\nUse this flow for Kalshi venue execution.\n\n```python\nquote = client.kalshi_quote(\n    market_ticker=\"KX...\",\n    side=\"YES\",\n    action=\"BUY\",\n    amount=10,\n    user_public_key=\"<solana-wallet>\",\n)\n\n# Sign quote[\"unsignedTransaction\"] locally (wallet implementation specific)\nsigned_tx = \"<base64-signed-tx>\"\n\nsubmit = client.kalshi_submit(\n    market_ticker=\"KX...\",\n    side=\"YES\",\n    action=\"BUY\",\n    amount=10,\n    quote_id=quote[\"quoteId\"],\n    signed_transaction=signed_tx,\n    user_public_key=\"<solana-wallet>\",\n    in_amount=quote.get(\"inAmount\"),\n    out_amount=quote.get(\"outAmount\"),\n    min_out_amount=quote.get(\"minOutAmount\"),\n)\nprint(submit)\n\n# Unified positions endpoint for Kalshi (venue = kalshi)\nkalshi_positions = client.get_current_positions(\n    user=\"<solana-wallet>\",\n    venue=\"kalshi\",\n)\nprint(kalshi_positions)\n```\n\nKalshi currently does not expose a dedicated cancel API in this SDK. Use a SELL flow (`kalshi_quote` -> sign -> `kalshi_submit`) to reduce/exit exposure.\n\n## Workflow: Order Management\n\n```python\n# List open orders\nopen_orders = client.get_open_orders()\n\n# Order history (with optional filters)\nhistory = client.get_order_history(limit=20, order_status=2)\n\n# Single order detail\ndetail = client.get_order_detail(\"ORDER_ID\")\n\n# Cancel one order\nclient.cancel_order(\"ORDER_ID\")\n\n# Cancel ALL orders (use with care)\nclient.cancel_all_orders()\n```\n\n---\n\n## Workflow: Heartbeat / Briefing\n\nCall periodically (every 30s–15min depending on strategy frequency).\n\n```python\n# wallet can be Polygon or Solana based on venue flow\nbriefing = client.get_briefing(user=wallet)\n\n# 1. Handle risk alerts first\nfor alert in briefing.get(\"riskAlerts\", []):\n    print(f\"⚠️  {alert}\")\n\n# 2. Review open orders\nopen_orders = client.get_open_orders()\nprint(f\"Open orders: {len(open_orders)}\")\n\n# 3. Scan opportunity markets\nfor opp in briefing.get(\"opportunityMarkets\", [])[:5]:\n    print(f\"Opportunity: {opp.get('id')} — {opp.get('question')}\")\n```\n\n---\n\n## Workflow: Redemption\n\nWhen a market settles, redeem winning positions:\n\n```python\nclient.redeem(market_id=\"MARKET_ID\", side=\"YES\")\n```\n\n---\n\n## Error Handling\n\n```python\nfrom aionmarket_sdk import AionMarketClient, ApiError\n\nclient = AionMarketClient()\n\ntry:\n    result = client.get_me()\nexcept ApiError as e:\n    if e.status_code == 401:\n        print(\"❌ Invalid or missing API key\")\n    elif e.status_code == 403:\n        print(\"❌ Agent not authorized — check claim status or wallet credentials\")\n    elif e.status_code == 429:\n        print(\"⏳ Rate limited — back off and retry\")\n    else:\n        print(f\"API Error {e.code}: {e.message}\")\n```\n\nWhen trading, an `ApiError` from AION Market may still hide a successful downstream venue execution. If the response is ambiguous, query venue-specific follow-up endpoints before concluding failure (Polymarket orders/trades, or Kalshi submit/positions state).\n\n---\n\n## SDK Method Reference\n\n### Agent Management\n\n| Method                                | Description                                       |\n| ------------------------------------- | ------------------------------------------------- |\n| `register_agent(name)`                | Create agent, returns API key + claim code        |\n| `claim_preview(claim_code)`           | Preview agent info via claim code                 |\n| `get_me()`                            | Current agent profile and balances                |\n| `get_settings()`                      | Read risk control settings                        |\n| `update_settings(...)`                | Update max trades, max amount, pause, auto-redeem |\n| `get_skills(category, limit, offset)` | List available strategy skills                    |\n\n### Market Operations\n\n| Method                                                       | Description                                         |\n| ------------------------------------------------------------ | --------------------------------------------------- |\n| `get_markets(q, limit, page, venue, events_status)`          | Search markets by keyword                           |\n| `get_market(market_id, venue)`                               | Single market details                               |\n| `check_market_exists(market_id, venue)`                      | Existence check                                     |\n| `get_prices_history(token_id, ...)`                          | Historical prices for a token                       |\n| `get_briefing(venue, since, user, include_markets)`          | Heartbeat: alerts + opportunities                   |\n| `get_market_context(market_id, venue, user, my_probability)` | Pre-trade context & risk                            |\n| `get_current_positions(user, venue, ...)`                    | Unified current positions (`polymarket` / `kalshi`) |\n\n### Wallet Management\n\n| Method                                                                             | Description                      |\n| ---------------------------------------------------------------------------------- | -------------------------------- |\n| `check_wallet_credentials(wallet_address)`                                         | Check if CLOB credentials exist  |\n| `register_wallet_credentials(wallet_address, api_key, api_secret, api_passphrase)` | Store encrypted CLOB credentials |\n\n### Trading Operations\n\n| Method                                               | Description                           |\n| ---------------------------------------------------- | ------------------------------------- |\n| `trade(payload)`                                     | Place a Polymarket market/limit order |\n| `get_open_orders(venue, market_condition_id, limit)` | List unfilled orders                  |\n| `get_order_history(venue, ..., limit, offset)`       | Historical orders with filters        |\n| `get_order_detail(order_id, venue, wallet_address)`  | Single order detail                   |\n| `cancel_order(order_id, venue, wallet_address)`      | Cancel one order                      |\n| `cancel_all_orders(venue, wallet_address)`           | Cancel all open orders                |\n| `redeem(market_id, side, venue, wallet_address)`     | Redeem settled position               |\n| `kalshi_quote(...)`                                  | Build unsigned Kalshi quote tx        |\n| `kalshi_submit(...)`                                 | Submit locally signed Kalshi tx       |\n\n---\n\n## Checklist: Ready to Trade\n\n- [ ] `pip install aionmarket-sdk py-clob-client python-dotenv` installed\n- [ ] `.env` file created with `AIONMARKET_API_KEY` and `WALLET_PRIVATE_KEY` (plus `SOLANA_PRIVATE_KEY` if using Kalshi)\n- [ ] `.env` added to `.gitignore`\n- [ ] `get_me()` returns valid agent info\n- [ ] Polymarket CLOB credentials derived from private key and registered via `register_wallet_credentials()`\n- [ ] automatic balance, gas/fees, and allowance checks are part of the trading flow\n- [ ] missing allowance is auto-approved when technically possible\n- [ ] Risk limits configured via `update_settings()`\n- [ ] Heartbeat loop (`get_briefing()`) running or planned\n- [ ] Error handling wraps every SDK call with `ApiError`\n- [ ] For Kalshi: quote -> sign -> submit flow validated with `kalshi_quote()` / `kalshi_submit()`\n- [ ] ambiguous trade responses are verified against venue-specific state endpoints\n\n> Once all boxes are checked, the agent is ready for strategy skills to drive\n> market discovery and automated trade execution.\n\nFile v1.0.5:_meta.json\n\n{\n  \"ownerId\": \"kn75fv5d7z6aj8q78vn72zsbnn84rb61\",\n  \"slug\": \"aionmarket-trading\",\n  \"version\": \"1.0.5\",\n  \"publishedAt\": 1776946539235\n}\n\nArchive v1.0.4: 2 files, 9036 bytes\n\nFiles: skill.md (24737b), _meta.json (137b)\n\nFile v1.0.4:skill.md\n\n---\nname: aionmarket-trading\ndescription: |\n  Core trading skill for AION Market prediction market agents.\n  Provides agent setup, wallet binding, market search, automated pre-trade\n  checks, risk-aware trading, order management, position monitoring, and\n  settlement workflows on Polymarket and Kalshi via the aionmarket-sdk Python package.\n\n  Use when: an AI agent needs to register, configure wallets, search markets,\n  place or cancel trades, monitor positions, or run settlement-related flows on AION Market / Polymarket / Kalshi.\nmetadata:\n  author: \"AION Market\"\n  version: \"0.3.0\"\n  homepage: \"https://pm-t1.bxingupdate.com/\"\n  docs: \"https://docs-t.aionmarket.com/\"\n  sdk: \"aionmarket-sdk (PyPI)\"\n---\n\n# Skill: aionmarket-trading\n\nCore trading operations for AI agents on AION Market / Polymarket / Kalshi.\nThis skill covers the **foundational** capabilities — agent lifecycle, wallet setup,\nmarket data, order execution, and position management.\n\n> **Strategy skills** (market discovery, signal generation, automated loops) are\n> separate skills that build on top of this one.\n\n---\n\n## Scope\n\n- **Applies to:** Any AI agent that needs to trade prediction markets through AION Market\n- **Does NOT cover:** Strategy logic, autonomous market scanning loops, or signal generation (see dedicated strategy skills)\n\n---\n\n## Prerequisites — USER MUST PROVIDE\n\nBefore this skill can operate, the user **must** supply:\n\n| Secret                 | Where to set                           | Example                               |\n| ---------------------- | -------------------------------------- | ------------------------------------- |\n| **Agent API Key**      | `AIONMARKET_API_KEY` env var or `.env` | `sk_live_Ab12Cd34...`                 |\n| **Wallet Private Key** | `WALLET_PRIVATE_KEY` env var or `.env` | `0xabc123...` (64 hex chars, Polygon) |\n| **Solana Private Key** | `SOLANA_PRIVATE_KEY` env var or `.env` | `<base58-key>` (Kalshi optional)      |\n\nThe skill will:\n\n1. Derive wallet addresses from provided keys (Polygon and/or Solana)\n2. For Polymarket, call CLOB auth to derive **API Key / Secret / Passphrase** from private key signature\n3. Register Polymarket CLOB credentials with AION Market via `register_wallet_credentials()` when needed\n4. For Kalshi, use quote -> local sign -> submit flow via DFlow-backed endpoints\n5. Automatically check wallet readiness before trading: balance, gas/fees, allowance (Polymarket), and market context\n\n> **If the private key is missing, STOP and ask the user to provide it.**\n> Never guess, fabricate, or skip credential setup.\n> Store secrets in a local `.env` file (never commit to git) or export as env vars.\n\n---\n\n## Assumptions\n\n- Python 3.9+\n- `aionmarket-sdk >= 0.1.2` installed (`pip install aionmarket-sdk`)\n- `py-clob-client` for Polymarket order signing and credential derivation\n- Agent has been registered or will be registered as part of the flow\n- Polymarket CLOB credentials are derived automatically from private key via `py-clob-client`\n- Kalshi trading uses quote -> sign -> submit; position queries use the unified `get_current_positions(..., venue=\"kalshi\")` endpoint\n- All SDK methods return plain dicts/lists; errors raise `ApiError`\n- **`get_markets()` returns events with nested `markets[]` sub-markets** — trading fields like `conditionId`, `clobTokenIds`, `outcomePrices` live on the sub-market, not the event\n\n---\n\n## Principles\n\n1. **Always check context before trading** — call `get_market_context()` before every order\n2. **Never trade without a thesis** — every trade needs explicit reasoning\n3. **Respect risk limits** — honour `riskLimit`, `maxTradesPerDay`, `maxTradeAmount`\n4. **Fail loudly** — catch `ApiError` and surface the message; never swallow errors\n5. **Self-custody** — wallet keys belong to the user; SDK only stores encrypted CLOB credentials\n6. **Automate mechanical steps** — do not ask the user to manually confirm balance checks, gas checks, allowance checks, or approval after the private key is available\n7. **Verify execution independently** — if the wrapper response is weak, validate through the corresponding venue (Polymarket or Kalshi) before reporting failure\n\n---\n\n## Automation Defaults\n\nUnless the user explicitly overrides them, the agent should use these defaults:\n\n- default trade mode: `market`\n- default buy size: `2` USDC\n- default behavior: auto-select a valid market candidate from the requested strategy scope\n- default pre-trade workflow: derive wallet, register wallet credentials, check balance, check gas, check allowance, auto-approve if needed, then trade\n- default post-trade workflow: query recent venue-specific trades/orders (Polymarket orders or Kalshi positions/orders) if the SDK result is generic, null, or ambiguous\n\nThe agent should ask the user only for information it cannot safely infer or execute itself.\n\n---\n\n## Constraints\n\n### MUST\n\n- Set `AIONMARKET_API_KEY` before any authenticated call\n- Register Polymarket CLOB credentials before live Polymarket trading\n- Check wallet balance, gas/fees, and relevant allowance before submitting any order\n- Call `get_market_context()` before placing any trade\n- Handle `ApiError` on every SDK call\n- Save the API key returned by `register_agent()` immediately — it is shown only once\n- For Polymarket, send a full signed order object and `walletAddress` with every trade\n- For Kalshi, follow quote -> local sign -> submit and include `userPublicKey` when executing BUY flows\n- Verify downstream execution via the target venue when SDK responses are incomplete\n\n### SHOULD\n\n- Use environment variables for all secrets (never hardcode)\n- Call `get_briefing()` periodically (heartbeat pattern) for risk alerts and opportunities\n- Set conservative risk limits first via `update_settings()`, then scale up\n- Cancel stale open orders promptly\n- Rotate API keys every 90 days\n- Prefer market orders for simple one-shot execution unless the user explicitly requests a limit order\n- Auto-approve required spenders when allowance is missing and gas is sufficient\n\n### AVOID\n\n- Trading without checking `warnings` from market context\n- Exceeding the agent's configured `maxTradeAmount`\n- Sharing or logging API keys, CLOB secrets, or private keys\n- Calling `cancel_all_orders()` without confirming with the user first\n- Making trades in markets the agent has not researched\n- Treating a wrapper `INTERNAL_ERROR` as final without checking whether the downstream venue actually accepted or matched the order\n\n---\n\n## Installation\n\n```bash\npip install aionmarket-sdk py-clob-client python-dotenv\n```\n\n- `py-clob-client` — Polymarket official SDK, derives CLOB API credentials from private key\n- `python-dotenv` — loads `.env` file automatically\n\n---\n\n## Environment Setup\n\nCreate a `.env` file in your project root (add `.env` to `.gitignore`):\n\n```bash\n# .env\nAIONMARKET_API_KEY=sk_live_...\nWALLET_PRIVATE_KEY=0xabc123...your_64_hex_char_private_key\n\n# Optional — only set this when AION Market docs tell you to use\n# a non-production environment URL for your target environment.\n# Do not hardcode a staging URL copied from an old example.\n# AIONMARKET_BASE_URL=https://<documented-aionmarket-base-url>/bvapi\n```\n\nOr export directly:\n\n```bash\nexport AIONMARKET_API_KEY=\"sk_live_...\"\nexport WALLET_PRIVATE_KEY=\"0xabc123...\"\n```\n\n### Derive Wallet Address and CLOB Credentials from Private Key\n\n```python\nimport os\nfrom dotenv import load_dotenv\nfrom py_clob_client.client import ClobClient\n\nload_dotenv()  # loads .env file\n\nprivate_key = os.environ[\"WALLET_PRIVATE_KEY\"]\n\n# Use Polymarket CLOB client to derive credentials from private key\npolymarket = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,\n    chain_id=137,\n)\ncreds = polymarket.create_or_derive_api_creds()\n# creds contains: api_key, api_secret, api_passphrase\n\nwallet_address = polymarket.get_address()\nprint(f\"Wallet address: {wallet_address}\")\nprint(f\"CLOB credentials derived successfully\")\n```\n\n**Base URL resolution priority:**\n\n1. Explicit `base_url` argument in code\n2. `AIONMARKET_BASE_URL` environment variable\n3. Production default: `https://pm-t1.bxingupdate.com/bvapi`\n\nUse the SDK's documented resolution order above. Do **not** hardcode a sandbox or staging URL in sample code unless that exact environment URL is the current one documented by AION Market.\n\n---\n\n## Workflow: Agent Bootstrap\n\nRun once to create an agent and bind a wallet.\n\n### Step 1 — Register Agent\n\n```python\nfrom aionmarket_sdk import AionMarketClient\n\nclient = AionMarketClient()  # no key needed for registration\nregistration = client.register_agent(\"my-trading-bot\")\n\napi_key = registration[\"apiKeyCode\"]\nclaim_code = registration[\"claimCode\"]\nprint(f\"API Key (save now!): {api_key}\")\nprint(f\"Claim URL: {registration['claimUrl']}\")\n```\n\n> Save `apiKeyCode` immediately — it is only returned once.\n> After the API key is generated, open or click `claimUrl` and complete the claim/auth flow. Generating the key alone does **not** finish agent authentication.\n\nThe `claimUrl` returned by `register_agent()` is environment-aware and points\ndirectly to the frontend claim page (staging or production). Open it in a\nbrowser to claim and authenticate the agent.\n\nThe URL format is:\n\n```\nhttps://<FRONTEND_DOMAIN>/agents/claim?code=<CLAIM_CODE>\n```\n\nOr use `claim_preview(claim_code)` to verify the agent name before claiming.\n\n### Step 2 — Verify Agent\n\n```python\nclient = AionMarketClient(api_key=api_key)\nme = client.get_me()\nprint(f\"Agent: {me['name']}, Status: {me['status']}\")\n```\n\n### Step 3 — Derive Polymarket CLOB Credentials & Register Wallet\n\nThe private key is used to call Polymarket's auth endpoint and derive CLOB credentials automatically.\nThe user does **not** need to manually copy API Key / Secret / Passphrase from Polymarket settings.\n\n```python\nimport os\nfrom dotenv import load_dotenv\nfrom py_clob_client.client import ClobClient\n\nload_dotenv()\n\nprivate_key = os.environ[\"WALLET_PRIVATE_KEY\"]\n\n# 1. Derive CLOB credentials from private key via Polymarket\npolymarket = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,\n    chain_id=137,\n)\ncreds = polymarket.create_or_derive_api_creds()\nwallet = polymarket.get_address()\n\nprint(f\"Wallet: {wallet}\")\nprint(f\"CLOB API Key: {creds.api_key}\")\n\n# 2. Register with AION Market\ncheck = client.check_wallet_credentials(wallet)\nif not check[\"hasCredentials\"]:\n    client.register_wallet_credentials(\n        wallet_address=wallet,\n        api_key=creds.api_key,\n        api_secret=creds.api_secret,\n        api_passphrase=creds.api_passphrase,\n    )\n    print(f\"Wallet credentials registered for {wallet}\")\nelse:\n    print(f\"Wallet {wallet} already configured.\")\n```\n\n### Step 4 — Configure Risk Limits\n\n```python\nclient.update_settings(\n    max_trades_per_day=50,\n    max_trade_amount=100.0,\n    trading_paused=False,\n    auto_redeem_enabled=True,\n)\nsettings = client.get_settings()\nprint(settings)\n```\n\n### Step 5 — Kalshi Prerequisites (Optional, for Kalshi venue)\n\n- Ensure Solana wallet is available (`SOLANA_PRIVATE_KEY` / `userPublicKey`)\n- Use `kalshi_quote()` to request unsigned tx, locally sign, then call `kalshi_submit()`\n- For BUY flows, provide `userPublicKey` so KYC/geo checks can be evaluated upstream\n\n---\n\n## Workflow: Market Search & Context\n\n### Understanding Market Data Structure\n\n> **Critical:** `get_markets()` returns **events**, each containing a nested `markets[]`\n> array of **sub-markets**. Trading fields like `conditionId`, `clobTokenIds`,\n> `outcomePrices`, `negRisk`, and `orderPriceMinTickSize` live on the **sub-market**, NOT the event.\n\n```python\nimport ast\n\n# Search returns events\nevents = client.get_markets(q=\"bitcoin\", limit=10)\n\nfor event in events:\n    print(f\"Event: {event['title']}\")\n    for sub in event.get(\"markets\", []):\n        # Parse JSON strings\n        prices = ast.literal_eval(sub.get(\"outcomePrices\", '[\"0.5\",\"0.5\"]'))\n        token_ids = ast.literal_eval(sub.get(\"clobTokenIds\", '[]'))\n        print(f\"  Sub-market: {sub['question']}\")\n        print(f\"    conditionId: {sub['conditionId']}\")\n        print(f\"    YES price: {prices[0]}, NO price: {prices[1]}\")\n        print(f\"    YES token: {token_ids[0] if token_ids else 'N/A'}\")\n        print(f\"    negRisk: {sub.get('negRisk', False)}\")\n        print(f\"    tickSize: {sub.get('orderPriceMinTickSize', 0.01)}\")\n        print(f\"    minSize: {sub.get('orderMinSize', 5)}\")\n```\n\n### Get Market Context (REQUIRED before trading)\n\n```python\ncontext = client.get_market_context(\"CONDITION_ID\", user=wallet)\n\nprint(f\"Name:       {context.get('name')}\")\nprint(f\"Position:   {context.get('myPosition')}\")\nprint(f\"Risk limit: {context.get('riskLimit')}\")\nprint(f\"Warnings:   {context.get('warnings')}\")\n\nif context.get(\"warnings\"):\n    print(\"⚠️  Review warnings before proceeding!\")\n```\n\n### Automatic Pre-Trade Readiness Checks\n\nBefore signing or submitting any order, the agent should automatically verify:\n\n- wallet credentials are already registered, otherwise register them\n- collateral balance is sufficient for the intended spend\n- Polygon gas balance is sufficient if an onchain approval may be needed\n- the required spender allowance already exists for the intended order\n\nIf allowance is insufficient and gas is available, the agent should send the approval transaction automatically instead of asking the user to do it manually.\n\n---\n\n## Workflow: Trade Execution\n\n### Building a Signed Order (REQUIRED)\n\nThe `trade()` endpoint requires a **complete EIP712-signed order** from `py-clob-client`.\nPassing `\"order\": {}` will cause a credential lookup failure — the server reads\n`order.signatureType` to find your wallet credentials.\n\n```python\nimport ast\nfrom py_clob_client.client import ClobClient\nfrom py_clob_client.clob_types import ApiCreds, CreateOrderOptions, OrderArgs\n\n# 1. Initialize CLOB client with creds (derived earlier in bootstrap)\nclob = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,     # WALLET_PRIVATE_KEY\n    chain_id=137,\n    creds=ApiCreds(\n        api_key=creds.api_key,\n        api_secret=creds.api_secret,\n        api_passphrase=creds.api_passphrase,\n    ),\n)\n\n# 2. Extract trading params from sub-market (NOT event)\nsub_market = event[\"markets\"][0]  # pick the sub-market you want to trade\ncondition_id = sub_market[\"conditionId\"]\ntoken_ids = ast.literal_eval(sub_market[\"clobTokenIds\"])\nyes_token_id = token_ids[0]   # index 0 = YES, index 1 = NO\nno_token_id = token_ids[1]\nneg_risk = sub_market.get(\"negRisk\", False)\ntick_size = str(sub_market.get(\"orderPriceMinTickSize\", \"0.01\"))\nmin_size = sub_market.get(\"orderMinSize\", 5)\n\n# 3. Build signed order — MUST use CreateOrderOptions for proper signing\nsigned_order = clob.create_order(\n    OrderArgs(\n        token_id=yes_token_id,   # or no_token_id for NO side\n        price=0.55,\n        size=min_size,           # must >= orderMinSize\n        side=\"BUY\",\n    ),\n    options=CreateOrderOptions(\n        tick_size=tick_size,     # from sub-market.orderPriceMinTickSize\n        neg_risk=neg_risk,       # CRITICAL for neg-risk markets!\n    ),\n)\n\n# 4. Convert dataclass to dict for JSON serialization\norder_dict = signed_order.dict()\n```\n\n### Place a Trade\n\n```python\nresult = client.trade({\n    \"marketConditionId\": condition_id,          # hex conditionId from sub-market\n    \"marketQuestion\": sub_market[\"question\"],   # question text\n    \"outcome\": \"YES\",                           # YES or NO\n    \"orderSize\": min_size,                      # number of contracts\n    \"price\": 0.55,                              # price per contract (0-1)\n    \"isLimitOrder\": True,                       # True=limit, False=market\n    \"order\": order_dict,                        # ← FULL signed order (never {})\n    \"walletAddress\": wallet,                    # ← REQUIRED\n    \"reasoning\": \"Strategy edge explanation\",\n})\nprint(f\"Order ID: {result.get('orderId')}\")\nprint(f\"Status:   {result.get('status')}\")\n```\n\n### Default Execution Policy\n\nFor general-purpose execution, use this default policy unless the user overrides it:\n\n1. prefer `market` mode\n2. use `2` USDC as default buy size\n3. derive a marketable cap from current prices or order book when using market-order helpers\n4. ask for a price only when the user explicitly requested a limit order and did not provide one\n5. report the market snapshot and final order parameters without blocking on extra confirmation\n\n> **Common pitfalls:**\n>\n> - `\"order\": {}` → server cannot find `signatureType`, returns credential error\n> - Using event numeric ID as `marketConditionId` → use sub-market hex `conditionId`\n> - Missing `walletAddress` → \"walletAddress 不能为空\" error\n> - Not setting `neg_risk=True` for neg-risk markets → invalid signature, Polymarket rejects\n> - `orderSize` below `orderMinSize` → order rejected\n> - Insufficient USDC balance → server returns generic `INTERNAL_ERROR`\n> - Insufficient allowance → downstream exchange cannot spend collateral\n> - SDK result is empty or generic → verify recent trades and orders before reporting failure\n\n**Order types:** `GTC` (default), `FOK`, `GTD`, `FAK`\n**Sides:** `BUY`, `SELL`\n**Outcomes:** `YES`, `NO`\n\n---\n\n## Workflow: Kalshi Quote -> Sign -> Submit\n\nUse this flow for Kalshi venue execution.\n\n```python\nquote = client.kalshi_quote(\n    market_ticker=\"KX...\",\n    side=\"YES\",\n    action=\"BUY\",\n    amount=10,\n    user_public_key=\"<solana-wallet>\",\n)\n\n# Sign quote[\"unsignedTransaction\"] locally (wallet implementation specific)\nsigned_tx = \"<base64-signed-tx>\"\n\nsubmit = client.kalshi_submit(\n    market_ticker=\"KX...\",\n    side=\"YES\",\n    action=\"BUY\",\n    amount=10,\n    quote_id=quote[\"quoteId\"],\n    signed_transaction=signed_tx,\n    user_public_key=\"<solana-wallet>\",\n    in_amount=quote.get(\"inAmount\"),\n    out_amount=quote.get(\"outAmount\"),\n    min_out_amount=quote.get(\"minOutAmount\"),\n)\nprint(submit)\n\n# Unified positions endpoint for Kalshi (venue = kalshi)\nkalshi_positions = client.get_current_positions(\n    user=\"<solana-wallet>\",\n    venue=\"kalshi\",\n)\nprint(kalshi_positions)\n```\n\nKalshi currently does not expose a dedicated cancel API in this SDK. Use a SELL flow (`kalshi_quote` -> sign -> `kalshi_submit`) to reduce/exit exposure.\n\n## Workflow: Order Management\n\n```python\n# List open orders\nopen_orders = client.get_open_orders()\n\n# Order history (with optional filters)\nhistory = client.get_order_history(limit=20, order_status=2)\n\n# Single order detail\ndetail = client.get_order_detail(\"ORDER_ID\")\n\n# Cancel one order\nclient.cancel_order(\"ORDER_ID\")\n\n# Cancel ALL orders (use with care)\nclient.cancel_all_orders()\n```\n\n---\n\n## Workflow: Heartbeat / Briefing\n\nCall periodically (every 30s–15min depending on strategy frequency).\n\n```python\n# wallet can be Polygon or Solana based on venue flow\nbriefing = client.get_briefing(user=wallet)\n\n# 1. Handle risk alerts first\nfor alert in briefing.get(\"riskAlerts\", []):\n    print(f\"⚠️  {alert}\")\n\n# 2. Review open orders\nopen_orders = client.get_open_orders()\nprint(f\"Open orders: {len(open_orders)}\")\n\n# 3. Scan opportunity markets\nfor opp in briefing.get(\"opportunityMarkets\", [])[:5]:\n    print(f\"Opportunity: {opp.get('id')} — {opp.get('question')}\")\n```\n\n---\n\n## Workflow: Redemption\n\nWhen a market settles, redeem winning positions:\n\n```python\nclient.redeem(market_id=\"MARKET_ID\", side=\"YES\")\n```\n\n---\n\n## Error Handling\n\n```python\nfrom aionmarket_sdk import AionMarketClient, ApiError\n\nclient = AionMarketClient()\n\ntry:\n    result = client.get_me()\nexcept ApiError as e:\n    if e.status_code == 401:\n        print(\"❌ Invalid or missing API key\")\n    elif e.status_code == 403:\n        print(\"❌ Agent not authorized — check claim status or wallet credentials\")\n    elif e.status_code == 429:\n        print(\"⏳ Rate limited — back off and retry\")\n    else:\n        print(f\"API Error {e.code}: {e.message}\")\n```\n\nWhen trading, an `ApiError` from AION Market may still hide a successful downstream venue execution. If the response is ambiguous, query venue-specific follow-up endpoints before concluding failure (Polymarket orders/trades, or Kalshi submit/positions state).\n\n---\n\n## SDK Method Reference\n\n### Agent Management\n\n| Method                                | Description                                       |\n| ------------------------------------- | ------------------------------------------------- |\n| `register_agent(name)`                | Create agent, returns API key + claim code        |\n| `claim_preview(claim_code)`           | Preview agent info via claim code                 |\n| `get_me()`                            | Current agent profile and balances                |\n| `get_settings()`                      | Read risk control settings                        |\n| `update_settings(...)`                | Update max trades, max amount, pause, auto-redeem |\n| `get_skills(category, limit, offset)` | List available strategy skills                    |\n\n### Market Operations\n\n| Method                                                       | Description                                         |\n| ------------------------------------------------------------ | --------------------------------------------------- |\n| `get_markets(q, limit, page, venue, events_status)`          | Search markets by keyword                           |\n| `get_market(market_id, venue)`                               | Single market details                               |\n| `check_market_exists(market_id, venue)`                      | Existence check                                     |\n| `get_prices_history(token_id, ...)`                          | Historical prices for a token                       |\n| `get_briefing(venue, since, user, include_markets)`          | Heartbeat: alerts + opportunities                   |\n| `get_market_context(market_id, venue, user, my_probability)` | Pre-trade context & risk                            |\n| `get_current_positions(user, venue, ...)`                    | Unified current positions (`polymarket` / `kalshi`) |\n\n### Wallet Management\n\n| Method                                                                             | Description                      |\n| ---------------------------------------------------------------------------------- | -------------------------------- |\n| `check_wallet_credentials(wallet_address)`                                         | Check if CLOB credentials exist  |\n| `register_wallet_credentials(wallet_address, api_key, api_secret, api_passphrase)` | Store encrypted CLOB credentials |\n\n### Trading Operations\n\n| Method                                               | Description                           |\n| ---------------------------------------------------- | ------------------------------------- |\n| `trade(payload)`                                     | Place a Polymarket market/limit order |\n| `get_open_orders(venue, market_condition_id, limit)` | List unfilled orders                  |\n| `get_order_history(venue, ..., limit, offset)`       | Historical orders with filters        |\n| `get_order_detail(order_id, venue, wallet_address)`  | Single order detail                   |\n| `cancel_order(order_id, venue, wallet_address)`      | Cancel one order                      |\n| `cancel_all_orders(venue, wallet_address)`           | Cancel all open orders                |\n| `redeem(market_id, side, venue, wallet_address)`     | Redeem settled position               |\n| `kalshi_quote(...)`                                  | Build unsigned Kalshi quote tx        |\n| `kalshi_submit(...)`                                 | Submit locally signed Kalshi tx       |\n\n---\n\n## Checklist: Ready to Trade\n\n- [ ] `pip install aionmarket-sdk py-clob-client python-dotenv` installed\n- [ ] `.env` file created with `AIONMARKET_API_KEY` and `WALLET_PRIVATE_KEY` (plus `SOLANA_PRIVATE_KEY` if using Kalshi)\n- [ ] `.env` added to `.gitignore`\n- [ ] `get_me()` returns valid agent info\n- [ ] Polymarket CLOB credentials derived from private key and registered via `register_wallet_credentials()`\n- [ ] automatic balance, gas/fees, and allowance checks are part of the trading flow\n- [ ] missing allowance is auto-approved when technically possible\n- [ ] Risk limits configured via `update_settings()`\n- [ ] Heartbeat loop (`get_briefing()`) running or planned\n- [ ] Error handling wraps every SDK call with `ApiError`\n- [ ] For Kalshi: quote -> sign -> submit flow validated with `kalshi_quote()` / `kalshi_submit()`\n- [ ] ambiguous trade responses are verified against venue-specific state endpoints\n\n> Once all boxes are checked, the agent is ready for strategy skills to drive\n> market discovery and automated trade execution.\n\nFile v1.0.4:_meta.json\n\n{\n  \"ownerId\": \"kn75fv5d7z6aj8q78vn72zsbnn84rb61\",\n  \"slug\": \"aionmarket-trading\",\n  \"version\": \"1.0.4\",\n  \"publishedAt\": 1776944645290\n}\n\nArchive v1.0.3: 2 files, 9026 bytes\n\nFiles: skill.md (24723b), _meta.json (137b)\n\nFile v1.0.3:skill.md\n\n---\nname: aionmarket-trading\ndescription: |\n  Core trading skill for AION Market prediction market agents.\n  Provides agent setup, wallet binding, market search, automated pre-trade\n  checks, risk-aware trading, order management, position monitoring, and\n  settlement workflows on Polymarket and Kalshi via the aionmarket-sdk Python package.\n\n  Use when: an AI agent needs to register, configure wallets, search markets,\n  place or cancel trades, monitor positions, or run settlement-related flows on AION Market / Polymarket / Kalshi.\nmetadata:\n  author: \"AION Market\"\n  version: \"0.3.0\"\n  homepage: \"https://aionmarket.com\"\n  docs: \"https://docs.aionmarket.com\"\n  sdk: \"aionmarket-sdk (PyPI)\"\n---\n\n# Skill: aionmarket-trading\n\nCore trading operations for AI agents on AION Market / Polymarket / Kalshi.\nThis skill covers the **foundational** capabilities — agent lifecycle, wallet setup,\nmarket data, order execution, and position management.\n\n> **Strategy skills** (market discovery, signal generation, automated loops) are\n> separate skills that build on top of this one.\n\n---\n\n## Scope\n\n- **Applies to:** Any AI agent that needs to trade prediction markets through AION Market\n- **Does NOT cover:** Strategy logic, autonomous market scanning loops, or signal generation (see dedicated strategy skills)\n\n---\n\n## Prerequisites — USER MUST PROVIDE\n\nBefore this skill can operate, the user **must** supply:\n\n| Secret                 | Where to set                           | Example                               |\n| ---------------------- | -------------------------------------- | ------------------------------------- |\n| **Agent API Key**      | `AIONMARKET_API_KEY` env var or `.env` | `sk_live_Ab12Cd34...`                 |\n| **Wallet Private Key** | `WALLET_PRIVATE_KEY` env var or `.env` | `0xabc123...` (64 hex chars, Polygon) |\n| **Solana Private Key** | `SOLANA_PRIVATE_KEY` env var or `.env` | `<base58-key>` (Kalshi optional)      |\n\nThe skill will:\n\n1. Derive wallet addresses from provided keys (Polygon and/or Solana)\n2. For Polymarket, call CLOB auth to derive **API Key / Secret / Passphrase** from private key signature\n3. Register Polymarket CLOB credentials with AION Market via `register_wallet_credentials()` when needed\n4. For Kalshi, use quote -> local sign -> submit flow via DFlow-backed endpoints\n5. Automatically check wallet readiness before trading: balance, gas/fees, allowance (Polymarket), and market context\n\n> **If the private key is missing, STOP and ask the user to provide it.**\n> Never guess, fabricate, or skip credential setup.\n> Store secrets in a local `.env` file (never commit to git) or export as env vars.\n\n---\n\n## Assumptions\n\n- Python 3.9+\n- `aionmarket-sdk >= 0.1.2` installed (`pip install aionmarket-sdk`)\n- `py-clob-client` for Polymarket order signing and credential derivation\n- Agent has been registered or will be registered as part of the flow\n- Polymarket CLOB credentials are derived automatically from private key via `py-clob-client`\n- Kalshi trading uses quote -> sign -> submit; position queries use the unified `get_current_positions(..., venue=\"kalshi\")` endpoint\n- All SDK methods return plain dicts/lists; errors raise `ApiError`\n- **`get_markets()` returns events with nested `markets[]` sub-markets** — trading fields like `conditionId`, `clobTokenIds`, `outcomePrices` live on the sub-market, not the event\n\n---\n\n## Principles\n\n1. **Always check context before trading** — call `get_market_context()` before every order\n2. **Never trade without a thesis** — every trade needs explicit reasoning\n3. **Respect risk limits** — honour `riskLimit`, `maxTradesPerDay`, `maxTradeAmount`\n4. **Fail loudly** — catch `ApiError` and surface the message; never swallow errors\n5. **Self-custody** — wallet keys belong to the user; SDK only stores encrypted CLOB credentials\n6. **Automate mechanical steps** — do not ask the user to manually confirm balance checks, gas checks, allowance checks, or approval after the private key is available\n7. **Verify execution independently** — if the wrapper response is weak, validate through the corresponding venue (Polymarket or Kalshi) before reporting failure\n\n---\n\n## Automation Defaults\n\nUnless the user explicitly overrides them, the agent should use these defaults:\n\n- default trade mode: `market`\n- default buy size: `2` USDC\n- default behavior: auto-select a valid market candidate from the requested strategy scope\n- default pre-trade workflow: derive wallet, register wallet credentials, check balance, check gas, check allowance, auto-approve if needed, then trade\n- default post-trade workflow: query recent venue-specific trades/orders (Polymarket orders or Kalshi positions/orders) if the SDK result is generic, null, or ambiguous\n\nThe agent should ask the user only for information it cannot safely infer or execute itself.\n\n---\n\n## Constraints\n\n### MUST\n\n- Set `AIONMARKET_API_KEY` before any authenticated call\n- Register Polymarket CLOB credentials before live Polymarket trading\n- Check wallet balance, gas/fees, and relevant allowance before submitting any order\n- Call `get_market_context()` before placing any trade\n- Handle `ApiError` on every SDK call\n- Save the API key returned by `register_agent()` immediately — it is shown only once\n- For Polymarket, send a full signed order object and `walletAddress` with every trade\n- For Kalshi, follow quote -> local sign -> submit and include `userPublicKey` when executing BUY flows\n- Verify downstream execution via the target venue when SDK responses are incomplete\n\n### SHOULD\n\n- Use environment variables for all secrets (never hardcode)\n- Call `get_briefing()` periodically (heartbeat pattern) for risk alerts and opportunities\n- Set conservative risk limits first via `update_settings()`, then scale up\n- Cancel stale open orders promptly\n- Rotate API keys every 90 days\n- Prefer market orders for simple one-shot execution unless the user explicitly requests a limit order\n- Auto-approve required spenders when allowance is missing and gas is sufficient\n\n### AVOID\n\n- Trading without checking `warnings` from market context\n- Exceeding the agent's configured `maxTradeAmount`\n- Sharing or logging API keys, CLOB secrets, or private keys\n- Calling `cancel_all_orders()` without confirming with the user first\n- Making trades in markets the agent has not researched\n- Treating a wrapper `INTERNAL_ERROR` as final without checking whether the downstream venue actually accepted or matched the order\n\n---\n\n## Installation\n\n```bash\npip install aionmarket-sdk py-clob-client python-dotenv\n```\n\n- `py-clob-client` — Polymarket official SDK, derives CLOB API credentials from private key\n- `python-dotenv` — loads `.env` file automatically\n\n---\n\n## Environment Setup\n\nCreate a `.env` file in your project root (add `.env` to `.gitignore`):\n\n```bash\n# .env\nAIONMARKET_API_KEY=sk_live_...\nWALLET_PRIVATE_KEY=0xabc123...your_64_hex_char_private_key\n\n# Optional — only set this when AION Market docs tell you to use\n# a non-production environment URL for your target environment.\n# Do not hardcode a staging URL copied from an old example.\n# AIONMARKET_BASE_URL=https://<documented-aionmarket-base-url>/bvapi\n```\n\nOr export directly:\n\n```bash\nexport AIONMARKET_API_KEY=\"sk_live_...\"\nexport WALLET_PRIVATE_KEY=\"0xabc123...\"\n```\n\n### Derive Wallet Address and CLOB Credentials from Private Key\n\n```python\nimport os\nfrom dotenv import load_dotenv\nfrom py_clob_client.client import ClobClient\n\nload_dotenv()  # loads .env file\n\nprivate_key = os.environ[\"WALLET_PRIVATE_KEY\"]\n\n# Use Polymarket CLOB client to derive credentials from private key\npolymarket = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,\n    chain_id=137,\n)\ncreds = polymarket.create_or_derive_api_creds()\n# creds contains: api_key, api_secret, api_passphrase\n\nwallet_address = polymarket.get_address()\nprint(f\"Wallet address: {wallet_address}\")\nprint(f\"CLOB credentials derived successfully\")\n```\n\n**Base URL resolution priority:**\n\n1. Explicit `base_url` argument in code\n2. `AIONMARKET_BASE_URL` environment variable\n3. Production default: `https://api.aionmarket.com/bvapi`\n\nUse the SDK's documented resolution order above. Do **not** hardcode a sandbox or staging URL in sample code unless that exact environment URL is the current one documented by AION Market.\n\n---\n\n## Workflow: Agent Bootstrap\n\nRun once to create an agent and bind a wallet.\n\n### Step 1 — Register Agent\n\n```python\nfrom aionmarket_sdk import AionMarketClient\n\nclient = AionMarketClient()  # no key needed for registration\nregistration = client.register_agent(\"my-trading-bot\")\n\napi_key = registration[\"apiKeyCode\"]\nclaim_code = registration[\"claimCode\"]\nprint(f\"API Key (save now!): {api_key}\")\nprint(f\"Claim URL: {registration['claimUrl']}\")\n```\n\n> Save `apiKeyCode` immediately — it is only returned once.\n> After the API key is generated, open or click `claimUrl` and complete the claim/auth flow. Generating the key alone does **not** finish agent authentication.\n\nThe `claimUrl` returned by `register_agent()` is environment-aware and points\ndirectly to the frontend claim page (staging or production). Open it in a\nbrowser to claim and authenticate the agent.\n\nThe URL format is:\n\n```\nhttps://<FRONTEND_DOMAIN>/agents/claim?code=<CLAIM_CODE>\n```\n\nOr use `claim_preview(claim_code)` to verify the agent name before claiming.\n\n### Step 2 — Verify Agent\n\n```python\nclient = AionMarketClient(api_key=api_key)\nme = client.get_me()\nprint(f\"Agent: {me['name']}, Status: {me['status']}\")\n```\n\n### Step 3 — Derive Polymarket CLOB Credentials & Register Wallet\n\nThe private key is used to call Polymarket's auth endpoint and derive CLOB credentials automatically.\nThe user does **not** need to manually copy API Key / Secret / Passphrase from Polymarket settings.\n\n```python\nimport os\nfrom dotenv import load_dotenv\nfrom py_clob_client.client import ClobClient\n\nload_dotenv()\n\nprivate_key = os.environ[\"WALLET_PRIVATE_KEY\"]\n\n# 1. Derive CLOB credentials from private key via Polymarket\npolymarket = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,\n    chain_id=137,\n)\ncreds = polymarket.create_or_derive_api_creds()\nwallet = polymarket.get_address()\n\nprint(f\"Wallet: {wallet}\")\nprint(f\"CLOB API Key: {creds.api_key}\")\n\n# 2. Register with AION Market\ncheck = client.check_wallet_credentials(wallet)\nif not check[\"hasCredentials\"]:\n    client.register_wallet_credentials(\n        wallet_address=wallet,\n        api_key=creds.api_key,\n        api_secret=creds.api_secret,\n        api_passphrase=creds.api_passphrase,\n    )\n    print(f\"Wallet credentials registered for {wallet}\")\nelse:\n    print(f\"Wallet {wallet} already configured.\")\n```\n\n### Step 4 — Configure Risk Limits\n\n```python\nclient.update_settings(\n    max_trades_per_day=50,\n    max_trade_amount=100.0,\n    trading_paused=False,\n    auto_redeem_enabled=True,\n)\nsettings = client.get_settings()\nprint(settings)\n```\n\n### Step 5 — Kalshi Prerequisites (Optional, for Kalshi venue)\n\n- Ensure Solana wallet is available (`SOLANA_PRIVATE_KEY` / `userPublicKey`)\n- Use `kalshi_quote()` to request unsigned tx, locally sign, then call `kalshi_submit()`\n- For BUY flows, provide `userPublicKey` so KYC/geo checks can be evaluated upstream\n\n---\n\n## Workflow: Market Search & Context\n\n### Understanding Market Data Structure\n\n> **Critical:** `get_markets()` returns **events**, each containing a nested `markets[]`\n> array of **sub-markets**. Trading fields like `conditionId`, `clobTokenIds`,\n> `outcomePrices`, `negRisk`, and `orderPriceMinTickSize` live on the **sub-market**, NOT the event.\n\n```python\nimport ast\n\n# Search returns events\nevents = client.get_markets(q=\"bitcoin\", limit=10)\n\nfor event in events:\n    print(f\"Event: {event['title']}\")\n    for sub in event.get(\"markets\", []):\n        # Parse JSON strings\n        prices = ast.literal_eval(sub.get(\"outcomePrices\", '[\"0.5\",\"0.5\"]'))\n        token_ids = ast.literal_eval(sub.get(\"clobTokenIds\", '[]'))\n        print(f\"  Sub-market: {sub['question']}\")\n        print(f\"    conditionId: {sub['conditionId']}\")\n        print(f\"    YES price: {prices[0]}, NO price: {prices[1]}\")\n        print(f\"    YES token: {token_ids[0] if token_ids else 'N/A'}\")\n        print(f\"    negRisk: {sub.get('negRisk', False)}\")\n        print(f\"    tickSize: {sub.get('orderPriceMinTickSize', 0.01)}\")\n        print(f\"    minSize: {sub.get('orderMinSize', 5)}\")\n```\n\n### Get Market Context (REQUIRED before trading)\n\n```python\ncontext = client.get_market_context(\"CONDITION_ID\", user=wallet)\n\nprint(f\"Name:       {context.get('name')}\")\nprint(f\"Position:   {context.get('myPosition')}\")\nprint(f\"Risk limit: {context.get('riskLimit')}\")\nprint(f\"Warnings:   {context.get('warnings')}\")\n\nif context.get(\"warnings\"):\n    print(\"⚠️  Review warnings before proceeding!\")\n```\n\n### Automatic Pre-Trade Readiness Checks\n\nBefore signing or submitting any order, the agent should automatically verify:\n\n- wallet credentials are already registered, otherwise register them\n- collateral balance is sufficient for the intended spend\n- Polygon gas balance is sufficient if an onchain approval may be needed\n- the required spender allowance already exists for the intended order\n\nIf allowance is insufficient and gas is available, the agent should send the approval transaction automatically instead of asking the user to do it manually.\n\n---\n\n## Workflow: Trade Execution\n\n### Building a Signed Order (REQUIRED)\n\nThe `trade()` endpoint requires a **complete EIP712-signed order** from `py-clob-client`.\nPassing `\"order\": {}` will cause a credential lookup failure — the server reads\n`order.signatureType` to find your wallet credentials.\n\n```python\nimport ast\nfrom py_clob_client.client import ClobClient\nfrom py_clob_client.clob_types import ApiCreds, CreateOrderOptions, OrderArgs\n\n# 1. Initialize CLOB client with creds (derived earlier in bootstrap)\nclob = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,     # WALLET_PRIVATE_KEY\n    chain_id=137,\n    creds=ApiCreds(\n        api_key=creds.api_key,\n        api_secret=creds.api_secret,\n        api_passphrase=creds.api_passphrase,\n    ),\n)\n\n# 2. Extract trading params from sub-market (NOT event)\nsub_market = event[\"markets\"][0]  # pick the sub-market you want to trade\ncondition_id = sub_market[\"conditionId\"]\ntoken_ids = ast.literal_eval(sub_market[\"clobTokenIds\"])\nyes_token_id = token_ids[0]   # index 0 = YES, index 1 = NO\nno_token_id = token_ids[1]\nneg_risk = sub_market.get(\"negRisk\", False)\ntick_size = str(sub_market.get(\"orderPriceMinTickSize\", \"0.01\"))\nmin_size = sub_market.get(\"orderMinSize\", 5)\n\n# 3. Build signed order — MUST use CreateOrderOptions for proper signing\nsigned_order = clob.create_order(\n    OrderArgs(\n        token_id=yes_token_id,   # or no_token_id for NO side\n        price=0.55,\n        size=min_size,           # must >= orderMinSize\n        side=\"BUY\",\n    ),\n    options=CreateOrderOptions(\n        tick_size=tick_size,     # from sub-market.orderPriceMinTickSize\n        neg_risk=neg_risk,       # CRITICAL for neg-risk markets!\n    ),\n)\n\n# 4. Convert dataclass to dict for JSON serialization\norder_dict = signed_order.dict()\n```\n\n### Place a Trade\n\n```python\nresult = client.trade({\n    \"marketConditionId\": condition_id,          # hex conditionId from sub-market\n    \"marketQuestion\": sub_market[\"question\"],   # question text\n    \"outcome\": \"YES\",                           # YES or NO\n    \"orderSize\": min_size,                      # number of contracts\n    \"price\": 0.55,                              # price per contract (0-1)\n    \"isLimitOrder\": True,                       # True=limit, False=market\n    \"order\": order_dict,                        # ← FULL signed order (never {})\n    \"walletAddress\": wallet,                    # ← REQUIRED\n    \"reasoning\": \"Strategy edge explanation\",\n})\nprint(f\"Order ID: {result.get('orderId')}\")\nprint(f\"Status:   {result.get('status')}\")\n```\n\n### Default Execution Policy\n\nFor general-purpose execution, use this default policy unless the user overrides it:\n\n1. prefer `market` mode\n2. use `2` USDC as default buy size\n3. derive a marketable cap from current prices or order book when using market-order helpers\n4. ask for a price only when the user explicitly requested a limit order and did not provide one\n5. report the market snapshot and final order parameters without blocking on extra confirmation\n\n> **Common pitfalls:**\n>\n> - `\"order\": {}` → server cannot find `signatureType`, returns credential error\n> - Using event numeric ID as `marketConditionId` → use sub-market hex `conditionId`\n> - Missing `walletAddress` → \"walletAddress 不能为空\" error\n> - Not setting `neg_risk=True` for neg-risk markets → invalid signature, Polymarket rejects\n> - `orderSize` below `orderMinSize` → order rejected\n> - Insufficient USDC balance → server returns generic `INTERNAL_ERROR`\n> - Insufficient allowance → downstream exchange cannot spend collateral\n> - SDK result is empty or generic → verify recent trades and orders before reporting failure\n\n**Order types:** `GTC` (default), `FOK`, `GTD`, `FAK`\n**Sides:** `BUY`, `SELL`\n**Outcomes:** `YES`, `NO`\n\n---\n\n## Workflow: Kalshi Quote -> Sign -> Submit\n\nUse this flow for Kalshi venue execution.\n\n```python\nquote = client.kalshi_quote(\n    market_ticker=\"KX...\",\n    side=\"YES\",\n    action=\"BUY\",\n    amount=10,\n    user_public_key=\"<solana-wallet>\",\n)\n\n# Sign quote[\"unsignedTransaction\"] locally (wallet implementation specific)\nsigned_tx = \"<base64-signed-tx>\"\n\nsubmit = client.kalshi_submit(\n    market_ticker=\"KX...\",\n    side=\"YES\",\n    action=\"BUY\",\n    amount=10,\n    quote_id=quote[\"quoteId\"],\n    signed_transaction=signed_tx,\n    user_public_key=\"<solana-wallet>\",\n    in_amount=quote.get(\"inAmount\"),\n    out_amount=quote.get(\"outAmount\"),\n    min_out_amount=quote.get(\"minOutAmount\"),\n)\nprint(submit)\n\n# Unified positions endpoint for Kalshi (venue = kalshi)\nkalshi_positions = client.get_current_positions(\n    user=\"<solana-wallet>\",\n    venue=\"kalshi\",\n)\nprint(kalshi_positions)\n```\n\nKalshi currently does not expose a dedicated cancel API in this SDK. Use a SELL flow (`kalshi_quote` -> sign -> `kalshi_submit`) to reduce/exit exposure.\n\n## Workflow: Order Management\n\n```python\n# List open orders\nopen_orders = client.get_open_orders()\n\n# Order history (with optional filters)\nhistory = client.get_order_history(limit=20, order_status=2)\n\n# Single order detail\ndetail = client.get_order_detail(\"ORDER_ID\")\n\n# Cancel one order\nclient.cancel_order(\"ORDER_ID\")\n\n# Cancel ALL orders (use with care)\nclient.cancel_all_orders()\n```\n\n---\n\n## Workflow: Heartbeat / Briefing\n\nCall periodically (every 30s–15min depending on strategy frequency).\n\n```python\n# wallet can be Polygon or Solana based on venue flow\nbriefing = client.get_briefing(user=wallet)\n\n# 1. Handle risk alerts first\nfor alert in briefing.get(\"riskAlerts\", []):\n    print(f\"⚠️  {alert}\")\n\n# 2. Review open orders\nopen_orders = client.get_open_orders()\nprint(f\"Open orders: {len(open_orders)}\")\n\n# 3. Scan opportunity markets\nfor opp in briefing.get(\"opportunityMarkets\", [])[:5]:\n    print(f\"Opportunity: {opp.get('id')} — {opp.get('question')}\")\n```\n\n---\n\n## Workflow: Redemption\n\nWhen a market settles, redeem winning positions:\n\n```python\nclient.redeem(market_id=\"MARKET_ID\", side=\"YES\")\n```\n\n---\n\n## Error Handling\n\n```python\nfrom aionmarket_sdk import AionMarketClient, ApiError\n\nclient = AionMarketClient()\n\ntry:\n    result = client.get_me()\nexcept ApiError as e:\n    if e.status_code == 401:\n        print(\"❌ Invalid or missing API key\")\n    elif e.status_code == 403:\n        print(\"❌ Agent not authorized — check claim status or wallet credentials\")\n    elif e.status_code == 429:\n        print(\"⏳ Rate limited — back off and retry\")\n    else:\n        print(f\"API Error {e.code}: {e.message}\")\n```\n\nWhen trading, an `ApiError` from AION Market may still hide a successful downstream venue execution. If the response is ambiguous, query venue-specific follow-up endpoints before concluding failure (Polymarket orders/trades, or Kalshi submit/positions state).\n\n---\n\n## SDK Method Reference\n\n### Agent Management\n\n| Method                                | Description                                       |\n| ------------------------------------- | ------------------------------------------------- |\n| `register_agent(name)`                | Create agent, returns API key + claim code        |\n| `claim_preview(claim_code)`           | Preview agent info via claim code                 |\n| `get_me()`                            | Current agent profile and balances                |\n| `get_settings()`                      | Read risk control settings                        |\n| `update_settings(...)`                | Update max trades, max amount, pause, auto-redeem |\n| `get_skills(category, limit, offset)` | List available strategy skills                    |\n\n### Market Operations\n\n| Method                                                       | Description                                         |\n| ------------------------------------------------------------ | --------------------------------------------------- |\n| `get_markets(q, limit, page, venue, events_status)`          | Search markets by keyword                           |\n| `get_market(market_id, venue)`                               | Single market details                               |\n| `check_market_exists(market_id, venue)`                      | Existence check                                     |\n| `get_prices_history(token_id, ...)`                          | Historical prices for a token                       |\n| `get_briefing(venue, since, user, include_markets)`          | Heartbeat: alerts + opportunities                   |\n| `get_market_context(market_id, venue, user, my_probability)` | Pre-trade context & risk                            |\n| `get_current_positions(user, venue, ...)`                    | Unified current positions (`polymarket` / `kalshi`) |\n\n### Wallet Management\n\n| Method                                                                             | Description                      |\n| ---------------------------------------------------------------------------------- | -------------------------------- |\n| `check_wallet_credentials(wallet_address)`                                         | Check if CLOB credentials exist  |\n| `register_wallet_credentials(wallet_address, api_key, api_secret, api_passphrase)` | Store encrypted CLOB credentials |\n\n### Trading Operations\n\n| Method                                               | Description                           |\n| ---------------------------------------------------- | ------------------------------------- |\n| `trade(payload)`                                     | Place a Polymarket market/limit order |\n| `get_open_orders(venue, market_condition_id, limit)` | List unfilled orders                  |\n| `get_order_history(venue, ..., limit, offset)`       | Historical orders with filters        |\n| `get_order_detail(order_id, venue, wallet_address)`  | Single order detail                   |\n| `cancel_order(order_id, venue, wallet_address)`      | Cancel one order                      |\n| `cancel_all_orders(venue, wallet_address)`           | Cancel all open orders                |\n| `redeem(market_id, side, venue, wallet_address)`     | Redeem settled position               |\n| `kalshi_quote(...)`                                  | Build unsigned Kalshi quote tx        |\n| `kalshi_submit(...)`                                 | Submit locally signed Kalshi tx       |\n\n---\n\n## Checklist: Ready to Trade\n\n- [ ] `pip install aionmarket-sdk py-clob-client python-dotenv` installed\n- [ ] `.env` file created with `AIONMARKET_API_KEY` and `WALLET_PRIVATE_KEY` (plus `SOLANA_PRIVATE_KEY` if using Kalshi)\n- [ ] `.env` added to `.gitignore`\n- [ ] `get_me()` returns valid agent info\n- [ ] Polymarket CLOB credentials derived from private key and registered via `register_wallet_credentials()`\n- [ ] automatic balance, gas/fees, and allowance checks are part of the trading flow\n- [ ] missing allowance is auto-approved when technically possible\n- [ ] Risk limits configured via `update_settings()`\n- [ ] Heartbeat loop (`get_briefing()`) running or planned\n- [ ] Error handling wraps every SDK call with `ApiError`\n- [ ] For Kalshi: quote -> sign -> submit flow validated with `kalshi_quote()` / `kalshi_submit()`\n- [ ] ambiguous trade responses are verified against venue-specific state endpoints\n\n> Once all boxes are checked, the agent is ready for strategy skills to drive\n> market discovery and automated trade execution.\n\nFile v1.0.3:_meta.json\n\n{\n  \"ownerId\": \"kn75fv5d7z6aj8q78vn72zsbnn84rb61\",\n  \"slug\": \"aionmarket-trading\",\n  \"version\": \"1.0.3\",\n  \"publishedAt\": 1776935316771\n}\n\nArchive v1.0.2: 2 files, 8493 bytes\n\nFiles: skill.md (22916b), _meta.json (137b)\n\nFile v1.0.2:skill.md\n\n---\nname: aionmarket-trading\ndescription: |\n  Core trading skill for AION Market prediction market agents.\n  Provides agent setup, wallet binding, market search, automated pre-trade\n  checks, risk-aware trading, order management, position monitoring, and\n  settlement redemption on Polymarket via the aionmarket-sdk Python package.\n\n  Use when: an AI agent needs to register, configure wallets, search markets,\n  place or cancel trades, monitor positions, or redeem winnings on AION Market / Polymarket.\nmetadata:\n  author: \"AION Market\"\n  version: \"0.3.0\"\n  tags: [polymarket, trading, prediction-market, aionmarket-sdk, ai-agent, yes-no-trade, risk-management]\n  homepage: \"https://aionmarket.com\"\n  docs: \"https://docs.aionmarket.com\"\n  sdk: \"aionmarket-sdk (PyPI)\"\n---\n\n# Skill: aionmarket-trading\n\nCore trading operations for AI agents on AION Market / Polymarket.\nThis skill covers the **foundational** capabilities — agent lifecycle, wallet setup,\nmarket data, order execution, and position management.\n\n> **Strategy skills** (market discovery, signal generation, automated loops) are\n> separate skills that build on top of this one.\n\n---\n\n## Scope\n\n- **Applies to:** Any AI agent that needs to trade prediction markets through AION Market\n- **Does NOT cover:** Strategy logic, autonomous market scanning loops, or signal generation (see dedicated strategy skills)\n\n---\n\n## Prerequisites — USER MUST PROVIDE\n\nBefore this skill can operate, the user **must** supply:\n\n| Secret                 | Where to set                           | Example                      |\n| ---------------------- | -------------------------------------- | ---------------------------- |\n| **Agent API Key**      | `AIONMARKET_API_KEY` env var or `.env` | `sk_live_Ab12Cd34...`        |\n| **Wallet Private Key** | `WALLET_PRIVATE_KEY` env var or `.env` | `0xabc123...` (64 hex chars) |\n\nThat's it. The skill will:\n\n1. Derive the **wallet address** from the private key automatically\n2. Call Polymarket's CLOB auth endpoint to derive **API Key / Secret / Passphrase** using the private key signature\n3. Register the CLOB credentials with AION Market via `register_wallet_credentials()`\n4. Automatically check wallet readiness before trading: balance, gas, allowance, and market context\n5. Automatically approve allowance if needed and technically possible\n\n> **If the private key is missing, STOP and ask the user to provide it.**\n> Never guess, fabricate, or skip credential setup.\n> Store secrets in a local `.env` file (never commit to git) or export as env vars.\n\n---\n\n## Assumptions\n\n- Python 3.9+\n- `aionmarket-sdk >= 0.1.2` installed (`pip install aionmarket-sdk`)\n- `py-clob-client` for order signing and credential derivation\n- Agent has been registered or w\n\nArchive v1.0.1: 2 files, 8167 bytes\n\nFiles: skill.md (22102b), _meta.json (137b)\n\nArchive v1.0.0: 2 files, 7820 bytes\n\nFiles: skill.md (21230b), _meta.json (137b)","readmeExcerpt":"Skill: Aionmarket Trading Owner: ssj124 Summary: Core trading skill for AION Market prediction market agents. Provides agent setup, wallet binding, market search, automated pre-trade checks, risk-aware trad... Tags: latest:1.0.7 Version history: v1.0.7 | 2026-05-11T14:30:23.851Z | auto - Documentation and metadata updates only—no functional or API changes. - Clarified usage, environment setup, and agent responsibilit","codeSnippets":[],"executableExamples":[{"language":"bash","snippet":"pip install aion-sdk py-clob-client python-dotenv"},{"language":"bash","snippet":"# .env\nAIONMARKET_API_KEY=sk_live_...\nWALLET_PRIVATE_KEY=0xabc123...your_64_hex_char_private_key\n\n# Optional — only set this when AION Market docs tell you to use\n# a non-production environment URL for your target environment.\n# Do not hardcode a staging URL copied from an old example.\n# AIONMARKET_BASE_URL=https://<documented-aionmarket-base-url>/bvapi"},{"language":"bash","snippet":"export AIONMARKET_API_KEY=\"sk_live_...\"\nexport WALLET_PRIVATE_KEY=\"0xabc123...\""},{"language":"python","snippet":"import os\nfrom dotenv import load_dotenv\nfrom py_clob_client.client import ClobClient\n\nload_dotenv()  # loads .env file\n\nprivate_key = os.environ[\"WALLET_PRIVATE_KEY\"]\n\n# Use Polymarket CLOB client to derive credentials from private key\npolymarket = ClobClient(\n    \"https://clob.polymarket.com\",\n    key=private_key,\n    chain_id=137,\n)\ncreds = polymarket.create_or_derive_api_creds()\n# creds contains: api_key, api_secret, api_passphrase\n\nwallet_address = polymarket.get_address()\nprint(f\"Wallet address: {wallet_address}\")\nprint(f\"CLOB credentials derived successfully\")"},{"language":"python","snippet":"from aion_sdk import AionMarketClient\n\nclient = AionMarketClient()  # no key needed for registration\nregistration = client.register_agent(\"my-trading-bot\")\n\napi_key = registration[\"apiKeyCode\"]\nclaim_code = registration[\"claimCode\"]\nprint(f\"API Key (save now!): {api_key}\")\nprint(f\"Claim URL: {registration['claimUrl']}\")"},{"language":"text","snippet":"https://<FRONTEND_DOMAIN>/agents/claim?code=<CLAIM_CODE>"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"skill.md","content":"---\nname: aionmarket-trading\ndescription: |\n  Core trading skill for AION Market prediction market agents.\n  Provides agent setup, wallet binding, market search, automated pre-trade\n  checks, risk-aware trading, order management, position monitoring, and\n  settlement workflows on Polymarket and Kalshi via the aion-sdk Python package.\n\n  Use when: an AI agent needs to register, configure wallets, search markets,\n  place or cancel trades, monitor positions, or run settlement-related flows on AION Market / Polymarket / Kalshi.\nmetadata:\n  author: \"AION Market\"\n  version: \"0.3.0\"\n  homepage: \"https://www.aionmarket.com/\"\n  docs: \"https://docs.aionmarket.com/\"\n  sdk: \"aion-sdk (PyPI)\"\n---\n\n# Skill: aionmarket-trading\n\nCore trading operations for AI agents on AION Market / Polymarket / Kalshi.\nThis skill covers the **foundational** capabilities — agent lifecycle, wallet setup,\nmarket data, order execution, and position management.\n\n> **Strategy skills** (market discovery, signal generation, automated loops) are\n> separate skills that build on top of this one.\n\n---\n\n## Scope\n\n- **Applies to:** Any AI agent that needs to trade prediction markets through AION Market\n- **Does NOT cover:** Strategy logic, autonomous market scanning loops, or signal generation (see dedicated strategy skills)\n\n---\n\n## Prerequisites — USER MUST PROVIDE\n\nBefore this skill can operate, the user **must** supply:\n\n| Secret                 | Where to set                           | Example                               |\n| ---------------------- | -------------------------------------- | ------------------------------------- |\n| **Agent API Key**      | `AIONMARKET_API_KEY` env var or `.env` | `sk_live_Ab12Cd34...`                 |\n| **Wallet Private Key** | `WALLET_PRIVATE_KEY` env var or `.env` | `0xabc123...` (64 hex chars, Polygon) |\n| **Solana Private Key** | `SOLANA_PRIVATE_KEY` env var or `.env` | `<base58-key>` (Kalshi optional)      |\n\nThe skill will:\n\n1. Derive wallet addresses from provided keys (Polygon and/or Solana)\n2. For Polymarket, call CLOB auth to derive **API Key / Secret / Passphrase** from private key signature\n3. Register Polymarket CLOB credentials with AION Market via `register_wallet_credentials()` when needed\n4. For Kalshi, use quote -> local sign -> submit flow via DFlow-backed endpoints\n5. Automatically check wallet readiness before trading: balance, gas/fees, allowance (Polymarket), and market context\n\n> **If the private key is missing, STOP and ask the user to provide it.**\n> Never guess, fabricate, or skip credential setup.\n> Store secrets in a local `.env` file (never commit to git) or export as env vars.\n\n---\n\n## Assumptions\n\n- Python 3.9+\n- `aion-sdk >= 0.1.2` installed (`pip install aion-sdk`)\n- `py-clob-client` for Polymarket order signing and credential derivation\n- Agent has been registered or will be registered as part of the flow\n- Polymarket CLOB credentials are derived automatically from private key via `py-clob-client`\n- Kalshi trading u"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn75fv5d7z6aj8q78vn72zsbnn84rb61\",\n  \"slug\": \"aionmarket-trading\",\n  \"version\": \"1.0.7\",\n  \"publishedAt\": 1778509823851\n}"},{"path":"skill-card.md","content":"## Description:\n\nCore trading skill for AION Market prediction market agents, covering setup, wallet binding, market search, pre-trade checks, risk-aware trading, order management, position monitoring, and settlement workflows on Polymarket and Kalshi via aion-sdk.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[ssj124](https://clawhub.ai/user/ssj124)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nExternal developers and agent operators use this skill to configure AION Market trading agents, connect wallets, inspect prediction markets, submit or cancel Polymarket and Kalshi orders, monitor positions, redeem settlements, and manage post-trade fee workflows.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Real-money prediction-market automation can approve spend, place trades, charge fees, or transfer funds with too much default authority.\n\nMitigation: Use a limited wallet, set strict allowance and trade caps, pause trading until limits are configured, and require explicit confirmation for every approval, trade, and fee transfer.\n\nRisk: Wallet private keys, API keys, derived CLOB credentials, and Solana keys can expose user funds if logged, committed, or reused broadly.\n\nMitigation: Keep secrets in environment variables or an uncommitted .env file, avoid printing credentials, use pinned dependencies, and prefer a separate signer or hardware wallet for live trading.\n\nRisk: Ambiguous SDK or venue responses can cause the agent to misreport whether an order, cancellation, settlement, or fee transfer succeeded.\n\nMitigation: Verify ambiguous outcomes through venue-specific order, trade, position, or transaction state before retrying or reporting final status.\n\n## Reference(s):\n\n- [AION Market documentation](https://docs.aionmarket.com/)\n- [AION Market homepage](https://www.aionmarket.com/)\n- [ClawHub skill page](https://clawhub.ai/ssj124/skills/aionmarket-trading)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown guidance with Python and shell code blocks]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [Guides authenticated SDK calls and wallet-dependent trading workflows; it does not itself produce market predictions or strategy signals.]\n\n## Skill Version(s):\n\n1.0.7 (source: server release metadata; artifact metadata.version is 0.3.0)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment."}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":null,"editorialQuality":{"score":100,"threshold":65,"status":"thin","wordCount":1523,"uniquenessScore":44,"reasons":["uniqueness-below-45"]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-09T20:29:14.402Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-09T20:29:14.402Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-10T02:45:53.689Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}