refactor: telegram + portfolio in-process (drop shared MCP)

Each bot now manages its own notification + portfolio aggregation:

* TelegramClient calls the public Bot API directly via httpx, reading
  CERBERO_BITE_TELEGRAM_BOT_TOKEN / CERBERO_BITE_TELEGRAM_CHAT_ID from
  env. No credentials → silent disabled mode.
* PortfolioClient composes DeribitClient + HyperliquidClient + the new
  MacroClient.get_asset_price/eur_usd_rate to expose equity (EUR) and
  per-asset exposure as the bot's own slice (no cross-bot view).
* mcp-telegram and mcp-portfolio removed from MCP_SERVICES / McpEndpoints
  and the cerbero-bite ping CLI; health_check no longer probes portfolio.

Docs (02/04/06/07) and docker-compose updated to reflect the new
architecture.

353/353 tests pass; ruff clean; mypy src clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-30 00:31:20 +02:00
parent 067f74bc89
commit abf5a140e2
26 changed files with 836 additions and 423 deletions
-7
View File
@@ -26,7 +26,6 @@ from cerbero_bite.clients import HttpToolClient, McpError
from cerbero_bite.clients.deribit import DeribitClient
from cerbero_bite.clients.hyperliquid import HyperliquidClient
from cerbero_bite.clients.macro import MacroClient
from cerbero_bite.clients.portfolio import PortfolioClient
from cerbero_bite.clients.sentiment import SentimentClient
from cerbero_bite.config.loader import compute_config_hash, load_strategy
from cerbero_bite.config.mcp_endpoints import (
@@ -560,12 +559,6 @@ async def _ping_one(
if service == "hyperliquid":
await HyperliquidClient(http).funding_rate_annualized("ETH")
return "ok", "ETH-PERP reachable"
if service == "portfolio":
await PortfolioClient(http).total_equity_eur()
return "ok", "portfolio reachable"
if service == "telegram":
# Notify-only: no read tool. Skip without hitting the bot.
return "skipped", "notify-only client (no health probe)"
return "skipped", "no probe defined" # pragma: no cover
except McpError as exc:
return "fail", f"{type(exc).__name__}: {exc}"
+23 -3
View File
@@ -1,13 +1,17 @@
"""Wrapper around ``mcp-hyperliquid``.
Cerbero Bite consumes a single tool: ``get_funding_rate`` for ETH-PERP,
used by entry filter §2.6 of ``docs/01-strategy-rules.md`` (cap on the
absolute annualised funding rate).
Cerbero Bite consumes:
* ``get_funding_rate`` — entry filter §2.6 cap on absolute annualised
funding rate (``docs/01-strategy-rules.md``).
* ``get_account_summary`` and ``get_positions`` — feed the in-process
portfolio aggregator (equity + ETH/BTC exposure on the perp side).
"""
from __future__ import annotations
from decimal import Decimal
from typing import Any
from cerbero_bite.clients._base import HttpToolClient
from cerbero_bite.clients._exceptions import McpDataAnomalyError
@@ -47,3 +51,19 @@ class HyperliquidClient:
tool="get_funding_rate",
)
return Decimal(str(rate)) * Decimal(HOURLY_FUNDING_PERIODS_PER_YEAR)
async def get_account_summary(self) -> dict[str, Any]:
"""Account equity and balances (USD)."""
raw: Any = await self._http.call("get_account_summary", {})
return raw if isinstance(raw, dict) else {}
async def get_positions(self) -> list[dict[str, Any]]:
"""Open perp positions (list of dicts)."""
raw: Any = await self._http.call("get_positions", {})
if isinstance(raw, list):
return raw
if isinstance(raw, dict):
inner = raw.get("positions")
if isinstance(inner, list):
return inner
return []
+30
View File
@@ -9,11 +9,13 @@ the requested window. The orchestrator feeds the result straight into
from __future__ import annotations
from datetime import UTC, datetime
from decimal import Decimal
from typing import Any
from pydantic import BaseModel, ConfigDict
from cerbero_bite.clients._base import HttpToolClient
from cerbero_bite.clients._exceptions import McpDataAnomalyError
__all__ = ["MacroClient", "MacroEvent"]
@@ -71,6 +73,34 @@ class MacroClient:
)
return out
async def get_asset_price(self, ticker: str) -> Decimal:
"""Return the latest cross-asset price for ``ticker`` (e.g. ``EURUSD``)."""
raw = await self._http.call("get_asset_price", {"ticker": ticker})
if not isinstance(raw, dict):
raise McpDataAnomalyError(
f"macro get_asset_price unexpected shape: {type(raw).__name__}",
service=self.SERVICE,
tool="get_asset_price",
)
if raw.get("error"):
raise McpDataAnomalyError(
f"macro get_asset_price error for {ticker}: {raw['error']}",
service=self.SERVICE,
tool="get_asset_price",
)
price = raw.get("price")
if price is None:
raise McpDataAnomalyError(
f"macro get_asset_price missing 'price' for {ticker}",
service=self.SERVICE,
tool="get_asset_price",
)
return Decimal(str(price))
async def eur_usd_rate(self) -> Decimal:
"""Return EUR→USD spot rate (i.e. ``EURUSD`` price)."""
return await self.get_asset_price("EURUSD")
async def next_high_severity_within(
self,
*,
+131 -66
View File
@@ -1,92 +1,157 @@
"""Wrapper around ``mcp-portfolio``.
"""In-process portfolio aggregator.
Cerbero Bite uses two pieces of information from this service:
Each Cerbero Suite bot now manages its own portfolio view: instead of
calling a shared ``mcp-portfolio`` service, this client composes the
account summaries and open positions from the exchanges the bot
actually uses (Deribit options + Hyperliquid perps) and converts them
to EUR via the macro service.
* total portfolio value (EUR) — fed to the sizing engine after FX
conversion to USD;
* exposure of a specific asset as percentage of the total portfolio —
used by entry filter §2.7 (``eth_holdings_pct_max``).
Two values are exposed:
The portfolio service stores everything in EUR. The orchestrator is
responsible for the EUR→USD conversion using a live FX rate.
* :py:meth:`total_equity_eur` — sum of USDC equity on Deribit and USD
equity on Hyperliquid, converted to EUR using the live ``EURUSD``
rate from ``mcp-macro``.
* :py:meth:`asset_pct_of_portfolio` — fraction (0..1) of total USD
equity exposed to a specific ticker via open positions on the two
exchanges. Used by entry filter §2.7 (``eth_holdings_pct_max``).
**Scope note**: this is the bot's own slice. Holdings on other
exchanges, in cold storage, or held by other bots in the suite are
*not* counted. The §2.7 limit is therefore a per-bot cap, not a
suite-wide one.
"""
from __future__ import annotations
import asyncio
from collections.abc import Iterable
from decimal import Decimal
from typing import Any
from typing import Any, cast
from cerbero_bite.clients._base import HttpToolClient
from cerbero_bite.clients._exceptions import McpDataAnomalyError
from cerbero_bite.clients.deribit import DeribitClient
from cerbero_bite.clients.hyperliquid import HyperliquidClient
from cerbero_bite.clients.macro import MacroClient
__all__ = ["PortfolioClient"]
class PortfolioClient:
SERVICE = "portfolio"
def _decimal_or_zero(value: Any) -> Decimal:
if value is None:
return Decimal(0)
try:
return Decimal(str(value))
except (ValueError, ArithmeticError):
return Decimal(0)
def __init__(self, http: HttpToolClient) -> None:
if http.service != self.SERVICE:
raise ValueError(
f"PortfolioClient requires service '{self.SERVICE}', got '{http.service}'"
)
self._http = http
def _position_notional_usd(pos: dict[str, Any]) -> Decimal:
"""Best-effort USD notional of an open position.
Prefers an explicit ``notional_usd`` / ``size_usd`` / ``value_usd``
field. Falls back to ``|size × mark_price|`` (or ``index_price`` if
mark is missing). Returns 0 on malformed entries.
"""
for key in ("notional_usd", "size_usd", "value_usd", "position_value"):
v = pos.get(key)
if v is not None:
return abs(_decimal_or_zero(v))
size = _decimal_or_zero(pos.get("size") or pos.get("szi"))
mark = _decimal_or_zero(
pos.get("mark_price")
or pos.get("entry_price")
or pos.get("index_price")
)
return abs(size * mark)
def _instrument_label(pos: dict[str, Any]) -> str:
for key in ("instrument_name", "instrument", "symbol", "coin", "asset"):
v = pos.get(key)
if v is not None:
return str(v).upper()
return ""
class PortfolioClient:
"""Aggregates equity + asset exposure across the bot's exchange accounts."""
def __init__(
self,
*,
deribit: DeribitClient,
hyperliquid: HyperliquidClient,
macro: MacroClient,
) -> None:
self._deribit = deribit
self._hyperliquid = hyperliquid
self._macro = macro
async def _equity_usd_components(self) -> tuple[Decimal, Decimal]:
"""Concurrent fetch of (deribit_equity_usd, hyperliquid_equity_usd)."""
deribit_summary, hl_summary = await asyncio.gather(
self._deribit.get_account_summary(currency="USDC"),
self._hyperliquid.get_account_summary(),
)
deribit_eq = _decimal_or_zero(deribit_summary.get("equity"))
hl_eq = _decimal_or_zero(hl_summary.get("equity"))
return deribit_eq, hl_eq
async def total_equity_usd(self) -> Decimal:
"""Sum equity USD across the bot's exchange accounts."""
deribit_eq, hl_eq = await self._equity_usd_components()
return deribit_eq + hl_eq
async def total_equity_eur(self) -> Decimal:
"""Return the aggregate portfolio value in EUR."""
raw = await self._http.call(
"get_total_portfolio_value", {"currency": "EUR"}
)
if not isinstance(raw, dict):
"""Return aggregate bot equity in EUR.
Concurrent: account summaries × FX. Raises
:class:`McpDataAnomalyError` if the FX rate is non-positive.
"""
components_t = asyncio.create_task(self._equity_usd_components())
fx_t = asyncio.create_task(self._macro.eur_usd_rate())
await asyncio.gather(components_t, fx_t)
deribit_eq, hl_eq = components_t.result()
fx = fx_t.result()
if fx <= 0:
raise McpDataAnomalyError(
f"portfolio total_value_eur unexpected shape: {type(raw).__name__}",
service=self.SERVICE,
tool="get_total_portfolio_value",
f"non-positive EURUSD rate: {fx}",
service="macro",
tool="get_asset_price",
)
value = raw.get("total_value_eur")
if value is None:
raise McpDataAnomalyError(
"portfolio response missing 'total_value_eur'",
service=self.SERVICE,
tool="get_total_portfolio_value",
)
return Decimal(str(value))
usd_total = deribit_eq + hl_eq
return usd_total / fx
async def asset_pct_of_portfolio(self, ticker: str) -> Decimal:
"""Return the fraction (0..1) of the portfolio held in ``ticker``.
"""Fraction of bot equity (USD) exposed to ``ticker``.
Iterates the holdings list and aggregates ``current_value_eur``
for any holding whose ticker contains ``ticker`` (case-insensitive).
Empty portfolio → 0.
Sums absolute USD notional of open positions whose instrument
label contains ``ticker`` (case-insensitive) on Deribit and
Hyperliquid, divided by the bot's total USD equity. Returns 0
when there is no equity or no exposure.
"""
holdings = await self._http.call("get_holdings", {"min_value_eur": 0})
if not isinstance(holdings, list):
raise McpDataAnomalyError(
f"portfolio get_holdings unexpected shape: {type(holdings).__name__}",
service=self.SERVICE,
tool="get_holdings",
)
target = ticker.upper()
matching_value = Decimal("0")
total_value = Decimal("0")
for entry in holdings:
if not isinstance(entry, dict):
continue
value = entry.get("current_value_eur")
if value is None:
continue
value_dec = Decimal(str(value))
total_value += value_dec
entry_ticker = str(entry.get("ticker") or "").upper()
if target in entry_ticker:
matching_value += value_dec
deribit_pos_t = asyncio.create_task(
self._deribit.get_positions(currency="USDC")
)
hl_pos_t = asyncio.create_task(self._hyperliquid.get_positions())
equity_t = asyncio.create_task(self._equity_usd_components())
await asyncio.gather(deribit_pos_t, hl_pos_t, equity_t)
if total_value == 0:
return Decimal("0")
return matching_value / total_value
exposure_usd = Decimal(0)
for raw_pos in cast(Iterable[Any], deribit_pos_t.result()):
if not isinstance(raw_pos, dict):
continue
if target in _instrument_label(raw_pos):
exposure_usd += _position_notional_usd(raw_pos)
for raw_pos in cast(Iterable[Any], hl_pos_t.result()):
if not isinstance(raw_pos, dict):
continue
if target in _instrument_label(raw_pos):
exposure_usd += _position_notional_usd(raw_pos)
async def health(self) -> dict[str, Any]:
"""Lightweight call used by ``cerbero-bite ping``."""
result: Any = await self._http.call("get_last_update_info", {})
return result if isinstance(result, dict) else {}
deribit_eq, hl_eq = equity_t.result()
total_eq = deribit_eq + hl_eq
if total_eq <= 0:
return Decimal(0)
return exposure_usd / total_eq
+126 -49
View File
@@ -1,41 +1,115 @@
"""Wrapper around ``mcp-telegram`` (notify-only mode).
"""Direct Telegram Bot API client (notify-only).
Cerbero Bite during the testnet phase (and through the soft launch) is
fully autonomous: Telegram is used purely to *notify* Adriano of what
the engine has done, never to gate execution. As a consequence:
Cerbero Bite is fully autonomous: Telegram is used solely to *notify*
the operator of what the engine has done — there is no inbound queue
and no confirmation logic.
* No ``send_with_buttons`` and no callback queue.
* Confirmation timeouts are handled inside the orchestrator's own
state machine, not by waiting on Telegram replies.
* All notifications go through one of the typed endpoints
(``notify``, ``notify_position_opened``, ``notify_position_closed``,
``notify_alert``, ``notify_system_error``) — the formatting lives
on the server side.
Credentials are read from the environment:
* ``CERBERO_BITE_TELEGRAM_BOT_TOKEN`` — bot token from BotFather.
* ``CERBERO_BITE_TELEGRAM_CHAT_ID`` — destination chat id.
If either is missing the client runs in **disabled** mode: every
``notify_*`` becomes a no-op logged at DEBUG. This keeps unconfigured
deployments and the test environment harmless.
"""
from __future__ import annotations
import logging
import os
from decimal import Decimal
from typing import Any
from cerbero_bite.clients._base import HttpToolClient
import httpx
__all__ = ["TelegramClient"]
__all__ = [
"TELEGRAM_BOT_TOKEN_ENV",
"TELEGRAM_CHAT_ID_ENV",
"TelegramClient",
"TelegramError",
"load_telegram_credentials",
]
def _to_float(value: Decimal | float) -> float:
return float(value) if isinstance(value, Decimal) else value
TELEGRAM_BOT_TOKEN_ENV = "CERBERO_BITE_TELEGRAM_BOT_TOKEN"
TELEGRAM_CHAT_ID_ENV = "CERBERO_BITE_TELEGRAM_CHAT_ID"
_log = logging.getLogger("cerbero_bite.clients.telegram")
class TelegramError(RuntimeError):
"""Raised when the Telegram Bot API rejects a sendMessage call."""
def _to_float(value: Decimal | float | int) -> float:
return float(value)
def load_telegram_credentials(
env: dict[str, str] | None = None,
) -> tuple[str | None, str | None]:
"""Return ``(bot_token, chat_id)`` from env. Empty strings → ``None``."""
e = env if env is not None else os.environ
token = (e.get(TELEGRAM_BOT_TOKEN_ENV) or "").strip() or None
chat = (e.get(TELEGRAM_CHAT_ID_ENV) or "").strip() or None
return token, chat
class TelegramClient:
SERVICE = "telegram"
"""Notify-only client over the public Telegram Bot API."""
def __init__(self, http: HttpToolClient) -> None:
if http.service != self.SERVICE:
raise ValueError(
f"TelegramClient requires service '{self.SERVICE}', got '{http.service}'"
BASE_URL = "https://api.telegram.org"
def __init__(
self,
*,
bot_token: str | None,
chat_id: str | None,
http_client: httpx.AsyncClient | None = None,
timeout_s: float = 5.0,
parse_mode: str = "HTML",
) -> None:
self._token = (bot_token or "").strip() or None
self._chat_id = (str(chat_id).strip() if chat_id is not None else "") or None
self._client = http_client
self._timeout = timeout_s
self._parse_mode = parse_mode
@property
def enabled(self) -> bool:
return self._token is not None and self._chat_id is not None
async def _send(self, text: str) -> None:
if not self.enabled:
_log.debug("telegram disabled, dropping message: %s", text[:120])
return
url = f"{self.BASE_URL}/bot{self._token}/sendMessage"
payload: dict[str, Any] = {
"chat_id": self._chat_id,
"text": text,
"parse_mode": self._parse_mode,
"disable_web_page_preview": True,
}
client = self._client
owns = client is None
if client is None:
client = httpx.AsyncClient(timeout=self._timeout)
try:
resp = await client.post(url, json=payload, timeout=self._timeout)
finally:
if owns:
await client.aclose()
if resp.status_code != 200:
raise TelegramError(
f"telegram HTTP {resp.status_code}: {resp.text[:200]}"
)
self._http = http
data = resp.json()
if not isinstance(data, dict) or not data.get("ok", False):
desc = (
data.get("description", "?") if isinstance(data, dict) else str(data)
)
raise TelegramError(f"telegram api error: {desc}")
async def notify(
self,
@@ -44,10 +118,10 @@ class TelegramClient:
priority: str = "normal",
tag: str | None = None,
) -> None:
body: dict[str, Any] = {"message": message, "priority": priority}
if tag is not None:
body["tag"] = tag
await self._http.call("notify", body)
prefix = f"[{priority.upper()}]"
if tag:
prefix = f"{prefix}[{tag}]"
await self._send(f"{prefix} {message}")
async def notify_position_opened(
self,
@@ -59,17 +133,19 @@ class TelegramClient:
greeks: dict[str, Decimal | float] | None = None,
expected_pnl_usd: Decimal | float | None = None,
) -> None:
body: dict[str, Any] = {
"instrument": instrument,
"side": side,
"size": float(size),
"strategy": strategy,
}
if greeks is not None:
body["greeks"] = {k: _to_float(v) for k, v in greeks.items()}
lines = [
"<b>POSITION OPENED</b>",
f"instrument: <code>{instrument}</code>",
f"side: {side} | size: {size} | strategy: {strategy}",
]
if greeks:
joined = ", ".join(
f"{k}={_to_float(v):+.4f}" for k, v in greeks.items()
)
lines.append(f"greeks: {joined}")
if expected_pnl_usd is not None:
body["expected_pnl"] = _to_float(expected_pnl_usd)
await self._http.call("notify_position_opened", body)
lines.append(f"expected pnl: ${_to_float(expected_pnl_usd):+.2f}")
await self._send("\n".join(lines))
async def notify_position_closed(
self,
@@ -78,13 +154,12 @@ class TelegramClient:
realized_pnl_usd: Decimal | float,
reason: str,
) -> None:
await self._http.call(
"notify_position_closed",
{
"instrument": instrument,
"realized_pnl": _to_float(realized_pnl_usd),
"reason": reason,
},
pnl = _to_float(realized_pnl_usd)
await self._send(
"<b>POSITION CLOSED</b>\n"
f"instrument: <code>{instrument}</code>\n"
f"realized pnl: ${pnl:+.2f}\n"
f"reason: {reason}"
)
async def notify_alert(
@@ -94,9 +169,10 @@ class TelegramClient:
message: str,
priority: str = "high",
) -> None:
await self._http.call(
"notify_alert",
{"source": source, "message": message, "priority": priority},
await self._send(
f"<b>ALERT [{priority.upper()}]</b>\n"
f"source: {source}\n"
f"{message}"
)
async def notify_system_error(
@@ -106,7 +182,8 @@ class TelegramClient:
component: str | None = None,
priority: str = "critical",
) -> None:
body: dict[str, Any] = {"message": message, "priority": priority}
if component is not None:
body["component"] = component
await self._http.call("notify_system_error", body)
text = f"<b>SYSTEM ERROR [{priority.upper()}]</b>\n"
if component:
text += f"component: {component}\n"
text += message
await self._send(text)
+4 -4
View File
@@ -31,13 +31,15 @@ __all__ = [
# Service identifier → (default Docker DNS host, default port, env var name)
#
# Telegram and Portfolio used to be shared MCP services; both are now
# in-process per bot (Telegram → public Bot API, Portfolio → aggregator
# over Deribit + Hyperliquid + Macro). They are no longer listed here.
MCP_SERVICES: dict[str, tuple[str, int, str]] = {
"deribit": ("mcp-deribit", 9011, "CERBERO_BITE_MCP_DERIBIT_URL"),
"hyperliquid": ("mcp-hyperliquid", 9012, "CERBERO_BITE_MCP_HYPERLIQUID_URL"),
"macro": ("mcp-macro", 9013, "CERBERO_BITE_MCP_MACRO_URL"),
"sentiment": ("mcp-sentiment", 9014, "CERBERO_BITE_MCP_SENTIMENT_URL"),
"telegram": ("mcp-telegram", 9017, "CERBERO_BITE_MCP_TELEGRAM_URL"),
"portfolio": ("mcp-portfolio", 9018, "CERBERO_BITE_MCP_PORTFOLIO_URL"),
}
@@ -58,8 +60,6 @@ class McpEndpoints:
hyperliquid: str
macro: str
sentiment: str
telegram: str
portfolio: str
def for_service(self, name: str) -> str:
try:
+4 -1
View File
@@ -71,8 +71,11 @@ class AlertManager:
return
if severity == Severity.MEDIUM:
# The TelegramClient already prefixes [PRIORITY][tag] in the
# rendered text, so we pass the raw message and let the
# client compose the final form.
await self._telegram.notify(
f"[{source}] {message}", priority="high", tag=source
message, priority="high", tag=source
)
return
+21 -7
View File
@@ -22,7 +22,7 @@ from cerbero_bite.clients.hyperliquid import HyperliquidClient
from cerbero_bite.clients.macro import MacroClient
from cerbero_bite.clients.portfolio import PortfolioClient
from cerbero_bite.clients.sentiment import SentimentClient
from cerbero_bite.clients.telegram import TelegramClient
from cerbero_bite.clients.telegram import TelegramClient, load_telegram_credentials
from cerbero_bite.config.mcp_endpoints import McpEndpoints
from cerbero_bite.config.schema import StrategyConfig
from cerbero_bite.runtime.alert_manager import AlertManager
@@ -145,11 +145,25 @@ def build_runtime(
client=http_client,
)
telegram = TelegramClient(_client("telegram"))
bot_token, chat_id = load_telegram_credentials()
telegram = TelegramClient(
bot_token=bot_token,
chat_id=chat_id,
http_client=http_client,
timeout_s=timeout_s,
)
alert_manager = AlertManager(
telegram=telegram, audit_log=audit_log, kill_switch=kill_switch
)
deribit = DeribitClient(_client("deribit"))
macro = MacroClient(_client("macro"))
sentiment = SentimentClient(_client("sentiment"))
hyperliquid = HyperliquidClient(_client("hyperliquid"))
portfolio = PortfolioClient(
deribit=deribit, hyperliquid=hyperliquid, macro=macro
)
return RuntimeContext(
cfg=cfg,
db_path=db_path,
@@ -158,11 +172,11 @@ def build_runtime(
audit_log=audit_log,
kill_switch=kill_switch,
alert_manager=alert_manager,
deribit=DeribitClient(_client("deribit")),
macro=MacroClient(_client("macro")),
sentiment=SentimentClient(_client("sentiment")),
hyperliquid=HyperliquidClient(_client("hyperliquid")),
portfolio=PortfolioClient(_client("portfolio")),
deribit=deribit,
macro=macro,
sentiment=sentiment,
hyperliquid=hyperliquid,
portfolio=portfolio,
telegram=telegram,
http_client=http_client,
clock=clk,
-1
View File
@@ -66,7 +66,6 @@ class HealthCheck:
_probe("macro", self._ctx.macro.get_calendar(days=1)),
_probe("sentiment", self._probe_sentiment()),
_probe("hyperliquid", self._ctx.hyperliquid.funding_rate_annualized("ETH")),
_probe("portfolio", self._ctx.portfolio.total_equity_eur()),
)
# SQLite health: lightweight transaction.