Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(portfolio): explain Binance HTTP 451 read failures

Yang6505b0422411
diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.py
index 267855fd8..2a0cd76e8 100644
--- a/agent/src/portfolio/service.py
+++ b/agent/src/portfolio/service.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import csv
import io
import json
+import re
import socket
import subprocess
import sys
@@ -82,6 +83,50 @@ _AUTH_REQUIRED_MARKERS = (
"connector authorize",
)
+_REDACT_URL_QUERY = re.compile(r"(?i)(https?://[^\s?#]+)\?[^\s#]+")
+_REDACT_SECRET_PARAMETER = re.compile(
+ r"(?i)\b(signature|api[_-]?key|secret)=([^&\s]+)"
+)
+
+
+def _portfolio_error_details(
+ error: BaseException | str,
+ *,
+ broker: str | None = None,
+ default_code: str = "ConnectorReadError",
+) -> tuple[str, str]:
+ """Return a user-safe connector error without signed request parameters."""
+ message = str(error)
+ if (
+ str(broker or "").lower() == "binance"
+ and re.search(r"\b451\b", message)
+ and any(marker in message.lower() for marker in ("restricted location", "eligibility"))
+ ):
+ return (
+ "binance_restricted_location",
+ "Binance denied the read with HTTP 451 because the current network location is restricted. "
+ "Confirm Binance is available for your region and that your account uses its supported API endpoint.",
+ )
+
+ message = _REDACT_URL_QUERY.sub(r"\1?<query redacted>", message)
+ message = _REDACT_SECRET_PARAMETER.sub(r"\1=<redacted>", message)
+ return default_code, message[:300]
+
+
+def _sanitize_snapshot_errors(snapshot: dict[str, Any]) -> dict[str, Any]:
+ """Clean error strings from stored snapshots before returning them to APIs."""
+ for account in snapshot.get("accounts", []):
+ if account.get("status") != "error":
+ continue
+ error_code, error = _portfolio_error_details(
+ account.get("error") or "",
+ broker=account.get("broker"),
+ default_code=str(account.get("error_code") or "ConnectorReadError"),
+ )
+ account["error_code"] = error_code
+ account["error"] = error
+ return snapshot
+
def _authorization_required(payload: dict[str, Any]) -> bool:
"""Return whether a connector failure explicitly asks for OAuth renewal."""
@@ -289,22 +334,30 @@ class PortfolioService:
if self._progress_callback is not None:
self._progress_callback(source.id, "ok", None)
except Exception as exc: # read failures are isolated per connector
+ failed_profile = None
+ failure_broker = None
try:
_, failed_profile = self._connection_profile(source)
+ failure_broker = failed_profile.connector
auth_required = failed_profile.transport == "remote_mcp" and _authorization_required(
{"error": str(exc)}
)
except Exception:
auth_required = False
+ error_code, error = _portfolio_error_details(
+ exc,
+ broker=failure_broker,
+ default_code=type(exc).__name__,
+ )
results[source.id] = {
"status": "error",
- "error_code": type(exc).__name__,
- "error": str(exc)[:300],
+ "error_code": error_code,
+ "error": error,
"failure_kind": "authorization" if auth_required else "transient",
"reconnect_required": auth_required,
}
if self._progress_callback is not None:
- self._progress_callback(source.id, "error", str(exc)[:160])
+ self._progress_callback(source.id, "error", error[:160])
positions: list[dict[str, Any]] = []
accounts: list[dict[str, Any]] = []
@@ -351,10 +404,15 @@ class PortfolioService:
1 for row in broker_positions if row.get("priced")
)
except Exception as exc:
+ error_code, error = _portfolio_error_details(
+ exc,
+ broker=broker,
+ default_code=type(exc).__name__,
+ )
failure = {
"status": "error",
- "error_code": type(exc).__name__,
- "error": str(exc)[:300],
+ "error_code": error_code,
+ "error": error,
"failure_kind": "transient",
"reconnect_required": False,
}
@@ -364,7 +422,7 @@ class PortfolioService:
)
)
if self._progress_callback is not None:
- self._progress_callback(source.id, "error", str(exc)[:160])
+ self._progress_callback(source.id, "error", error[:160])
continue
accounts.append(
@@ -537,7 +595,7 @@ class PortfolioService:
}
for account in snapshot.get("accounts", [])
]
- return snapshot
+ return _sanitize_snapshot_errors(snapshot)
def snapshot_by_id(self, snapshot_id: str) -> dict[str, Any] | None:
"""Return one stored snapshot exactly as persisted, never recomputed.
@@ -555,7 +613,7 @@ class PortfolioService:
return None
enabled = {source.id for source in self.settings_store.load().sources if source.enabled}
observed = {str(account.get("source_id") or account.get("broker")) for account in snapshot.get("accounts", [])}
- return snapshot if observed <= enabled else None
+ return _sanitize_snapshot_errors(snapshot) if observed <= enabled else None
def reconnect_source(self, source_id: str) -> dict[str, Any]:
"""Run a source's interactive OAuth flow on explicit user request.
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index d59c3bc82..f8e169623 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -2203,6 +2203,7 @@
"failed": "تعذّرت قراءته — غير محتسب في الإجمالي",
"lastSuccess": "آخر قراءة ناجحة {{time}}",
"noSuccess": "لا توجد قراءة ناجحة بعد",
+ "binanceRestrictedLocation": "حظرت Binance هذه القراءة (HTTP 451): موقع الشبكة الحالي مقيّد. تحقق من توفر Binance في منطقتك واستخدم واجهة API الرسمية المدعومة.",
"reconnect": "إعادة الاتصال",
"retryRead": "إعادة محاولة القراءة"
},
diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json
index 64e343daf..4986c75be 100644
--- a/frontend/src/i18n/locales/de.json
+++ b/frontend/src/i18n/locales/de.json
@@ -2203,6 +2203,7 @@
"failed": "Konnte nicht gelesen werden — nicht in der Summe enthalten",
"lastSuccess": "Letzter erfolgreicher Abruf {{time}}",
"noSuccess": "Noch kein erfolgreicher Abruf",
+ "binanceRestrictedLocation": "Binance hat diesen Abruf (HTTP 451) blockiert: Der aktuelle Netzwerkstandort ist eingeschränkt. Prüfe, ob Binance in deiner Region verfügbar ist, und verwende den unterstützten API-Endpunkt.",
"reconnect": "Neu verbinden",
"retryRead": "Lesen wiederholen"
},
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 76328abca..d6d522c04 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -2203,6 +2203,7 @@
"failed": "Could not be read — not counted in the total",
"lastSuccess": "Last successful read {{time}}",
"noSuccess": "No successful read yet",
+ "binanceRestrictedLocation": "Binance blocked this read (HTTP 451): the current network location is restricted. Check Binance availability for your region and use its supported API endpoint.",
"reconnect": "Reconnect",
"retryRead": "Retry read"
},
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index d747beeb6..ce6f9f3f3 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -2203,6 +2203,7 @@
"failed": "No se pudo leer: no cuenta en el total",
"lastSuccess": "Última lectura correcta {{time}}",
"noSuccess": "Todavía sin ninguna lectura correcta",
+ "binanceRestrictedLocation": "Binance bloqueó esta lectura (HTTP 451): la ubicación de red actual está restringida. Comprueba la disponibilidad de Binance en tu región y usa su endpoint API compatible.",
"reconnect": "Volver a conectar",
"retryRead": "Reintentar lectura"
},
diff --git a/frontend/src/i18n/locales/fa.json b/frontend/src/i18n/locales/fa.json
index 3228c8f6b..9f760b9d0 100644
--- a/frontend/src/i18n/locales/fa.json
+++ b/frontend/src/i18n/locales/fa.json
@@ -2203,6 +2203,7 @@
"failed": "خوانده نشد — در جمع لحاظ نمی‌شود",
"lastSuccess": "آخرین خواندن موفق {{time}}",
"noSuccess": "هنوز خواندن موفقی نداشته است",
+ "binanceRestrictedLocation": "Binance این خواندن را مسدود کرد (HTTP 451): موقعیت فعلی شبکه محدود است. دسترس‌پذیری Binance در منطقه خود را بررسی کنید و از درگاه API پشتیبانی‌شده استفاده کنید.",
"reconnect": "اتصال دوباره",
"retryRead": "تلاش دوباره برای خواندن"
},
diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json
index 5daf85376..0dfc57dbe 100644
--- a/frontend/src/i18n/locales/id.json
+++ b/frontend/src/i18n/locales/id.json
@@ -2203,6 +2203,7 @@
"failed": "Tidak dapat dibaca — tidak dihitung dalam total",
"lastSuccess": "Terakhir berhasil dibaca {{time}}",
"noSuccess": "Belum pernah berhasil dibaca",
+ "binanceRestrictedLocation": "Binance memblokir pembacaan ini (HTTP 451): lokasi jaringan saat ini dibatasi. Periksa ketersediaan Binance di wilayah Anda dan gunakan endpoint API yang didukung.",
"reconnect": "Hubungkan ulang",
"retryRead": "Coba baca lagi"
},
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index 507f74e13..ef1c6d74d 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -2203,6 +2203,7 @@
"failed": "読み取れませんでした — 合計に含まれていません",
"lastSuccess": "最後に読み取れたのは {{time}}",
"noSuccess": "まだ一度も読み取れていません",
+ "binanceRestrictedLocation": "Binance が読み取りを拒否しました(HTTP 451)。現在のネットワーク所在地は利用制限の対象です。お住まいの地域で Binance が利用可能か確認し、サポート対象の公式 API エンドポイントを使用してください。",
"reconnect": "再接続",
"retryRead": "再読み込み"
},
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 07a29f6dc..3781459aa 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -2203,6 +2203,7 @@
"failed": "읽지 못했습니다 — 합계에 포함되지 않음",
"lastSuccess": "마지막으로 성공한 읽기 {{time}}",
"noSuccess": "아직 성공한 읽기가 없습니다",
+ "binanceRestrictedLocation": "Binance가 이 읽기를 차단했습니다(HTTP 451). 현재 네트워크 위치가 제한되어 있습니다. 해당 지역에서 Binance를 사용할 수 있는지 확인하고 지원되는 공식 API 엔드포인트를 사용하세요.",
"reconnect": "다시 연결",
"retryRead": "다시 읽기"
},
diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.json
index 7589029ec..a01b59cb8 100644
--- a/frontend/src/i18n/locales/pt-BR.json
+++ b/frontend/src/i18n/locales/pt-BR.json
@@ -2203,6 +2203,7 @@
"failed": "Não foi possível ler – não foi contabilizado no total",
"lastSuccess": "Última leitura bem-sucedida {{time}}",
"noSuccess": "Nenhuma leitura bem-sucedida ainda",
+ "binanceRestrictedLocation": "A Binance bloqueou esta leitura (HTTP 451): a localização atual da rede é restrita. Verifique a disponibilidade da Binance na sua região e use o endpoint de API compatível.",
"reconnect": "Reconectar",
"retryRead": "Tente ler novamente"
},
diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.json
index 6236923be..5ee4d9a17 100644
--- a/frontend/src/i18n/locales/tr.json
+++ b/frontend/src/i18n/locales/tr.json
@@ -2169,6 +2169,7 @@
"failed": "Okunamadı; toplama katılmadı",
"lastSuccess": "Son başarılı okuma: {{time}}",
"noSuccess": "Henüz başarılı okuma yok",
+ "binanceRestrictedLocation": "Binance bu okumayı engelledi (HTTP 451): mevcut ağ konumu kısıtlı. Bölgenizde Binance kullanılabilirliğini kontrol edin ve desteklenen API uç noktasını kullanın.",
"reconnect": "Yeniden bağlan",
"retryRead": "Okumayı yeniden dene"
},
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index 60d731055..ca5dc5ace 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -2203,6 +2203,7 @@
"failed": "读取失败 — 未计入合计",
"lastSuccess": "上一次成功读取于 {{time}}",
"noSuccess": "尚未成功读取过",
+ "binanceRestrictedLocation": "Binance 返回 HTTP 451,当前网络出口地区受限,暂时无法读取。请确认所在地区可使用 Binance,并检查账户对应的官方 API 入口。",
"reconnect": "重新连接",
"retryRead": "重试读取"
},
diff --git a/frontend/src/pages/Portfolio.tsx b/frontend/src/pages/Portfolio.tsx
index 0c4b4254d..d5d838233 100644
--- a/frontend/src/pages/Portfolio.tsx
+++ b/frontend/src/pages/Portfolio.tsx
@@ -548,6 +548,9 @@ function AccountCard({ account, active, displayCurrency, fx, onClick, onReconnec
const { t } = useTranslation();
const failed = account.status === "error";
const accountDisplay = displayValue(account.total_usd, account.total_cny, displayCurrency, fx);
+ const accountError = account.error_code === "binance_restricted_location"
+ ? t("portfolio.accounts.binanceRestrictedLocation")
+ : account.error;
return <div role="button" tabIndex={0} onClick={onClick} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") onClick(); }} className={`cursor-pointer rounded-xl border bg-card p-5 transition ${active ? "border-primary ring-1 ring-primary/20" : "hover:border-primary/40"}`}>
<div className="flex items-center justify-between gap-3">
<div><div className="font-medium">{account.label ?? account.broker.toUpperCase()}</div><div className="mt-1 flex flex-wrap items-center gap-2 text-xs"><BrokerBadge broker={account.broker} /><PortfolioCompatibilityBadge compatibility={account.portfolio_compatibility} /></div></div>
@@ -565,7 +568,7 @@ function AccountCard({ account, active, displayCurrency, fx, onClick, onReconnec
<div className="mt-4 flex items-center justify-between border-t pt-3 text-xs"><span className="text-positive">{account.source_kind === "extraetf" ? t("portfolio.imports.source") : t("portfolio.accounts.fresh")}</span><span className="text-muted-foreground">{dateTime(account.import_metadata?.source_mtime ?? account.last_success_at)}</span></div>
</>
)}
- {failed && account.error ? <p className="mt-3 line-clamp-2 text-xs text-muted-foreground" title={account.error}>{account.error}</p> : null}
+ {failed && accountError ? <p className="mt-3 line-clamp-2 text-xs text-muted-foreground" title={accountError}>{accountError}</p> : null}
{failed && onReconnect ? <button onClick={(event) => { event.stopPropagation(); onReconnect(); }} disabled={actionsDisabled} className="mt-3 inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-50">{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}{t("portfolio.accounts.reconnect")}</button> : null}
{failed && onRetry ? <button onClick={(event) => { event.stopPropagation(); onRetry(); }} disabled={actionsDisabled} className="mt-3 inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-50">{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}{t("portfolio.accounts.retryRead")}</button> : null}
</div>;