"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
"""Scaffold, validate, and install user-owned local read-only connectors."""
from __future__ import annotations
import json
import re
import shutil
from pathlib import Path
from src.trading.local_plugins import (
MANIFEST_FILENAME,
LocalConnectorPlugin,
parse_manifest,
plugin_root,
)
_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
_ADAPTER_TEMPLATE = '''"""Read-only local connector generated by Vibe-Trading.
Implement these functions from the broker's official read API. Never add order,
transfer, withdrawal, or credential logging code to this adapter.
"""
from __future__ import annotations
from typing import Any, Mapping
def check_status(*, credentials: Mapping[str, str], config: Mapping[str, Any]) -> dict[str, Any]:
missing = [name for name in ("api_key", "api_secret") if not credentials.get(name)]
return {
"status": "ok" if not missing else "error",
"configured": not missing,
"readonly": True,
"missing_fields": missing,
}
def get_account_snapshot(*, credentials: Mapping[str, str], config: Mapping[str, Any]) -> dict[str, Any]:
raise NotImplementedError("Call the broker account endpoint and return a normalized account envelope")
def get_positions(*, credentials: Mapping[str, str], config: Mapping[str, Any]) -> dict[str, Any]:
raise NotImplementedError("Call the broker positions endpoint and return {'positions': [...]}")
'''
def scaffold_connector(connector_id: str, destination: Path) -> Path:
"""Create a read-only local connector starter for a developer to fill in.
Args:
connector_id: Lowercase connector id used for the directory name, the
generated profile id, and the manifest connector field.
destination: Parent directory the template directory is created in.
Returns:
The created template directory.
Raises:
ValueError: If the connector id is not lowercase letters, numbers and
dashes, or the destination directory already exists.
"""
clean = str(connector_id or "").strip().lower()
if not _ID_RE.fullmatch(clean):
raise ValueError("connector id must use lowercase letters, numbers, and dashes")
target = destination.expanduser().resolve() / clean
if target.exists():
raise ValueError(f"destination already exists: {target}")
target.mkdir(parents=True)
manifest = {
"schema_version": 1,
"profile": {
"id": f"{clean}-live-readonly",
"connector": clean,
"label": f"{clean.title()} Live · Local Read-Only",
"environment": "live",
"readonly": True,
"capabilities": ["account.read", "positions.read"],
"notes": "User-installed local connector. Credentials remain in the OS credential store.",
},
"entrypoint": "adapter.py",
"auth": {
"type": "api_key",
"fields": [
{
"name": "api_key",
"label": "API Key",
"secret": True,
"required": True,
},
{
"name": "api_secret",
"label": "API Secret",
"secret": True,
"required": True,
},
],
},
}
(target / MANIFEST_FILENAME).write_text(
json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
(target / "adapter.py").write_text(_ADAPTER_TEMPLATE, encoding="utf-8")
(target / "README.md").write_text(
f"# {clean} local connector\n\n"
"This directory is local-only. Implement `adapter.py` from the broker's official "
"read-only API docs, "
"then run `vibe-trading connector validate .` and `vibe-trading connector install .`.\n",
encoding="utf-8",
)
return target
def validate_connector(directory: Path) -> LocalConnectorPlugin:
"""Validate a local connector directory without importing its Python code.
Args:
directory: Directory holding a ``connector.json`` manifest.
Returns:
The validated plugin described by the manifest.
Raises:
ValueError: If the manifest is missing, malformed, or declares
anything beyond read-only capabilities.
"""
return parse_manifest(directory.expanduser().resolve() / MANIFEST_FILENAME)
def install_connector(directory: Path) -> Path:
"""Install a validated local connector under the user's runtime directory.
Args:
directory: Directory holding the connector to install.
Returns:
The installed directory under the operator's plugin root.
Raises:
ValueError: If the manifest fails validation, or a connector with the
same id is already installed.
"""
plugin = validate_connector(directory)
root = plugin_root()
root.mkdir(parents=True, exist_ok=True)
target = root / plugin.profile.connector
if target.exists():
raise ValueError(f"connector is already installed: {target}")
shutil.copytree(plugin.directory, target)
return target