perpbrain 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.
- perpbrain-0.1.0/PKG-INFO +44 -0
- perpbrain-0.1.0/README.md +13 -0
- perpbrain-0.1.0/pyproject.toml +70 -0
- perpbrain-0.1.0/setup.cfg +4 -0
- perpbrain-0.1.0/src/perpbrain/__init__.py +5 -0
- perpbrain-0.1.0/src/perpbrain/__main__.py +6 -0
- perpbrain-0.1.0/src/perpbrain/_dist.py +34 -0
- perpbrain-0.1.0/src/perpbrain/_version.py +9 -0
- perpbrain-0.1.0/src/perpbrain/adapters.py +159 -0
- perpbrain-0.1.0/src/perpbrain/cli.py +272 -0
- perpbrain-0.1.0/src/perpbrain/core/__init__.py +25 -0
- perpbrain-0.1.0/src/perpbrain/core/guards.py +27 -0
- perpbrain-0.1.0/src/perpbrain/core/live/__init__.py +310 -0
- perpbrain-0.1.0/src/perpbrain/core/live/builder_fee.py +499 -0
- perpbrain-0.1.0/src/perpbrain/core/live/cancel.py +177 -0
- perpbrain-0.1.0/src/perpbrain/core/live/client.py +865 -0
- perpbrain-0.1.0/src/perpbrain/core/live/daily_baseline.py +136 -0
- perpbrain-0.1.0/src/perpbrain/core/live/endpoints.py +59 -0
- perpbrain-0.1.0/src/perpbrain/core/live/feeds.py +173 -0
- perpbrain-0.1.0/src/perpbrain/core/live/geoblock.py +180 -0
- perpbrain-0.1.0/src/perpbrain/core/live/intent.py +174 -0
- perpbrain-0.1.0/src/perpbrain/core/live/live_guard.py +391 -0
- perpbrain-0.1.0/src/perpbrain/core/live/local_signer.py +279 -0
- perpbrain-0.1.0/src/perpbrain/core/live/market_rules.py +150 -0
- perpbrain-0.1.0/src/perpbrain/core/live/mode.py +133 -0
- perpbrain-0.1.0/src/perpbrain/core/live/order_store.py +394 -0
- perpbrain-0.1.0/src/perpbrain/core/live/payload.py +240 -0
- perpbrain-0.1.0/src/perpbrain/core/live/signer.py +90 -0
- perpbrain-0.1.0/src/perpbrain/core/live/summary.py +147 -0
- perpbrain-0.1.0/src/perpbrain/core/live/terminal.py +93 -0
- perpbrain-0.1.0/src/perpbrain/core/live/transport.py +179 -0
- perpbrain-0.1.0/src/perpbrain/core/live/wallet_policy.py +174 -0
- perpbrain-0.1.0/src/perpbrain/core/orders.py +20 -0
- perpbrain-0.1.0/src/perpbrain/guards.py +972 -0
- perpbrain-0.1.0/src/perpbrain/market_snapshot.py +95 -0
- perpbrain-0.1.0/src/perpbrain/mcp/__init__.py +20 -0
- perpbrain-0.1.0/src/perpbrain/mcp/__main__.py +6 -0
- perpbrain-0.1.0/src/perpbrain/mcp/server.py +510 -0
- perpbrain-0.1.0/src/perpbrain/paper.py +280 -0
- perpbrain-0.1.0/src/perpbrain/py.typed +0 -0
- perpbrain-0.1.0/src/perpbrain/receipt.py +363 -0
- perpbrain-0.1.0/src/perpbrain/sim_guard.py +128 -0
- perpbrain-0.1.0/src/perpbrain/survival.py +110 -0
- perpbrain-0.1.0/src/perpbrain/telemetry/__init__.py +5 -0
- perpbrain-0.1.0/src/perpbrain.egg-info/PKG-INFO +44 -0
- perpbrain-0.1.0/src/perpbrain.egg-info/SOURCES.txt +78 -0
- perpbrain-0.1.0/src/perpbrain.egg-info/dependency_links.txt +1 -0
- perpbrain-0.1.0/src/perpbrain.egg-info/entry_points.txt +3 -0
- perpbrain-0.1.0/src/perpbrain.egg-info/requires.txt +9 -0
- perpbrain-0.1.0/src/perpbrain.egg-info/top_level.txt +1 -0
- perpbrain-0.1.0/tests/test_card_cli.py +119 -0
- perpbrain-0.1.0/tests/test_cli.py +149 -0
- perpbrain-0.1.0/tests/test_frozen_guards.py +993 -0
- perpbrain-0.1.0/tests/test_guards.py +34 -0
- perpbrain-0.1.0/tests/test_live_builder_fee.py +859 -0
- perpbrain-0.1.0/tests/test_live_cancel.py +693 -0
- perpbrain-0.1.0/tests/test_live_client.py +767 -0
- perpbrain-0.1.0/tests/test_live_daily_baseline.py +335 -0
- perpbrain-0.1.0/tests/test_live_endpoints.py +61 -0
- perpbrain-0.1.0/tests/test_live_feeds.py +203 -0
- perpbrain-0.1.0/tests/test_live_geoblock.py +188 -0
- perpbrain-0.1.0/tests/test_live_guard.py +548 -0
- perpbrain-0.1.0/tests/test_live_market_rules.py +459 -0
- perpbrain-0.1.0/tests/test_live_mode.py +179 -0
- perpbrain-0.1.0/tests/test_live_order_store.py +866 -0
- perpbrain-0.1.0/tests/test_live_signer.py +369 -0
- perpbrain-0.1.0/tests/test_live_terminal.py +79 -0
- perpbrain-0.1.0/tests/test_live_testnet_wiring.py +194 -0
- perpbrain-0.1.0/tests/test_live_transport.py +328 -0
- perpbrain-0.1.0/tests/test_live_wallet_policy.py +426 -0
- perpbrain-0.1.0/tests/test_local_signer.py +512 -0
- perpbrain-0.1.0/tests/test_mcp.py +483 -0
- perpbrain-0.1.0/tests/test_orders.py +28 -0
- perpbrain-0.1.0/tests/test_paper.py +338 -0
- perpbrain-0.1.0/tests/test_perpbrain_dist.py +21 -0
- perpbrain-0.1.0/tests/test_sim_guard.py +89 -0
- perpbrain-0.1.0/tests/test_soak_support.py +453 -0
- perpbrain-0.1.0/tests/test_surface.py +17 -0
- perpbrain-0.1.0/tests/test_testnet_integration.py +430 -0
- perpbrain-0.1.0/tests/test_verify_receipt.py +263 -0
perpbrain-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: perpbrain
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Read-only Hyperliquid data, a simulator, and an MCP server. Verified and reproducible. Phase 1 has no live trading.
|
|
5
|
+
Author-email: PERPBRAIN <info@perpbrain.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://perpbrain.com/
|
|
8
|
+
Project-URL: Documentation, https://perpbrain.com/docs
|
|
9
|
+
Project-URL: Repository, https://github.com/PERPBRAIN/perpbrain
|
|
10
|
+
Project-URL: Issues, https://github.com/PERPBRAIN/perpbrain/issues
|
|
11
|
+
Project-URL: Changelog, https://github.com/PERPBRAIN/perpbrain/blob/main/CHANGELOG.md
|
|
12
|
+
Keywords: hyperliquid,perps,trading agent,mcp,simulation,receipts,verifiable
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Operating System :: OS Independent
|
|
20
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
Requires-Dist: perpbrain-read==0.1.0
|
|
24
|
+
Provides-Extra: live
|
|
25
|
+
Requires-Dist: certifi==2026.10.18; extra == "live"
|
|
26
|
+
Requires-Dist: eth-account==0.13.7; extra == "live"
|
|
27
|
+
Requires-Dist: eth-keys==0.8.0; extra == "live"
|
|
28
|
+
Requires-Dist: eth-utils==5.3.1; extra == "live"
|
|
29
|
+
Requires-Dist: hyperliquid-python-sdk==0.24.0; extra == "live"
|
|
30
|
+
Requires-Dist: keyring==25.7.0; extra == "live"
|
|
31
|
+
|
|
32
|
+
# perpbrain
|
|
33
|
+
|
|
34
|
+
Read-only Hyperliquid data, a simulator, and an MCP server. The data path is verified and reproducible. Phase 1 has no live trading.
|
|
35
|
+
|
|
36
|
+
The live route is testnet-only and experimental; mainnet is disabled in code; its dependencies are in the [live] extra.
|
|
37
|
+
|
|
38
|
+
Simulation output is labelled `SIMULATED`. It is not advice.
|
|
39
|
+
|
|
40
|
+
These are limits you set; losses are still possible.
|
|
41
|
+
|
|
42
|
+
This package is `0.1.0`. It is not published from this tree.
|
|
43
|
+
|
|
44
|
+
mcp-name: io.github.PERPBRAIN/perpbrain
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# perpbrain
|
|
2
|
+
|
|
3
|
+
Read-only Hyperliquid data, a simulator, and an MCP server. The data path is verified and reproducible. Phase 1 has no live trading.
|
|
4
|
+
|
|
5
|
+
The live route is testnet-only and experimental; mainnet is disabled in code; its dependencies are in the [live] extra.
|
|
6
|
+
|
|
7
|
+
Simulation output is labelled `SIMULATED`. It is not advice.
|
|
8
|
+
|
|
9
|
+
These are limits you set; losses are still possible.
|
|
10
|
+
|
|
11
|
+
This package is `0.1.0`. It is not published from this tree.
|
|
12
|
+
|
|
13
|
+
mcp-name: io.github.PERPBRAIN/perpbrain
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "perpbrain"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Read-only Hyperliquid data, a simulator, and an MCP server. Verified and reproducible. Phase 1 has no live trading."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
authors = [{ name = "PERPBRAIN", email = "info@perpbrain.com" }]
|
|
9
|
+
keywords = [
|
|
10
|
+
"hyperliquid",
|
|
11
|
+
"perps",
|
|
12
|
+
"trading agent",
|
|
13
|
+
"mcp",
|
|
14
|
+
"simulation",
|
|
15
|
+
"receipts",
|
|
16
|
+
"verifiable",
|
|
17
|
+
]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 3 - Alpha",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Operating System :: OS Independent",
|
|
26
|
+
"Topic :: Office/Business :: Financial :: Investment",
|
|
27
|
+
]
|
|
28
|
+
dependencies = ["perpbrain-read==0.1.0"]
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
# Testnet-only live-route work (docs/live-route-design.md, task L0). Not installed by default:
|
|
32
|
+
# a plain `pip install perpbrain` stays read + sim. Pins are exact; owner review required.
|
|
33
|
+
# eth-account and keyring serve only the optional user-local signer (task L1b,
|
|
34
|
+
# core/live/local_signer.py), which runs on the user's own machine.
|
|
35
|
+
# certifi pins the CA bundle the testnet transport verifies against (L9 S1; env CA vars ignored).
|
|
36
|
+
live = [
|
|
37
|
+
"certifi==2026.10.18",
|
|
38
|
+
"eth-account==0.13.7",
|
|
39
|
+
"eth-keys==0.8.0",
|
|
40
|
+
"eth-utils==5.3.1",
|
|
41
|
+
"hyperliquid-python-sdk==0.24.0",
|
|
42
|
+
"keyring==25.7.0",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
[project.urls]
|
|
46
|
+
Homepage = "https://perpbrain.com/"
|
|
47
|
+
Documentation = "https://perpbrain.com/docs"
|
|
48
|
+
Repository = "https://github.com/PERPBRAIN/perpbrain"
|
|
49
|
+
Issues = "https://github.com/PERPBRAIN/perpbrain/issues"
|
|
50
|
+
Changelog = "https://github.com/PERPBRAIN/perpbrain/blob/main/CHANGELOG.md"
|
|
51
|
+
|
|
52
|
+
[project.scripts]
|
|
53
|
+
perpbrain = "perpbrain.cli:main"
|
|
54
|
+
perpbrain-mcp = "perpbrain.mcp.server:main"
|
|
55
|
+
|
|
56
|
+
[tool.perpbrain]
|
|
57
|
+
dist-name = "perpbrain"
|
|
58
|
+
|
|
59
|
+
[tool.uv.sources]
|
|
60
|
+
perpbrain-read = { workspace = true }
|
|
61
|
+
|
|
62
|
+
[build-system]
|
|
63
|
+
requires = ["setuptools==84.0.0"]
|
|
64
|
+
build-backend = "setuptools.build_meta"
|
|
65
|
+
|
|
66
|
+
[tool.setuptools.packages.find]
|
|
67
|
+
where = ["src"]
|
|
68
|
+
|
|
69
|
+
[tool.setuptools.package-data]
|
|
70
|
+
perpbrain = ["py.typed"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Distribution name, configured in pyproject.toml."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import tomllib
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def distribution_name(pyproject: Path | None = None) -> str:
|
|
10
|
+
"""Return the configured distribution name.
|
|
11
|
+
|
|
12
|
+
The name lives in ``tool.perpbrain.dist-name`` and must match
|
|
13
|
+
``project.name``. Change the package name there.
|
|
14
|
+
"""
|
|
15
|
+
path = pyproject if pyproject is not None else _default_pyproject()
|
|
16
|
+
data = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
17
|
+
tool = data.get("tool")
|
|
18
|
+
project = data.get("project")
|
|
19
|
+
if not isinstance(tool, dict) or not isinstance(project, dict):
|
|
20
|
+
raise RuntimeError("pyproject is missing tool or project tables")
|
|
21
|
+
configured_table = tool.get("perpbrain")
|
|
22
|
+
if not isinstance(configured_table, dict):
|
|
23
|
+
raise RuntimeError("pyproject is missing tool.perpbrain")
|
|
24
|
+
configured = configured_table.get("dist-name")
|
|
25
|
+
project_name = project.get("name")
|
|
26
|
+
if not isinstance(configured, str) or not isinstance(project_name, str):
|
|
27
|
+
raise RuntimeError("dist-name and project.name must be strings")
|
|
28
|
+
if configured != project_name:
|
|
29
|
+
raise RuntimeError("tool.perpbrain.dist-name must match project.name")
|
|
30
|
+
return configured
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _default_pyproject() -> Path:
|
|
34
|
+
return Path(__file__).resolve().parents[2] / "pyproject.toml"
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Package version, reported as the MCP ``serverInfo.version``.
|
|
2
|
+
|
|
3
|
+
Kept as a constant so an installed wheel (no pyproject.toml beside it) reports it too.
|
|
4
|
+
tests/test_release_packaging.py keeps it equal to ``project.version`` in pyproject.toml.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Tool schemas for agent clients. Phase 1 has no order tool.
|
|
2
|
+
|
|
3
|
+
The schemas describe read and simulation tools. Optional framework packages
|
|
4
|
+
are not imported here.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from perpbrain.mcp import TOOL_NAMES
|
|
10
|
+
|
|
11
|
+
_BLOCKED = frozenset(
|
|
12
|
+
{
|
|
13
|
+
"order",
|
|
14
|
+
"submit_order",
|
|
15
|
+
"submit-order",
|
|
16
|
+
"sign",
|
|
17
|
+
"signing",
|
|
18
|
+
"withdraw",
|
|
19
|
+
"withdrawal",
|
|
20
|
+
}
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
_DESCRIPTIONS: dict[str, str] = {
|
|
24
|
+
"markets": "List perpetual markets from the public info endpoint.",
|
|
25
|
+
"order_book": "Read a capped public order book and its data age.",
|
|
26
|
+
"funding": "Read funding, mark, and open interest for one coin.",
|
|
27
|
+
"positions": "Read positions for one address from the public info endpoint.",
|
|
28
|
+
"fees": "Read the address fee rates and their data age.",
|
|
29
|
+
"simulate": (
|
|
30
|
+
"Simulate a closed-bar decision on a supplied book. "
|
|
31
|
+
"The result is SIMULATED and is verified and reproducible from the inputs."
|
|
32
|
+
),
|
|
33
|
+
"funding_extremes": "Z-score of the public hourly funding rate against a trailing window.",
|
|
34
|
+
"book_imbalance": "Bid depth divided by ask depth inside a public-book band.",
|
|
35
|
+
"get_limits": "Read the owner limits and the remaining headroom.",
|
|
36
|
+
"trigger_kill_switch": "Latch the kill switch. A tool call cannot clear it.",
|
|
37
|
+
"get_cost_breakdown": (
|
|
38
|
+
"Recompute the execution-cost breakdown from a simulation receipt. "
|
|
39
|
+
"The result is SIMULATED and is verified and reproducible from the inputs."
|
|
40
|
+
),
|
|
41
|
+
"paper": (
|
|
42
|
+
"Read the live public book and funding for one coin, then run the guarded "
|
|
43
|
+
"simulator. The result is SIMULATED, no keys are used, and no order is placed. "
|
|
44
|
+
"Funding is captured in the tape snapshot but not charged: the single flat bar "
|
|
45
|
+
"has no holding period. The receipt carries the live tape snapshot that produced it."
|
|
46
|
+
),
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
_STRING = {"type": "string"}
|
|
50
|
+
_INTEGER = {"type": "integer"}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def function_tools() -> list[dict[str, object]]:
|
|
54
|
+
"""OpenAI-style function-calling tools. Order, signing, and withdraw are absent."""
|
|
55
|
+
tools: list[dict[str, object]] = []
|
|
56
|
+
for name in TOOL_NAMES:
|
|
57
|
+
_reject_blocked(name)
|
|
58
|
+
tools.append(
|
|
59
|
+
{
|
|
60
|
+
"type": "function",
|
|
61
|
+
"function": {
|
|
62
|
+
"name": name,
|
|
63
|
+
"description": _DESCRIPTIONS[name],
|
|
64
|
+
"parameters": _parameters(name),
|
|
65
|
+
},
|
|
66
|
+
}
|
|
67
|
+
)
|
|
68
|
+
return tools
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _reject_blocked(name: str) -> None:
|
|
72
|
+
if name in _BLOCKED:
|
|
73
|
+
raise ValueError("Phase 1 has no mainnet order path")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def tool_names() -> tuple[str, ...]:
|
|
77
|
+
names: list[str] = []
|
|
78
|
+
for tool in function_tools():
|
|
79
|
+
function = tool.get("function")
|
|
80
|
+
if not isinstance(function, dict):
|
|
81
|
+
continue
|
|
82
|
+
name = function.get("name")
|
|
83
|
+
if isinstance(name, str):
|
|
84
|
+
names.append(name)
|
|
85
|
+
return tuple(names)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _parameters(name: str) -> dict[str, object]:
|
|
89
|
+
if name == "simulate":
|
|
90
|
+
return {
|
|
91
|
+
"type": "object",
|
|
92
|
+
"additionalProperties": False,
|
|
93
|
+
"required": ["market", "decision", "bars", "book"],
|
|
94
|
+
"properties": {
|
|
95
|
+
"market": _STRING,
|
|
96
|
+
"decision": {"type": "object"},
|
|
97
|
+
"bars": {"type": "array", "items": {"type": "object"}},
|
|
98
|
+
"book": {"type": "object"},
|
|
99
|
+
"fee_version": _STRING,
|
|
100
|
+
"funding": {"type": "array", "items": {"type": "object"}},
|
|
101
|
+
"funding_interval_ms": _INTEGER,
|
|
102
|
+
"leverage": _STRING,
|
|
103
|
+
"open_positions": _INTEGER,
|
|
104
|
+
"daily_loss_usd": _STRING,
|
|
105
|
+
"daily_loss_pct": _STRING,
|
|
106
|
+
"age_ms": _INTEGER,
|
|
107
|
+
"now_ms": _INTEGER,
|
|
108
|
+
},
|
|
109
|
+
}
|
|
110
|
+
if name in {"order_book", "funding", "funding_extremes", "book_imbalance"}:
|
|
111
|
+
properties: dict[str, object] = {"coin": _STRING}
|
|
112
|
+
required = ["coin"]
|
|
113
|
+
if name == "order_book":
|
|
114
|
+
properties["depth"] = _INTEGER
|
|
115
|
+
if name == "funding_extremes":
|
|
116
|
+
properties["window_hours"] = _INTEGER
|
|
117
|
+
if name == "book_imbalance":
|
|
118
|
+
properties["band_bps"] = _INTEGER
|
|
119
|
+
return _object(properties, required)
|
|
120
|
+
if name in {"positions", "fees"}:
|
|
121
|
+
return _object({"address": _STRING}, ["address"])
|
|
122
|
+
if name == "trigger_kill_switch":
|
|
123
|
+
return _object({"engage": {"type": "boolean"}}, [])
|
|
124
|
+
if name in {"markets", "get_limits"}:
|
|
125
|
+
return _object({}, [])
|
|
126
|
+
if name == "get_cost_breakdown":
|
|
127
|
+
return _object({"receipt": {"type": "object"}}, ["receipt"])
|
|
128
|
+
if name == "paper":
|
|
129
|
+
return {
|
|
130
|
+
"type": "object",
|
|
131
|
+
"additionalProperties": False,
|
|
132
|
+
"required": ["coin", "side", "size"],
|
|
133
|
+
"properties": {
|
|
134
|
+
"coin": _STRING,
|
|
135
|
+
"side": {"type": "string", "enum": ["long", "short"]},
|
|
136
|
+
"size": _STRING,
|
|
137
|
+
"stop": _STRING,
|
|
138
|
+
"target": _STRING,
|
|
139
|
+
"liquidity": {"type": "string", "enum": ["taker", "maker"]},
|
|
140
|
+
"fee_version": _STRING,
|
|
141
|
+
"depth": _INTEGER,
|
|
142
|
+
"leverage": _STRING,
|
|
143
|
+
"open_positions": _INTEGER,
|
|
144
|
+
"daily_loss_usd": _STRING,
|
|
145
|
+
"daily_loss_pct": _STRING,
|
|
146
|
+
},
|
|
147
|
+
}
|
|
148
|
+
raise ValueError(f"unknown tool: {name}")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _object(properties: dict[str, object], required: list[str]) -> dict[str, object]:
|
|
152
|
+
body: dict[str, object] = {
|
|
153
|
+
"type": "object",
|
|
154
|
+
"additionalProperties": False,
|
|
155
|
+
"properties": properties,
|
|
156
|
+
}
|
|
157
|
+
if required:
|
|
158
|
+
body["required"] = required
|
|
159
|
+
return body
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""Record, verify, draw a results card, and print an execution-cost breakdown."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import cast
|
|
10
|
+
|
|
11
|
+
from perpbrain.guards import GuardBlocked, GuardSession
|
|
12
|
+
from perpbrain.mcp.server import main as serve_mcp
|
|
13
|
+
from perpbrain.paper import build_paper_inputs, run_paper_decision, write_paper_receipt
|
|
14
|
+
from perpbrain.receipt import verify_receipt_at
|
|
15
|
+
from perpbrain_read.read.age import wall_ms
|
|
16
|
+
from perpbrain_read.read.dataset import (
|
|
17
|
+
Thresholds,
|
|
18
|
+
collect_frames,
|
|
19
|
+
parse_frame,
|
|
20
|
+
record_frames,
|
|
21
|
+
verify_dir,
|
|
22
|
+
)
|
|
23
|
+
from perpbrain_read.read.hl_feed import HlFeed
|
|
24
|
+
from perpbrain_read.read.info import InfoClient, urllib_transport, urlopen_opener
|
|
25
|
+
from perpbrain_read.read.queries import BookResult, FundingResult, funding, order_book
|
|
26
|
+
from perpbrain_read.read.ws_conn import open_websocket
|
|
27
|
+
from perpbrain_read.sim.card import render_card_svg
|
|
28
|
+
from perpbrain_read.sim.engine import Liquidity, PositionSide
|
|
29
|
+
from perpbrain_read.sim.receipt import cost_breakdown_from_receipt
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def main(argv: list[str] | None = None) -> int:
|
|
33
|
+
parser = argparse.ArgumentParser(prog="perpbrain")
|
|
34
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
35
|
+
record = sub.add_parser("record", help="record a public market-data tape")
|
|
36
|
+
record.add_argument("--coin", required=True)
|
|
37
|
+
record.add_argument("--hours", required=True, type=float)
|
|
38
|
+
record.add_argument("--out", default="data")
|
|
39
|
+
record.add_argument("--tape", help="JSON tape. Without it, read the public endpoints.")
|
|
40
|
+
verify = sub.add_parser("verify", help="rebuild derived files and compare them")
|
|
41
|
+
verify.add_argument("directory")
|
|
42
|
+
verify_receipt = sub.add_parser(
|
|
43
|
+
"verify-receipt",
|
|
44
|
+
help="re-derive a simulation receipt and rerun the sim",
|
|
45
|
+
)
|
|
46
|
+
verify_receipt.add_argument("receipt")
|
|
47
|
+
card = sub.add_parser("card", help="write an SVG card for a verified receipt")
|
|
48
|
+
card.add_argument("receipt")
|
|
49
|
+
card.add_argument("--out", help="write the SVG to this path instead of stdout")
|
|
50
|
+
costs = sub.add_parser(
|
|
51
|
+
"costs", help="print the execution-cost breakdown for a verified receipt"
|
|
52
|
+
)
|
|
53
|
+
costs.add_argument("receipt")
|
|
54
|
+
sub.add_parser(
|
|
55
|
+
"mcp",
|
|
56
|
+
help="serve the MCP tools on stdio (same as perpbrain-mcp and python -m perpbrain.mcp)",
|
|
57
|
+
)
|
|
58
|
+
paper = sub.add_parser(
|
|
59
|
+
"paper",
|
|
60
|
+
help=(
|
|
61
|
+
"read the live public book and funding, then run one guarded paper decision. "
|
|
62
|
+
"No keys. No order is placed."
|
|
63
|
+
),
|
|
64
|
+
)
|
|
65
|
+
paper.add_argument("--coin", required=True)
|
|
66
|
+
paper.add_argument("--side", required=True, choices=["long", "short"])
|
|
67
|
+
paper.add_argument("--size", required=True)
|
|
68
|
+
paper.add_argument("--stop")
|
|
69
|
+
paper.add_argument("--target")
|
|
70
|
+
paper.add_argument("--liquidity", choices=["taker", "maker"])
|
|
71
|
+
paper.add_argument("--fee-version")
|
|
72
|
+
paper.add_argument("--depth", type=int, default=20)
|
|
73
|
+
paper.add_argument("--preset", default="standard", choices=["conservative", "standard", "pro"])
|
|
74
|
+
paper.add_argument("--out", default="paper")
|
|
75
|
+
paper.add_argument(
|
|
76
|
+
"--tape",
|
|
77
|
+
help="JSON {book, funding} read. Without it, read the public endpoints.",
|
|
78
|
+
)
|
|
79
|
+
paper.add_argument(
|
|
80
|
+
"--now-ms",
|
|
81
|
+
type=int,
|
|
82
|
+
help=(
|
|
83
|
+
"Clock reading used for data age. Only with --tape (replay); "
|
|
84
|
+
"a live read uses the wall clock."
|
|
85
|
+
),
|
|
86
|
+
)
|
|
87
|
+
try:
|
|
88
|
+
namespace = parser.parse_args(argv)
|
|
89
|
+
except SystemExit as exc:
|
|
90
|
+
code = exc.code
|
|
91
|
+
if isinstance(code, int):
|
|
92
|
+
return code
|
|
93
|
+
return 2
|
|
94
|
+
try:
|
|
95
|
+
if namespace.command == "record":
|
|
96
|
+
return _record(
|
|
97
|
+
str(namespace.coin),
|
|
98
|
+
float(namespace.hours),
|
|
99
|
+
Path(str(namespace.out)),
|
|
100
|
+
None if namespace.tape is None else Path(str(namespace.tape)),
|
|
101
|
+
)
|
|
102
|
+
if namespace.command == "verify":
|
|
103
|
+
return _verify(Path(str(namespace.directory)))
|
|
104
|
+
if namespace.command == "verify-receipt":
|
|
105
|
+
return _verify_receipt(Path(str(namespace.receipt)))
|
|
106
|
+
if namespace.command == "card":
|
|
107
|
+
destination = None if namespace.out is None else Path(str(namespace.out))
|
|
108
|
+
return _card(Path(str(namespace.receipt)), destination)
|
|
109
|
+
if namespace.command == "costs":
|
|
110
|
+
return _costs(Path(str(namespace.receipt)))
|
|
111
|
+
if namespace.command == "paper":
|
|
112
|
+
return _paper(namespace)
|
|
113
|
+
if namespace.command == "mcp":
|
|
114
|
+
return _mcp()
|
|
115
|
+
except (OSError, ValueError, json.JSONDecodeError) as exc:
|
|
116
|
+
print(str(exc), file=sys.stderr)
|
|
117
|
+
return 1
|
|
118
|
+
return 2
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _mcp() -> int:
|
|
122
|
+
serve_mcp()
|
|
123
|
+
return 0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _record(coin: str, hours: float, root: Path, tape: Path | None) -> int:
|
|
127
|
+
duration_ms = _duration_ms(hours)
|
|
128
|
+
if tape is None:
|
|
129
|
+
frames = collect_frames(coin, duration_ms, _live_feed(coin), wall_ms, Thresholds())
|
|
130
|
+
directory = record_frames(frames, root, coin=coin, duration_ms=duration_ms)
|
|
131
|
+
else:
|
|
132
|
+
directory = record_frames(_load_tape(tape), root, coin=coin, duration_ms=duration_ms)
|
|
133
|
+
print(directory)
|
|
134
|
+
return 0
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _verify(directory: Path) -> int:
|
|
138
|
+
errors = verify_dir(directory)
|
|
139
|
+
if errors:
|
|
140
|
+
print("\n".join(errors), file=sys.stderr)
|
|
141
|
+
return 1
|
|
142
|
+
print("verify ok")
|
|
143
|
+
return 0
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _verify_receipt(path: Path) -> int:
|
|
147
|
+
report = verify_receipt_at(path)
|
|
148
|
+
if report["status"] == "VERIFIED":
|
|
149
|
+
print("VERIFIED")
|
|
150
|
+
return 0
|
|
151
|
+
print("\n".join(report["mismatches"]))
|
|
152
|
+
return 1
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _card(path: Path, out: Path | None) -> int:
|
|
156
|
+
report = verify_receipt_at(path)
|
|
157
|
+
if report["status"] != "VERIFIED":
|
|
158
|
+
print("\n".join(report["mismatches"]), file=sys.stderr)
|
|
159
|
+
return 1
|
|
160
|
+
loaded = json.loads(path.read_text(encoding="utf-8"))
|
|
161
|
+
if not isinstance(loaded, dict):
|
|
162
|
+
print("receipt mismatch", file=sys.stderr)
|
|
163
|
+
return 1
|
|
164
|
+
receipt = {str(key): value for key, value in loaded.items()}
|
|
165
|
+
svg = render_card_svg(receipt)
|
|
166
|
+
if out is None:
|
|
167
|
+
sys.stdout.write(svg)
|
|
168
|
+
return 0
|
|
169
|
+
out.write_text(svg, encoding="utf-8")
|
|
170
|
+
print(out)
|
|
171
|
+
return 0
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _costs(path: Path) -> int:
|
|
175
|
+
report = verify_receipt_at(path)
|
|
176
|
+
if report["status"] != "VERIFIED":
|
|
177
|
+
print("\n".join(report["mismatches"]), file=sys.stderr)
|
|
178
|
+
return 1
|
|
179
|
+
loaded = json.loads(path.read_text(encoding="utf-8"))
|
|
180
|
+
if not isinstance(loaded, dict):
|
|
181
|
+
print("receipt mismatch", file=sys.stderr)
|
|
182
|
+
return 1
|
|
183
|
+
receipt = {str(key): value for key, value in loaded.items()}
|
|
184
|
+
breakdown = cost_breakdown_from_receipt(receipt)
|
|
185
|
+
sys.stdout.write(json.dumps(breakdown, indent=2, sort_keys=True) + "\n")
|
|
186
|
+
return 0
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _paper(namespace: argparse.Namespace) -> int:
|
|
190
|
+
coin = str(namespace.coin)
|
|
191
|
+
side = cast(PositionSide, str(namespace.side))
|
|
192
|
+
size = str(namespace.size)
|
|
193
|
+
stop = None if namespace.stop is None else str(namespace.stop)
|
|
194
|
+
target = None if namespace.target is None else str(namespace.target)
|
|
195
|
+
liquidity = None if namespace.liquidity is None else cast(Liquidity, str(namespace.liquidity))
|
|
196
|
+
fee_version = None if namespace.fee_version is None else str(namespace.fee_version)
|
|
197
|
+
depth = int(namespace.depth)
|
|
198
|
+
tape = None if namespace.tape is None else Path(str(namespace.tape))
|
|
199
|
+
now_ms = None if namespace.now_ms is None else int(namespace.now_ms)
|
|
200
|
+
if tape is None:
|
|
201
|
+
if now_ms is not None:
|
|
202
|
+
# Issue 6: a live read is aged against the wall clock, never a supplied one.
|
|
203
|
+
raise ValueError("--now-ms is only for --tape replay; a live read uses the wall clock")
|
|
204
|
+
clock = wall_ms()
|
|
205
|
+
client = InfoClient(urllib_transport(urlopen_opener()))
|
|
206
|
+
book = order_book(client, coin, depth=depth, now_ms=clock)
|
|
207
|
+
funded = funding(client, coin, now_ms=clock)
|
|
208
|
+
else:
|
|
209
|
+
if now_ms is None:
|
|
210
|
+
raise ValueError("--now-ms is required with --tape")
|
|
211
|
+
clock = now_ms
|
|
212
|
+
book, funded = _load_paper_tape(tape)
|
|
213
|
+
inputs = build_paper_inputs(
|
|
214
|
+
coin,
|
|
215
|
+
side,
|
|
216
|
+
size,
|
|
217
|
+
book,
|
|
218
|
+
funded,
|
|
219
|
+
stop=stop,
|
|
220
|
+
target=target,
|
|
221
|
+
liquidity=liquidity,
|
|
222
|
+
fee_version=fee_version,
|
|
223
|
+
now_ms=clock,
|
|
224
|
+
)
|
|
225
|
+
session = GuardSession.from_config(str(namespace.preset))
|
|
226
|
+
try:
|
|
227
|
+
outcome = run_paper_decision(inputs, session)
|
|
228
|
+
except GuardBlocked as blocked:
|
|
229
|
+
print(json.dumps(blocked.result, indent=2, sort_keys=True))
|
|
230
|
+
return 1
|
|
231
|
+
path = write_paper_receipt(Path(str(namespace.out)), outcome, session)
|
|
232
|
+
print(path)
|
|
233
|
+
return 0
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _load_paper_tape(path: Path) -> tuple[BookResult, FundingResult]:
|
|
237
|
+
loaded = json.loads(path.read_text(encoding="utf-8"))
|
|
238
|
+
if not isinstance(loaded, dict):
|
|
239
|
+
raise ValueError("tape must be an object")
|
|
240
|
+
book = loaded.get("book")
|
|
241
|
+
funded = loaded.get("funding")
|
|
242
|
+
if not isinstance(book, dict) or not isinstance(funded, dict):
|
|
243
|
+
raise ValueError("tape must have book and funding objects")
|
|
244
|
+
return cast(BookResult, book), cast(FundingResult, funded)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _duration_ms(hours: float) -> int:
|
|
248
|
+
if hours <= 0:
|
|
249
|
+
raise ValueError("hours must be positive")
|
|
250
|
+
return round(hours * 3_600_000)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _load_tape(path: Path) -> list[dict[str, object]]:
|
|
254
|
+
loaded = json.loads(path.read_text(encoding="utf-8"))
|
|
255
|
+
if not isinstance(loaded, list):
|
|
256
|
+
raise ValueError("tape must be a list")
|
|
257
|
+
frames: list[dict[str, object]] = []
|
|
258
|
+
for item in loaded:
|
|
259
|
+
if not isinstance(item, dict):
|
|
260
|
+
raise ValueError("tape frame must be an object")
|
|
261
|
+
frame = parse_frame({str(key): value for key, value in item.items()})
|
|
262
|
+
frames.append(dict(frame))
|
|
263
|
+
return frames
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _live_feed(coin: str) -> HlFeed:
|
|
267
|
+
info = InfoClient(urllib_transport(urlopen_opener()))
|
|
268
|
+
return HlFeed(coin, info, open_websocket(), wall_ms)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
if __name__ == "__main__":
|
|
272
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Frozen core. Order and guard modules live here and are owner-reviewed."""
|
|
2
|
+
|
|
3
|
+
from perpbrain.core.guards import (
|
|
4
|
+
DEFAULT_MAX_DAILY_LOSS,
|
|
5
|
+
DEFAULT_MAX_DAILY_NOTIONAL,
|
|
6
|
+
DEFAULT_MAX_LEVERAGE,
|
|
7
|
+
DEFAULT_MAX_ORDER_NOTIONAL,
|
|
8
|
+
DEFAULT_MIN_LIQUIDATION_DISTANCE,
|
|
9
|
+
tighten,
|
|
10
|
+
within_limit,
|
|
11
|
+
)
|
|
12
|
+
from perpbrain.core.orders import MainnetDisabled, mainnet_orders_enabled, submit_order
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"DEFAULT_MAX_DAILY_LOSS",
|
|
16
|
+
"DEFAULT_MAX_DAILY_NOTIONAL",
|
|
17
|
+
"DEFAULT_MAX_LEVERAGE",
|
|
18
|
+
"DEFAULT_MAX_ORDER_NOTIONAL",
|
|
19
|
+
"DEFAULT_MIN_LIQUIDATION_DISTANCE",
|
|
20
|
+
"MainnetDisabled",
|
|
21
|
+
"mainnet_orders_enabled",
|
|
22
|
+
"submit_order",
|
|
23
|
+
"tighten",
|
|
24
|
+
"within_limit",
|
|
25
|
+
]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Frozen limits. A limit can be tightened and cannot be loosened."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
DEFAULT_MAX_LEVERAGE = 5
|
|
6
|
+
DEFAULT_MAX_ORDER_NOTIONAL = 25_000
|
|
7
|
+
DEFAULT_MAX_DAILY_NOTIONAL = 100_000
|
|
8
|
+
DEFAULT_MIN_LIQUIDATION_DISTANCE = 0.15
|
|
9
|
+
DEFAULT_MAX_DAILY_LOSS = 0.05
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def tighten(current: int, requested: int) -> int:
|
|
13
|
+
"""Return the tighter positive limit. A higher request is ignored."""
|
|
14
|
+
if current < 1:
|
|
15
|
+
raise ValueError("current limit must be >= 1")
|
|
16
|
+
if requested < 1:
|
|
17
|
+
raise ValueError("requested limit must be >= 1")
|
|
18
|
+
if requested > current:
|
|
19
|
+
return current
|
|
20
|
+
return requested
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def within_limit(amount: int, limit: int) -> bool:
|
|
24
|
+
"""True when amount is allowed by limit. An amount above the limit is rejected."""
|
|
25
|
+
if amount < 0 or limit < 1:
|
|
26
|
+
raise ValueError("amount must be >= 0 and limit must be >= 1")
|
|
27
|
+
return amount <= limit
|