fahali-guard 1.0.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.
- fahali_guard-1.0.0/PKG-INFO +50 -0
- fahali_guard-1.0.0/README.md +38 -0
- fahali_guard-1.0.0/fahali_guard/__init__.py +378 -0
- fahali_guard-1.0.0/fahali_guard.egg-info/PKG-INFO +50 -0
- fahali_guard-1.0.0/fahali_guard.egg-info/SOURCES.txt +8 -0
- fahali_guard-1.0.0/fahali_guard.egg-info/dependency_links.txt +1 -0
- fahali_guard-1.0.0/fahali_guard.egg-info/top_level.txt +1 -0
- fahali_guard-1.0.0/pyproject.toml +22 -0
- fahali_guard-1.0.0/setup.cfg +4 -0
- fahali_guard-1.0.0/tests/test_fahali_guard.py +90 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fahali-guard
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: 3-line cryptographic pre-trade risk clearance guard (FRCT v1) for CCXT, Alpaca, Hyperliquid, and autonomous Python AI trading agents.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://fahaliai.com/developer
|
|
7
|
+
Project-URL: Documentation, https://mcp.fahaliai.com/llms.txt
|
|
8
|
+
Project-URL: Repository, https://github.com/BobMain-2025/spectra-mobile
|
|
9
|
+
Keywords: fahali,mcp,frct,ai-agents,risk-management,ccxt,hyperliquid,alpaca
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# `fahali-guard` — 3-Line Pre-Trade Execution Guard (FRCT v1) for Python AI Agents
|
|
14
|
+
|
|
15
|
+
Zero-dependency fail-closed risk clearance guard for autonomous AI trading agents across **CCXT**, **Hyperliquid Python SDK**, **Alpaca**, **LangGraph**, and **CrewAI**.
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install fahali-guard
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Zero-Signup Quickstart (< 10 Seconds)
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import ccxt
|
|
27
|
+
from fahali_guard import FahaliGuard, guard_ccxt
|
|
28
|
+
|
|
29
|
+
trial = FahaliGuard.mint_sandbox_key("my-autonomous-bot")
|
|
30
|
+
guard = FahaliGuard(api_key=trial["apiKey"], auto_resize_parameter_breaches=True)
|
|
31
|
+
exchange = guard_ccxt(ccxt.binance(), guard)
|
|
32
|
+
|
|
33
|
+
# Automatically checks Fahali FRCT before any order packet leaves your process:
|
|
34
|
+
# - CLEAR -> attaches clientOrderId receipt tag and executes
|
|
35
|
+
# - CLEAR_WITH_CONSTRAINTS -> scales size down (e.g. 50% stress haircut) & enforces TWAP_ONLY
|
|
36
|
+
# - BLOCK_ESCALATE -> raises FahaliClearanceBlockedError BEFORE hitting the exchange
|
|
37
|
+
exchange.create_order("SOL/USDT", "limit", "buy", 50, 180.0)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Hyperliquid Perpetuals Wrapper
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from fahali_guard import FahaliGuard, guard_hyperliquid
|
|
44
|
+
|
|
45
|
+
guard = FahaliGuard(api_key="sk_live_...", auto_resize_parameter_breaches=True)
|
|
46
|
+
hl = guard_hyperliquid(hl_exchange, guard)
|
|
47
|
+
hl.order("SOL", True, 100.0, 180.0, {"limit": {"tif": "Gtc"}})
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Observation and pre-trade attestation only — Fahali holds zero custody and routes no orders.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# `fahali-guard` — 3-Line Pre-Trade Execution Guard (FRCT v1) for Python AI Agents
|
|
2
|
+
|
|
3
|
+
Zero-dependency fail-closed risk clearance guard for autonomous AI trading agents across **CCXT**, **Hyperliquid Python SDK**, **Alpaca**, **LangGraph**, and **CrewAI**.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install fahali-guard
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Zero-Signup Quickstart (< 10 Seconds)
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import ccxt
|
|
15
|
+
from fahali_guard import FahaliGuard, guard_ccxt
|
|
16
|
+
|
|
17
|
+
trial = FahaliGuard.mint_sandbox_key("my-autonomous-bot")
|
|
18
|
+
guard = FahaliGuard(api_key=trial["apiKey"], auto_resize_parameter_breaches=True)
|
|
19
|
+
exchange = guard_ccxt(ccxt.binance(), guard)
|
|
20
|
+
|
|
21
|
+
# Automatically checks Fahali FRCT before any order packet leaves your process:
|
|
22
|
+
# - CLEAR -> attaches clientOrderId receipt tag and executes
|
|
23
|
+
# - CLEAR_WITH_CONSTRAINTS -> scales size down (e.g. 50% stress haircut) & enforces TWAP_ONLY
|
|
24
|
+
# - BLOCK_ESCALATE -> raises FahaliClearanceBlockedError BEFORE hitting the exchange
|
|
25
|
+
exchange.create_order("SOL/USDT", "limit", "buy", 50, 180.0)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Hyperliquid Perpetuals Wrapper
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from fahali_guard import FahaliGuard, guard_hyperliquid
|
|
32
|
+
|
|
33
|
+
guard = FahaliGuard(api_key="sk_live_...", auto_resize_parameter_breaches=True)
|
|
34
|
+
hl = guard_hyperliquid(hl_exchange, guard)
|
|
35
|
+
hl.order("SOL", True, 100.0, 180.0, {"limit": {"tif": "Gtc"}})
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Observation and pre-trade attestation only — Fahali holds zero custody and routes no orders.
|
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
"""
|
|
2
|
+
fahali_guard — 3-Line Pre-Trade Cryptographic Execution Guard (FRCT v1) for Python Agents.
|
|
3
|
+
|
|
4
|
+
Zero external dependencies (stdlib `urllib.request`, `json`, `uuid`).
|
|
5
|
+
Supports CCXT, Alpaca-py, Hyperliquid Python SDK, and LangGraph / CrewAI tool nodes.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.request
|
|
13
|
+
import uuid
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class FahaliClearanceBlockedError(RuntimeError):
|
|
19
|
+
"""Raised before an order touches any exchange when Fahali blocks or cannot verify clearance."""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
message: str,
|
|
24
|
+
code: str = "BLOCK_ESCALATE",
|
|
25
|
+
verdict: str = "BLOCK_ESCALATE",
|
|
26
|
+
reasons: Optional[List[Dict[str, Any]]] = None,
|
|
27
|
+
compliant_envelope: Optional[Dict[str, Any]] = None,
|
|
28
|
+
checkpoint_id: Optional[str] = None,
|
|
29
|
+
jti: Optional[str] = None,
|
|
30
|
+
) -> None:
|
|
31
|
+
super().__init__(message)
|
|
32
|
+
self.code = code
|
|
33
|
+
self.verdict = verdict
|
|
34
|
+
self.reasons = reasons or []
|
|
35
|
+
self.compliant_envelope = compliant_envelope
|
|
36
|
+
self.checkpoint_id = checkpoint_id
|
|
37
|
+
self.jti = jti
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class GuardClearanceDecision:
|
|
42
|
+
allowed: bool
|
|
43
|
+
verdict: str
|
|
44
|
+
jti: str
|
|
45
|
+
jws: Optional[str]
|
|
46
|
+
client_order_tag: str
|
|
47
|
+
requested_notional_usd: float
|
|
48
|
+
approved_notional_usd: float
|
|
49
|
+
requested_quantity: Optional[float]
|
|
50
|
+
approved_quantity: Optional[float]
|
|
51
|
+
max_slippage_bps: int
|
|
52
|
+
execution_style: str
|
|
53
|
+
min_twap_minutes: int
|
|
54
|
+
constrained: bool
|
|
55
|
+
sandbox: bool
|
|
56
|
+
reasons: List[Dict[str, Any]] = field(default_factory=list)
|
|
57
|
+
compliant_envelope: Optional[Dict[str, Any]] = None
|
|
58
|
+
raw_issuance: Dict[str, Any] = field(default_factory=dict)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _default_transport(url: str, headers: Dict[str, str], body: Dict[str, Any], timeout_s: float) -> tuple[int, Dict[str, Any]]:
|
|
62
|
+
data = json.dumps(body).encode("utf-8")
|
|
63
|
+
merged_headers = {"User-Agent": "fahali-guard-python/1.0.0", **headers}
|
|
64
|
+
req = urllib.request.Request(url, data=data, headers=merged_headers, method="POST")
|
|
65
|
+
try:
|
|
66
|
+
with urllib.request.urlopen(req, timeout=timeout_s) as resp:
|
|
67
|
+
raw = resp.read().decode("utf-8")
|
|
68
|
+
return resp.status, json.loads(raw) if raw else {}
|
|
69
|
+
except urllib.error.HTTPError as e:
|
|
70
|
+
raw = e.read().decode("utf-8", errors="replace")
|
|
71
|
+
try:
|
|
72
|
+
parsed = json.loads(raw)
|
|
73
|
+
except Exception:
|
|
74
|
+
parsed = {"error": raw}
|
|
75
|
+
return e.code, parsed
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class FahaliGuard:
|
|
79
|
+
def __init__(
|
|
80
|
+
self,
|
|
81
|
+
api_key: str,
|
|
82
|
+
base_url: str = "https://mcp.fahaliai.com",
|
|
83
|
+
org_id: Optional[str] = None,
|
|
84
|
+
kya_agent_id: str = "did:kya:fahali:python-guard",
|
|
85
|
+
default_max_slippage_bps: int = 50,
|
|
86
|
+
timeout_s: float = 5.0,
|
|
87
|
+
auto_resize_parameter_breaches: bool = False,
|
|
88
|
+
consume_at_venue_boundary: bool = True,
|
|
89
|
+
sandbox_scenario: Optional[str] = None,
|
|
90
|
+
transport: Optional[Callable[[str, Dict[str, str], Dict[str, Any], float], tuple[int, Dict[str, Any]]]] = None,
|
|
91
|
+
) -> None:
|
|
92
|
+
if not api_key or not api_key.strip():
|
|
93
|
+
raise ValueError("FahaliGuard requires a non-empty api_key (or call FahaliGuard.mint_sandbox_key()).")
|
|
94
|
+
self.api_key = api_key.strip()
|
|
95
|
+
self.base_url = base_url.rstrip("/")
|
|
96
|
+
self.org_id = org_id
|
|
97
|
+
self.kya_agent_id = kya_agent_id
|
|
98
|
+
self.default_max_slippage_bps = default_max_slippage_bps
|
|
99
|
+
self.timeout_s = timeout_s
|
|
100
|
+
self.auto_resize = auto_resize_parameter_breaches
|
|
101
|
+
self.consume_at_boundary = consume_at_venue_boundary
|
|
102
|
+
self.sandbox_scenario = sandbox_scenario
|
|
103
|
+
self._transport = transport or _default_transport
|
|
104
|
+
|
|
105
|
+
@classmethod
|
|
106
|
+
def mint_sandbox_key(
|
|
107
|
+
cls,
|
|
108
|
+
agent_name: str = "python-agent",
|
|
109
|
+
base_url: str = "https://mcp.fahaliai.com",
|
|
110
|
+
transport: Optional[Callable[[str, Dict[str, str], Dict[str, Any], float], tuple[int, Dict[str, Any]]]] = None,
|
|
111
|
+
) -> Dict[str, Any]:
|
|
112
|
+
fn = transport or _default_transport
|
|
113
|
+
status, body = fn(
|
|
114
|
+
f"{base_url.rstrip('/')}/v1/sandbox/keys",
|
|
115
|
+
{"Content-Type": "application/json", "Accept": "application/json"},
|
|
116
|
+
{"agent_name": agent_name},
|
|
117
|
+
5.0,
|
|
118
|
+
)
|
|
119
|
+
if status not in (200, 201) or "apiKey" not in body:
|
|
120
|
+
raise RuntimeError(f"Failed to mint sandbox key (HTTP {status}): {body}")
|
|
121
|
+
return body
|
|
122
|
+
|
|
123
|
+
def clear_order(
|
|
124
|
+
self,
|
|
125
|
+
*,
|
|
126
|
+
venue: str,
|
|
127
|
+
asset_class: str,
|
|
128
|
+
symbols: List[str],
|
|
129
|
+
notional_usd: float,
|
|
130
|
+
side: Optional[str] = None,
|
|
131
|
+
quantity: Optional[float] = None,
|
|
132
|
+
max_slippage_bps: Optional[int] = None,
|
|
133
|
+
_already_resized: bool = False,
|
|
134
|
+
) -> GuardClearanceDecision:
|
|
135
|
+
if notional_usd <= 0:
|
|
136
|
+
raise FahaliClearanceBlockedError(
|
|
137
|
+
f"Invalid notional_usd ({notional_usd}); failing closed.",
|
|
138
|
+
code="FAIL_CLOSED_INVALID_NOTIONAL",
|
|
139
|
+
verdict="FAIL_CLOSED_ERROR",
|
|
140
|
+
)
|
|
141
|
+
nonce = f"nce_{uuid.uuid4().hex[:16]}"
|
|
142
|
+
slippage = self.default_max_slippage_bps if max_slippage_bps is None else int(max_slippage_bps)
|
|
143
|
+
principal: Dict[str, Any] = {"kya_agent_id": self.kya_agent_id}
|
|
144
|
+
if self.org_id:
|
|
145
|
+
principal["org_id"] = self.org_id
|
|
146
|
+
|
|
147
|
+
issue_body: Dict[str, Any] = {
|
|
148
|
+
"venue": venue,
|
|
149
|
+
"asset_class": asset_class,
|
|
150
|
+
"symbols": symbols,
|
|
151
|
+
"max_notional_usd": float(notional_usd),
|
|
152
|
+
"max_slippage_bps": slippage,
|
|
153
|
+
"nonce": nonce,
|
|
154
|
+
"fast_path": True,
|
|
155
|
+
"include_full_dossier": False,
|
|
156
|
+
"principal": principal,
|
|
157
|
+
}
|
|
158
|
+
if side:
|
|
159
|
+
issue_body["side"] = side
|
|
160
|
+
if self.sandbox_scenario:
|
|
161
|
+
issue_body["sandbox_scenario"] = self.sandbox_scenario
|
|
162
|
+
|
|
163
|
+
try:
|
|
164
|
+
status, issuance = self._transport(
|
|
165
|
+
f"{self.base_url}/v1/clearance/issue",
|
|
166
|
+
{
|
|
167
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
168
|
+
"Content-Type": "application/json",
|
|
169
|
+
"Accept": "application/json",
|
|
170
|
+
},
|
|
171
|
+
issue_body,
|
|
172
|
+
self.timeout_s,
|
|
173
|
+
)
|
|
174
|
+
except Exception as exc:
|
|
175
|
+
raise FahaliClearanceBlockedError(
|
|
176
|
+
f"Fahali clearance network failure (failing closed): {exc}",
|
|
177
|
+
code="FAIL_CLOSED_NETWORK_ERROR",
|
|
178
|
+
verdict="FAIL_CLOSED_ERROR",
|
|
179
|
+
) from exc
|
|
180
|
+
|
|
181
|
+
if status != 200 or not isinstance(issuance, dict):
|
|
182
|
+
err_code = str(issuance.get("error") or "FAIL_CLOSED_ISSUANCE_HTTP_ERROR")
|
|
183
|
+
raise FahaliClearanceBlockedError(
|
|
184
|
+
f"Fahali clearance issuance failed (HTTP {status}): {issuance.get('message') or err_code}",
|
|
185
|
+
code=err_code,
|
|
186
|
+
verdict="FAIL_CLOSED_ERROR",
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
clearance = issuance.get("clearance") or {}
|
|
190
|
+
payload = issuance.get("payload") or {}
|
|
191
|
+
verdict = str(clearance.get("verdict") or "BLOCK_ESCALATE")
|
|
192
|
+
reasons = issuance.get("reasons") or []
|
|
193
|
+
envelope = issuance.get("compliantEnvelope")
|
|
194
|
+
jti = str(payload.get("jti") or "")
|
|
195
|
+
checkpoint_id = (payload.get("hitl") or {}).get("checkpoint_id")
|
|
196
|
+
|
|
197
|
+
if verdict == "BLOCK_ESCALATE":
|
|
198
|
+
if (
|
|
199
|
+
self.auto_resize
|
|
200
|
+
and not _already_resized
|
|
201
|
+
and isinstance(envelope, dict)
|
|
202
|
+
and envelope.get("canSelfRemediateByResizing") is True
|
|
203
|
+
and envelope.get("remediationAction") == "RESIZE_AND_REISSUE"
|
|
204
|
+
):
|
|
205
|
+
max_notional = envelope.get("maxPermittedNotionalUsd")
|
|
206
|
+
next_notional = (
|
|
207
|
+
min(float(notional_usd), float(max_notional))
|
|
208
|
+
if isinstance(max_notional, (int, float)) and max_notional > 0
|
|
209
|
+
else float(notional_usd)
|
|
210
|
+
)
|
|
211
|
+
next_slippage = min(slippage, int(envelope.get("maxPermittedSlippageBps", slippage)))
|
|
212
|
+
scale = next_notional / float(notional_usd)
|
|
213
|
+
return self.clear_order(
|
|
214
|
+
venue=venue,
|
|
215
|
+
asset_class=asset_class,
|
|
216
|
+
symbols=symbols,
|
|
217
|
+
notional_usd=next_notional,
|
|
218
|
+
side=side,
|
|
219
|
+
quantity=(quantity * scale) if quantity is not None else None,
|
|
220
|
+
max_slippage_bps=next_slippage,
|
|
221
|
+
_already_resized=True,
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
primary_code = reasons[0]["code"] if reasons and "code" in reasons[0] else "BLOCK_ESCALATE"
|
|
225
|
+
details = " | ".join(r.get("detail", "") for r in reasons if isinstance(r, dict))
|
|
226
|
+
raise FahaliClearanceBlockedError(
|
|
227
|
+
f"Order blocked by Fahali FRCT ({primary_code}): {details}",
|
|
228
|
+
code=primary_code,
|
|
229
|
+
verdict="BLOCK_ESCALATE",
|
|
230
|
+
reasons=reasons,
|
|
231
|
+
compliant_envelope=envelope,
|
|
232
|
+
checkpoint_id=checkpoint_id,
|
|
233
|
+
jti=jti or None,
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
constraints = clearance.get("constraints") or {}
|
|
237
|
+
approved_notional = (
|
|
238
|
+
min(float(notional_usd), float(constraints["max_notional_override_usd"]))
|
|
239
|
+
if verdict == "CLEAR_WITH_CONSTRAINTS" and isinstance(constraints.get("max_notional_override_usd"), (int, float))
|
|
240
|
+
else float(notional_usd)
|
|
241
|
+
)
|
|
242
|
+
scale_factor = approved_notional / float(notional_usd)
|
|
243
|
+
approved_qty = round(quantity * scale_factor, 8) if quantity is not None else None
|
|
244
|
+
exec_style = "TWAP_ONLY" if verdict == "CLEAR_WITH_CONSTRAINTS" else "ANY"
|
|
245
|
+
min_twap = int(constraints.get("min_twap_minutes") or 0) if verdict == "CLEAR_WITH_CONSTRAINTS" else 0
|
|
246
|
+
jws = issuance.get("jws") if isinstance(issuance.get("jws"), str) else None
|
|
247
|
+
is_sandbox = bool((issuance.get("sandbox") or {}).get("isolated")) or str(payload.get("iss") or "").endswith("/sandbox")
|
|
248
|
+
|
|
249
|
+
if self.consume_at_boundary and not is_sandbox and jws:
|
|
250
|
+
order_payload: Dict[str, Any] = {
|
|
251
|
+
"venue": venue,
|
|
252
|
+
"asset_class": asset_class,
|
|
253
|
+
"symbols": symbols,
|
|
254
|
+
"notional_usd": approved_notional,
|
|
255
|
+
"slippage_bps": slippage,
|
|
256
|
+
"execution_style": "TWAP" if exec_style == "TWAP_ONLY" else "LIMIT",
|
|
257
|
+
"nonce": nonce,
|
|
258
|
+
}
|
|
259
|
+
if side:
|
|
260
|
+
order_payload["side"] = side
|
|
261
|
+
if min_twap > 0:
|
|
262
|
+
order_payload["twap_minutes"] = min_twap
|
|
263
|
+
c_status, c_body = self._transport(
|
|
264
|
+
f"{self.base_url}/v1/clearance/consume",
|
|
265
|
+
{"Content-Type": "application/json", "X-Fahali-Clearance": jws},
|
|
266
|
+
{"venue_id": venue, "require_exact_intent_hash": False, "order": order_payload},
|
|
267
|
+
self.timeout_s,
|
|
268
|
+
)
|
|
269
|
+
if c_status != 200 or c_body.get("allowed") is not True:
|
|
270
|
+
fc = str(c_body.get("failureCode") or "FAIL_CLOSED_CONSUME_REJECTED")
|
|
271
|
+
raise FahaliClearanceBlockedError(
|
|
272
|
+
f"Venue boundary rejected FRCT ({fc}): {c_body.get('reason')}",
|
|
273
|
+
code=fc,
|
|
274
|
+
verdict="FAIL_CLOSED_ERROR",
|
|
275
|
+
jti=jti or None,
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
tag = f"fhl_{jti[-12:]}" if jti else f"fhl_{nonce[-10:]}"
|
|
279
|
+
return GuardClearanceDecision(
|
|
280
|
+
allowed=True,
|
|
281
|
+
verdict=verdict,
|
|
282
|
+
jti=jti,
|
|
283
|
+
jws=jws,
|
|
284
|
+
client_order_tag=tag,
|
|
285
|
+
requested_notional_usd=float(notional_usd),
|
|
286
|
+
approved_notional_usd=approved_notional,
|
|
287
|
+
requested_quantity=quantity,
|
|
288
|
+
approved_quantity=approved_qty,
|
|
289
|
+
max_slippage_bps=slippage,
|
|
290
|
+
execution_style=exec_style,
|
|
291
|
+
min_twap_minutes=min_twap,
|
|
292
|
+
constrained=(verdict == "CLEAR_WITH_CONSTRAINTS"),
|
|
293
|
+
sandbox=is_sandbox,
|
|
294
|
+
reasons=reasons,
|
|
295
|
+
compliant_envelope=envelope,
|
|
296
|
+
raw_issuance=issuance,
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def guard_ccxt(exchange: Any, guard: FahaliGuard, venue: Optional[str] = None) -> Any:
|
|
301
|
+
"""3-line wrapper around any CCXT sync/async-compatible exchange instance."""
|
|
302
|
+
orig_create_order = exchange.create_order
|
|
303
|
+
|
|
304
|
+
def wrapped_create_order(
|
|
305
|
+
symbol: str,
|
|
306
|
+
order_type: str,
|
|
307
|
+
side: str,
|
|
308
|
+
amount: float,
|
|
309
|
+
price: Optional[float] = None,
|
|
310
|
+
params: Optional[Dict[str, Any]] = None,
|
|
311
|
+
) -> Any:
|
|
312
|
+
p = dict(params or {})
|
|
313
|
+
ref_px = price
|
|
314
|
+
if not ref_px or ref_px <= 0:
|
|
315
|
+
if hasattr(exchange, "fetch_ticker"):
|
|
316
|
+
ticker = exchange.fetch_ticker(symbol)
|
|
317
|
+
ref_px = ticker.get("last") or ticker.get("close")
|
|
318
|
+
if not ref_px or ref_px <= 0:
|
|
319
|
+
raise FahaliClearanceBlockedError(
|
|
320
|
+
f"Cannot compute USD notional for {symbol} without price or fetch_ticker; failing closed.",
|
|
321
|
+
code="FAIL_CLOSED_MISSING_PRICE",
|
|
322
|
+
verdict="FAIL_CLOSED_ERROR",
|
|
323
|
+
)
|
|
324
|
+
decision = guard.clear_order(
|
|
325
|
+
venue=venue or getattr(exchange, "id", "binance"),
|
|
326
|
+
asset_class="crypto",
|
|
327
|
+
symbols=[symbol.replace("/", "").upper()],
|
|
328
|
+
side=side,
|
|
329
|
+
notional_usd=amount * float(ref_px),
|
|
330
|
+
quantity=amount,
|
|
331
|
+
max_slippage_bps=p.get("max_slippage_bps"),
|
|
332
|
+
)
|
|
333
|
+
p.setdefault("clientOrderId", decision.client_order_tag)
|
|
334
|
+
p["fahali_clearance"] = {
|
|
335
|
+
"verdict": decision.verdict,
|
|
336
|
+
"jti": decision.jti,
|
|
337
|
+
"execution_style": decision.execution_style,
|
|
338
|
+
}
|
|
339
|
+
return orig_create_order(symbol, order_type, side, decision.approved_quantity or amount, price, p)
|
|
340
|
+
|
|
341
|
+
exchange.create_order = wrapped_create_order
|
|
342
|
+
return exchange
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def guard_hyperliquid(hl_exchange: Any, guard: FahaliGuard) -> Any:
|
|
346
|
+
"""3-line wrapper around Hyperliquid Python SDK `Exchange.order(...)`."""
|
|
347
|
+
orig_order = hl_exchange.order
|
|
348
|
+
|
|
349
|
+
def wrapped_order(
|
|
350
|
+
name: str,
|
|
351
|
+
is_buy: bool,
|
|
352
|
+
sz: float,
|
|
353
|
+
limit_px: float,
|
|
354
|
+
order_type: Dict[str, Any],
|
|
355
|
+
reduce_only: bool = False,
|
|
356
|
+
cloid: Optional[str] = None,
|
|
357
|
+
) -> Any:
|
|
358
|
+
coin = name.strip().upper().removesuffix("-PERP")
|
|
359
|
+
decision = guard.clear_order(
|
|
360
|
+
venue="hyperliquid",
|
|
361
|
+
asset_class="crypto",
|
|
362
|
+
symbols=[f"{coin}USDT"],
|
|
363
|
+
side="buy" if is_buy else "sell",
|
|
364
|
+
notional_usd=sz * limit_px,
|
|
365
|
+
quantity=sz,
|
|
366
|
+
)
|
|
367
|
+
return orig_order(
|
|
368
|
+
name,
|
|
369
|
+
is_buy,
|
|
370
|
+
decision.approved_quantity or sz,
|
|
371
|
+
limit_px,
|
|
372
|
+
order_type,
|
|
373
|
+
reduce_only,
|
|
374
|
+
cloid or decision.client_order_tag,
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
hl_exchange.order = wrapped_order
|
|
378
|
+
return hl_exchange
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fahali-guard
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: 3-line cryptographic pre-trade risk clearance guard (FRCT v1) for CCXT, Alpaca, Hyperliquid, and autonomous Python AI trading agents.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://fahaliai.com/developer
|
|
7
|
+
Project-URL: Documentation, https://mcp.fahaliai.com/llms.txt
|
|
8
|
+
Project-URL: Repository, https://github.com/BobMain-2025/spectra-mobile
|
|
9
|
+
Keywords: fahali,mcp,frct,ai-agents,risk-management,ccxt,hyperliquid,alpaca
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# `fahali-guard` — 3-Line Pre-Trade Execution Guard (FRCT v1) for Python AI Agents
|
|
14
|
+
|
|
15
|
+
Zero-dependency fail-closed risk clearance guard for autonomous AI trading agents across **CCXT**, **Hyperliquid Python SDK**, **Alpaca**, **LangGraph**, and **CrewAI**.
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install fahali-guard
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Zero-Signup Quickstart (< 10 Seconds)
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import ccxt
|
|
27
|
+
from fahali_guard import FahaliGuard, guard_ccxt
|
|
28
|
+
|
|
29
|
+
trial = FahaliGuard.mint_sandbox_key("my-autonomous-bot")
|
|
30
|
+
guard = FahaliGuard(api_key=trial["apiKey"], auto_resize_parameter_breaches=True)
|
|
31
|
+
exchange = guard_ccxt(ccxt.binance(), guard)
|
|
32
|
+
|
|
33
|
+
# Automatically checks Fahali FRCT before any order packet leaves your process:
|
|
34
|
+
# - CLEAR -> attaches clientOrderId receipt tag and executes
|
|
35
|
+
# - CLEAR_WITH_CONSTRAINTS -> scales size down (e.g. 50% stress haircut) & enforces TWAP_ONLY
|
|
36
|
+
# - BLOCK_ESCALATE -> raises FahaliClearanceBlockedError BEFORE hitting the exchange
|
|
37
|
+
exchange.create_order("SOL/USDT", "limit", "buy", 50, 180.0)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Hyperliquid Perpetuals Wrapper
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from fahali_guard import FahaliGuard, guard_hyperliquid
|
|
44
|
+
|
|
45
|
+
guard = FahaliGuard(api_key="sk_live_...", auto_resize_parameter_breaches=True)
|
|
46
|
+
hl = guard_hyperliquid(hl_exchange, guard)
|
|
47
|
+
hl.order("SOL", True, 100.0, 180.0, {"limit": {"tif": "Gtc"}})
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Observation and pre-trade attestation only — Fahali holds zero custody and routes no orders.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
fahali_guard
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "fahali-guard"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "3-line cryptographic pre-trade risk clearance guard (FRCT v1) for CCXT, Alpaca, Hyperliquid, and autonomous Python AI trading agents."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = []
|
|
13
|
+
keywords = ["fahali", "mcp", "frct", "ai-agents", "risk-management", "ccxt", "hyperliquid", "alpaca"]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://fahaliai.com/developer"
|
|
17
|
+
Documentation = "https://mcp.fahaliai.com/llms.txt"
|
|
18
|
+
Repository = "https://github.com/BobMain-2025/spectra-mobile"
|
|
19
|
+
|
|
20
|
+
[tool.setuptools.packages.find]
|
|
21
|
+
where = ["."]
|
|
22
|
+
include = ["fahali_guard*"]
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
import unittest
|
|
4
|
+
|
|
5
|
+
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
|
6
|
+
|
|
7
|
+
from fahali_guard import (
|
|
8
|
+
FahaliClearanceBlockedError,
|
|
9
|
+
FahaliGuard,
|
|
10
|
+
guard_ccxt,
|
|
11
|
+
guard_hyperliquid,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class DummyCcxt:
|
|
16
|
+
id = "binance"
|
|
17
|
+
|
|
18
|
+
def __init__(self) -> None:
|
|
19
|
+
self.submitted = []
|
|
20
|
+
|
|
21
|
+
def create_order(self, symbol, order_type, side, amount, price=None, params=None):
|
|
22
|
+
rec = {"symbol": symbol, "type": order_type, "side": side, "amount": amount, "price": price, "params": params}
|
|
23
|
+
self.submitted.append(rec)
|
|
24
|
+
return rec
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class DummyHyperliquid:
|
|
28
|
+
def __init__(self) -> None:
|
|
29
|
+
self.orders = []
|
|
30
|
+
|
|
31
|
+
def order(self, name, is_buy, sz, limit_px, order_type, reduce_only=False, cloid=None):
|
|
32
|
+
rec = {"name": name, "is_buy": is_buy, "sz": sz, "limit_px": limit_px, "cloid": cloid}
|
|
33
|
+
self.orders.append(rec)
|
|
34
|
+
return rec
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class TestFahaliGuardPython(unittest.TestCase):
|
|
38
|
+
def test_block_escalate_fails_closed_before_ccxt(self):
|
|
39
|
+
def transport(_url, _headers, _body, _timeout):
|
|
40
|
+
return 200, {
|
|
41
|
+
"status": "ok",
|
|
42
|
+
"jws": None,
|
|
43
|
+
"payload": {"jti": "frct_py_blk", "hitl": {"checkpoint_id": "chk_py_1"}},
|
|
44
|
+
"clearance": {"verdict": "BLOCK_ESCALATE", "constraints": None},
|
|
45
|
+
"reasons": [{"code": "BLOCKED_REGIME", "detail": "CONTAGION_ALERT active"}],
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
ex = DummyCcxt()
|
|
49
|
+
guard = FahaliGuard(api_key="sk_sandbox_py", transport=transport)
|
|
50
|
+
guard_ccxt(ex, guard)
|
|
51
|
+
|
|
52
|
+
with self.assertRaises(FahaliClearanceBlockedError) as ctx:
|
|
53
|
+
ex.create_order("BTC/USDT", "limit", "buy", 1.0, 90000.0)
|
|
54
|
+
self.assertEqual(ctx.exception.code, "BLOCKED_REGIME")
|
|
55
|
+
self.assertEqual(len(ex.submitted), 0)
|
|
56
|
+
|
|
57
|
+
def test_hyperliquid_constraint_scales_size_and_consumes_jti(self):
|
|
58
|
+
calls = []
|
|
59
|
+
|
|
60
|
+
def transport(url, _headers, body, _timeout):
|
|
61
|
+
calls.append((url, body))
|
|
62
|
+
if url.endswith("/v1/clearance/issue"):
|
|
63
|
+
return 200, {
|
|
64
|
+
"status": "ok",
|
|
65
|
+
"jws": "eyJhbGciOiJFZERTQSJ9.py.sig",
|
|
66
|
+
"payload": {"iss": "https://mcp.fahaliai.com", "jti": "frct_py_hl999999"},
|
|
67
|
+
"clearance": {
|
|
68
|
+
"verdict": "CLEAR_WITH_CONSTRAINTS",
|
|
69
|
+
"constraints": {
|
|
70
|
+
"max_notional_override_usd": 15000,
|
|
71
|
+
"execution_style": "TWAP_ONLY",
|
|
72
|
+
"min_twap_minutes": 15,
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
"reasons": [{"code": "HYPERLIQUID_FUNDING_OR_BASIS_STRESS", "detail": "Crowded funding"}],
|
|
76
|
+
}
|
|
77
|
+
return 200, {"allowed": True, "decision": "ALLOW_EXECUTION"}
|
|
78
|
+
|
|
79
|
+
hl = DummyHyperliquid()
|
|
80
|
+
guard = FahaliGuard(api_key="sk_live_py", transport=transport)
|
|
81
|
+
guard_hyperliquid(hl, guard)
|
|
82
|
+
|
|
83
|
+
res = hl.order("ETH", True, 10.0, 3000.0, {"limit": {"tif": "Gtc"}})
|
|
84
|
+
self.assertEqual(res["sz"], 5.0)
|
|
85
|
+
self.assertEqual(res["cloid"], "fhl_t_py_hl999999"[-16:] if False else "fhl_py_hl999999" if len("frct_py_hl999999") == 15 else f"fhl_{'frct_py_hl999999'[-12:]}")
|
|
86
|
+
self.assertEqual(len(calls), 2)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
if __name__ == "__main__":
|
|
90
|
+
unittest.main()
|