clearfills-firewall 0.1.0__tar.gz
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.
- clearfills_firewall-0.1.0/.gitignore +10 -0
- clearfills_firewall-0.1.0/PKG-INFO +122 -0
- clearfills_firewall-0.1.0/README.md +91 -0
- clearfills_firewall-0.1.0/pyproject.toml +68 -0
- clearfills_firewall-0.1.0/src/clearfills_firewall/__init__.py +50 -0
- clearfills_firewall-0.1.0/src/clearfills_firewall/adapters.py +196 -0
- clearfills_firewall-0.1.0/src/clearfills_firewall/attestation.py +260 -0
- clearfills_firewall-0.1.0/src/clearfills_firewall/killswitch.py +185 -0
- clearfills_firewall-0.1.0/src/clearfills_firewall/ledger.py +180 -0
- clearfills_firewall-0.1.0/src/clearfills_firewall/mcp_server.py +206 -0
- clearfills_firewall-0.1.0/src/clearfills_firewall/models.py +222 -0
- clearfills_firewall-0.1.0/src/clearfills_firewall/policy.py +275 -0
- clearfills_firewall-0.1.0/src/clearfills_firewall/server.py +284 -0
- clearfills_firewall-0.1.0/tests/test_adapters_and_interfaces.py +261 -0
- clearfills_firewall-0.1.0/tests/test_firewall_core.py +317 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: clearfills-firewall
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Deterministic Ed25519 pre-trade risk firewall & MCP server for AI trading agents (clearfills.com)
|
|
5
|
+
Project-URL: Homepage, https://clearfills.com
|
|
6
|
+
Project-URL: Documentation, https://clearfills.com/llms.txt
|
|
7
|
+
Project-URL: Repository, https://github.com/clearfills/clearfills
|
|
8
|
+
Project-URL: Issues, https://github.com/clearfills/clearfills/issues
|
|
9
|
+
Author-email: "ClearFills / MLDSAI Inc." <desk@mldsai.com>
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
Keywords: ai-trading,alpaca,ed25519,ibkr,kalshi,mcp,polymarket,quant,risk-firewall,trading-agents
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
15
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
20
|
+
Classifier: Topic :: Security :: Cryptography
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Requires-Dist: cryptography>=42.0.0
|
|
23
|
+
Requires-Dist: fastapi>=0.111.0
|
|
24
|
+
Requires-Dist: pydantic>=2.0.0
|
|
25
|
+
Requires-Dist: pyyaml>=6.0.0
|
|
26
|
+
Requires-Dist: uvicorn>=0.30.0
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: httpx>=0.27.0; extra == 'dev'
|
|
29
|
+
Requires-Dist: pytest>=8.0.0; extra == 'dev'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# ClearFills Pre-Trade Risk Firewall (`clearfills-firewall`)
|
|
33
|
+
|
|
34
|
+
[](https://www.apache.org/licenses/LICENSE-2.0)
|
|
35
|
+
[](https://www.python.org/downloads/)
|
|
36
|
+
[](https://clearfills.com)
|
|
37
|
+
|
|
38
|
+
**Deterministic Ed25519 pre-trade risk firewall & MCP server for AI trading agents.**
|
|
39
|
+
|
|
40
|
+
Sits between any untrusted AI trading agent (Claude, Grok, Codex, `TradingAgents`, `ai-hedge-fund`, or custom Python loops) and your execution gateway so LLMs **never hold brokerage API keys** and can never hallucinate or get prompt-injected into an unbounded market sweep.
|
|
41
|
+
|
|
42
|
+
- **Interactive Simulator & Live Arena:** [https://clearfills.com](https://clearfills.com)
|
|
43
|
+
- **LLM Overview:** [https://clearfills.com/llms.txt](https://clearfills.com/llms.txt)
|
|
44
|
+
- **Agent Operational Contract:** [https://clearfills.com/agents.txt](https://clearfills.com/agents.txt)
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install clearfills-firewall
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Run the MCP stdio server:
|
|
55
|
+
```bash
|
|
56
|
+
clearfills-firewall-mcp
|
|
57
|
+
# or: uvx --from clearfills-firewall clearfills-firewall-mcp
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Run the FastAPI HTTP firewall service:
|
|
61
|
+
```bash
|
|
62
|
+
clearfills-firewall
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Connect to Claude Code & Cursor
|
|
68
|
+
|
|
69
|
+
### Claude Code
|
|
70
|
+
```bash
|
|
71
|
+
claude mcp add clearfills -- uvx --from clearfills-firewall clearfills-firewall-mcp
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Cursor (`.cursor/mcp.json`) / Project `.mcp.json`
|
|
75
|
+
```json
|
|
76
|
+
{
|
|
77
|
+
"mcpServers": {
|
|
78
|
+
"clearfills": {
|
|
79
|
+
"command": "uvx",
|
|
80
|
+
"args": ["--from", "clearfills-firewall", "clearfills-firewall-mcp"]
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## Deterministic Policy Invariants (Zero LLM in the Loop)
|
|
89
|
+
|
|
90
|
+
Every `TradeProposal` must satisfy all deterministic math rules before an Ed25519 attestation is signed:
|
|
91
|
+
|
|
92
|
+
| Rejection Code | Invariant Enforced |
|
|
93
|
+
| :--- | :--- |
|
|
94
|
+
| `MARKET_ORDER_FORBIDDEN` | Strict `LMT` (limit) orders only — `MKT` sweeps are unconditionally vetoed |
|
|
95
|
+
| `MISSING_HARD_STOP` | Atomic bracket stop-loss required (or bounded binary collateral on Polymarket/Kalshi) |
|
|
96
|
+
| `MAX_TRADE_RISK_EXCEEDED` | <= 1.5% NLV per equity trade / <= 1.0% fractional Kelly cap on binary markets |
|
|
97
|
+
| `MAX_POSITION_NOTIONAL_EXCEEDED` | <= 20% gross NLV concentration cap |
|
|
98
|
+
| `DAILY_DRAWDOWN_KILLSWITCH` | Fail-closed intraday halt at -3.0% PnL |
|
|
99
|
+
| `NONCE_ALREADY_SPENT` | Single-use 120-second Ed25519 attestation nonce; replays rejected and logged |
|
|
100
|
+
|
|
101
|
+
Every `APPROVED`, `VETO`, and `VETO (REPLAY)` decision appends to a **SHA-256 hash-chained audit ledger** (`prev_hash -> entry_hash`).
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
## Drop-In Shims for Open-Source Trading Agents
|
|
106
|
+
|
|
107
|
+
Wrap `TauricResearch/TradingAgents` or `virattt/ai-hedge-fund` without rewriting their research pipelines:
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
from clearfills_firewall import FirewallService
|
|
111
|
+
from clearfills_firewall.shims import TradingAgentsShim, AIHedgeFundShim
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## Open Core vs. Pro Infrastructure Kit
|
|
117
|
+
|
|
118
|
+
- **Open Core (`clearfills-firewall`, Apache-2.0 — $0):** Deterministic risk engine, Ed25519 120s TTL attestation authority, replay protection, kill-switch, SHA-256 audit ledger, MCP stdio server, FastAPI server, and `TradingAgents` / `ai-hedge-fund` shims.
|
|
119
|
+
- **Pro Infrastructure Kit ($299 one-time):** Turnkey private source repo with Fly.io + Tailscale private mesh, headless IB Gateway + IBC + API-handshake watchdog, attested-only IBKR / Alpaca / Polymarket CLOB / Kalshi adapters, and Web Console → [clearfills.com/#pricing](https://clearfills.com/#pricing).
|
|
120
|
+
- **Private Desk Install (MLDSAI Inc., $15k–$25k):** Custom deployment for family offices and prop desks → [Book 30-min call](https://cal.com/richard-abrich/30min).
|
|
121
|
+
|
|
122
|
+
*Risk engineering and execution software only. Not investment advice.*
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# ClearFills Pre-Trade Risk Firewall (`clearfills-firewall`)
|
|
2
|
+
|
|
3
|
+
[](https://www.apache.org/licenses/LICENSE-2.0)
|
|
4
|
+
[](https://www.python.org/downloads/)
|
|
5
|
+
[](https://clearfills.com)
|
|
6
|
+
|
|
7
|
+
**Deterministic Ed25519 pre-trade risk firewall & MCP server for AI trading agents.**
|
|
8
|
+
|
|
9
|
+
Sits between any untrusted AI trading agent (Claude, Grok, Codex, `TradingAgents`, `ai-hedge-fund`, or custom Python loops) and your execution gateway so LLMs **never hold brokerage API keys** and can never hallucinate or get prompt-injected into an unbounded market sweep.
|
|
10
|
+
|
|
11
|
+
- **Interactive Simulator & Live Arena:** [https://clearfills.com](https://clearfills.com)
|
|
12
|
+
- **LLM Overview:** [https://clearfills.com/llms.txt](https://clearfills.com/llms.txt)
|
|
13
|
+
- **Agent Operational Contract:** [https://clearfills.com/agents.txt](https://clearfills.com/agents.txt)
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install clearfills-firewall
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Run the MCP stdio server:
|
|
24
|
+
```bash
|
|
25
|
+
clearfills-firewall-mcp
|
|
26
|
+
# or: uvx --from clearfills-firewall clearfills-firewall-mcp
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Run the FastAPI HTTP firewall service:
|
|
30
|
+
```bash
|
|
31
|
+
clearfills-firewall
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## Connect to Claude Code & Cursor
|
|
37
|
+
|
|
38
|
+
### Claude Code
|
|
39
|
+
```bash
|
|
40
|
+
claude mcp add clearfills -- uvx --from clearfills-firewall clearfills-firewall-mcp
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Cursor (`.cursor/mcp.json`) / Project `.mcp.json`
|
|
44
|
+
```json
|
|
45
|
+
{
|
|
46
|
+
"mcpServers": {
|
|
47
|
+
"clearfills": {
|
|
48
|
+
"command": "uvx",
|
|
49
|
+
"args": ["--from", "clearfills-firewall", "clearfills-firewall-mcp"]
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Deterministic Policy Invariants (Zero LLM in the Loop)
|
|
58
|
+
|
|
59
|
+
Every `TradeProposal` must satisfy all deterministic math rules before an Ed25519 attestation is signed:
|
|
60
|
+
|
|
61
|
+
| Rejection Code | Invariant Enforced |
|
|
62
|
+
| :--- | :--- |
|
|
63
|
+
| `MARKET_ORDER_FORBIDDEN` | Strict `LMT` (limit) orders only — `MKT` sweeps are unconditionally vetoed |
|
|
64
|
+
| `MISSING_HARD_STOP` | Atomic bracket stop-loss required (or bounded binary collateral on Polymarket/Kalshi) |
|
|
65
|
+
| `MAX_TRADE_RISK_EXCEEDED` | <= 1.5% NLV per equity trade / <= 1.0% fractional Kelly cap on binary markets |
|
|
66
|
+
| `MAX_POSITION_NOTIONAL_EXCEEDED` | <= 20% gross NLV concentration cap |
|
|
67
|
+
| `DAILY_DRAWDOWN_KILLSWITCH` | Fail-closed intraday halt at -3.0% PnL |
|
|
68
|
+
| `NONCE_ALREADY_SPENT` | Single-use 120-second Ed25519 attestation nonce; replays rejected and logged |
|
|
69
|
+
|
|
70
|
+
Every `APPROVED`, `VETO`, and `VETO (REPLAY)` decision appends to a **SHA-256 hash-chained audit ledger** (`prev_hash -> entry_hash`).
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## Drop-In Shims for Open-Source Trading Agents
|
|
75
|
+
|
|
76
|
+
Wrap `TauricResearch/TradingAgents` or `virattt/ai-hedge-fund` without rewriting their research pipelines:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from clearfills_firewall import FirewallService
|
|
80
|
+
from clearfills_firewall.shims import TradingAgentsShim, AIHedgeFundShim
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## Open Core vs. Pro Infrastructure Kit
|
|
86
|
+
|
|
87
|
+
- **Open Core (`clearfills-firewall`, Apache-2.0 — $0):** Deterministic risk engine, Ed25519 120s TTL attestation authority, replay protection, kill-switch, SHA-256 audit ledger, MCP stdio server, FastAPI server, and `TradingAgents` / `ai-hedge-fund` shims.
|
|
88
|
+
- **Pro Infrastructure Kit ($299 one-time):** Turnkey private source repo with Fly.io + Tailscale private mesh, headless IB Gateway + IBC + API-handshake watchdog, attested-only IBKR / Alpaca / Polymarket CLOB / Kalshi adapters, and Web Console → [clearfills.com/#pricing](https://clearfills.com/#pricing).
|
|
89
|
+
- **Private Desk Install (MLDSAI Inc., $15k–$25k):** Custom deployment for family offices and prop desks → [Book 30-min call](https://cal.com/richard-abrich/30min).
|
|
90
|
+
|
|
91
|
+
*Risk engineering and execution software only. Not investment advice.*
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25.0"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "clearfills-firewall"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Deterministic Ed25519 pre-trade risk firewall & MCP server for AI trading agents (clearfills.com)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "ClearFills / MLDSAI Inc.", email = "desk@mldsai.com" },
|
|
14
|
+
]
|
|
15
|
+
keywords = [
|
|
16
|
+
"ai-trading",
|
|
17
|
+
"mcp",
|
|
18
|
+
"risk-firewall",
|
|
19
|
+
"ed25519",
|
|
20
|
+
"ibkr",
|
|
21
|
+
"alpaca",
|
|
22
|
+
"polymarket",
|
|
23
|
+
"kalshi",
|
|
24
|
+
"trading-agents",
|
|
25
|
+
"quant",
|
|
26
|
+
]
|
|
27
|
+
classifiers = [
|
|
28
|
+
"Development Status :: 4 - Beta",
|
|
29
|
+
"Intended Audience :: Developers",
|
|
30
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
31
|
+
"License :: OSI Approved :: Apache Software License",
|
|
32
|
+
"Programming Language :: Python :: 3",
|
|
33
|
+
"Programming Language :: Python :: 3.11",
|
|
34
|
+
"Programming Language :: Python :: 3.12",
|
|
35
|
+
"Topic :: Office/Business :: Financial :: Investment",
|
|
36
|
+
"Topic :: Security :: Cryptography",
|
|
37
|
+
]
|
|
38
|
+
dependencies = [
|
|
39
|
+
"pydantic>=2.0.0",
|
|
40
|
+
"cryptography>=42.0.0",
|
|
41
|
+
"fastapi>=0.111.0",
|
|
42
|
+
"uvicorn>=0.30.0",
|
|
43
|
+
"pyyaml>=6.0.0",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
[project.optional-dependencies]
|
|
47
|
+
dev = [
|
|
48
|
+
"pytest>=8.0.0",
|
|
49
|
+
"httpx>=0.27.0",
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
[project.urls]
|
|
53
|
+
Homepage = "https://clearfills.com"
|
|
54
|
+
Documentation = "https://clearfills.com/llms.txt"
|
|
55
|
+
Repository = "https://github.com/clearfills/clearfills"
|
|
56
|
+
Issues = "https://github.com/clearfills/clearfills/issues"
|
|
57
|
+
|
|
58
|
+
[project.scripts]
|
|
59
|
+
clearfills-firewall = "clearfills_firewall.server:main"
|
|
60
|
+
clearfills-mcp = "clearfills_firewall.mcp_server:main"
|
|
61
|
+
clearfills-firewall-mcp = "clearfills_firewall.mcp_server:main"
|
|
62
|
+
|
|
63
|
+
[tool.hatch.build.targets.wheel]
|
|
64
|
+
packages = ["src/clearfills_firewall"]
|
|
65
|
+
|
|
66
|
+
[tool.pytest.ini_options]
|
|
67
|
+
testpaths = ["tests"]
|
|
68
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""ClearFills Universal Pre-Trade Risk Firewall & MCP Server (clearfills.com)."""
|
|
2
|
+
|
|
3
|
+
from .adapters import from_ai_hedge_fund_signal, from_tradingagents_decision
|
|
4
|
+
from .attestation import AttestationAuthority, canonical_order_hash
|
|
5
|
+
from .killswitch import KillSwitch, KillSwitchState
|
|
6
|
+
from .ledger import AuditLedger, GENESIS_HASH
|
|
7
|
+
from .mcp_server import handle_jsonrpc_request, run_stdio_server
|
|
8
|
+
from .models import (
|
|
9
|
+
AuditEntry,
|
|
10
|
+
DecisionStatus,
|
|
11
|
+
ExecutionReceipt,
|
|
12
|
+
OrderType,
|
|
13
|
+
PortfolioSnapshot,
|
|
14
|
+
Position,
|
|
15
|
+
RiskDecision,
|
|
16
|
+
Side,
|
|
17
|
+
SignedAttestation,
|
|
18
|
+
TradeProposal,
|
|
19
|
+
VenueType,
|
|
20
|
+
)
|
|
21
|
+
from .policy import RiskPolicy, evaluate_proposal
|
|
22
|
+
from .server import FirewallService, create_app
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"AttestationAuthority",
|
|
26
|
+
"AuditEntry",
|
|
27
|
+
"AuditLedger",
|
|
28
|
+
"DecisionStatus",
|
|
29
|
+
"ExecutionReceipt",
|
|
30
|
+
"FirewallService",
|
|
31
|
+
"GENESIS_HASH",
|
|
32
|
+
"KillSwitch",
|
|
33
|
+
"KillSwitchState",
|
|
34
|
+
"OrderType",
|
|
35
|
+
"PortfolioSnapshot",
|
|
36
|
+
"Position",
|
|
37
|
+
"RiskDecision",
|
|
38
|
+
"RiskPolicy",
|
|
39
|
+
"Side",
|
|
40
|
+
"SignedAttestation",
|
|
41
|
+
"TradeProposal",
|
|
42
|
+
"VenueType",
|
|
43
|
+
"canonical_order_hash",
|
|
44
|
+
"create_app",
|
|
45
|
+
"evaluate_proposal",
|
|
46
|
+
"from_ai_hedge_fund_signal",
|
|
47
|
+
"from_tradingagents_decision",
|
|
48
|
+
"handle_jsonrpc_request",
|
|
49
|
+
"run_stdio_server",
|
|
50
|
+
]
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""Pluggable upstream agent backend shims for open-source trading frameworks.
|
|
2
|
+
|
|
3
|
+
Allows frameworks such as `TauricResearch/TradingAgents` and `virattt/ai-hedge-fund`
|
|
4
|
+
to route proposals through the ClearFills Pre-Trade Risk Firewall without modifying
|
|
5
|
+
their core agent loops.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from typing import Any, Optional
|
|
12
|
+
|
|
13
|
+
from .models import OrderType, Side, TradeProposal, VenueType
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _parse_side(raw_action: str) -> Side:
|
|
17
|
+
normalized = raw_action.strip().upper()
|
|
18
|
+
if normalized in {"BUY", "LONG", "BULLISH", "COVER"} or re.search(r"\bBUY\b", normalized):
|
|
19
|
+
return Side.BUY
|
|
20
|
+
if normalized in {"SELL", "SHORT", "BEARISH"} or re.search(r"\bSELL\b|\bSHORT\b", normalized):
|
|
21
|
+
return Side.SELL
|
|
22
|
+
raise ValueError(f"Unsupported or non-actionable trade decision: '{raw_action}'")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _normalize_confidence(raw: Any, default: float = 0.55) -> float:
|
|
26
|
+
if raw is None:
|
|
27
|
+
return default
|
|
28
|
+
val = float(raw)
|
|
29
|
+
if val > 1.0:
|
|
30
|
+
# Frameworks like ai-hedge-fund often emit confidence on a 0..100 scale
|
|
31
|
+
val = val / 100.0
|
|
32
|
+
return max(0.0, min(1.0, val))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _coerce_float(val: Any) -> Optional[float]:
|
|
36
|
+
if val is None or val == "":
|
|
37
|
+
return None
|
|
38
|
+
return float(val)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def from_tradingagents_decision(payload: dict[str, Any]) -> TradeProposal:
|
|
42
|
+
"""Map a `TauricResearch/TradingAgents` state/decision dict into a `TradeProposal`.
|
|
43
|
+
|
|
44
|
+
Expected fields (supports standard TradingAgents graph output):
|
|
45
|
+
- `final_trade_decision`: str (e.g. `"BUY"`, `"FINAL TRANSACTION PROPOSAL: **BUY**"`) or dict
|
|
46
|
+
- `company_of_interest` or `ticker` or `symbol`
|
|
47
|
+
- `investment_debate_state`: optional dict with `bull_history`, `bear_history`, `judge_decision`
|
|
48
|
+
- `risk_debate_state`: optional dict with `judge_decision`
|
|
49
|
+
- `quantity`, `limit_price` (or `price`), `stop_price`, `target_price`, `venue`, `agent_id`
|
|
50
|
+
"""
|
|
51
|
+
decision_raw = payload.get("final_trade_decision")
|
|
52
|
+
if decision_raw is None:
|
|
53
|
+
raise ValueError("TradingAgents payload missing 'final_trade_decision'")
|
|
54
|
+
|
|
55
|
+
if isinstance(decision_raw, dict):
|
|
56
|
+
action_str = str(decision_raw.get("action") or decision_raw.get("decision") or "")
|
|
57
|
+
decision_rationale = str(decision_raw.get("reasoning") or decision_raw.get("summary") or "")
|
|
58
|
+
else:
|
|
59
|
+
action_str = str(decision_raw)
|
|
60
|
+
decision_rationale = action_str
|
|
61
|
+
|
|
62
|
+
side = _parse_side(action_str)
|
|
63
|
+
|
|
64
|
+
symbol = str(
|
|
65
|
+
payload.get("company_of_interest")
|
|
66
|
+
or payload.get("ticker")
|
|
67
|
+
or payload.get("symbol")
|
|
68
|
+
or ""
|
|
69
|
+
).strip()
|
|
70
|
+
if not symbol:
|
|
71
|
+
raise ValueError("TradingAgents payload missing 'company_of_interest' / 'ticker' / 'symbol'")
|
|
72
|
+
|
|
73
|
+
debate = payload.get("investment_debate_state") or {}
|
|
74
|
+
risk_debate = payload.get("risk_debate_state") or {}
|
|
75
|
+
|
|
76
|
+
trace_parts: list[str] = []
|
|
77
|
+
if decision_rationale:
|
|
78
|
+
trace_parts.append(f"Final Decision: {decision_rationale}")
|
|
79
|
+
if isinstance(debate, dict):
|
|
80
|
+
if debate.get("bull_history"):
|
|
81
|
+
trace_parts.append(f"Bull Case: {debate['bull_history']}")
|
|
82
|
+
if debate.get("bear_history"):
|
|
83
|
+
trace_parts.append(f"Bear Case: {debate['bear_history']}")
|
|
84
|
+
if debate.get("judge_decision"):
|
|
85
|
+
trace_parts.append(f"Research Judge: {debate['judge_decision']}")
|
|
86
|
+
if isinstance(risk_debate, dict) and risk_debate.get("judge_decision"):
|
|
87
|
+
trace_parts.append(f"Risk Judge: {risk_debate['judge_decision']}")
|
|
88
|
+
|
|
89
|
+
citations: list[str] = list(payload.get("source_citations") or [])
|
|
90
|
+
for report_key in ("market_report", "sentiment_report", "news_report", "fundamentals_report"):
|
|
91
|
+
if payload.get(report_key):
|
|
92
|
+
citations.append(f"tradingagents:{report_key}")
|
|
93
|
+
|
|
94
|
+
quantity = float(payload.get("quantity", 1.0))
|
|
95
|
+
limit_price = _coerce_float(payload.get("limit_price") or payload.get("price"))
|
|
96
|
+
stop_price = _coerce_float(payload.get("stop_price"))
|
|
97
|
+
target_price = _coerce_float(payload.get("target_price"))
|
|
98
|
+
confidence = _normalize_confidence(payload.get("confidence"), default=0.60)
|
|
99
|
+
|
|
100
|
+
venue = str(payload.get("venue", "ibkr"))
|
|
101
|
+
venue_type_raw = str(payload.get("venue_type", VenueType.EQUITY.value)).upper()
|
|
102
|
+
venue_type = VenueType(venue_type_raw)
|
|
103
|
+
|
|
104
|
+
order_type_raw = str(payload.get("order_type", OrderType.LIMIT.value)).upper()
|
|
105
|
+
order_type = OrderType(order_type_raw)
|
|
106
|
+
|
|
107
|
+
return TradeProposal(
|
|
108
|
+
agent_id=str(payload.get("agent_id", "tradingagents-orchestrator")),
|
|
109
|
+
venue=venue,
|
|
110
|
+
venue_type=venue_type,
|
|
111
|
+
symbol=symbol,
|
|
112
|
+
side=side,
|
|
113
|
+
order_type=order_type,
|
|
114
|
+
quantity=quantity,
|
|
115
|
+
limit_price=limit_price,
|
|
116
|
+
stop_price=stop_price,
|
|
117
|
+
target_price=target_price,
|
|
118
|
+
reasoning_trace="\n\n".join(trace_parts),
|
|
119
|
+
source_citations=citations,
|
|
120
|
+
confidence=confidence,
|
|
121
|
+
strategy_id=str(payload.get("strategy_id", "tradingagents_debate")),
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def from_ai_hedge_fund_signal(payload: dict[str, Any]) -> TradeProposal:
|
|
126
|
+
"""Map a `virattt/ai-hedge-fund` portfolio manager / analyst signal into a `TradeProposal`.
|
|
127
|
+
|
|
128
|
+
Expected fields:
|
|
129
|
+
- `ticker` or `symbol`
|
|
130
|
+
- `action` or `signal` (e.g. `"buy"`, `"sell"`, `"short"`, `"bullish"`, `"bearish"`)
|
|
131
|
+
- `quantity`
|
|
132
|
+
- `confidence` (0..100 or 0.0..1.0)
|
|
133
|
+
- `reasoning`: str or dict
|
|
134
|
+
- `analyst_signals`: optional dict of `{analyst_name: {signal, confidence, reasoning}}`
|
|
135
|
+
- `limit_price` (or `price`), `stop_price`, `target_price`, `venue`, `agent_id`
|
|
136
|
+
"""
|
|
137
|
+
symbol = str(payload.get("ticker") or payload.get("symbol") or "").strip()
|
|
138
|
+
if not symbol:
|
|
139
|
+
raise ValueError("ai-hedge-fund payload missing 'ticker' / 'symbol'")
|
|
140
|
+
|
|
141
|
+
raw_action = payload.get("action") or payload.get("signal")
|
|
142
|
+
if not raw_action:
|
|
143
|
+
raise ValueError("ai-hedge-fund payload missing 'action' / 'signal'")
|
|
144
|
+
side = _parse_side(str(raw_action))
|
|
145
|
+
|
|
146
|
+
quantity = float(payload.get("quantity", 1.0))
|
|
147
|
+
confidence = _normalize_confidence(payload.get("confidence"), default=0.55)
|
|
148
|
+
|
|
149
|
+
reasoning_raw = payload.get("reasoning", "")
|
|
150
|
+
trace_parts: list[str] = []
|
|
151
|
+
if isinstance(reasoning_raw, dict):
|
|
152
|
+
for k, v in reasoning_raw.items():
|
|
153
|
+
trace_parts.append(f"{k}: {v}")
|
|
154
|
+
elif reasoning_raw:
|
|
155
|
+
trace_parts.append(str(reasoning_raw))
|
|
156
|
+
|
|
157
|
+
citations: list[str] = list(payload.get("source_citations") or [])
|
|
158
|
+
analyst_signals = payload.get("analyst_signals") or {}
|
|
159
|
+
if isinstance(analyst_signals, dict):
|
|
160
|
+
for analyst_name, sig_data in analyst_signals.items():
|
|
161
|
+
citations.append(f"ai-hedge-fund:{analyst_name}")
|
|
162
|
+
if isinstance(sig_data, dict):
|
|
163
|
+
sig_label = sig_data.get("signal", "neutral")
|
|
164
|
+
sig_conf = sig_data.get("confidence", "")
|
|
165
|
+
sig_reason = sig_data.get("reasoning", "")
|
|
166
|
+
trace_parts.append(
|
|
167
|
+
f"[{analyst_name}] signal={sig_label} conf={sig_conf}: {sig_reason}"
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
limit_price = _coerce_float(payload.get("limit_price") or payload.get("price"))
|
|
171
|
+
stop_price = _coerce_float(payload.get("stop_price"))
|
|
172
|
+
target_price = _coerce_float(payload.get("target_price"))
|
|
173
|
+
|
|
174
|
+
venue = str(payload.get("venue", "alpaca"))
|
|
175
|
+
venue_type_raw = str(payload.get("venue_type", VenueType.EQUITY.value)).upper()
|
|
176
|
+
venue_type = VenueType(venue_type_raw)
|
|
177
|
+
|
|
178
|
+
order_type_raw = str(payload.get("order_type", OrderType.LIMIT.value)).upper()
|
|
179
|
+
order_type = OrderType(order_type_raw)
|
|
180
|
+
|
|
181
|
+
return TradeProposal(
|
|
182
|
+
agent_id=str(payload.get("agent_id", "ai-hedge-fund-pm")),
|
|
183
|
+
venue=venue,
|
|
184
|
+
venue_type=venue_type,
|
|
185
|
+
symbol=symbol,
|
|
186
|
+
side=side,
|
|
187
|
+
order_type=order_type,
|
|
188
|
+
quantity=quantity,
|
|
189
|
+
limit_price=limit_price,
|
|
190
|
+
stop_price=stop_price,
|
|
191
|
+
target_price=target_price,
|
|
192
|
+
reasoning_trace="\n".join(trace_parts),
|
|
193
|
+
source_citations=citations,
|
|
194
|
+
confidence=confidence,
|
|
195
|
+
strategy_id=str(payload.get("strategy_id", "ai_hedge_fund_consensus")),
|
|
196
|
+
)
|