polyrob 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agents/README.md +453 -0
- agents/__init__.py +164 -0
- agents/base_agent.py +743 -0
- agents/personality/character.py +119 -0
- agents/personality/character_manager.py +309 -0
- agents/personality/characters/rob.character.json +56 -0
- agents/personality/characters/trump.character.json +63 -0
- agents/personality/persona_render.py +78 -0
- agents/personality/persona_resolver.py +115 -0
- agents/prompt/__init__.py +58 -0
- agents/prompt/base_prompt.py +92 -0
- agents/prompt/system.py +417 -0
- agents/task/README_PATH_MANAGEMENT.md +141 -0
- agents/task/__init__.py +162 -0
- agents/task/agent/__init__.py +70 -0
- agents/task/agent/agent_state.py +408 -0
- agents/task/agent/async_delegation.py +274 -0
- agents/task/agent/autonomy_state.py +275 -0
- agents/task/agent/conversation.py +75 -0
- agents/task/agent/core/__init__.py +6 -0
- agents/task/agent/core/aux_metering.py +61 -0
- agents/task/agent/core/background_review.py +157 -0
- agents/task/agent/core/construction.py +1179 -0
- agents/task/agent/core/conversational_exit.py +49 -0
- agents/task/agent/core/correspondent_gate.py +227 -0
- agents/task/agent/core/curator.py +246 -0
- agents/task/agent/core/episodic_digest.py +103 -0
- agents/task/agent/core/error_recovery.py +480 -0
- agents/task/agent/core/history_io.py +257 -0
- agents/task/agent/core/llm_provisioning.py +287 -0
- agents/task/agent/core/llm_runner.py +547 -0
- agents/task/agent/core/logging_io.py +276 -0
- agents/task/agent/core/loop_detection.py +262 -0
- agents/task/agent/core/memory_prefetch.py +325 -0
- agents/task/agent/core/memory_writer.py +667 -0
- agents/task/agent/core/model_introspection.py +82 -0
- agents/task/agent/core/model_swap.py +177 -0
- agents/task/agent/core/next_action_internal.py +1331 -0
- agents/task/agent/core/output_validation.py +303 -0
- agents/task/agent/core/project_context.py +272 -0
- agents/task/agent/core/resources.py +93 -0
- agents/task/agent/core/result_processing.py +389 -0
- agents/task/agent/core/run_loop.py +661 -0
- agents/task/agent/core/safety_lifecycle.py +228 -0
- agents/task/agent/core/secret_guard.py +293 -0
- agents/task/agent/core/self_wake.py +280 -0
- agents/task/agent/core/session_metadata.py +104 -0
- agents/task/agent/core/step.py +781 -0
- agents/task/agent/core/step_execution.py +398 -0
- agents/task/agent/core/step_telemetry.py +222 -0
- agents/task/agent/core/test_aux_metering.py +50 -0
- agents/task/agent/core/test_billing_failover.py +68 -0
- agents/task/agent/core/test_fatal_error_classifier.py +38 -0
- agents/task/agent/core/test_judge_validation.py +275 -0
- agents/task/agent/core/test_model_swap.py +190 -0
- agents/task/agent/core/test_reflection_offload.py +54 -0
- agents/task/agent/core/turn_input.py +8 -0
- agents/task/agent/core/untrusted_wrap.py +103 -0
- agents/task/agent/core/user_ingress.py +228 -0
- agents/task/agent/hitl_manager.py +396 -0
- agents/task/agent/log_sanitize.py +36 -0
- agents/task/agent/message_manager/config.py +97 -0
- agents/task/agent/message_manager/service.py +758 -0
- agents/task/agent/message_manager/tests.py +305 -0
- agents/task/agent/message_manager/tool_call_builder.py +539 -0
- agents/task/agent/message_manager/tool_message_repair.py +364 -0
- agents/task/agent/message_manager/views.py +143 -0
- agents/task/agent/messages/__init__.py +8 -0
- agents/task/agent/messages/builders.py +309 -0
- agents/task/agent/messages/compactor.py +611 -0
- agents/task/agent/messages/context_references.py +271 -0
- agents/task/agent/messages/filters.py +333 -0
- agents/task/agent/messages/guidance.py +328 -0
- agents/task/agent/messages/persistence.py +448 -0
- agents/task/agent/messages/retrieval.py +506 -0
- agents/task/agent/messages/sqlite_persistence.py +85 -0
- agents/task/agent/messages/test_compaction_upgrade.py +349 -0
- agents/task/agent/messages/test_persistence_subdir_fix.py +28 -0
- agents/task/agent/messages/test_sqlite_persistence.py +54 -0
- agents/task/agent/messages/token_counter.py +532 -0
- agents/task/agent/orchestrator.py +776 -0
- agents/task/agent/profile_manager.py +105 -0
- agents/task/agent/profile_registry.py +173 -0
- agents/task/agent/prompts.py +1090 -0
- agents/task/agent/scenario_registry.py +226 -0
- agents/task/agent/service.py +509 -0
- agents/task/agent/session.py +984 -0
- agents/task/agent/skill_discovery.py +110 -0
- agents/task/agent/skill_frontmatter.py +94 -0
- agents/task/agent/skill_manager.py +1201 -0
- agents/task/agent/skill_store.py +627 -0
- agents/task/agent/skill_validation.py +56 -0
- agents/task/agent/skill_writer.py +492 -0
- agents/task/agent/sub_agent_manager.py +1137 -0
- agents/task/agent/test_session_disk_recovery.py +34 -0
- agents/task/agent/tests.py +513 -0
- agents/task/agent/tool_call_tracker.py +511 -0
- agents/task/agent/views.py +469 -0
- agents/task/config.py +432 -0
- agents/task/constants.py +1384 -0
- agents/task/flag_defaults.py +63 -0
- agents/task/goals/__init__.py +1 -0
- agents/task/goals/autonomy_marker.py +28 -0
- agents/task/goals/board.py +690 -0
- agents/task/goals/completion_judge.py +247 -0
- agents/task/goals/context.py +62 -0
- agents/task/goals/dispatcher.py +848 -0
- agents/task/goals/escalation.py +102 -0
- agents/task/goals/planner.py +114 -0
- agents/task/logging_config.py +155 -0
- agents/task/path.py +991 -0
- agents/task/robust_parse_config.py +400 -0
- agents/task/runtime/__init__.py +0 -0
- agents/task/runtime/run_as_session.py +130 -0
- agents/task/runtime_safety.py +308 -0
- agents/task/session/__init__.py +5 -0
- agents/task/session/browser_pool.py +130 -0
- agents/task/session/cleanup.py +612 -0
- agents/task/session/execution.py +397 -0
- agents/task/session/feed.py +200 -0
- agents/task/session/hitl_ingress.py +201 -0
- agents/task/session/hooks.py +83 -0
- agents/task/session/multi_agent.py +243 -0
- agents/task/session/workspace.py +91 -0
- agents/task/session_registry.py +91 -0
- agents/task/session_route.py +35 -0
- agents/task/sqlite_session_registry.py +261 -0
- agents/task/surface_config.py +185 -0
- agents/task/telemetry/__init__.py +58 -0
- agents/task/telemetry/event_log.py +180 -0
- agents/task/telemetry/formatters.py +642 -0
- agents/task/telemetry/manager.py +571 -0
- agents/task/telemetry/memory_events.py +66 -0
- agents/task/telemetry/self_events.py +53 -0
- agents/task/telemetry/sequence.py +160 -0
- agents/task/telemetry/service.py +1265 -0
- agents/task/telemetry/views.py +882 -0
- agents/task/templates.py +98 -0
- agents/task/test_aux_chain.py +151 -0
- agents/task/test_aux_router.py +41 -0
- agents/task/tests/test_parse_robustness.py +170 -0
- agents/task/tool_defaults.py +110 -0
- agents/task/utils.py +762 -0
- agents/task/utils_json.py +768 -0
- agents/task/utils_webview.py +86 -0
- agents/task/workspace_context.py +229 -0
- agents/task_agent_lite.py +2398 -0
- api/README.md +683 -0
- api/TASK_API_DOCS.md +151 -0
- api/__init__.py +0 -0
- api/a2a/__init__.py +37 -0
- api/a2a/agent_card.py +337 -0
- api/a2a/client.py +657 -0
- api/a2a/endpoints.py +375 -0
- api/a2a/models.py +268 -0
- api/a2a/streaming.py +419 -0
- api/a2a/task_handler.py +929 -0
- api/admin_endpoints.py +1584 -0
- api/app.py +923 -0
- api/auth_constants.py +28 -0
- api/auth_endpoints.py +402 -0
- api/auth_state.py +36 -0
- api/chat_via_task.py +42 -0
- api/conversation_manager.py +231 -0
- api/dependencies.py +186 -0
- api/eip8004_endpoints.py +452 -0
- api/hyperliquid_models.py +174 -0
- api/hyperliquid_routes.py +450 -0
- api/interfaces.py +207 -0
- api/jwt_middleware.py +83 -0
- api/kb/__init__.py +1 -0
- api/kb/endpoints.py +314 -0
- api/mcp_models.py +279 -0
- api/mcp_routes.py +438 -0
- api/middleware.py +526 -0
- api/models.py +176 -0
- api/openai_compat/__init__.py +0 -0
- api/openai_compat/model_map.py +25 -0
- api/openai_compat/models.py +59 -0
- api/openai_compat/router.py +140 -0
- api/payment_endpoints.py +444 -0
- api/payment_verification.py +138 -0
- api/polymarket_models.py +155 -0
- api/polymarket_routes.py +501 -0
- api/pricing_endpoints.py +89 -0
- api/session_routing.py +54 -0
- api/skill_endpoints.py +453 -0
- api/task_http_api.py +1856 -0
- api/webhooks.py +52 -0
- api/x402_endpoints.py +280 -0
- avatar/README.md +44 -0
- avatar/__init__.py +1 -0
- avatar/config/rob.json +7 -0
- avatar/mindprint.js +395 -0
- avatar/renders/rob.meta.json +20 -0
- avatar/renders/rob.png +0 -0
- avatar/studio.html +373 -0
- avatar/webview/avatar-live.js +44 -0
- cli/README.md +89 -0
- cli/__init__.py +0 -0
- cli/cli_surface.py +67 -0
- cli/commands/__init__.py +0 -0
- cli/commands/_bootstrap.py +49 -0
- cli/commands/_errors.py +53 -0
- cli/commands/chat.py +973 -0
- cli/commands/config.py +100 -0
- cli/commands/dashboard.py +103 -0
- cli/commands/doctor.py +222 -0
- cli/commands/email.py +174 -0
- cli/commands/gateway.py +346 -0
- cli/commands/goals.py +509 -0
- cli/commands/init.py +276 -0
- cli/commands/journey.py +30 -0
- cli/commands/kb.py +280 -0
- cli/commands/model.py +107 -0
- cli/commands/owner.py +431 -0
- cli/commands/pfp.py +232 -0
- cli/commands/run.py +414 -0
- cli/commands/serve.py +41 -0
- cli/commands/session.py +684 -0
- cli/commands/skill_install.py +786 -0
- cli/commands/skills.py +128 -0
- cli/commands/subagents.py +100 -0
- cli/commands/surface.py +81 -0
- cli/commands/telegram.py +185 -0
- cli/commands/todos.py +209 -0
- cli/commands/tools.py +102 -0
- cli/commands/update.py +316 -0
- cli/commands/whatsapp.py +175 -0
- cli/config_store.py +276 -0
- cli/gitignore.py +43 -0
- cli/inventory.py +46 -0
- cli/keys.py +101 -0
- cli/persona.py +17 -0
- cli/polyrob.py +137 -0
- cli/ui/__init__.py +64 -0
- cli/ui/activity.py +141 -0
- cli/ui/app.py +538 -0
- cli/ui/banner.py +233 -0
- cli/ui/blocks.py +534 -0
- cli/ui/bootstrap_notice.py +47 -0
- cli/ui/commands/__init__.py +41 -0
- cli/ui/commands/h_cron.py +64 -0
- cli/ui/commands/h_journey.py +164 -0
- cli/ui/commands/h_kb.py +121 -0
- cli/ui/commands/h_learn.py +100 -0
- cli/ui/commands/h_mcp.py +215 -0
- cli/ui/commands/h_self.py +113 -0
- cli/ui/commands/h_skills.py +314 -0
- cli/ui/commands/handlers.py +1672 -0
- cli/ui/commands/registry.py +426 -0
- cli/ui/dialog.py +425 -0
- cli/ui/event_registry.py +110 -0
- cli/ui/event_specs.py +45 -0
- cli/ui/events.py +433 -0
- cli/ui/identity.py +15 -0
- cli/ui/lifecycle.py +159 -0
- cli/ui/live_hooks.py +43 -0
- cli/ui/model_selector.py +532 -0
- cli/ui/persistent_loop.py +181 -0
- cli/ui/pick.py +113 -0
- cli/ui/plain_renderer.py +351 -0
- cli/ui/renderer.py +384 -0
- cli/ui/rich_renderer.py +533 -0
- cli/ui/secrets.py +115 -0
- cli/ui/state.py +376 -0
- cli/ui/statusbar.py +231 -0
- cli/ui/streaming.py +254 -0
- cli/ui/terminal_render.py +105 -0
- cli/ui/theme.py +132 -0
- cli/update/__init__.py +6 -0
- cli/update/context.py +121 -0
- cli/update/detect.py +176 -0
- cli/update/engine.py +95 -0
- cli/update/migrate_guarded.py +55 -0
- cli/update/process_guard.py +215 -0
- cli/update/runners.py +78 -0
- cli/update/snapshot.py +270 -0
- cli/update/versions.py +205 -0
- core/README.md +377 -0
- core/__init__.py +174 -0
- core/assets.py +87 -0
- core/async_bridge.py +76 -0
- core/autonomy_runtime.py +259 -0
- core/base_component.py +302 -0
- core/bootstrap.py +681 -0
- core/bot.py +310 -0
- core/config.py +833 -0
- core/constants.py +126 -0
- core/container.py +462 -0
- core/db_manifest.py +101 -0
- core/embedding.py +57 -0
- core/env.py +39 -0
- core/exceptions.py +287 -0
- core/flags.py +144 -0
- core/flags_catalog.py +345 -0
- core/home_migration.py +62 -0
- core/identity.py +118 -0
- core/initialization.py +1004 -0
- core/instance.py +537 -0
- core/interactive_gate.py +96 -0
- core/logging.py +436 -0
- core/owner_doc_writer.py +176 -0
- core/pairing.py +193 -0
- core/path_safety.py +20 -0
- core/paths.py +27 -0
- core/payment_config.py +21 -0
- core/permissions.py +322 -0
- core/runtime_config.py +96 -0
- core/runtime_paths.py +135 -0
- core/seams.py +35 -0
- core/secret_scan.py +25 -0
- core/secret_scrub.py +71 -0
- core/secrets.py +35 -0
- core/security_logging_filter.py +148 -0
- core/self_context_writer.py +333 -0
- core/self_evolution.py +294 -0
- core/session_context.py +47 -0
- core/sqlite_util.py +59 -0
- core/surfaces/__init__.py +16 -0
- core/surfaces/access.py +118 -0
- core/surfaces/binding.py +88 -0
- core/surfaces/bootstrap.py +78 -0
- core/surfaces/circuit.py +168 -0
- core/surfaces/continuity.py +77 -0
- core/surfaces/correspondents.py +228 -0
- core/surfaces/dispatcher.py +216 -0
- core/surfaces/envelopes.py +75 -0
- core/surfaces/gc.py +30 -0
- core/surfaces/idempotency.py +57 -0
- core/surfaces/inbound_webhook.py +124 -0
- core/surfaces/media.py +32 -0
- core/surfaces/message_router.py +91 -0
- core/surfaces/outbound_allowlist.py +80 -0
- core/surfaces/outbound_dispatcher.py +110 -0
- core/surfaces/outbound_mirror.py +37 -0
- core/surfaces/outbound_queue.py +107 -0
- core/surfaces/outbound_target.py +12 -0
- core/surfaces/owner_admin.py +29 -0
- core/surfaces/proactive.py +78 -0
- core/surfaces/progress.py +108 -0
- core/surfaces/rate_bucket.py +21 -0
- core/surfaces/registry.py +51 -0
- core/surfaces/rendering.py +53 -0
- core/surfaces/send_policy.py +14 -0
- core/surfaces/serialize.py +24 -0
- core/surfaces/session_chat_registry.py +112 -0
- core/surfaces/session_policy.py +60 -0
- core/surfaces/surface.py +288 -0
- core/surfaces/transcription.py +88 -0
- core/surfaces/voice_echo.py +26 -0
- core/surfaces/voice_guard.py +23 -0
- core/tickers.py +174 -0
- core/tool_catalog.py +192 -0
- core/version.py +75 -0
- core/wallet/__init__.py +5 -0
- core/wallet/agent_wallet.py +59 -0
- core/wallet/audit_sink.py +61 -0
- core/wallet/config.py +70 -0
- core/wallet/factory.py +87 -0
- core/wallet/policy.py +104 -0
- core/wallet/signer.py +51 -0
- cron/README.md +65 -0
- cron/__init__.py +0 -0
- cron/delivery.py +277 -0
- cron/digest.py +124 -0
- cron/jobs.py +207 -0
- cron/runner.py +297 -0
- cron/schedule.py +194 -0
- cron/scheduler.py +201 -0
- cron/service.py +57 -0
- cron/wake_gate.py +223 -0
- data/__init__.py +1 -0
- data/prompts/autov2_prompts.json +87 -0
- data/prompts/skills/browser-automation/SKILL.md +43 -0
- data/prompts/skills/coding-workflow/SKILL.md +36 -0
- data/prompts/skills/crypto-trading-safety/SKILL.md +53 -0
- data/prompts/skills/document-writing/SKILL.md +33 -0
- data/prompts/skills/email-comms/SKILL.md +33 -0
- data/prompts/skills/file-data-ops/SKILL.md +35 -0
- data/prompts/skills/hyperliquid-account-review/SKILL.md +48 -0
- data/prompts/skills/hyperliquid-market-data/SKILL.md +52 -0
- data/prompts/skills/hyperliquid-trading/SKILL.md +59 -0
- data/prompts/skills/lead-research/SKILL.md +86 -0
- data/prompts/skills/market-research-brief/SKILL.md +104 -0
- data/prompts/skills/person-analyzer/SKILL.md +124 -0
- data/prompts/skills/polymarket-market-research/SKILL.md +54 -0
- data/prompts/skills/polymarket-portfolio-review/SKILL.md +50 -0
- data/prompts/skills/polymarket-trading/SKILL.md +55 -0
- data/prompts/skills/presentation-creator/SKILL.md +36 -0
- data/prompts/skills/project-analyzer/SKILL.md +169 -0
- data/prompts/skills/rules.json +268 -0
- data/prompts/skills/secret-handling/SKILL.md +20 -0
- data/prompts/skills/skill-authoring/SKILL.md +31 -0
- data/prompts/skills/skill-security-review/SKILL.md +27 -0
- data/prompts/skills/social-discovery/SKILL.md +57 -0
- data/prompts/skills/task-planning/SKILL.md +33 -0
- data/prompts/skills/web-research/SKILL.md +39 -0
- data/prompts/skills/web-scraping/SKILL.md +73 -0
- data/prompts/skills/x-engagement/SKILL.md +69 -0
- data/prompts/system_prompts.json +4 -0
- data/subscription_channels.json +5 -0
- modules/README.md +503 -0
- modules/__init__.py +124 -0
- modules/auth/__init__.py +13 -0
- modules/auth/api_key_manager.py +157 -0
- modules/auth/identity_mapper.py +380 -0
- modules/auth/siwe_auth.py +273 -0
- modules/auth/tier_manager.py +173 -0
- modules/base_module.py +190 -0
- modules/credits/__init__.py +29 -0
- modules/credits/balance_manager.py +237 -0
- modules/credits/cost_utils.py +129 -0
- modules/credits/pricing.py +139 -0
- modules/credits/unified_ledger.py +148 -0
- modules/credits/usage_meter.py +310 -0
- modules/credits/usage_tracker.py +674 -0
- modules/database/__init__.py +33 -0
- modules/database/audit_log.py +322 -0
- modules/database/auth_tables.py +276 -0
- modules/database/connection.py +644 -0
- modules/database/connection_pool.py +305 -0
- modules/database/conversation_contexts.py +446 -0
- modules/database/database_manager.py +237 -0
- modules/database/hyperliquid.py +375 -0
- modules/database/polymarket.py +574 -0
- modules/database/user_mcp_servers.py +728 -0
- modules/database/user_profiles.py +562 -0
- modules/database/utils.py +107 -0
- modules/database/x402_tables.py +92 -0
- modules/eip8004/README.md +1069 -0
- modules/eip8004/__init__.py +65 -0
- modules/eip8004/contracts.py +498 -0
- modules/eip8004/models.py +271 -0
- modules/eip8004/registration.py +148 -0
- modules/eip8004/reputation.py +367 -0
- modules/eip8004/validation.py +277 -0
- modules/llm/__init__.py +97 -0
- modules/llm/adapters.py +963 -0
- modules/llm/anthropic_client.py +831 -0
- modules/llm/available_models.py +106 -0
- modules/llm/brain_scrubber.py +137 -0
- modules/llm/cache_hints.py +162 -0
- modules/llm/deepseek_client.py +562 -0
- modules/llm/gemini_client.py +1367 -0
- modules/llm/llm_client.py +1139 -0
- modules/llm/llm_client_registry.py +188 -0
- modules/llm/llm_factory.py +237 -0
- modules/llm/llm_manager.py +1036 -0
- modules/llm/messages.py +374 -0
- modules/llm/model_registry.py +1935 -0
- modules/llm/nvidia_client.py +125 -0
- modules/llm/openai_client.py +800 -0
- modules/llm/openrouter_client.py +969 -0
- modules/llm/profiles.py +178 -0
- modules/llm/test_anthropic_cache_capture.py +35 -0
- modules/llm/test_cached_pricing_derivation.py +24 -0
- modules/llm/think_scrubber.py +444 -0
- modules/llm/token_counter.py +268 -0
- modules/memory/__init__.py +35 -0
- modules/memory/backend_factory.py +83 -0
- modules/memory/cache_manager.py +186 -0
- modules/memory/episodic.py +108 -0
- modules/memory/local_vector_memory_provider.py +552 -0
- modules/memory/memory_manager.py +225 -0
- modules/memory/models.py +312 -0
- modules/memory/provider.py +210 -0
- modules/memory/registry.py +205 -0
- modules/memory/sqlite_memory_provider.py +767 -0
- modules/memory/task/__init__.py +52 -0
- modules/memory/task/compaction_manager.py +157 -0
- modules/memory/task/context_retriever.py +809 -0
- modules/memory/task/hierarchical_memory.py +1002 -0
- modules/memory/task/lexical_retriever.py +71 -0
- modules/memory/task/null_context_manager.py +213 -0
- modules/memory/task/phase_manager.py +625 -0
- modules/memory/task/reflection_service.py +157 -0
- modules/memory/task/semantic_retriever.py +218 -0
- modules/memory/task/task_context_manager.py +1165 -0
- modules/memory/task/test_forgetting_engages.py +24 -0
- modules/memory/task/test_reflection_llm.py +39 -0
- modules/memory/task/test_threat_scan.py +53 -0
- modules/memory/task/threat_scan.py +90 -0
- modules/memory/test_sqlite_memory_provider.py +106 -0
- modules/memory/user_profile_manager.py +527 -0
- modules/payments/__init__.py +11 -0
- modules/payments/deposit_monitor.py +478 -0
- modules/payments/price_oracle.py +70 -0
- modules/payments/treasury_sweeper.py +401 -0
- modules/payments/wallet_generator.py +145 -0
- modules/pfp/__init__.py +1 -0
- modules/pfp/config.py +92 -0
- modules/pfp/mesh.py +565 -0
- modules/pfp/push.py +69 -0
- modules/pfp/renderer.py +85 -0
- modules/pfp/store.py +82 -0
- modules/skills/__init__.py +1 -0
- modules/skills/skill_usage.py +248 -0
- modules/transcription/__init__.py +24 -0
- modules/transcription/base.py +20 -0
- modules/transcription/faster_whisper_transcriber.py +55 -0
- modules/x402/README.md +249 -0
- modules/x402/__init__.py +22 -0
- modules/x402/invoicing.py +416 -0
- modules/x402/middleware.py +364 -0
- modules/x402/settlement_watcher.py +145 -0
- modules/x402/x402_integration.py +344 -0
- polyrob-0.5.0.dist-info/METADATA +482 -0
- polyrob-0.5.0.dist-info/RECORD +745 -0
- polyrob-0.5.0.dist-info/WHEEL +5 -0
- polyrob-0.5.0.dist-info/entry_points.txt +2 -0
- polyrob-0.5.0.dist-info/licenses/LICENSE +21 -0
- polyrob-0.5.0.dist-info/top_level.txt +12 -0
- surfaces/README.md +70 -0
- surfaces/__init__.py +0 -0
- surfaces/email/__init__.py +0 -0
- surfaces/email/dedup.py +44 -0
- surfaces/email/harness.py +187 -0
- surfaces/email/inbound.py +159 -0
- surfaces/email/seed.py +60 -0
- surfaces/email/surface.py +105 -0
- surfaces/telegram/__init__.py +0 -0
- surfaces/telegram/dedup.py +83 -0
- surfaces/telegram/harness.py +886 -0
- surfaces/telegram/inbound.py +145 -0
- surfaces/telegram/interactive_tools.py +49 -0
- surfaces/telegram/markdown.py +347 -0
- surfaces/telegram/rate_limit.py +167 -0
- surfaces/telegram/surface.py +187 -0
- surfaces/telegram/voice.py +52 -0
- surfaces/whatsapp/__init__.py +0 -0
- surfaces/whatsapp/client.py +51 -0
- surfaces/whatsapp/harness.py +62 -0
- surfaces/whatsapp/inbound.py +132 -0
- surfaces/whatsapp/surface.py +64 -0
- surfaces/whatsapp/window.py +34 -0
- tools/README.md +578 -0
- tools/__init__.py +424 -0
- tools/alchemy/__init__.py +5 -0
- tools/alchemy/alchemy_tool.py +389 -0
- tools/anysite/__init__.py +17 -0
- tools/anysite/client.py +88 -0
- tools/anysite/tool.py +89 -0
- tools/base_tool.py +468 -0
- tools/browser/__init__.py +22 -0
- tools/browser/actions.py +118 -0
- tools/browser/browser.py +1457 -0
- tools/browser/browser_manager.py +690 -0
- tools/browser/context.py +1748 -0
- tools/browser/playwright_utils.py +137 -0
- tools/browser/views.py +56 -0
- tools/code_exec/SANDBOX_SECURITY.md +144 -0
- tools/code_exec/__init__.py +178 -0
- tools/code_exec/backend.py +73 -0
- tools/code_exec/backends/__init__.py +1 -0
- tools/code_exec/backends/docker.py +779 -0
- tools/code_exec/backends/local_subprocess.py +154 -0
- tools/code_exec/env_policy.py +45 -0
- tools/code_exec/result.py +42 -0
- tools/code_exec/sandbox_guard.py +59 -0
- tools/code_exec/tool.py +227 -0
- tools/coding/__init__.py +50 -0
- tools/coding/edit.py +107 -0
- tools/coding/search.py +113 -0
- tools/coding/tool.py +353 -0
- tools/collabland/__init__.py +5 -0
- tools/collabland/collabland_tool.py +471 -0
- tools/controller/__init__.py +0 -0
- tools/controller/_helpers.py +165 -0
- tools/controller/action_registration.py +1765 -0
- tools/controller/approval.py +244 -0
- tools/controller/approval_interactive.py +90 -0
- tools/controller/delegation.py +195 -0
- tools/controller/execution.py +797 -0
- tools/controller/execution_context.py +141 -0
- tools/controller/hooks.py +135 -0
- tools/controller/introspection.py +344 -0
- tools/controller/mcp_registrar.py +190 -0
- tools/controller/message_send.py +31 -0
- tools/controller/registry/__init__.py +4 -0
- tools/controller/registry/schema_generators.py +395 -0
- tools/controller/registry/schema_sanitizer.py +406 -0
- tools/controller/registry/service.py +1266 -0
- tools/controller/registry/views.py +151 -0
- tools/controller/service.py +409 -0
- tools/controller/tool_management.py +334 -0
- tools/controller/types.py +28 -0
- tools/controller/views.py +450 -0
- tools/cronjob_tools.py +166 -0
- tools/crypto_trade_gate.py +59 -0
- tools/descriptors.py +452 -0
- tools/dom/__init__.py +0 -0
- tools/dom/history_tree_processor/service.py +244 -0
- tools/dom/history_tree_processor/view.py +99 -0
- tools/dom/service.py +471 -0
- tools/dom/views.py +346 -0
- tools/email_tool.py +403 -0
- tools/exceptions.py +169 -0
- tools/filesystem.py +1038 -0
- tools/filesystem_docproc.py +331 -0
- tools/filesystem_pdf.py +755 -0
- tools/git/__init__.py +42 -0
- tools/git/tool.py +258 -0
- tools/github/__init__.py +33 -0
- tools/github/client.py +94 -0
- tools/github/tool.py +237 -0
- tools/goal_tools.py +309 -0
- tools/hyperliquid/__init__.py +56 -0
- tools/hyperliquid/models.py +233 -0
- tools/hyperliquid/service.py +1680 -0
- tools/knowledge_ingest.py +950 -0
- tools/mcp/README.md +535 -0
- tools/mcp/__init__.py +52 -0
- tools/mcp/catalog.py +115 -0
- tools/mcp/config.py +337 -0
- tools/mcp/mcp_tool.py +1415 -0
- tools/mcp/param_coercion.py +289 -0
- tools/mcp/protocol.py +1520 -0
- tools/mcp/rate_limit.py +50 -0
- tools/mcp/security.py +424 -0
- tools/mcp/self_install.py +111 -0
- tools/mcp/server_manager.py +829 -0
- tools/mcp/subscriptions.py +72 -0
- tools/mcp/user_mcp_service.py +899 -0
- tools/mcp/validation_tracker.py +89 -0
- tools/mcp/views.py +346 -0
- tools/oauth/__init__.py +17 -0
- tools/oauth/manager.py +75 -0
- tools/oauth/provider.py +69 -0
- tools/oauth/providers/__init__.py +1 -0
- tools/oauth/providers/generic_oauth2.py +96 -0
- tools/perplexity_tool.py +280 -0
- tools/polymarket/__init__.py +41 -0
- tools/polymarket/clob_adapter.py +76 -0
- tools/polymarket/models.py +182 -0
- tools/polymarket/service.py +2082 -0
- tools/self_env/__init__.py +61 -0
- tools/self_env/tool.py +274 -0
- tools/shell/__init__.py +80 -0
- tools/shell/backend_pool.py +118 -0
- tools/shell/discipline.py +62 -0
- tools/shell/executor.py +157 -0
- tools/shell/loopback_allow.py +87 -0
- tools/shell/process_registry.py +113 -0
- tools/shell/process_tool.py +131 -0
- tools/shell/state.py +129 -0
- tools/shell/tool.py +151 -0
- tools/task_tool.py +637 -0
- tools/twitter_tool.py +2086 -0
- tools/user_directory.py +179 -0
- tools/web_fetch/__init__.py +3 -0
- tools/web_fetch/fetcher.py +144 -0
- tools/web_fetch/render.py +44 -0
- tools/web_fetch/tool.py +60 -0
- tools/x402/__init__.py +60 -0
- tools/x402/client.py +47 -0
- tools/x402/invoice_tool.py +143 -0
- tools/x402/real_client.py +250 -0
- tools/x402/service.py +131 -0
- utils/README.md +498 -0
- utils/__init__.py +46 -0
- utils/auth_utils.py +114 -0
- utils/bounded_collections.py +162 -0
- utils/circuit_breaker.py +389 -0
- utils/gif_utils.py +435 -0
- utils/markdown_utils.py +291 -0
- utils/message_utils.py +147 -0
- utils/metrics.py +36 -0
- utils/path_validator.py +227 -0
- utils/rate_limit_manager.py +399 -0
- utils/result_size.py +296 -0
- utils/time_utils.py +206 -0
- utils/user_utils.py +188 -0
- webview/README.md +111 -0
- webview/RENAME_AND_ALIGN_HANDOFF.md +200 -0
- webview/__init__.py +8 -0
- webview/activity.py +636 -0
- webview/owner_auth.py +108 -0
- webview/pages.py +448 -0
- webview/repair_sessions.py +399 -0
- webview/server.py +4323 -0
- webview/server_launcher.py +112 -0
- webview/static/css/activity.css +89 -0
- webview/static/css/chat.css +1772 -0
- webview/static/css/components.css +1190 -0
- webview/static/css/config-panel.css +651 -0
- webview/static/css/pages/admin.css +766 -0
- webview/static/css/pages/profile.css +231 -0
- webview/static/css/pages/settings.css +297 -0
- webview/static/css/pages/signin.css +316 -0
- webview/static/css/style.css +4250 -0
- webview/static/css/variables.css +147 -0
- webview/static/css/workspace-fullwidth-fix.css +109 -0
- webview/static/img/favicon.ico +0 -0
- webview/static/js/activity.js +394 -0
- webview/static/js/admin/activity.js +186 -0
- webview/static/js/admin/dashboard.js +163 -0
- webview/static/js/admin/user_detail.js +400 -0
- webview/static/js/admin/users.js +174 -0
- webview/static/js/admin/utils.js +214 -0
- webview/static/js/chat.js +3178 -0
- webview/static/js/config-panel.js +522 -0
- webview/static/js/constants.js +20 -0
- webview/static/js/error-handler.js +226 -0
- webview/static/js/ethers.min.js +1 -0
- webview/static/js/event-filter.js +137 -0
- webview/static/js/event-store.js +351 -0
- webview/static/js/file-attachments.js +374 -0
- webview/static/js/file-loader.js +163 -0
- webview/static/js/index.js +103 -0
- webview/static/js/performance-utils.js +196 -0
- webview/static/js/profile.js +396 -0
- webview/static/js/screenshot.js +386 -0
- webview/static/js/session.js +1527 -0
- webview/static/js/settings.js +1288 -0
- webview/static/js/sidebar-data.js +766 -0
- webview/static/js/sidebar-toggle.js +296 -0
- webview/static/js/socket.io.min.js +7 -0
- webview/static/js/stats.js +355 -0
- webview/static/js/ui-utils.js +420 -0
- webview/static/js/workspace.js +966 -0
- webview/stats_service.py +613 -0
- webview/templates/__init__.py +1 -0
- webview/templates/__pycache__/__init__.cpython-311.pyc +0 -0
- webview/templates/activity.html +36 -0
- webview/templates/admin/activity.html +122 -0
- webview/templates/admin/dashboard.html +112 -0
- webview/templates/admin/user_detail.html +228 -0
- webview/templates/admin/users.html +105 -0
- webview/templates/autonomy.html +60 -0
- webview/templates/error.html +133 -0
- webview/templates/finance.html +90 -0
- webview/templates/identity.html +73 -0
- webview/templates/index.html +42 -0
- webview/templates/layout.html +125 -0
- webview/templates/memory.html +59 -0
- webview/templates/owner_login.html +15 -0
- webview/templates/profile.html +121 -0
- webview/templates/session.html +312 -0
- webview/templates/settings.html +534 -0
- webview/templates/sidebar.html +112 -0
- webview/templates/signin.html +213 -0
- webview/templates/status.html +14 -0
- webview/templates/system.html +45 -0
- webview/webgate.py +196 -0
|
@@ -0,0 +1,2082 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Polymarket Tool - Direct API Integration.
|
|
3
|
+
|
|
4
|
+
Provides direct integration with Polymarket APIs (Gamma + CLOB)
|
|
5
|
+
using native Python API calls.
|
|
6
|
+
|
|
7
|
+
Architecture:
|
|
8
|
+
- Uses httpx for async HTTP requests
|
|
9
|
+
- Direct Gamma API integration for market data
|
|
10
|
+
- Direct CLOB API integration for trading (via py-clob-client)
|
|
11
|
+
- Reuses existing credential storage (PolymarketDBHandler)
|
|
12
|
+
|
|
13
|
+
Usage by agents:
|
|
14
|
+
Tool action: polymarket.search_markets(query="...")
|
|
15
|
+
|
|
16
|
+
Agents can call actions directly on this tool.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
import time
|
|
21
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from datetime import datetime, timedelta
|
|
24
|
+
from enum import Enum
|
|
25
|
+
from pydantic import BaseModel, Field
|
|
26
|
+
|
|
27
|
+
import httpx
|
|
28
|
+
|
|
29
|
+
# Authenticated CLOB trading client — sourced from the single adapter seam so a
|
|
30
|
+
# missing/incompatible client is a LOUD, typed failure instead of a silent read-only
|
|
31
|
+
# degrade. The legacy py-clob-client is archived/non-functional; clob_adapter imports
|
|
32
|
+
# the maintained py-clob-client-v2 only.
|
|
33
|
+
from tools.polymarket.clob_adapter import (
|
|
34
|
+
ClobClient,
|
|
35
|
+
ApiCreds,
|
|
36
|
+
OrderArgs,
|
|
37
|
+
OrderType,
|
|
38
|
+
CLOB_AVAILABLE,
|
|
39
|
+
trade_capability,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
# Back-compat alias (some call sites/tests referenced the old flag name).
|
|
43
|
+
CLOB_CLIENT_AVAILABLE = CLOB_AVAILABLE
|
|
44
|
+
|
|
45
|
+
from tools.base_tool import BaseTool, ToolStatus
|
|
46
|
+
from tools.polymarket.models import (
|
|
47
|
+
TradingLimits,
|
|
48
|
+
PolymarketCredentials,
|
|
49
|
+
ExecutionResult,
|
|
50
|
+
ApiCredentials,
|
|
51
|
+
POLYGON_MAINNET,
|
|
52
|
+
SIGNATURE_TYPE_PROXY,
|
|
53
|
+
MIN_ORDER_VALUE_USD,
|
|
54
|
+
)
|
|
55
|
+
from modules.database.polymarket import PolymarketDBHandler
|
|
56
|
+
from core.logging import get_component_logger
|
|
57
|
+
from core.exceptions import ToolError
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# =============================================================================
|
|
61
|
+
# PARAMETER MODELS
|
|
62
|
+
# =============================================================================
|
|
63
|
+
|
|
64
|
+
class SearchMarketsParams(BaseModel):
|
|
65
|
+
"""Parameters for market search."""
|
|
66
|
+
query: str = Field(..., description="Search query string")
|
|
67
|
+
category: Optional[str] = Field(None, description="Category filter (e.g., 'politics', 'sports', 'crypto')")
|
|
68
|
+
limit: int = Field(10, ge=1, le=100, description="Maximum results to return")
|
|
69
|
+
active_only: bool = Field(True, description="Only return active markets")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class TrendingMarketsParams(BaseModel):
|
|
73
|
+
"""Parameters for trending markets."""
|
|
74
|
+
limit: int = Field(10, ge=1, le=50, description="Maximum results to return")
|
|
75
|
+
category: Optional[str] = Field(None, description="Optional category filter")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class MarketDetailsParams(BaseModel):
|
|
79
|
+
"""Parameters for market details."""
|
|
80
|
+
market_id: str = Field(..., description="Market slug (e.g., 'will-trump-win-2024') or condition ID (0x...). Use slug from search results.")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class GetPriceParams(BaseModel):
|
|
84
|
+
"""Parameters for current price."""
|
|
85
|
+
token_id: str = Field(..., description="Token ID to get price for")
|
|
86
|
+
market_id: Optional[str] = Field(None, description="Market ID for fallback pricing")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class GetOrderbookParams(BaseModel):
|
|
90
|
+
"""Parameters for orderbook."""
|
|
91
|
+
token_id: str = Field(..., description="Token ID")
|
|
92
|
+
depth: int = Field(10, ge=1, le=100, description="Orderbook depth")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class GetSpreadParams(BaseModel):
|
|
96
|
+
"""Parameters for spread calculation."""
|
|
97
|
+
token_id: str = Field(..., description="Token ID")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class GetVolumeParams(BaseModel):
|
|
101
|
+
"""Parameters for market volume."""
|
|
102
|
+
market_id: str = Field(..., description="Market slug (e.g., 'will-trump-win-2024') from search results")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class GetPositionsParams(BaseModel):
|
|
106
|
+
"""Parameters for positions."""
|
|
107
|
+
include_closed: bool = Field(False, description="Include closed positions")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class PortfolioSummaryParams(BaseModel):
|
|
111
|
+
"""Parameters for portfolio summary."""
|
|
112
|
+
include_positions: bool = Field(True, description="Include position details")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class GetBalanceParams(BaseModel):
|
|
116
|
+
"""Parameters for balance check."""
|
|
117
|
+
pass # No parameters needed, uses authenticated user's wallet
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class GetTradeHistoryParams(BaseModel):
|
|
121
|
+
"""Parameters for trade history."""
|
|
122
|
+
limit: int = Field(50, ge=1, le=500, description="Maximum trades to return")
|
|
123
|
+
market_id: Optional[str] = Field(None, description="Filter by market ID")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class PlaceLimitOrderParams(BaseModel):
|
|
127
|
+
"""Parameters for limit order placement."""
|
|
128
|
+
market_id: str = Field(..., description="Market slug or condition ID (use slug from search results)")
|
|
129
|
+
token_id: str = Field(..., description="Token ID from market outcomes (e.g., '123456789...')")
|
|
130
|
+
side: str = Field(..., description="BUY or SELL")
|
|
131
|
+
price: float = Field(..., ge=0.01, le=0.99, description="Limit price (0.01-0.99)")
|
|
132
|
+
size_usd: float = Field(..., ge=1, description="Order size in USD")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class PlaceMarketOrderParams(BaseModel):
|
|
136
|
+
"""Parameters for market order placement."""
|
|
137
|
+
market_id: str = Field(..., description="Market slug or condition ID (use slug from search results)")
|
|
138
|
+
token_id: str = Field(..., description="Token ID from market outcomes (e.g., '123456789...')")
|
|
139
|
+
side: str = Field(..., description="BUY or SELL")
|
|
140
|
+
size_usd: float = Field(..., ge=1, description="Order size in USD")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class CancelOrderParams(BaseModel):
|
|
144
|
+
"""Parameters for order cancellation."""
|
|
145
|
+
order_id: str = Field(..., description="Order ID to cancel")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class CancelAllOrdersParams(BaseModel):
|
|
149
|
+
"""Parameters for canceling all orders."""
|
|
150
|
+
market_id: Optional[str] = Field(None, description="Cancel only orders in this market")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class GetOpenOrdersParams(BaseModel):
|
|
154
|
+
"""Parameters for open orders."""
|
|
155
|
+
market_id: Optional[str] = Field(None, description="Filter by market ID")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class GetOrderHistoryParams(BaseModel):
|
|
159
|
+
"""Parameters for order history."""
|
|
160
|
+
limit: int = Field(50, ge=1, le=500, description="Maximum orders to return")
|
|
161
|
+
status: Optional[str] = Field(None, description="Filter by status (filled, cancelled, etc.)")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class FilterByCategoryParams(BaseModel):
|
|
165
|
+
"""Parameters for category filtering."""
|
|
166
|
+
category: str = Field(..., description="Category slug")
|
|
167
|
+
limit: int = Field(10, ge=1, le=100, description="Maximum results")
|
|
168
|
+
active_only: bool = Field(True, description="Only active markets")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class ClosingSoonParams(BaseModel):
|
|
172
|
+
"""Parameters for closing soon markets."""
|
|
173
|
+
hours: int = Field(24, ge=1, le=168, description="Hours until close")
|
|
174
|
+
limit: int = Field(10, ge=1, le=50, description="Maximum results")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class EmptyParams(BaseModel):
|
|
178
|
+
"""Empty parameters for parameterless actions."""
|
|
179
|
+
pass
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
# =============================================================================
|
|
183
|
+
# POLYMARKET SERVICE
|
|
184
|
+
# =============================================================================
|
|
185
|
+
|
|
186
|
+
class PolymarketTool(BaseTool):
|
|
187
|
+
"""
|
|
188
|
+
Direct Polymarket API integration tool.
|
|
189
|
+
|
|
190
|
+
Provides native Python API access to Polymarket's Gamma and CLOB APIs.
|
|
191
|
+
|
|
192
|
+
Tool Categories:
|
|
193
|
+
- Market Discovery: Search, trending, filtering (Gamma API)
|
|
194
|
+
- Market Data: Prices, orderbooks, volume (CLOB + Gamma API)
|
|
195
|
+
- Portfolio: Positions, P&L, history (CLOB API, requires auth)
|
|
196
|
+
- Trading: Orders, cancellations (CLOB API, requires auth)
|
|
197
|
+
"""
|
|
198
|
+
|
|
199
|
+
tool_id = "polymarket"
|
|
200
|
+
name = "polymarket"
|
|
201
|
+
description = "Polymarket prediction markets - trading and market data"
|
|
202
|
+
|
|
203
|
+
# API endpoints
|
|
204
|
+
GAMMA_API_URL = "https://gamma-api.polymarket.com"
|
|
205
|
+
CLOB_API_URL = "https://clob.polymarket.com"
|
|
206
|
+
# Public user-analytics API (positions/trades/leaderboards) — keyed by address,
|
|
207
|
+
# NO auth/signing required. Used for portfolio reads so they need no wallet.
|
|
208
|
+
DATA_API_URL = "https://data-api.polymarket.com"
|
|
209
|
+
|
|
210
|
+
def __init__(
|
|
211
|
+
self,
|
|
212
|
+
name: str = "polymarket",
|
|
213
|
+
config: Any = None,
|
|
214
|
+
container: Any = None,
|
|
215
|
+
db_handler: Optional[PolymarketDBHandler] = None
|
|
216
|
+
):
|
|
217
|
+
super().__init__(name=name, config=config, container=container)
|
|
218
|
+
self.db = db_handler
|
|
219
|
+
self._user_id: Optional[str] = None
|
|
220
|
+
self._credentials_cache: Dict[str, PolymarketCredentials] = {}
|
|
221
|
+
self._http_client: Optional[httpx.AsyncClient] = None
|
|
222
|
+
|
|
223
|
+
# CLOB client cache per user (for authenticated operations)
|
|
224
|
+
self._clob_clients: Dict[str, ClobClient] = {}
|
|
225
|
+
|
|
226
|
+
# Tool discovery cache
|
|
227
|
+
self._tools_cache: Optional[List[Dict[str, Any]]] = None
|
|
228
|
+
|
|
229
|
+
self.logger = get_component_logger("PolymarketTool")
|
|
230
|
+
|
|
231
|
+
# Enable by default (no external API key needed for market data)
|
|
232
|
+
self._enabled = True
|
|
233
|
+
|
|
234
|
+
# Check if py-clob-client is available
|
|
235
|
+
if not CLOB_AVAILABLE:
|
|
236
|
+
self.logger.warning(
|
|
237
|
+
"polymarket trading client unavailable - trade actions disabled (%s)",
|
|
238
|
+
trade_capability()["install_hint"],
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
@property
|
|
242
|
+
def required_services(self) -> Dict[str, str]:
|
|
243
|
+
"""Get required services."""
|
|
244
|
+
return {
|
|
245
|
+
'rate_limit_manager': 'Rate limit management for API calls'
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
@property
|
|
249
|
+
def optional_services(self) -> Dict[str, str]:
|
|
250
|
+
"""Get optional services."""
|
|
251
|
+
return {
|
|
252
|
+
'cache_manager': 'Cache for market data',
|
|
253
|
+
'database_manager': 'Database for credentials (via polymarket_db)'
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async def _initialize(self) -> None:
|
|
257
|
+
"""Initialize the service."""
|
|
258
|
+
await super()._initialize()
|
|
259
|
+
|
|
260
|
+
# Get or create DB handler
|
|
261
|
+
if not self.db and self.container:
|
|
262
|
+
self.db = self.container.get_service('polymarket_db')
|
|
263
|
+
if not self.db:
|
|
264
|
+
# Create it ourselves
|
|
265
|
+
db_manager = self.container.get_service('database_manager')
|
|
266
|
+
if db_manager:
|
|
267
|
+
from modules.database.polymarket import PolymarketDBHandler
|
|
268
|
+
self.db = PolymarketDBHandler(db_manager.connection)
|
|
269
|
+
# Register so API routes can access it
|
|
270
|
+
self.container.register_service('polymarket_db', self.db)
|
|
271
|
+
|
|
272
|
+
# Create HTTP client with connection pooling
|
|
273
|
+
self._http_client = httpx.AsyncClient(
|
|
274
|
+
timeout=httpx.Timeout(30.0, connect=10.0),
|
|
275
|
+
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
|
|
276
|
+
follow_redirects=True
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
# Ensure DB tables exist
|
|
280
|
+
if self.db:
|
|
281
|
+
await self.db.ensure_tables()
|
|
282
|
+
|
|
283
|
+
self._status = ToolStatus.HEALTHY
|
|
284
|
+
self.logger.info("PolymarketTool initialized (direct API integration)")
|
|
285
|
+
|
|
286
|
+
async def _cleanup(self) -> None:
|
|
287
|
+
"""Cleanup service resources."""
|
|
288
|
+
if self._http_client:
|
|
289
|
+
await self._http_client.aclose()
|
|
290
|
+
self._http_client = None
|
|
291
|
+
self._credentials_cache.clear()
|
|
292
|
+
self._status = ToolStatus.UNINITIALIZED
|
|
293
|
+
self.logger.info("PolymarketTool cleaned up")
|
|
294
|
+
|
|
295
|
+
def set_user_context(self, user_id: str) -> None:
|
|
296
|
+
"""Set current user for credential resolution."""
|
|
297
|
+
if user_id != self._user_id:
|
|
298
|
+
self._user_id = user_id
|
|
299
|
+
self.logger.debug(f"Polymarket user context set: {user_id}")
|
|
300
|
+
|
|
301
|
+
async def _get_user_credentials(self) -> Optional[PolymarketCredentials]:
|
|
302
|
+
"""Get current user's credentials."""
|
|
303
|
+
if not self._user_id:
|
|
304
|
+
return None
|
|
305
|
+
|
|
306
|
+
# Check cache first
|
|
307
|
+
if self._user_id in self._credentials_cache:
|
|
308
|
+
return self._credentials_cache[self._user_id]
|
|
309
|
+
|
|
310
|
+
# Fetch from database
|
|
311
|
+
if self.db:
|
|
312
|
+
credentials = await self.db.get_credentials(self._user_id)
|
|
313
|
+
if credentials:
|
|
314
|
+
self._credentials_cache[self._user_id] = credentials
|
|
315
|
+
return credentials
|
|
316
|
+
|
|
317
|
+
return None
|
|
318
|
+
|
|
319
|
+
def _check_trading_limits(
|
|
320
|
+
self,
|
|
321
|
+
limits: TradingLimits,
|
|
322
|
+
size_usd: float
|
|
323
|
+
) -> Optional[str]:
|
|
324
|
+
"""Check if order complies with trading limits."""
|
|
325
|
+
if size_usd > limits.max_order_size_usd:
|
|
326
|
+
return f"Order size ${size_usd:.2f} exceeds limit ${limits.max_order_size_usd}"
|
|
327
|
+
|
|
328
|
+
if not limits.enable_autonomous_trading:
|
|
329
|
+
return "Autonomous trading is disabled. Enable in Settings → Polymarket → Trading Limits"
|
|
330
|
+
|
|
331
|
+
return None
|
|
332
|
+
|
|
333
|
+
async def _check_position_limit(self, limits: TradingLimits, params) -> Optional[str]:
|
|
334
|
+
"""Enforce max_position_per_market_usd cumulatively (fail closed).
|
|
335
|
+
|
|
336
|
+
_check_trading_limits only bounds a SINGLE order against max_order_size_usd,
|
|
337
|
+
so N sequential sub-limit BUYs on the same market could exceed the per-market
|
|
338
|
+
cap the operator configured. Sum the current USD value of positions in the
|
|
339
|
+
target market and reject when existing + this order would exceed the cap.
|
|
340
|
+
Sell orders de-risk (Polymarket has no shorting) and are exempt. Fail CLOSED
|
|
341
|
+
if the position snapshot can't be fetched (don't open blind).
|
|
342
|
+
"""
|
|
343
|
+
cap = getattr(limits, "max_position_per_market_usd", None)
|
|
344
|
+
if not cap:
|
|
345
|
+
return None
|
|
346
|
+
if str(getattr(params, "side", "")).lower() == "sell":
|
|
347
|
+
return None # reducing exposure
|
|
348
|
+
market_id = getattr(params, "market_id", None)
|
|
349
|
+
if not market_id:
|
|
350
|
+
return None
|
|
351
|
+
res = await self.get_all_positions(GetPositionsParams(include_closed=False))
|
|
352
|
+
if not res.get("success"):
|
|
353
|
+
return "Cannot verify per-market position (position fetch failed); refusing to open"
|
|
354
|
+
existing = sum(
|
|
355
|
+
float(p.get("value", 0) or 0)
|
|
356
|
+
for p in res.get("positions", [])
|
|
357
|
+
if p.get("market_id") == market_id
|
|
358
|
+
)
|
|
359
|
+
projected = existing + float(getattr(params, "size_usd", 0) or 0)
|
|
360
|
+
if projected > cap:
|
|
361
|
+
return (
|
|
362
|
+
f"Per-market position cap ${cap:.2f} would be exceeded on {market_id} "
|
|
363
|
+
f"(existing ${existing:.2f} + ${float(getattr(params, 'size_usd', 0)):.2f})"
|
|
364
|
+
)
|
|
365
|
+
return None
|
|
366
|
+
|
|
367
|
+
# =========================================================================
|
|
368
|
+
# CLOB CLIENT MANAGEMENT
|
|
369
|
+
# =========================================================================
|
|
370
|
+
|
|
371
|
+
async def _get_clob_client(self) -> Optional[ClobClient]:
|
|
372
|
+
"""
|
|
373
|
+
Get authenticated CLOB client for current user with proxy wallet support.
|
|
374
|
+
|
|
375
|
+
Creates L1 client with private key, optionally adds L2 API credentials.
|
|
376
|
+
Supports proxy wallets for Polymarket website users (signature_type=2).
|
|
377
|
+
|
|
378
|
+
Returns None if user not authenticated or py-clob-client not available.
|
|
379
|
+
"""
|
|
380
|
+
if not CLOB_AVAILABLE:
|
|
381
|
+
return None
|
|
382
|
+
|
|
383
|
+
if not self._user_id:
|
|
384
|
+
return None
|
|
385
|
+
|
|
386
|
+
# Check cache first
|
|
387
|
+
if self._user_id in self._clob_clients:
|
|
388
|
+
return self._clob_clients[self._user_id]
|
|
389
|
+
|
|
390
|
+
credentials = await self._get_user_credentials()
|
|
391
|
+
if not credentials or credentials.demo_mode or not credentials.private_key:
|
|
392
|
+
return None
|
|
393
|
+
|
|
394
|
+
try:
|
|
395
|
+
# Build client arguments with proxy wallet support
|
|
396
|
+
client_args = {
|
|
397
|
+
"host": self.CLOB_API_URL,
|
|
398
|
+
"chain_id": credentials.chain_id,
|
|
399
|
+
"key": credentials.private_key,
|
|
400
|
+
"signature_type": credentials.signature_type, # 0=EOA, 1=Magic, 2=Proxy
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
# Set funder for proxy wallet users
|
|
404
|
+
# The funder is the address that holds the funds (proxy wallet if set)
|
|
405
|
+
if credentials.proxy_wallet_address:
|
|
406
|
+
client_args["funder"] = credentials.proxy_wallet_address
|
|
407
|
+
|
|
408
|
+
# Add L2 credentials if available
|
|
409
|
+
if credentials.api_credentials:
|
|
410
|
+
client_args["creds"] = ApiCreds(
|
|
411
|
+
api_key=credentials.api_credentials.api_key,
|
|
412
|
+
api_secret=credentials.api_credentials.api_secret,
|
|
413
|
+
api_passphrase=credentials.api_credentials.api_passphrase
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
client = ClobClient(**client_args)
|
|
417
|
+
self._clob_clients[self._user_id] = client
|
|
418
|
+
|
|
419
|
+
sig_type_name = {0: "EOA", 1: "Magic", 2: "Proxy"}.get(credentials.signature_type, "Unknown")
|
|
420
|
+
self.logger.info(
|
|
421
|
+
f"Created CLOB client for user {self._user_id[:8]}... "
|
|
422
|
+
f"(sig_type={sig_type_name}, funder={'proxy' if credentials.proxy_wallet_address else 'eoa'})"
|
|
423
|
+
)
|
|
424
|
+
return client
|
|
425
|
+
|
|
426
|
+
except Exception as e:
|
|
427
|
+
self.logger.error(f"Failed to create CLOB client: {e}")
|
|
428
|
+
return None
|
|
429
|
+
|
|
430
|
+
async def _ensure_api_credentials(self) -> Optional[ApiCredentials]:
|
|
431
|
+
"""
|
|
432
|
+
Ensure user has L2 API credentials, creating them if needed.
|
|
433
|
+
|
|
434
|
+
L2 credentials are required for authenticated operations like
|
|
435
|
+
placing orders, viewing positions, etc.
|
|
436
|
+
|
|
437
|
+
Returns:
|
|
438
|
+
ApiCredentials if available/created, None otherwise
|
|
439
|
+
"""
|
|
440
|
+
if not self._user_id:
|
|
441
|
+
return None
|
|
442
|
+
|
|
443
|
+
credentials = await self._get_user_credentials()
|
|
444
|
+
if not credentials or credentials.demo_mode:
|
|
445
|
+
return None
|
|
446
|
+
|
|
447
|
+
# Already have API credentials
|
|
448
|
+
if credentials.api_credentials:
|
|
449
|
+
return credentials.api_credentials
|
|
450
|
+
|
|
451
|
+
# Need to create new API credentials
|
|
452
|
+
client = await self._get_clob_client()
|
|
453
|
+
if not client:
|
|
454
|
+
return None
|
|
455
|
+
|
|
456
|
+
try:
|
|
457
|
+
self.logger.info(
|
|
458
|
+
f"Creating L2 API credentials for user {self._user_id[:8]}... "
|
|
459
|
+
f"(sig_type={credentials.signature_type}, funder={credentials.funder_address[:10] if credentials.funder_address else 'none'}...)"
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
# Use create_or_derive_api_key (v2) - works better with proxy wallets
|
|
463
|
+
# This is the method used in the working 15-minute trading script
|
|
464
|
+
api_creds = client.create_or_derive_api_key()
|
|
465
|
+
|
|
466
|
+
# Set the API creds on the client (as recommended in docs)
|
|
467
|
+
client.set_api_creds(api_creds)
|
|
468
|
+
|
|
469
|
+
# Build our model
|
|
470
|
+
api_credentials = ApiCredentials(
|
|
471
|
+
api_key=api_creds.api_key,
|
|
472
|
+
api_secret=api_creds.api_secret,
|
|
473
|
+
api_passphrase=api_creds.api_passphrase,
|
|
474
|
+
created_at=datetime.utcnow().isoformat()
|
|
475
|
+
)
|
|
476
|
+
|
|
477
|
+
# Store in database
|
|
478
|
+
if self.db:
|
|
479
|
+
await self.db.save_api_credentials(self._user_id, api_credentials)
|
|
480
|
+
|
|
481
|
+
# Update cache
|
|
482
|
+
credentials.api_credentials = api_credentials
|
|
483
|
+
self._credentials_cache[self._user_id] = credentials
|
|
484
|
+
|
|
485
|
+
# Reinitialize client with new credentials
|
|
486
|
+
del self._clob_clients[self._user_id]
|
|
487
|
+
await self._get_clob_client()
|
|
488
|
+
|
|
489
|
+
self.logger.info(f"Created API credentials: {api_credentials.api_key[:8]}...")
|
|
490
|
+
return api_credentials
|
|
491
|
+
|
|
492
|
+
except Exception as e:
|
|
493
|
+
import traceback
|
|
494
|
+
self.logger.error(
|
|
495
|
+
f"Failed to create API credentials: {e}\n"
|
|
496
|
+
f"Wallet: {credentials.wallet_address}\n"
|
|
497
|
+
f"Proxy: {credentials.proxy_wallet_address}\n"
|
|
498
|
+
f"Sig Type: {credentials.signature_type}\n"
|
|
499
|
+
f"Traceback: {traceback.format_exc()}"
|
|
500
|
+
)
|
|
501
|
+
return None
|
|
502
|
+
|
|
503
|
+
async def _get_authenticated_client(self) -> Tuple[Optional[ClobClient], Optional[str]]:
|
|
504
|
+
"""
|
|
505
|
+
Get fully authenticated (L2) CLOB client.
|
|
506
|
+
|
|
507
|
+
Returns:
|
|
508
|
+
Tuple of (client, error_message). If error, client is None.
|
|
509
|
+
"""
|
|
510
|
+
if not CLOB_AVAILABLE:
|
|
511
|
+
return None, f"Polymarket trading client unavailable: {trade_capability()['install_hint']}"
|
|
512
|
+
|
|
513
|
+
credentials = await self._get_user_credentials()
|
|
514
|
+
|
|
515
|
+
if not credentials:
|
|
516
|
+
return None, "No Polymarket credentials configured. Configure in Settings → Polymarket"
|
|
517
|
+
|
|
518
|
+
if credentials.demo_mode:
|
|
519
|
+
return None, "Trading requires wallet configuration (disable demo mode)"
|
|
520
|
+
|
|
521
|
+
if not credentials.enabled:
|
|
522
|
+
return None, "Polymarket is disabled for your account"
|
|
523
|
+
|
|
524
|
+
if not credentials.private_key:
|
|
525
|
+
return None, "Wallet private key not configured"
|
|
526
|
+
|
|
527
|
+
# Ensure API credentials exist
|
|
528
|
+
api_creds = await self._ensure_api_credentials()
|
|
529
|
+
if not api_creds:
|
|
530
|
+
return None, "Failed to create API credentials"
|
|
531
|
+
|
|
532
|
+
client = await self._get_clob_client()
|
|
533
|
+
if not client:
|
|
534
|
+
return None, "Failed to initialize CLOB client"
|
|
535
|
+
|
|
536
|
+
return client, None
|
|
537
|
+
|
|
538
|
+
async def get_balance_and_allowances(self) -> ExecutionResult:
|
|
539
|
+
"""
|
|
540
|
+
Get user's USDC balance and allowance status.
|
|
541
|
+
|
|
542
|
+
Returns balance in USD and whether allowances are set for trading.
|
|
543
|
+
This uses the correct signature_type for the user's wallet configuration.
|
|
544
|
+
"""
|
|
545
|
+
start_time = time.time()
|
|
546
|
+
|
|
547
|
+
try:
|
|
548
|
+
client = await self._get_clob_client()
|
|
549
|
+
if not client:
|
|
550
|
+
return ExecutionResult(
|
|
551
|
+
success=False,
|
|
552
|
+
error="CLOB client not available. Configure wallet in Settings → Polymarket.",
|
|
553
|
+
tool_name="get_balance_and_allowances"
|
|
554
|
+
)
|
|
555
|
+
|
|
556
|
+
credentials = await self._get_user_credentials()
|
|
557
|
+
if not credentials:
|
|
558
|
+
return ExecutionResult(
|
|
559
|
+
success=False,
|
|
560
|
+
error="No credentials configured",
|
|
561
|
+
tool_name="get_balance_and_allowances"
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
# Balance/allowance types come from the same adapter seam.
|
|
565
|
+
from tools.polymarket.clob_adapter import BalanceAllowanceParams, AssetType
|
|
566
|
+
if BalanceAllowanceParams is None or AssetType is None:
|
|
567
|
+
return ExecutionResult(
|
|
568
|
+
success=False,
|
|
569
|
+
error=f"Polymarket trading client unavailable: {trade_capability()['install_hint']}",
|
|
570
|
+
tool_name="get_balance_and_allowances"
|
|
571
|
+
)
|
|
572
|
+
|
|
573
|
+
params = BalanceAllowanceParams(
|
|
574
|
+
asset_type=AssetType.COLLATERAL,
|
|
575
|
+
signature_type=credentials.signature_type
|
|
576
|
+
)
|
|
577
|
+
|
|
578
|
+
result = client.get_balance_allowance(params)
|
|
579
|
+
|
|
580
|
+
balance_wei = int(result.get('balance', 0))
|
|
581
|
+
balance_usd = balance_wei / 1e6 # USDC has 6 decimals
|
|
582
|
+
|
|
583
|
+
allowances = result.get('allowances', {})
|
|
584
|
+
allowances_set = all(int(v) > 0 for v in allowances.values()) if allowances else False
|
|
585
|
+
|
|
586
|
+
return ExecutionResult(
|
|
587
|
+
success=True,
|
|
588
|
+
data={
|
|
589
|
+
"balance_usd": balance_usd,
|
|
590
|
+
"allowances_set": allowances_set,
|
|
591
|
+
"allowances": {addr: int(v) > 0 for addr, v in allowances.items()},
|
|
592
|
+
"can_trade": balance_usd >= MIN_ORDER_VALUE_USD and allowances_set,
|
|
593
|
+
"funder_address": credentials.funder_address,
|
|
594
|
+
"signature_type": credentials.signature_type,
|
|
595
|
+
},
|
|
596
|
+
tool_name="get_balance_and_allowances",
|
|
597
|
+
execution_time_ms=(time.time() - start_time) * 1000
|
|
598
|
+
)
|
|
599
|
+
|
|
600
|
+
except Exception as e:
|
|
601
|
+
self.logger.error(f"Failed to get balance/allowances: {e}")
|
|
602
|
+
return ExecutionResult(
|
|
603
|
+
success=False,
|
|
604
|
+
error=str(e),
|
|
605
|
+
tool_name="get_balance_and_allowances",
|
|
606
|
+
execution_time_ms=(time.time() - start_time) * 1000
|
|
607
|
+
)
|
|
608
|
+
|
|
609
|
+
async def _validate_trading_ready(self) -> Tuple[bool, str]:
|
|
610
|
+
"""
|
|
611
|
+
Validate that wallet is ready for trading.
|
|
612
|
+
|
|
613
|
+
Checks:
|
|
614
|
+
1. CLOB client available
|
|
615
|
+
2. Balance sufficient (>= $1.00)
|
|
616
|
+
3. Allowances set
|
|
617
|
+
|
|
618
|
+
Returns:
|
|
619
|
+
(ready: bool, message: str)
|
|
620
|
+
"""
|
|
621
|
+
result = await self.get_balance_and_allowances()
|
|
622
|
+
|
|
623
|
+
if not result.success:
|
|
624
|
+
return False, f"Failed to check balance: {result.error}"
|
|
625
|
+
|
|
626
|
+
data = result.data
|
|
627
|
+
|
|
628
|
+
if not data.get("allowances_set"):
|
|
629
|
+
return False, (
|
|
630
|
+
"Trading allowances not set. Please make one trade via "
|
|
631
|
+
"polymarket.com to enable API trading, or set allowances manually."
|
|
632
|
+
)
|
|
633
|
+
|
|
634
|
+
balance = data.get("balance_usd", 0)
|
|
635
|
+
if balance < MIN_ORDER_VALUE_USD:
|
|
636
|
+
return False, f"Insufficient balance: ${balance:.2f} (minimum ${MIN_ORDER_VALUE_USD:.2f})"
|
|
637
|
+
|
|
638
|
+
return True, f"Ready to trade (balance: ${balance:.2f})"
|
|
639
|
+
|
|
640
|
+
def _parse_market_outcomes(self, market: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
641
|
+
"""
|
|
642
|
+
Parse market outcomes from Gamma API response.
|
|
643
|
+
|
|
644
|
+
The Gamma API returns outcomes, outcomePrices, and clobTokenIds as JSON strings.
|
|
645
|
+
This method parses them and combines into a usable format.
|
|
646
|
+
|
|
647
|
+
Returns:
|
|
648
|
+
List of outcome dicts with name, token_id, and price
|
|
649
|
+
"""
|
|
650
|
+
import json
|
|
651
|
+
|
|
652
|
+
outcomes = []
|
|
653
|
+
|
|
654
|
+
# Parse JSON strings from Gamma API
|
|
655
|
+
try:
|
|
656
|
+
outcome_names = json.loads(market.get("outcomes", "[]"))
|
|
657
|
+
except (json.JSONDecodeError, TypeError):
|
|
658
|
+
outcome_names = []
|
|
659
|
+
|
|
660
|
+
try:
|
|
661
|
+
outcome_prices = json.loads(market.get("outcomePrices", "[]"))
|
|
662
|
+
except (json.JSONDecodeError, TypeError):
|
|
663
|
+
outcome_prices = []
|
|
664
|
+
|
|
665
|
+
try:
|
|
666
|
+
token_ids = json.loads(market.get("clobTokenIds", "[]"))
|
|
667
|
+
except (json.JSONDecodeError, TypeError):
|
|
668
|
+
token_ids = []
|
|
669
|
+
|
|
670
|
+
# Combine into outcome objects
|
|
671
|
+
for i, name in enumerate(outcome_names):
|
|
672
|
+
outcome = {
|
|
673
|
+
"name": name,
|
|
674
|
+
"token_id": token_ids[i] if i < len(token_ids) else "",
|
|
675
|
+
"price": float(outcome_prices[i]) if i < len(outcome_prices) else 0.0
|
|
676
|
+
}
|
|
677
|
+
outcomes.append(outcome)
|
|
678
|
+
|
|
679
|
+
return outcomes
|
|
680
|
+
|
|
681
|
+
def _format_market(self, m: Dict[str, Any], include_description: bool = False) -> Dict[str, Any]:
|
|
682
|
+
"""
|
|
683
|
+
Format a market from Gamma API response for consistent output.
|
|
684
|
+
|
|
685
|
+
Args:
|
|
686
|
+
m: Raw market data from Gamma API
|
|
687
|
+
include_description: Whether to include description (truncated)
|
|
688
|
+
|
|
689
|
+
Returns:
|
|
690
|
+
Formatted market dict with parsed outcomes and token_ids
|
|
691
|
+
"""
|
|
692
|
+
formatted = {
|
|
693
|
+
"slug": m.get("slug", ""),
|
|
694
|
+
"condition_id": m.get("conditionId") or m.get("id", ""),
|
|
695
|
+
"question": m.get("question", ""),
|
|
696
|
+
"volume": m.get("volume", 0),
|
|
697
|
+
"volume_24h": m.get("volume24hr", 0),
|
|
698
|
+
"liquidity": m.get("liquidity", 0),
|
|
699
|
+
"end_date": m.get("endDate"),
|
|
700
|
+
"active": m.get("active", False),
|
|
701
|
+
"closed": m.get("closed", False),
|
|
702
|
+
"outcomes": self._parse_market_outcomes(m),
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
if include_description:
|
|
706
|
+
desc = m.get("description", "") or ""
|
|
707
|
+
formatted["description"] = desc[:500] if len(desc) > 500 else desc
|
|
708
|
+
|
|
709
|
+
# Add category from tags if available
|
|
710
|
+
tags = m.get("tags")
|
|
711
|
+
if tags and isinstance(tags, list) and len(tags) > 0:
|
|
712
|
+
formatted["category"] = tags[0].get("label", "")
|
|
713
|
+
else:
|
|
714
|
+
formatted["category"] = ""
|
|
715
|
+
|
|
716
|
+
return formatted
|
|
717
|
+
|
|
718
|
+
# =========================================================================
|
|
719
|
+
# MARKET DISCOVERY ACTIONS
|
|
720
|
+
# =========================================================================
|
|
721
|
+
|
|
722
|
+
@BaseTool.action(
|
|
723
|
+
'Search for prediction markets on Polymarket. Returns slug, condition_id, and token_ids for each market.',
|
|
724
|
+
param_model=SearchMarketsParams
|
|
725
|
+
)
|
|
726
|
+
async def search_markets(self, params: SearchMarketsParams) -> Dict[str, Any]:
|
|
727
|
+
"""
|
|
728
|
+
Search markets using Gamma API.
|
|
729
|
+
|
|
730
|
+
Returns markets with:
|
|
731
|
+
- slug: Use this with get_market_details (e.g., 'will-trump-win-2024')
|
|
732
|
+
- condition_id: The 0x... condition ID
|
|
733
|
+
- outcomes: Each has token_id needed for trading
|
|
734
|
+
"""
|
|
735
|
+
await self.ensure_initialized()
|
|
736
|
+
await self.rate_limit("search_markets")
|
|
737
|
+
|
|
738
|
+
try:
|
|
739
|
+
query_params = {
|
|
740
|
+
"_limit": params.limit,
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
# Add search query
|
|
744
|
+
if params.query:
|
|
745
|
+
query_params["_q"] = params.query
|
|
746
|
+
|
|
747
|
+
if params.category:
|
|
748
|
+
query_params["tag_slug"] = params.category
|
|
749
|
+
|
|
750
|
+
if params.active_only:
|
|
751
|
+
query_params["active"] = "true"
|
|
752
|
+
query_params["closed"] = "false"
|
|
753
|
+
|
|
754
|
+
response = await self._http_client.get(
|
|
755
|
+
f"{self.GAMMA_API_URL}/markets",
|
|
756
|
+
params=query_params
|
|
757
|
+
)
|
|
758
|
+
response.raise_for_status()
|
|
759
|
+
markets = response.json()
|
|
760
|
+
|
|
761
|
+
# Format results using helper (properly parses JSON strings for outcomes/tokens)
|
|
762
|
+
formatted_markets = [
|
|
763
|
+
self._format_market(m, include_description=True) for m in markets
|
|
764
|
+
]
|
|
765
|
+
|
|
766
|
+
return {
|
|
767
|
+
"success": True,
|
|
768
|
+
"count": len(formatted_markets),
|
|
769
|
+
"markets": formatted_markets,
|
|
770
|
+
"note": "Use 'slug' with get_market_details, use 'token_id' from outcomes for trading"
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
except httpx.HTTPStatusError as e:
|
|
774
|
+
self.logger.error(f"Search markets API error: {e}")
|
|
775
|
+
return {"success": False, "error": f"API error: {e.response.status_code}", "markets": []}
|
|
776
|
+
except Exception as e:
|
|
777
|
+
self.logger.error(f"Search markets failed: {e}")
|
|
778
|
+
return {"success": False, "error": str(e), "markets": []}
|
|
779
|
+
|
|
780
|
+
@BaseTool.action(
|
|
781
|
+
'Get trending prediction markets by volume',
|
|
782
|
+
param_model=TrendingMarketsParams
|
|
783
|
+
)
|
|
784
|
+
async def get_trending_markets(self, params: TrendingMarketsParams) -> Dict[str, Any]:
|
|
785
|
+
"""Get trending markets sorted by 24h volume."""
|
|
786
|
+
await self.ensure_initialized()
|
|
787
|
+
await self.rate_limit("get_trending_markets")
|
|
788
|
+
|
|
789
|
+
try:
|
|
790
|
+
query_params = {
|
|
791
|
+
"_limit": params.limit,
|
|
792
|
+
"_sort": "-volume24hr",
|
|
793
|
+
"active": "true",
|
|
794
|
+
"closed": "false"
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
if params.category:
|
|
798
|
+
query_params["tag_slug"] = params.category
|
|
799
|
+
|
|
800
|
+
response = await self._http_client.get(
|
|
801
|
+
f"{self.GAMMA_API_URL}/markets",
|
|
802
|
+
params=query_params
|
|
803
|
+
)
|
|
804
|
+
response.raise_for_status()
|
|
805
|
+
markets = response.json()
|
|
806
|
+
|
|
807
|
+
# Format results using helper (properly parses JSON strings for outcomes/tokens)
|
|
808
|
+
formatted_markets = [self._format_market(m) for m in markets]
|
|
809
|
+
|
|
810
|
+
return {
|
|
811
|
+
"success": True,
|
|
812
|
+
"count": len(formatted_markets),
|
|
813
|
+
"sorted_by": "24h_volume",
|
|
814
|
+
"markets": formatted_markets,
|
|
815
|
+
"note": "Use 'slug' with get_market_details, use 'token_id' from outcomes for trading"
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
except Exception as e:
|
|
819
|
+
self.logger.error(f"Get trending markets failed: {e}")
|
|
820
|
+
return {"success": False, "error": str(e), "markets": []}
|
|
821
|
+
|
|
822
|
+
@BaseTool.action(
|
|
823
|
+
'Get markets by category',
|
|
824
|
+
param_model=FilterByCategoryParams
|
|
825
|
+
)
|
|
826
|
+
async def filter_markets_by_category(self, params: FilterByCategoryParams) -> Dict[str, Any]:
|
|
827
|
+
"""Filter markets by category slug."""
|
|
828
|
+
await self.ensure_initialized()
|
|
829
|
+
await self.rate_limit("filter_markets_by_category")
|
|
830
|
+
|
|
831
|
+
try:
|
|
832
|
+
query_params = {
|
|
833
|
+
"_limit": params.limit,
|
|
834
|
+
"tag_slug": params.category,
|
|
835
|
+
"_sort": "-volume24hr"
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
if params.active_only:
|
|
839
|
+
query_params["active"] = "true"
|
|
840
|
+
query_params["closed"] = "false"
|
|
841
|
+
|
|
842
|
+
response = await self._http_client.get(
|
|
843
|
+
f"{self.GAMMA_API_URL}/markets",
|
|
844
|
+
params=query_params
|
|
845
|
+
)
|
|
846
|
+
response.raise_for_status()
|
|
847
|
+
markets = response.json()
|
|
848
|
+
|
|
849
|
+
# Format results using helper
|
|
850
|
+
formatted_markets = [self._format_market(m) for m in markets]
|
|
851
|
+
|
|
852
|
+
return {
|
|
853
|
+
"success": True,
|
|
854
|
+
"category": params.category,
|
|
855
|
+
"count": len(formatted_markets),
|
|
856
|
+
"markets": formatted_markets,
|
|
857
|
+
"note": "Use 'slug' with get_market_details, use 'token_id' from outcomes for trading"
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
except Exception as e:
|
|
861
|
+
self.logger.error(f"Filter by category failed: {e}")
|
|
862
|
+
return {"success": False, "error": str(e), "markets": []}
|
|
863
|
+
|
|
864
|
+
@BaseTool.action(
|
|
865
|
+
'Get featured markets',
|
|
866
|
+
param_model=TrendingMarketsParams
|
|
867
|
+
)
|
|
868
|
+
async def get_featured_markets(self, params: TrendingMarketsParams) -> Dict[str, Any]:
|
|
869
|
+
"""Get featured/highlighted markets."""
|
|
870
|
+
await self.ensure_initialized()
|
|
871
|
+
await self.rate_limit("get_featured_markets")
|
|
872
|
+
|
|
873
|
+
try:
|
|
874
|
+
query_params = {
|
|
875
|
+
"_limit": params.limit,
|
|
876
|
+
"featured": "true",
|
|
877
|
+
"active": "true",
|
|
878
|
+
"_sort": "-volume24hr"
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
response = await self._http_client.get(
|
|
882
|
+
f"{self.GAMMA_API_URL}/markets",
|
|
883
|
+
params=query_params
|
|
884
|
+
)
|
|
885
|
+
response.raise_for_status()
|
|
886
|
+
markets = response.json()
|
|
887
|
+
|
|
888
|
+
# Format results using helper
|
|
889
|
+
formatted_markets = [self._format_market(m) for m in markets]
|
|
890
|
+
|
|
891
|
+
return {
|
|
892
|
+
"success": True,
|
|
893
|
+
"count": len(formatted_markets),
|
|
894
|
+
"markets": formatted_markets,
|
|
895
|
+
"note": "Use 'slug' with get_market_details, use 'token_id' from outcomes for trading"
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
except Exception as e:
|
|
899
|
+
self.logger.error(f"Get featured markets failed: {e}")
|
|
900
|
+
return {"success": False, "error": str(e), "markets": []}
|
|
901
|
+
|
|
902
|
+
@BaseTool.action(
|
|
903
|
+
'Get markets closing soon',
|
|
904
|
+
param_model=ClosingSoonParams
|
|
905
|
+
)
|
|
906
|
+
async def get_closing_soon_markets(self, params: ClosingSoonParams) -> Dict[str, Any]:
|
|
907
|
+
"""
|
|
908
|
+
Get markets closing within specified hours.
|
|
909
|
+
|
|
910
|
+
The Gamma API doesn't support date range filters directly,
|
|
911
|
+
so we fetch active markets and filter client-side.
|
|
912
|
+
"""
|
|
913
|
+
await self.ensure_initialized()
|
|
914
|
+
await self.rate_limit("get_closing_soon_markets")
|
|
915
|
+
|
|
916
|
+
try:
|
|
917
|
+
# Calculate end time threshold
|
|
918
|
+
now = datetime.utcnow()
|
|
919
|
+
end_threshold = now + timedelta(hours=params.hours)
|
|
920
|
+
|
|
921
|
+
# Fetch more markets than needed so we can filter
|
|
922
|
+
# We'll request active markets sorted by volume
|
|
923
|
+
query_params = {
|
|
924
|
+
"_limit": 100, # Fetch more to filter
|
|
925
|
+
"active": "true",
|
|
926
|
+
"closed": "false",
|
|
927
|
+
"_sort": "-volume" # Sort by volume descending
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
response = await self._http_client.get(
|
|
931
|
+
f"{self.GAMMA_API_URL}/markets",
|
|
932
|
+
params=query_params
|
|
933
|
+
)
|
|
934
|
+
response.raise_for_status()
|
|
935
|
+
all_markets = response.json()
|
|
936
|
+
|
|
937
|
+
# Filter markets closing within the threshold
|
|
938
|
+
closing_soon = []
|
|
939
|
+
for m in all_markets:
|
|
940
|
+
end_date_str = m.get("endDate")
|
|
941
|
+
if not end_date_str:
|
|
942
|
+
continue
|
|
943
|
+
|
|
944
|
+
try:
|
|
945
|
+
# Parse ISO date
|
|
946
|
+
end_date = datetime.fromisoformat(end_date_str.replace("Z", "+00:00"))
|
|
947
|
+
# Make naive for comparison
|
|
948
|
+
end_date_naive = end_date.replace(tzinfo=None)
|
|
949
|
+
|
|
950
|
+
if now < end_date_naive <= end_threshold:
|
|
951
|
+
hours_remaining = (end_date_naive - now).total_seconds() / 3600
|
|
952
|
+
closing_soon.append({
|
|
953
|
+
"id": m.get("conditionId") or m.get("id"),
|
|
954
|
+
"question": m.get("question", ""),
|
|
955
|
+
"end_date": end_date_str,
|
|
956
|
+
"hours_remaining": round(hours_remaining, 1),
|
|
957
|
+
"volume": m.get("volume", 0),
|
|
958
|
+
"volume_24h": m.get("volume24hr", 0),
|
|
959
|
+
"liquidity": m.get("liquidity", 0)
|
|
960
|
+
})
|
|
961
|
+
except (ValueError, TypeError):
|
|
962
|
+
continue
|
|
963
|
+
|
|
964
|
+
# Sort by hours remaining and limit
|
|
965
|
+
closing_soon.sort(key=lambda x: x["hours_remaining"])
|
|
966
|
+
closing_soon = closing_soon[:params.limit]
|
|
967
|
+
|
|
968
|
+
return {
|
|
969
|
+
"success": True,
|
|
970
|
+
"hours_until_close": params.hours,
|
|
971
|
+
"count": len(closing_soon),
|
|
972
|
+
"markets": closing_soon
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
except Exception as e:
|
|
976
|
+
self.logger.error(f"Get closing soon markets failed: {e}")
|
|
977
|
+
return {"success": False, "error": str(e), "markets": []}
|
|
978
|
+
|
|
979
|
+
@BaseTool.action(
|
|
980
|
+
'Get sports betting markets',
|
|
981
|
+
param_model=TrendingMarketsParams
|
|
982
|
+
)
|
|
983
|
+
async def get_sports_markets(self, params: TrendingMarketsParams) -> Dict[str, Any]:
|
|
984
|
+
"""Get sports category markets."""
|
|
985
|
+
return await self.filter_markets_by_category(
|
|
986
|
+
FilterByCategoryParams(category="sports", limit=params.limit, active_only=True)
|
|
987
|
+
)
|
|
988
|
+
|
|
989
|
+
@BaseTool.action(
|
|
990
|
+
'Get cryptocurrency markets',
|
|
991
|
+
param_model=TrendingMarketsParams
|
|
992
|
+
)
|
|
993
|
+
async def get_crypto_markets(self, params: TrendingMarketsParams) -> Dict[str, Any]:
|
|
994
|
+
"""Get crypto category markets."""
|
|
995
|
+
return await self.filter_markets_by_category(
|
|
996
|
+
FilterByCategoryParams(category="crypto", limit=params.limit, active_only=True)
|
|
997
|
+
)
|
|
998
|
+
|
|
999
|
+
# =========================================================================
|
|
1000
|
+
# MARKET DATA ACTIONS
|
|
1001
|
+
# =========================================================================
|
|
1002
|
+
|
|
1003
|
+
@BaseTool.action(
|
|
1004
|
+
'Get detailed market information. Pass the slug from search results (e.g., "will-trump-win-2024").',
|
|
1005
|
+
param_model=MarketDetailsParams
|
|
1006
|
+
)
|
|
1007
|
+
async def get_market_details(self, params: MarketDetailsParams) -> Dict[str, Any]:
|
|
1008
|
+
"""
|
|
1009
|
+
Get comprehensive market details.
|
|
1010
|
+
|
|
1011
|
+
IMPORTANT: Use the 'slug' from search_markets/get_trending_markets results.
|
|
1012
|
+
Example: market_id="will-trump-win-2024" (NOT the 0x... condition_id)
|
|
1013
|
+
|
|
1014
|
+
Lookup strategies:
|
|
1015
|
+
- /markets/slug/{slug} - for slug-based lookups (preferred)
|
|
1016
|
+
- /markets?conditionId={id} - for condition ID lookups
|
|
1017
|
+
"""
|
|
1018
|
+
await self.ensure_initialized()
|
|
1019
|
+
await self.rate_limit("get_market_details")
|
|
1020
|
+
|
|
1021
|
+
market_id = params.market_id
|
|
1022
|
+
market = None
|
|
1023
|
+
|
|
1024
|
+
try:
|
|
1025
|
+
# Strategy 1: If it looks like a slug (no 0x prefix), try slug endpoint
|
|
1026
|
+
# Correct endpoint is /markets/slug/{slug} NOT /markets/{slug}
|
|
1027
|
+
if not market_id.startswith("0x") and not market_id.isdigit():
|
|
1028
|
+
response = await self._http_client.get(
|
|
1029
|
+
f"{self.GAMMA_API_URL}/markets/slug/{market_id}"
|
|
1030
|
+
)
|
|
1031
|
+
if response.status_code == 200:
|
|
1032
|
+
market = response.json()
|
|
1033
|
+
else:
|
|
1034
|
+
self.logger.debug(f"Slug lookup failed with status {response.status_code}")
|
|
1035
|
+
|
|
1036
|
+
# Strategy 2: Search by conditionId (hex string)
|
|
1037
|
+
if not market and market_id.startswith("0x"):
|
|
1038
|
+
response = await self._http_client.get(
|
|
1039
|
+
f"{self.GAMMA_API_URL}/markets",
|
|
1040
|
+
params={"conditionId": market_id, "_limit": 1}
|
|
1041
|
+
)
|
|
1042
|
+
if response.status_code == 200:
|
|
1043
|
+
markets = response.json()
|
|
1044
|
+
if markets and len(markets) > 0:
|
|
1045
|
+
market = markets[0]
|
|
1046
|
+
|
|
1047
|
+
# Strategy 3: Search by slug parameter if direct didn't work
|
|
1048
|
+
if not market and not market_id.startswith("0x"):
|
|
1049
|
+
response = await self._http_client.get(
|
|
1050
|
+
f"{self.GAMMA_API_URL}/markets",
|
|
1051
|
+
params={"slug": market_id, "_limit": 1}
|
|
1052
|
+
)
|
|
1053
|
+
if response.status_code == 200:
|
|
1054
|
+
markets = response.json()
|
|
1055
|
+
if markets and len(markets) > 0:
|
|
1056
|
+
market = markets[0]
|
|
1057
|
+
|
|
1058
|
+
# Strategy 4: Try CLOB API for market data
|
|
1059
|
+
if not market:
|
|
1060
|
+
try:
|
|
1061
|
+
clob_response = await self._http_client.get(
|
|
1062
|
+
f"{self.CLOB_API_URL}/markets/{market_id}"
|
|
1063
|
+
)
|
|
1064
|
+
if clob_response.status_code == 200:
|
|
1065
|
+
clob_data = clob_response.json()
|
|
1066
|
+
# CLOB returns different structure, parse tokens
|
|
1067
|
+
tokens = clob_data.get("tokens", [])
|
|
1068
|
+
outcomes = []
|
|
1069
|
+
for t in tokens:
|
|
1070
|
+
outcomes.append({
|
|
1071
|
+
"name": t.get("outcome", ""),
|
|
1072
|
+
"token_id": t.get("token_id", ""),
|
|
1073
|
+
"price": 0 # CLOB tokens may not have price
|
|
1074
|
+
})
|
|
1075
|
+
return {
|
|
1076
|
+
"success": True,
|
|
1077
|
+
"source": "clob",
|
|
1078
|
+
"market": {
|
|
1079
|
+
"id": clob_data.get("condition_id", market_id),
|
|
1080
|
+
"slug": "",
|
|
1081
|
+
"question": clob_data.get("question", ""),
|
|
1082
|
+
"description": clob_data.get("description", ""),
|
|
1083
|
+
"volume": 0,
|
|
1084
|
+
"volume_24h": 0,
|
|
1085
|
+
"liquidity": 0,
|
|
1086
|
+
"end_date": clob_data.get("end_date_iso"),
|
|
1087
|
+
"active": clob_data.get("active", False),
|
|
1088
|
+
"closed": clob_data.get("closed", False),
|
|
1089
|
+
"outcomes": outcomes
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
except Exception as e:
|
|
1093
|
+
self.logger.debug(f"CLOB lookup failed: {e}")
|
|
1094
|
+
|
|
1095
|
+
if not market:
|
|
1096
|
+
return {
|
|
1097
|
+
"success": False,
|
|
1098
|
+
"error": f"Market not found: {market_id}",
|
|
1099
|
+
"suggestion": "Use search_markets to find valid market slugs"
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
# Format the response using helper for proper JSON parsing
|
|
1103
|
+
formatted = self._format_market(market, include_description=True)
|
|
1104
|
+
|
|
1105
|
+
# Add additional detail fields
|
|
1106
|
+
formatted["start_date"] = market.get("startDate")
|
|
1107
|
+
formatted["resolved"] = market.get("resolved", False)
|
|
1108
|
+
formatted["resolution_source"] = market.get("resolutionSource", "")
|
|
1109
|
+
|
|
1110
|
+
# Add events if present
|
|
1111
|
+
events = market.get("events", [])
|
|
1112
|
+
if events:
|
|
1113
|
+
formatted["events"] = [
|
|
1114
|
+
{
|
|
1115
|
+
"id": e.get("id", ""),
|
|
1116
|
+
"slug": e.get("slug", ""),
|
|
1117
|
+
"title": e.get("title", "")
|
|
1118
|
+
}
|
|
1119
|
+
for e in events
|
|
1120
|
+
]
|
|
1121
|
+
|
|
1122
|
+
return {
|
|
1123
|
+
"success": True,
|
|
1124
|
+
"source": "gamma",
|
|
1125
|
+
"market": formatted,
|
|
1126
|
+
"note": "Use 'token_id' from outcomes array for place_limit_order"
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
except httpx.HTTPStatusError as e:
|
|
1130
|
+
self.logger.error(f"Get market details API error: {e}")
|
|
1131
|
+
return {"success": False, "error": f"API error: {e.response.status_code}"}
|
|
1132
|
+
except Exception as e:
|
|
1133
|
+
self.logger.error(f"Get market details failed: {e}")
|
|
1134
|
+
return {"success": False, "error": str(e)}
|
|
1135
|
+
|
|
1136
|
+
@BaseTool.action(
|
|
1137
|
+
'Get current price for a market token',
|
|
1138
|
+
param_model=GetPriceParams
|
|
1139
|
+
)
|
|
1140
|
+
async def get_current_price(self, params: GetPriceParams) -> Dict[str, Any]:
|
|
1141
|
+
"""Get current price from CLOB orderbook, fallback to Gamma."""
|
|
1142
|
+
await self.ensure_initialized()
|
|
1143
|
+
await self.rate_limit("get_current_price")
|
|
1144
|
+
|
|
1145
|
+
# Try CLOB first
|
|
1146
|
+
try:
|
|
1147
|
+
response = await self._http_client.get(
|
|
1148
|
+
f"{self.CLOB_API_URL}/price",
|
|
1149
|
+
params={"token_id": params.token_id, "side": "BUY"}
|
|
1150
|
+
)
|
|
1151
|
+
|
|
1152
|
+
if response.status_code == 200:
|
|
1153
|
+
data = response.json()
|
|
1154
|
+
return {
|
|
1155
|
+
"success": True,
|
|
1156
|
+
"price": data.get("price"),
|
|
1157
|
+
"source": "clob",
|
|
1158
|
+
"token_id": params.token_id
|
|
1159
|
+
}
|
|
1160
|
+
except Exception as e:
|
|
1161
|
+
self.logger.debug(f"CLOB price failed, trying Gamma: {e}")
|
|
1162
|
+
|
|
1163
|
+
# Fallback to Gamma API via market details
|
|
1164
|
+
if params.market_id:
|
|
1165
|
+
try:
|
|
1166
|
+
details = await self.get_market_details(MarketDetailsParams(market_id=params.market_id))
|
|
1167
|
+
if details.get("success") and details.get("market"):
|
|
1168
|
+
for outcome in details["market"].get("outcomes", []):
|
|
1169
|
+
if outcome.get("token_id") == params.token_id:
|
|
1170
|
+
return {
|
|
1171
|
+
"success": True,
|
|
1172
|
+
"price": outcome.get("price"),
|
|
1173
|
+
"source": "gamma",
|
|
1174
|
+
"token_id": params.token_id
|
|
1175
|
+
}
|
|
1176
|
+
except Exception as e:
|
|
1177
|
+
self.logger.debug(f"Gamma price fallback failed: {e}")
|
|
1178
|
+
|
|
1179
|
+
return {
|
|
1180
|
+
"success": False,
|
|
1181
|
+
"error": "Price not available - market may be closed or inactive",
|
|
1182
|
+
"suggestion": "Try with an active market token_id"
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
@BaseTool.action(
|
|
1186
|
+
'Get orderbook for a market token',
|
|
1187
|
+
param_model=GetOrderbookParams
|
|
1188
|
+
)
|
|
1189
|
+
async def get_orderbook(self, params: GetOrderbookParams) -> Dict[str, Any]:
|
|
1190
|
+
"""Get orderbook depth from CLOB API."""
|
|
1191
|
+
await self.ensure_initialized()
|
|
1192
|
+
await self.rate_limit("get_orderbook")
|
|
1193
|
+
|
|
1194
|
+
try:
|
|
1195
|
+
response = await self._http_client.get(
|
|
1196
|
+
f"{self.CLOB_API_URL}/book",
|
|
1197
|
+
params={"token_id": params.token_id}
|
|
1198
|
+
)
|
|
1199
|
+
|
|
1200
|
+
if response.status_code == 404:
|
|
1201
|
+
return {
|
|
1202
|
+
"success": False,
|
|
1203
|
+
"error": "Market not found or closed - no active orderbook",
|
|
1204
|
+
"suggestion": "Use an active market token_id"
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
response.raise_for_status()
|
|
1208
|
+
book = response.json()
|
|
1209
|
+
|
|
1210
|
+
# Limit to requested depth
|
|
1211
|
+
bids = book.get("bids", [])[:params.depth]
|
|
1212
|
+
asks = book.get("asks", [])[:params.depth]
|
|
1213
|
+
|
|
1214
|
+
# Calculate spread
|
|
1215
|
+
spread = None
|
|
1216
|
+
if bids and asks:
|
|
1217
|
+
best_bid = float(bids[0].get("price", 0))
|
|
1218
|
+
best_ask = float(asks[0].get("price", 1))
|
|
1219
|
+
if best_bid > 0:
|
|
1220
|
+
spread = (best_ask - best_bid) / best_bid
|
|
1221
|
+
|
|
1222
|
+
return {
|
|
1223
|
+
"success": True,
|
|
1224
|
+
"token_id": params.token_id,
|
|
1225
|
+
"bids": bids,
|
|
1226
|
+
"asks": asks,
|
|
1227
|
+
"spread": spread,
|
|
1228
|
+
"spread_percent": f"{spread * 100:.2f}%" if spread else None
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
except httpx.HTTPStatusError as e:
|
|
1232
|
+
return {"success": False, "error": f"CLOB API error: {e.response.status_code}"}
|
|
1233
|
+
except Exception as e:
|
|
1234
|
+
self.logger.error(f"Get orderbook failed: {e}")
|
|
1235
|
+
return {"success": False, "error": str(e)}
|
|
1236
|
+
|
|
1237
|
+
@BaseTool.action(
|
|
1238
|
+
'Get bid-ask spread for a token',
|
|
1239
|
+
param_model=GetSpreadParams
|
|
1240
|
+
)
|
|
1241
|
+
async def get_spread(self, params: GetSpreadParams) -> Dict[str, Any]:
|
|
1242
|
+
"""Get bid-ask spread."""
|
|
1243
|
+
result = await self.get_orderbook(GetOrderbookParams(token_id=params.token_id, depth=1))
|
|
1244
|
+
|
|
1245
|
+
if not result.get("success"):
|
|
1246
|
+
return result
|
|
1247
|
+
|
|
1248
|
+
return {
|
|
1249
|
+
"success": True,
|
|
1250
|
+
"token_id": params.token_id,
|
|
1251
|
+
"spread": result.get("spread"),
|
|
1252
|
+
"spread_percent": result.get("spread_percent"),
|
|
1253
|
+
"best_bid": result.get("bids", [{}])[0].get("price") if result.get("bids") else None,
|
|
1254
|
+
"best_ask": result.get("asks", [{}])[0].get("price") if result.get("asks") else None
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
@BaseTool.action(
|
|
1258
|
+
'Get market volume statistics',
|
|
1259
|
+
param_model=GetVolumeParams
|
|
1260
|
+
)
|
|
1261
|
+
async def get_market_volume(self, params: GetVolumeParams) -> Dict[str, Any]:
|
|
1262
|
+
"""Get volume statistics for a market."""
|
|
1263
|
+
details = await self.get_market_details(MarketDetailsParams(market_id=params.market_id))
|
|
1264
|
+
|
|
1265
|
+
if not details.get("success"):
|
|
1266
|
+
return details
|
|
1267
|
+
|
|
1268
|
+
market = details.get("market", {})
|
|
1269
|
+
return {
|
|
1270
|
+
"success": True,
|
|
1271
|
+
"market_id": params.market_id,
|
|
1272
|
+
"volume_total": market.get("volume", 0),
|
|
1273
|
+
"volume_24h": market.get("volume_24h", 0),
|
|
1274
|
+
"liquidity": market.get("liquidity", 0)
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
# =========================================================================
|
|
1278
|
+
# PORTFOLIO ACTIONS (Require Authentication)
|
|
1279
|
+
# =========================================================================
|
|
1280
|
+
|
|
1281
|
+
@BaseTool.action(
|
|
1282
|
+
'Get all portfolio positions',
|
|
1283
|
+
param_model=GetPositionsParams
|
|
1284
|
+
)
|
|
1285
|
+
async def get_all_positions(self, params: GetPositionsParams) -> Dict[str, Any]:
|
|
1286
|
+
"""Get user's portfolio positions via the PUBLIC Data API (no wallet/signing)."""
|
|
1287
|
+
await self.ensure_initialized()
|
|
1288
|
+
await self.rate_limit("get_all_positions")
|
|
1289
|
+
|
|
1290
|
+
try:
|
|
1291
|
+
credentials = await self._get_user_credentials()
|
|
1292
|
+
address = getattr(credentials, "funder_address", None) or getattr(credentials, "wallet_address", None)
|
|
1293
|
+
if not address:
|
|
1294
|
+
return {"success": False, "error": "No wallet address configured for position lookup"}
|
|
1295
|
+
|
|
1296
|
+
# Positions are public by address — query the Data API, no signing.
|
|
1297
|
+
resp = await self._http_client.get(
|
|
1298
|
+
f"{self.DATA_API_URL}/positions",
|
|
1299
|
+
params={"user": address},
|
|
1300
|
+
)
|
|
1301
|
+
resp.raise_for_status()
|
|
1302
|
+
positions_data = resp.json() or []
|
|
1303
|
+
|
|
1304
|
+
# Format positions
|
|
1305
|
+
positions = []
|
|
1306
|
+
for pos in positions_data:
|
|
1307
|
+
positions.append({
|
|
1308
|
+
"market_id": pos.get("market", ""),
|
|
1309
|
+
"token_id": pos.get("asset", ""),
|
|
1310
|
+
"outcome": pos.get("outcome", ""),
|
|
1311
|
+
"size": float(pos.get("size", 0)),
|
|
1312
|
+
"avg_price": float(pos.get("avgPrice", 0)),
|
|
1313
|
+
"current_price": float(pos.get("curPrice", 0)),
|
|
1314
|
+
"cost_basis": float(pos.get("size", 0)) * float(pos.get("avgPrice", 0)),
|
|
1315
|
+
"value": float(pos.get("size", 0)) * float(pos.get("curPrice", 0)),
|
|
1316
|
+
"unrealized_pnl": float(pos.get("pnl", 0)),
|
|
1317
|
+
"realized_pnl": float(pos.get("realizedPnl", 0))
|
|
1318
|
+
})
|
|
1319
|
+
|
|
1320
|
+
return {
|
|
1321
|
+
"success": True,
|
|
1322
|
+
"position_count": len(positions),
|
|
1323
|
+
"positions": positions
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
except Exception as e:
|
|
1327
|
+
self.logger.error(f"Get positions failed: {e}")
|
|
1328
|
+
return {"success": False, "error": f"Failed to fetch positions: {str(e)}"}
|
|
1329
|
+
|
|
1330
|
+
@BaseTool.action(
|
|
1331
|
+
'Get portfolio value and P&L summary',
|
|
1332
|
+
param_model=PortfolioSummaryParams
|
|
1333
|
+
)
|
|
1334
|
+
async def get_portfolio_summary(self, params: PortfolioSummaryParams) -> Dict[str, Any]:
|
|
1335
|
+
"""Get portfolio summary with P&L calculations."""
|
|
1336
|
+
# Delegate to get_all_positions for now
|
|
1337
|
+
positions_result = await self.get_all_positions(GetPositionsParams(include_closed=False))
|
|
1338
|
+
|
|
1339
|
+
if not positions_result.get("success"):
|
|
1340
|
+
return positions_result
|
|
1341
|
+
|
|
1342
|
+
# Calculate summary if we have positions
|
|
1343
|
+
positions = positions_result.get("positions", [])
|
|
1344
|
+
|
|
1345
|
+
total_cost = sum(float(p.get("cost_basis", 0)) for p in positions)
|
|
1346
|
+
total_value = sum(float(p.get("value", 0)) for p in positions)
|
|
1347
|
+
unrealized_pnl = total_value - total_cost
|
|
1348
|
+
|
|
1349
|
+
return {
|
|
1350
|
+
"success": True,
|
|
1351
|
+
"portfolio_value_usd": total_value,
|
|
1352
|
+
"total_cost_basis_usd": total_cost,
|
|
1353
|
+
"unrealized_pnl_usd": unrealized_pnl,
|
|
1354
|
+
"unrealized_pnl_percent": (unrealized_pnl / total_cost * 100) if total_cost > 0 else 0,
|
|
1355
|
+
"position_count": len(positions),
|
|
1356
|
+
"positions": positions if params.include_positions else None
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
@BaseTool.action(
|
|
1360
|
+
'Get wallet balance and allowances',
|
|
1361
|
+
param_model=GetBalanceParams
|
|
1362
|
+
)
|
|
1363
|
+
async def get_balance(self, params: GetBalanceParams) -> Dict[str, Any]:
|
|
1364
|
+
"""Get user's USDC balance and allowances via authenticated CLOB API."""
|
|
1365
|
+
await self.ensure_initialized()
|
|
1366
|
+
await self.rate_limit("get_balance")
|
|
1367
|
+
|
|
1368
|
+
client, error = await self._get_authenticated_client()
|
|
1369
|
+
if error:
|
|
1370
|
+
return {"success": False, "error": error}
|
|
1371
|
+
|
|
1372
|
+
try:
|
|
1373
|
+
credentials = await self._get_user_credentials()
|
|
1374
|
+
|
|
1375
|
+
# Get balance and allowance from CLOB API
|
|
1376
|
+
balance_data = client.get_balance_allowance()
|
|
1377
|
+
|
|
1378
|
+
return {
|
|
1379
|
+
"success": True,
|
|
1380
|
+
"wallet_address": credentials.wallet_address,
|
|
1381
|
+
"usdc_balance": float(balance_data.get("balance", 0)) / 1e6, # USDC has 6 decimals
|
|
1382
|
+
"usdc_allowance": float(balance_data.get("allowance", 0)) / 1e6,
|
|
1383
|
+
"collateral_balance": float(balance_data.get("collateralBalance", 0)) / 1e6,
|
|
1384
|
+
"note": "Balances shown in USD (USDC on Polygon)"
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
except Exception as e:
|
|
1388
|
+
self.logger.error(f"Get balance failed: {e}")
|
|
1389
|
+
return {"success": False, "error": f"Failed to fetch balance: {str(e)}"}
|
|
1390
|
+
|
|
1391
|
+
@BaseTool.action(
|
|
1392
|
+
'Get trade history',
|
|
1393
|
+
param_model=GetTradeHistoryParams
|
|
1394
|
+
)
|
|
1395
|
+
async def get_trade_history(self, params: GetTradeHistoryParams) -> Dict[str, Any]:
|
|
1396
|
+
"""Get user's trade history via the PUBLIC Data API (no wallet/signing)."""
|
|
1397
|
+
await self.ensure_initialized()
|
|
1398
|
+
await self.rate_limit("get_trade_history")
|
|
1399
|
+
|
|
1400
|
+
try:
|
|
1401
|
+
credentials = await self._get_user_credentials()
|
|
1402
|
+
address = getattr(credentials, "funder_address", None) or getattr(credentials, "wallet_address", None)
|
|
1403
|
+
if not address:
|
|
1404
|
+
return {"success": False, "error": "No wallet address configured for trade lookup"}
|
|
1405
|
+
|
|
1406
|
+
# Trades are public by address — query the Data API, no signing.
|
|
1407
|
+
resp = await self._http_client.get(
|
|
1408
|
+
f"{self.DATA_API_URL}/trades",
|
|
1409
|
+
params={"user": address, "limit": params.limit},
|
|
1410
|
+
)
|
|
1411
|
+
resp.raise_for_status()
|
|
1412
|
+
trades_data = resp.json() or []
|
|
1413
|
+
|
|
1414
|
+
# Filter by market if specified
|
|
1415
|
+
if params.market_id:
|
|
1416
|
+
trades_data = [t for t in trades_data if t.get("market") == params.market_id]
|
|
1417
|
+
|
|
1418
|
+
# Limit results
|
|
1419
|
+
trades_data = trades_data[:params.limit]
|
|
1420
|
+
|
|
1421
|
+
# Format trades
|
|
1422
|
+
trades = []
|
|
1423
|
+
for trade in trades_data:
|
|
1424
|
+
trades.append({
|
|
1425
|
+
"trade_id": trade.get("id", ""),
|
|
1426
|
+
"market_id": trade.get("market", ""),
|
|
1427
|
+
"token_id": trade.get("asset", ""),
|
|
1428
|
+
"side": trade.get("side", ""),
|
|
1429
|
+
"price": float(trade.get("price", 0)),
|
|
1430
|
+
"size": float(trade.get("size", 0)),
|
|
1431
|
+
"timestamp": trade.get("timestamp"),
|
|
1432
|
+
"fee": float(trade.get("fee", 0))
|
|
1433
|
+
})
|
|
1434
|
+
|
|
1435
|
+
return {
|
|
1436
|
+
"success": True,
|
|
1437
|
+
"trade_count": len(trades),
|
|
1438
|
+
"trades": trades
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
except Exception as e:
|
|
1442
|
+
self.logger.error(f"Get trade history failed: {e}")
|
|
1443
|
+
return {"success": False, "error": f"Failed to fetch trades: {str(e)}"}
|
|
1444
|
+
|
|
1445
|
+
# =========================================================================
|
|
1446
|
+
# TRADING ACTIONS (Require Authentication + Limits Check)
|
|
1447
|
+
# =========================================================================
|
|
1448
|
+
|
|
1449
|
+
@BaseTool.action(
|
|
1450
|
+
'Place a limit order on Polymarket',
|
|
1451
|
+
param_model=PlaceLimitOrderParams
|
|
1452
|
+
)
|
|
1453
|
+
async def place_limit_order(self, params: PlaceLimitOrderParams) -> Dict[str, Any]:
|
|
1454
|
+
"""Place a limit order via authenticated CLOB API."""
|
|
1455
|
+
await self.ensure_initialized()
|
|
1456
|
+
|
|
1457
|
+
if not CLOB_AVAILABLE:
|
|
1458
|
+
cap = trade_capability()
|
|
1459
|
+
self.logger.warning("polymarket.clob_unavailable: %s", cap["reason"])
|
|
1460
|
+
return {
|
|
1461
|
+
"success": False,
|
|
1462
|
+
"error_code": "POLYMARKET_CLIENT_MISSING",
|
|
1463
|
+
"error": f"Polymarket trading client unavailable: {cap['reason']}",
|
|
1464
|
+
"suggestion": cap["install_hint"],
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
credentials = await self._get_user_credentials()
|
|
1468
|
+
|
|
1469
|
+
if not credentials:
|
|
1470
|
+
return {
|
|
1471
|
+
"success": False,
|
|
1472
|
+
"error": "No Polymarket credentials configured",
|
|
1473
|
+
"suggestion": "Configure your wallet in Settings → Polymarket"
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
if credentials.demo_mode:
|
|
1477
|
+
return {
|
|
1478
|
+
"success": False,
|
|
1479
|
+
"error": "Cannot place orders in demo mode",
|
|
1480
|
+
"suggestion": "Configure your wallet with a private key for trading"
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
if not credentials.enabled:
|
|
1484
|
+
return {
|
|
1485
|
+
"success": False,
|
|
1486
|
+
"error": "Polymarket is disabled for your account"
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
# Check trading limits
|
|
1490
|
+
limits = credentials.trading_limits
|
|
1491
|
+
limit_error = self._check_trading_limits(limits, params.size_usd)
|
|
1492
|
+
if limit_error:
|
|
1493
|
+
return {"success": False, "error": limit_error}
|
|
1494
|
+
|
|
1495
|
+
# Additional confirmation check for large orders
|
|
1496
|
+
if params.size_usd > limits.require_confirmation_above_usd:
|
|
1497
|
+
return {
|
|
1498
|
+
"success": False,
|
|
1499
|
+
"error": f"Orders above ${limits.require_confirmation_above_usd} require manual confirmation",
|
|
1500
|
+
"order_details": {
|
|
1501
|
+
"market_id": params.market_id,
|
|
1502
|
+
"side": params.side,
|
|
1503
|
+
"price": params.price,
|
|
1504
|
+
"size_usd": params.size_usd
|
|
1505
|
+
},
|
|
1506
|
+
"suggestion": "Use a smaller order size or adjust your confirmation threshold"
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
# N2: route value-moving trades through the wallet PolicyGate (catastrophic
|
|
1510
|
+
# ceiling + daily/venue caps + audit). idempotency_key=None: orders may
|
|
1511
|
+
# legitimately repeat, so caps/ceiling/audit apply without replay-blocking.
|
|
1512
|
+
from core.wallet.factory import get_policy_gate
|
|
1513
|
+
policy = get_policy_gate()
|
|
1514
|
+
decision = policy.check(venue="polymarket", amount_usd=params.size_usd, idempotency_key=None)
|
|
1515
|
+
if not decision.allowed:
|
|
1516
|
+
return {"success": False, "error": f"Policy gate denied: {decision.reason}"}
|
|
1517
|
+
|
|
1518
|
+
# T11 live kill-switch: only submit a real order when the master + venue switches
|
|
1519
|
+
# are on AND within the live cap; otherwise dry-run (validated, never submitted).
|
|
1520
|
+
from tools.crypto_trade_gate import evaluate_live_trade
|
|
1521
|
+
gate = evaluate_live_trade("polymarket", params.size_usd)
|
|
1522
|
+
if not gate.live:
|
|
1523
|
+
return {
|
|
1524
|
+
"success": False,
|
|
1525
|
+
"dry_run": True,
|
|
1526
|
+
"error": f"Order not submitted (dry-run): {gate.reason}",
|
|
1527
|
+
"order_details": {
|
|
1528
|
+
"market_id": params.market_id, "token_id": params.token_id,
|
|
1529
|
+
"side": params.side, "price": params.price, "size_usd": params.size_usd,
|
|
1530
|
+
},
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
# LIVE-only: enforce the cumulative per-market position cap (sell-exempt; fail
|
|
1534
|
+
# closed). Placed after the dry-run gate so a dry-run never triggers a live
|
|
1535
|
+
# position fetch (and never fail-closes when there is nothing to submit).
|
|
1536
|
+
position_error = await self._check_position_limit(limits, params)
|
|
1537
|
+
if position_error:
|
|
1538
|
+
return {"success": False, "error": position_error}
|
|
1539
|
+
|
|
1540
|
+
await self.rate_limit("place_limit_order")
|
|
1541
|
+
|
|
1542
|
+
client, error = await self._get_authenticated_client()
|
|
1543
|
+
if error:
|
|
1544
|
+
return {"success": False, "error": error}
|
|
1545
|
+
|
|
1546
|
+
try:
|
|
1547
|
+
# Calculate size in shares from USD amount
|
|
1548
|
+
size_shares = params.size_usd / params.price
|
|
1549
|
+
|
|
1550
|
+
# Build order arguments
|
|
1551
|
+
order_args = OrderArgs(
|
|
1552
|
+
token_id=params.token_id,
|
|
1553
|
+
price=params.price,
|
|
1554
|
+
size=size_shares,
|
|
1555
|
+
side=params.side.upper()
|
|
1556
|
+
)
|
|
1557
|
+
|
|
1558
|
+
# Create and post order
|
|
1559
|
+
result = client.create_and_post_order(order_args)
|
|
1560
|
+
|
|
1561
|
+
policy.record(
|
|
1562
|
+
venue="polymarket", action="place_limit_order",
|
|
1563
|
+
amount_usd=params.size_usd, counterparty=params.market_id,
|
|
1564
|
+
idempotency_key=None, result_ref=str(result.get("orderID"))[:80],
|
|
1565
|
+
)
|
|
1566
|
+
|
|
1567
|
+
# Log to audit
|
|
1568
|
+
if self.db:
|
|
1569
|
+
await self.db.audit_log(
|
|
1570
|
+
self._user_id,
|
|
1571
|
+
"order_placed",
|
|
1572
|
+
tool_name="polymarket",
|
|
1573
|
+
market_id=params.market_id,
|
|
1574
|
+
details={
|
|
1575
|
+
"order_id": result.get("orderID"),
|
|
1576
|
+
"side": params.side,
|
|
1577
|
+
"price": params.price,
|
|
1578
|
+
"size_usd": params.size_usd,
|
|
1579
|
+
"size_shares": size_shares
|
|
1580
|
+
}
|
|
1581
|
+
)
|
|
1582
|
+
|
|
1583
|
+
return {
|
|
1584
|
+
"success": True,
|
|
1585
|
+
"order_id": result.get("orderID"),
|
|
1586
|
+
"status": result.get("status", "pending"),
|
|
1587
|
+
"order_details": {
|
|
1588
|
+
"market_id": params.market_id,
|
|
1589
|
+
"token_id": params.token_id,
|
|
1590
|
+
"side": params.side,
|
|
1591
|
+
"price": params.price,
|
|
1592
|
+
"size_usd": params.size_usd,
|
|
1593
|
+
"size_shares": size_shares
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
except Exception as e:
|
|
1598
|
+
self.logger.error(f"Place order failed: {e}")
|
|
1599
|
+
|
|
1600
|
+
# Log failure
|
|
1601
|
+
if self.db:
|
|
1602
|
+
await self.db.audit_log(
|
|
1603
|
+
self._user_id,
|
|
1604
|
+
"order_failed",
|
|
1605
|
+
tool_name="polymarket",
|
|
1606
|
+
market_id=params.market_id,
|
|
1607
|
+
details={"error": str(e)}
|
|
1608
|
+
)
|
|
1609
|
+
|
|
1610
|
+
return {"success": False, "error": f"Order placement failed: {str(e)}"}
|
|
1611
|
+
|
|
1612
|
+
@BaseTool.action(
|
|
1613
|
+
'Place a marketable order on Polymarket (crosses the spread for immediate fill)',
|
|
1614
|
+
param_model=PlaceMarketOrderParams
|
|
1615
|
+
)
|
|
1616
|
+
async def place_market_order(self, params: PlaceMarketOrderParams) -> Dict[str, Any]:
|
|
1617
|
+
"""Marketable order: price aggressively across the spread, then route through the
|
|
1618
|
+
same gates as place_limit_order (limits, >$500 confirmation, PolicyGate, exposure)."""
|
|
1619
|
+
await self.ensure_initialized()
|
|
1620
|
+
|
|
1621
|
+
price_res = await self.get_current_price(
|
|
1622
|
+
GetPriceParams(token_id=params.token_id, market_id=params.market_id)
|
|
1623
|
+
)
|
|
1624
|
+
mid = price_res.get("price") if price_res.get("success") else None
|
|
1625
|
+
if mid is None:
|
|
1626
|
+
return {"success": False, "error": "Cannot fetch a market price for the market order"}
|
|
1627
|
+
|
|
1628
|
+
# Cross the spread by a slippage buffer; clamp to the valid 0.01–0.99 band.
|
|
1629
|
+
SLIPPAGE = 0.03
|
|
1630
|
+
mid = float(mid)
|
|
1631
|
+
if params.side.upper() == "BUY":
|
|
1632
|
+
limit_price = min(0.99, round(mid * (1 + SLIPPAGE), 2))
|
|
1633
|
+
else:
|
|
1634
|
+
limit_price = max(0.01, round(mid * (1 - SLIPPAGE), 2))
|
|
1635
|
+
|
|
1636
|
+
return await self.place_limit_order(PlaceLimitOrderParams(
|
|
1637
|
+
market_id=params.market_id,
|
|
1638
|
+
token_id=params.token_id,
|
|
1639
|
+
side=params.side,
|
|
1640
|
+
price=limit_price,
|
|
1641
|
+
size_usd=params.size_usd,
|
|
1642
|
+
))
|
|
1643
|
+
|
|
1644
|
+
@BaseTool.action(
|
|
1645
|
+
'Get open orders',
|
|
1646
|
+
param_model=GetOpenOrdersParams
|
|
1647
|
+
)
|
|
1648
|
+
async def get_open_orders(self, params: GetOpenOrdersParams) -> Dict[str, Any]:
|
|
1649
|
+
"""Get user's open orders via authenticated CLOB API."""
|
|
1650
|
+
await self.ensure_initialized()
|
|
1651
|
+
await self.rate_limit("get_open_orders")
|
|
1652
|
+
|
|
1653
|
+
credentials = await self._get_user_credentials()
|
|
1654
|
+
|
|
1655
|
+
if not credentials or credentials.demo_mode:
|
|
1656
|
+
return {
|
|
1657
|
+
"success": True,
|
|
1658
|
+
"total_open_orders": 0,
|
|
1659
|
+
"orders": [],
|
|
1660
|
+
"note": "Demo mode - no trading orders"
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
client, error = await self._get_authenticated_client()
|
|
1664
|
+
if error:
|
|
1665
|
+
return {"success": False, "error": error}
|
|
1666
|
+
|
|
1667
|
+
try:
|
|
1668
|
+
# Get orders from CLOB API
|
|
1669
|
+
orders_params = {}
|
|
1670
|
+
if params.market_id:
|
|
1671
|
+
orders_params["market"] = params.market_id
|
|
1672
|
+
|
|
1673
|
+
orders_data = client.get_open_orders(**orders_params)
|
|
1674
|
+
|
|
1675
|
+
# Format orders
|
|
1676
|
+
orders = []
|
|
1677
|
+
for order in orders_data:
|
|
1678
|
+
orders.append({
|
|
1679
|
+
"order_id": order.get("id", ""),
|
|
1680
|
+
"market_id": order.get("market", ""),
|
|
1681
|
+
"token_id": order.get("asset", ""),
|
|
1682
|
+
"side": order.get("side", ""),
|
|
1683
|
+
"price": float(order.get("price", 0)),
|
|
1684
|
+
"size": float(order.get("size", 0)),
|
|
1685
|
+
"size_matched": float(order.get("sizeMatched", 0)),
|
|
1686
|
+
"status": order.get("status", ""),
|
|
1687
|
+
"created_at": order.get("createdAt")
|
|
1688
|
+
})
|
|
1689
|
+
|
|
1690
|
+
return {
|
|
1691
|
+
"success": True,
|
|
1692
|
+
"total_open_orders": len(orders),
|
|
1693
|
+
"orders": orders
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
except Exception as e:
|
|
1697
|
+
self.logger.error(f"Get open orders failed: {e}")
|
|
1698
|
+
return {"success": False, "error": f"Failed to fetch orders: {str(e)}"}
|
|
1699
|
+
|
|
1700
|
+
@BaseTool.action(
|
|
1701
|
+
'Get order history',
|
|
1702
|
+
param_model=GetOrderHistoryParams
|
|
1703
|
+
)
|
|
1704
|
+
async def get_order_history(self, params: GetOrderHistoryParams) -> Dict[str, Any]:
|
|
1705
|
+
"""Get user's order history via authenticated CLOB API."""
|
|
1706
|
+
await self.ensure_initialized()
|
|
1707
|
+
await self.rate_limit("get_order_history")
|
|
1708
|
+
|
|
1709
|
+
credentials = await self._get_user_credentials()
|
|
1710
|
+
|
|
1711
|
+
if not credentials or credentials.demo_mode:
|
|
1712
|
+
return {
|
|
1713
|
+
"success": True,
|
|
1714
|
+
"total_orders": 0,
|
|
1715
|
+
"orders": [],
|
|
1716
|
+
"note": "Demo mode - no trading orders"
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
client, error = await self._get_authenticated_client()
|
|
1720
|
+
if error:
|
|
1721
|
+
return {"success": False, "error": error}
|
|
1722
|
+
|
|
1723
|
+
try:
|
|
1724
|
+
# Get all orders (includes historical)
|
|
1725
|
+
# Note: CLOB API may not have direct history endpoint, using get_orders
|
|
1726
|
+
orders_data = client.get_open_orders()
|
|
1727
|
+
|
|
1728
|
+
# Filter by status if specified
|
|
1729
|
+
if params.status:
|
|
1730
|
+
orders_data = [o for o in orders_data if o.get("status") == params.status]
|
|
1731
|
+
|
|
1732
|
+
# Limit results
|
|
1733
|
+
orders_data = orders_data[:params.limit]
|
|
1734
|
+
|
|
1735
|
+
# Format orders
|
|
1736
|
+
orders = []
|
|
1737
|
+
for order in orders_data:
|
|
1738
|
+
orders.append({
|
|
1739
|
+
"order_id": order.get("id", ""),
|
|
1740
|
+
"market_id": order.get("market", ""),
|
|
1741
|
+
"token_id": order.get("asset", ""),
|
|
1742
|
+
"side": order.get("side", ""),
|
|
1743
|
+
"price": float(order.get("price", 0)),
|
|
1744
|
+
"size": float(order.get("size", 0)),
|
|
1745
|
+
"size_matched": float(order.get("sizeMatched", 0)),
|
|
1746
|
+
"status": order.get("status", ""),
|
|
1747
|
+
"created_at": order.get("createdAt")
|
|
1748
|
+
})
|
|
1749
|
+
|
|
1750
|
+
return {
|
|
1751
|
+
"success": True,
|
|
1752
|
+
"total_orders": len(orders),
|
|
1753
|
+
"orders": orders
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
except Exception as e:
|
|
1757
|
+
self.logger.error(f"Get order history failed: {e}")
|
|
1758
|
+
return {"success": False, "error": f"Failed to fetch order history: {str(e)}"}
|
|
1759
|
+
|
|
1760
|
+
@BaseTool.action(
|
|
1761
|
+
'Cancel an order',
|
|
1762
|
+
param_model=CancelOrderParams
|
|
1763
|
+
)
|
|
1764
|
+
async def cancel_order(self, params: CancelOrderParams) -> Dict[str, Any]:
|
|
1765
|
+
"""Cancel an open order via authenticated CLOB API."""
|
|
1766
|
+
await self.ensure_initialized()
|
|
1767
|
+
await self.rate_limit("cancel_order")
|
|
1768
|
+
|
|
1769
|
+
client, error = await self._get_authenticated_client()
|
|
1770
|
+
if error:
|
|
1771
|
+
return {"success": False, "error": error}
|
|
1772
|
+
|
|
1773
|
+
try:
|
|
1774
|
+
# Cancel the order
|
|
1775
|
+
result = client.cancel_order(params.order_id)
|
|
1776
|
+
|
|
1777
|
+
# Log to audit
|
|
1778
|
+
if self.db:
|
|
1779
|
+
await self.db.audit_log(
|
|
1780
|
+
self._user_id,
|
|
1781
|
+
"order_cancelled",
|
|
1782
|
+
tool_name="polymarket",
|
|
1783
|
+
details={"order_id": params.order_id}
|
|
1784
|
+
)
|
|
1785
|
+
|
|
1786
|
+
return {
|
|
1787
|
+
"success": True,
|
|
1788
|
+
"order_id": params.order_id,
|
|
1789
|
+
"status": "cancelled",
|
|
1790
|
+
"message": "Order cancelled successfully"
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
except Exception as e:
|
|
1794
|
+
self.logger.error(f"Cancel order failed: {e}")
|
|
1795
|
+
return {"success": False, "error": f"Failed to cancel order: {str(e)}"}
|
|
1796
|
+
|
|
1797
|
+
@BaseTool.action(
|
|
1798
|
+
'Cancel all orders',
|
|
1799
|
+
param_model=CancelAllOrdersParams
|
|
1800
|
+
)
|
|
1801
|
+
async def cancel_all_orders(self, params: CancelAllOrdersParams) -> Dict[str, Any]:
|
|
1802
|
+
"""Cancel all open orders via authenticated CLOB API."""
|
|
1803
|
+
await self.ensure_initialized()
|
|
1804
|
+
await self.rate_limit("cancel_all_orders")
|
|
1805
|
+
|
|
1806
|
+
client, error = await self._get_authenticated_client()
|
|
1807
|
+
if error:
|
|
1808
|
+
return {"success": False, "error": error}
|
|
1809
|
+
|
|
1810
|
+
try:
|
|
1811
|
+
# Cancel all orders (optionally filtered by market)
|
|
1812
|
+
if params.market_id:
|
|
1813
|
+
result = client.cancel_market_orders(market=params.market_id)
|
|
1814
|
+
else:
|
|
1815
|
+
result = client.cancel_all()
|
|
1816
|
+
|
|
1817
|
+
# Log to audit
|
|
1818
|
+
if self.db:
|
|
1819
|
+
await self.db.audit_log(
|
|
1820
|
+
self._user_id,
|
|
1821
|
+
"all_orders_cancelled",
|
|
1822
|
+
tool_name="polymarket",
|
|
1823
|
+
market_id=params.market_id,
|
|
1824
|
+
details={"market_filter": params.market_id}
|
|
1825
|
+
)
|
|
1826
|
+
|
|
1827
|
+
return {
|
|
1828
|
+
"success": True,
|
|
1829
|
+
"market_id": params.market_id,
|
|
1830
|
+
"status": "all_cancelled",
|
|
1831
|
+
"message": f"All orders cancelled{' for market ' + params.market_id if params.market_id else ''}"
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
except Exception as e:
|
|
1835
|
+
self.logger.error(f"Cancel all orders failed: {e}")
|
|
1836
|
+
return {"success": False, "error": f"Failed to cancel orders: {str(e)}"}
|
|
1837
|
+
|
|
1838
|
+
# =========================================================================
|
|
1839
|
+
# TOOL DISCOVERY
|
|
1840
|
+
# =========================================================================
|
|
1841
|
+
|
|
1842
|
+
def get_available_tools(self) -> List[Dict[str, Any]]:
|
|
1843
|
+
"""
|
|
1844
|
+
Get tool list for LLM discovery.
|
|
1845
|
+
|
|
1846
|
+
Returns list of available actions with their schemas.
|
|
1847
|
+
"""
|
|
1848
|
+
if self._tools_cache is not None:
|
|
1849
|
+
return self._tools_cache
|
|
1850
|
+
|
|
1851
|
+
tools = [
|
|
1852
|
+
# Market Discovery
|
|
1853
|
+
{
|
|
1854
|
+
"name": "search_markets",
|
|
1855
|
+
"description": "Search for prediction markets on Polymarket",
|
|
1856
|
+
"inputSchema": SearchMarketsParams.model_json_schema()
|
|
1857
|
+
},
|
|
1858
|
+
{
|
|
1859
|
+
"name": "get_trending_markets",
|
|
1860
|
+
"description": "Get trending prediction markets by 24h volume",
|
|
1861
|
+
"inputSchema": TrendingMarketsParams.model_json_schema()
|
|
1862
|
+
},
|
|
1863
|
+
{
|
|
1864
|
+
"name": "filter_markets_by_category",
|
|
1865
|
+
"description": "Filter markets by category (politics, sports, crypto, etc.)",
|
|
1866
|
+
"inputSchema": FilterByCategoryParams.model_json_schema()
|
|
1867
|
+
},
|
|
1868
|
+
{
|
|
1869
|
+
"name": "get_featured_markets",
|
|
1870
|
+
"description": "Get featured/highlighted markets",
|
|
1871
|
+
"inputSchema": TrendingMarketsParams.model_json_schema()
|
|
1872
|
+
},
|
|
1873
|
+
{
|
|
1874
|
+
"name": "get_closing_soon_markets",
|
|
1875
|
+
"description": "Get markets closing within specified hours",
|
|
1876
|
+
"inputSchema": ClosingSoonParams.model_json_schema()
|
|
1877
|
+
},
|
|
1878
|
+
{
|
|
1879
|
+
"name": "get_sports_markets",
|
|
1880
|
+
"description": "Get sports betting markets",
|
|
1881
|
+
"inputSchema": TrendingMarketsParams.model_json_schema()
|
|
1882
|
+
},
|
|
1883
|
+
{
|
|
1884
|
+
"name": "get_crypto_markets",
|
|
1885
|
+
"description": "Get cryptocurrency-related markets",
|
|
1886
|
+
"inputSchema": TrendingMarketsParams.model_json_schema()
|
|
1887
|
+
},
|
|
1888
|
+
# Market Data
|
|
1889
|
+
{
|
|
1890
|
+
"name": "get_market_details",
|
|
1891
|
+
"description": "Get detailed information about a specific market",
|
|
1892
|
+
"inputSchema": MarketDetailsParams.model_json_schema()
|
|
1893
|
+
},
|
|
1894
|
+
{
|
|
1895
|
+
"name": "get_current_price",
|
|
1896
|
+
"description": "Get current price for a market token",
|
|
1897
|
+
"inputSchema": GetPriceParams.model_json_schema()
|
|
1898
|
+
},
|
|
1899
|
+
{
|
|
1900
|
+
"name": "get_orderbook",
|
|
1901
|
+
"description": "Get orderbook depth for a market token",
|
|
1902
|
+
"inputSchema": GetOrderbookParams.model_json_schema()
|
|
1903
|
+
},
|
|
1904
|
+
{
|
|
1905
|
+
"name": "get_spread",
|
|
1906
|
+
"description": "Get bid-ask spread for a token",
|
|
1907
|
+
"inputSchema": GetSpreadParams.model_json_schema()
|
|
1908
|
+
},
|
|
1909
|
+
{
|
|
1910
|
+
"name": "get_market_volume",
|
|
1911
|
+
"description": "Get volume statistics for a market",
|
|
1912
|
+
"inputSchema": GetVolumeParams.model_json_schema()
|
|
1913
|
+
},
|
|
1914
|
+
# Portfolio (requires auth)
|
|
1915
|
+
{
|
|
1916
|
+
"name": "get_all_positions",
|
|
1917
|
+
"description": "Get all portfolio positions (requires trading credentials)",
|
|
1918
|
+
"inputSchema": GetPositionsParams.model_json_schema()
|
|
1919
|
+
},
|
|
1920
|
+
{
|
|
1921
|
+
"name": "get_portfolio_summary",
|
|
1922
|
+
"description": "Get portfolio value and P&L summary (requires trading credentials)",
|
|
1923
|
+
"inputSchema": PortfolioSummaryParams.model_json_schema()
|
|
1924
|
+
},
|
|
1925
|
+
{
|
|
1926
|
+
"name": "get_trade_history",
|
|
1927
|
+
"description": "Get trade history (requires trading credentials)",
|
|
1928
|
+
"inputSchema": GetTradeHistoryParams.model_json_schema()
|
|
1929
|
+
},
|
|
1930
|
+
# Trading (requires auth)
|
|
1931
|
+
{
|
|
1932
|
+
"name": "place_limit_order",
|
|
1933
|
+
"description": "Place a limit order (requires trading credentials)",
|
|
1934
|
+
"inputSchema": PlaceLimitOrderParams.model_json_schema()
|
|
1935
|
+
},
|
|
1936
|
+
{
|
|
1937
|
+
"name": "place_market_order",
|
|
1938
|
+
"description": "Place a marketable order for immediate fill (requires trading credentials)",
|
|
1939
|
+
"inputSchema": PlaceMarketOrderParams.model_json_schema()
|
|
1940
|
+
},
|
|
1941
|
+
{
|
|
1942
|
+
"name": "get_open_orders",
|
|
1943
|
+
"description": "Get open orders",
|
|
1944
|
+
"inputSchema": GetOpenOrdersParams.model_json_schema()
|
|
1945
|
+
},
|
|
1946
|
+
{
|
|
1947
|
+
"name": "get_order_history",
|
|
1948
|
+
"description": "Get order history",
|
|
1949
|
+
"inputSchema": GetOrderHistoryParams.model_json_schema()
|
|
1950
|
+
},
|
|
1951
|
+
{
|
|
1952
|
+
"name": "cancel_order",
|
|
1953
|
+
"description": "Cancel an open order (requires trading credentials)",
|
|
1954
|
+
"inputSchema": CancelOrderParams.model_json_schema()
|
|
1955
|
+
},
|
|
1956
|
+
{
|
|
1957
|
+
"name": "cancel_all_orders",
|
|
1958
|
+
"description": "Cancel all open orders (requires trading credentials)",
|
|
1959
|
+
"inputSchema": CancelAllOrdersParams.model_json_schema()
|
|
1960
|
+
},
|
|
1961
|
+
{
|
|
1962
|
+
"name": "get_balance",
|
|
1963
|
+
"description": "Get USDC balance and allowances (requires trading credentials)",
|
|
1964
|
+
"inputSchema": GetBalanceParams.model_json_schema()
|
|
1965
|
+
},
|
|
1966
|
+
]
|
|
1967
|
+
|
|
1968
|
+
self._tools_cache = tools
|
|
1969
|
+
return tools
|
|
1970
|
+
|
|
1971
|
+
async def execute_action(self, tool_name: str, arguments: Dict[str, Any]) -> ExecutionResult:
|
|
1972
|
+
"""
|
|
1973
|
+
Execute an action by name.
|
|
1974
|
+
|
|
1975
|
+
Maps action names to methods for programmatic access.
|
|
1976
|
+
Called by API routes and agents.
|
|
1977
|
+
"""
|
|
1978
|
+
start_time = time.time()
|
|
1979
|
+
|
|
1980
|
+
# Map tool name to method
|
|
1981
|
+
tool_map = {
|
|
1982
|
+
"search_markets": (self.search_markets, SearchMarketsParams),
|
|
1983
|
+
"get_trending_markets": (self.get_trending_markets, TrendingMarketsParams),
|
|
1984
|
+
"filter_markets_by_category": (self.filter_markets_by_category, FilterByCategoryParams),
|
|
1985
|
+
"get_featured_markets": (self.get_featured_markets, TrendingMarketsParams),
|
|
1986
|
+
"get_closing_soon_markets": (self.get_closing_soon_markets, ClosingSoonParams),
|
|
1987
|
+
"get_sports_markets": (self.get_sports_markets, TrendingMarketsParams),
|
|
1988
|
+
"get_crypto_markets": (self.get_crypto_markets, TrendingMarketsParams),
|
|
1989
|
+
"get_market_details": (self.get_market_details, MarketDetailsParams),
|
|
1990
|
+
"get_current_price": (self.get_current_price, GetPriceParams),
|
|
1991
|
+
"get_orderbook": (self.get_orderbook, GetOrderbookParams),
|
|
1992
|
+
"get_spread": (self.get_spread, GetSpreadParams),
|
|
1993
|
+
"get_market_volume": (self.get_market_volume, GetVolumeParams),
|
|
1994
|
+
"get_all_positions": (self.get_all_positions, GetPositionsParams),
|
|
1995
|
+
"get_portfolio_summary": (self.get_portfolio_summary, PortfolioSummaryParams),
|
|
1996
|
+
"get_trade_history": (self.get_trade_history, GetTradeHistoryParams),
|
|
1997
|
+
"place_limit_order": (self.place_limit_order, PlaceLimitOrderParams),
|
|
1998
|
+
"place_market_order": (self.place_market_order, PlaceMarketOrderParams),
|
|
1999
|
+
"get_open_orders": (self.get_open_orders, GetOpenOrdersParams),
|
|
2000
|
+
"get_order_history": (self.get_order_history, GetOrderHistoryParams),
|
|
2001
|
+
"cancel_order": (self.cancel_order, CancelOrderParams),
|
|
2002
|
+
"cancel_all_orders": (self.cancel_all_orders, CancelAllOrdersParams),
|
|
2003
|
+
"get_balance": (self.get_balance, GetBalanceParams),
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
if tool_name not in tool_map:
|
|
2007
|
+
return ExecutionResult(
|
|
2008
|
+
success=False,
|
|
2009
|
+
error=f"Unknown tool: {tool_name}. Available: {', '.join(tool_map.keys())}",
|
|
2010
|
+
tool_name=tool_name
|
|
2011
|
+
)
|
|
2012
|
+
|
|
2013
|
+
method, param_class = tool_map[tool_name]
|
|
2014
|
+
|
|
2015
|
+
try:
|
|
2016
|
+
# Parse and validate parameters
|
|
2017
|
+
params = param_class(**arguments)
|
|
2018
|
+
|
|
2019
|
+
# Execute
|
|
2020
|
+
result = await method(params)
|
|
2021
|
+
|
|
2022
|
+
execution_time = (time.time() - start_time) * 1000
|
|
2023
|
+
|
|
2024
|
+
return ExecutionResult(
|
|
2025
|
+
success=result.get("success", False),
|
|
2026
|
+
data=result,
|
|
2027
|
+
error=result.get("error"),
|
|
2028
|
+
tool_name=tool_name,
|
|
2029
|
+
execution_time_ms=execution_time
|
|
2030
|
+
)
|
|
2031
|
+
|
|
2032
|
+
except Exception as e:
|
|
2033
|
+
execution_time = (time.time() - start_time) * 1000
|
|
2034
|
+
self.logger.error(f"Tool execution failed: {tool_name}: {e}")
|
|
2035
|
+
return ExecutionResult(
|
|
2036
|
+
success=False,
|
|
2037
|
+
error=str(e),
|
|
2038
|
+
tool_name=tool_name,
|
|
2039
|
+
execution_time_ms=execution_time
|
|
2040
|
+
)
|
|
2041
|
+
|
|
2042
|
+
|
|
2043
|
+
|
|
2044
|
+
# =============================================================================
|
|
2045
|
+
# READ / TRADE SPLIT (additive)
|
|
2046
|
+
# =============================================================================
|
|
2047
|
+
|
|
2048
|
+
# Wallet-free read actions. Discovery + market data are public (Gamma/CLOB reads);
|
|
2049
|
+
# positions/trades are public via the Data API. Order-status reads (get_open_orders/
|
|
2050
|
+
# get_order_history) and get_balance stay on the gated trade tool (CLOB auth).
|
|
2051
|
+
PM_READ_ACTIONS = frozenset({
|
|
2052
|
+
"search_markets", "get_trending_markets", "filter_markets_by_category",
|
|
2053
|
+
"get_featured_markets", "get_closing_soon_markets", "get_sports_markets",
|
|
2054
|
+
"get_crypto_markets", "get_market_details", "get_current_price", "get_orderbook",
|
|
2055
|
+
"get_spread", "get_market_volume", "get_all_positions", "get_portfolio_summary",
|
|
2056
|
+
"get_trade_history",
|
|
2057
|
+
})
|
|
2058
|
+
|
|
2059
|
+
|
|
2060
|
+
class PolymarketDataTool(PolymarketTool):
|
|
2061
|
+
"""Read-only Polymarket tool (no wallet, delegatable). Exposes only PM_READ_ACTIONS;
|
|
2062
|
+
trade actions are filtered at registration, advertisement, and execution."""
|
|
2063
|
+
|
|
2064
|
+
tool_id = "polymarket_data"
|
|
2065
|
+
name = "polymarket_data"
|
|
2066
|
+
description = "Polymarket prediction markets — read-only market data & research (no wallet)"
|
|
2067
|
+
|
|
2068
|
+
def get_actions(self) -> Dict[str, Any]:
|
|
2069
|
+
return {k: v for k, v in super().get_actions().items() if k in PM_READ_ACTIONS}
|
|
2070
|
+
|
|
2071
|
+
def get_available_tools(self) -> List[Dict[str, Any]]:
|
|
2072
|
+
return [t for t in super().get_available_tools() if t.get("name") in PM_READ_ACTIONS]
|
|
2073
|
+
|
|
2074
|
+
async def execute_action(self, tool_name: str, arguments: Dict[str, Any]):
|
|
2075
|
+
if tool_name not in PM_READ_ACTIONS:
|
|
2076
|
+
return ExecutionResult(
|
|
2077
|
+
success=False,
|
|
2078
|
+
error=f"'{tool_name}' is a trade action; use the gated 'polymarket' tool. "
|
|
2079
|
+
f"'polymarket_data' is read-only.",
|
|
2080
|
+
tool_name=tool_name,
|
|
2081
|
+
)
|
|
2082
|
+
return await super().execute_action(tool_name, arguments)
|