| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394 |
- from __future__ import annotations
- from contextlib import asynccontextmanager
- import asyncio
- from fastapi import FastAPI, Form, HTTPException
- from fastapi.responses import HTMLResponse, RedirectResponse
- from fastmcp import FastMCP
- from .models import AccountView
- from . import repo
- from .services_bitstamp import fetch_account_info as fetch_remote_account_info, fetch_account_fees as fetch_remote_account_fees
- from .bitstamp_metadata import METADATA_REFRESH_SECONDS, refresh_metadata, list_markets as bitstamp_list_markets, list_currencies as bitstamp_list_currencies
- from .bitstamp_fx import FX_REFRESH_SECONDS, refresh_eur_usd
- from .bitstamp_private_ws import private_ws_main
- from .services_orders import place_order as service_place_order, query_order as service_query_order, cancel_order as service_cancel_order, get_open_orders as service_get_open_orders, cancel_all_orders as service_cancel_all_orders
- from .storage import init_db
- mcp = FastMCP("exec-mcp")
- async def _metadata_refresh_loop() -> None:
- while True:
- try:
- refresh_metadata()
- except Exception:
- pass
- await asyncio.sleep(METADATA_REFRESH_SECONDS)
- async def _fx_refresh_loop() -> None:
- while True:
- try:
- refresh_eur_usd()
- except Exception:
- pass
- await asyncio.sleep(FX_REFRESH_SECONDS)
- @asynccontextmanager
- async def lifespan(_: FastAPI):
- init_db()
- try:
- refresh_metadata()
- except Exception:
- pass
- stop_event = asyncio.Event()
- metadata_task = asyncio.create_task(_metadata_refresh_loop())
- fx_task = asyncio.create_task(_fx_refresh_loop())
- private_ws_task = asyncio.create_task(private_ws_main(stop_event))
- try:
- yield
- finally:
- stop_event.set()
- metadata_task.cancel()
- fx_task.cancel()
- private_ws_task.cancel()
- app = FastAPI(title="exec-mcp", lifespan=lifespan)
- app.mount("/mcp", mcp.http_app(path="/sse", transport="sse"))
- SUPPORTED_VENUES = {"bitstamp"}
- REPORT_ORDER_STATUSES = {"all", "open", "cancelled", "finished"}
- def _normalize_report_status(status: str) -> str:
- value = str(status or "").strip().lower()
- if value not in REPORT_ORDER_STATUSES:
- raise HTTPException(status_code=400, detail="status must be one of all, open, cancelled, finished")
- return value
- def _normalize_report_limit(limit: int) -> int:
- try:
- value = int(limit)
- except Exception as exc:
- raise HTTPException(status_code=400, detail="limit must be an integer") from exc
- if value < 1:
- raise HTTPException(status_code=400, detail="limit must be at least 1")
- if value > 500:
- raise HTTPException(status_code=400, detail="limit must be at most 500")
- return value
- @app.get("/", response_class=HTMLResponse)
- def http_root() -> str:
- return """
- <html><body style="font-family: system-ui, sans-serif; max-width: 900px; margin: 32px auto; padding: 0 16px;">
- <header style="margin-bottom: 24px;">
- <h1>exec-mcp</h1>
- </header>
- <main>
- <p>Execution layer for Trader27, with a dashboard for account management.</p>
- <ul>
- <li><a href="/dashboard">Dashboard</a></li>
- <li><a href="/health">/health</a></li>
- </ul>
- </main>
- <footer style="margin-top: 32px; padding-top: 12px; border-top: 1px solid #e5e7eb; color: #6b7280;">
- exec-mcp
- </footer>
- </body></html>
- """
- @app.get("/health")
- def http_health() -> dict:
- return {"ok": True, "server": "exec-mcp"}
- @app.get("/dashboard", response_class=HTMLResponse)
- def http_dashboard() -> str:
- rows = list_accounts(enabled_only=False)
- options = "".join(f'<option value="{v}">{v}</option>' for v in sorted(SUPPORTED_VENUES))
- table_rows = "".join(
- f"""
- <tr>
- <td>{row['display_name'] or ''}</td>
- <td>{row['venue'] or ''}</td>
- <td>{row['venue_account_ref'] or ''}</td>
- <td>{row['description'] or ''}</td>
- <td>{'yes' if row['enabled'] else 'no'}</td>
- <td class="actions">
- <form method="get" action="/dashboard/accounts/{row['id']}/edit">
- <button type="submit">Edit</button>
- </form>
- <form method="post" action="/dashboard/accounts/{row['id']}/delete">
- <button type="submit" class="danger">Delete</button>
- </form>
- </td>
- </tr>
- """
- for row in rows
- )
- return f"""
- <html>
- <head>
- <style>
- body {{ font-family: system-ui, sans-serif; max-width: 1100px; margin: 32px auto; padding: 0 16px; color: #1f2937; }}
- header, footer {{ padding: 12px 0; }}
- header {{ border-bottom: 1px solid #e5e7eb; margin-bottom: 20px; }}
- footer {{ border-top: 1px solid #e5e7eb; margin-top: 32px; color: #6b7280; }}
- .panel {{ background: #f8fafc; border: 1px solid #e5e7eb; border-radius: 12px; padding: 16px; margin-bottom: 20px; }}
- summary {{ list-style: none; }}
- summary::-webkit-details-marker {{ display: none; }}
- form {{ display: grid; gap: 10px; max-width: 520px; }}
- input, select, button {{ padding: 10px 12px; border-radius: 8px; border: 1px solid #cbd5e1; }}
- button {{ background: #111827; color: white; cursor: pointer; }}
- button.danger {{ background: #991b1b; }}
- table {{ width: 100%; border-collapse: collapse; margin-top: 12px; }}
- th, td {{ border-bottom: 1px solid #e5e7eb; padding: 10px 8px; text-align: left; vertical-align: top; }}
- .actions {{ display: flex; gap: 8px; align-items: center; }}
- .actions form {{ display: inline; }}
- </style>
- </head>
- <body>
- <header>
- <h1>exec-mcp dashboard</h1>
- </header>
- <details class="panel">
- <summary style="cursor:pointer; font-size: 1.1rem; font-weight: 600;">Create account</summary>
- <form method="post" action="/dashboard/accounts/create" style="margin-top: 12px;">
- <input name="display_name" placeholder="name" />
- <select name="venue">{options}</select>
- <input name="venue_account_ref" placeholder="exchange account ref" />
- <input name="api_key" placeholder="api key" required />
- <input name="api_secret" placeholder="api secret" required />
- <input name="description" placeholder="description" />
- <label><input type="checkbox" name="enabled" checked /> enabled</label>
- <button type="submit">Create</button>
- </form>
- </details>
- <div class="panel">
- <h2>Accounts</h2>
- <table>
- <tr>
- <th>name</th><th>venue</th><th>exchange account ref</th><th>description</th><th>enabled</th><th>actions</th>
- </tr>
- {table_rows}
- </table>
- </div>
- <footer>
- exec-mcp
- </footer>
- </body>
- </html>
- """
- @app.post("/dashboard/accounts/create")
- def http_dashboard_create_account(
- display_name: str = Form(""),
- venue: str = Form(...),
- venue_account_ref: str = Form(""),
- api_key: str = Form(...),
- api_secret: str = Form(...),
- description: str | None = Form(None),
- enabled: bool = Form(False),
- ) -> RedirectResponse:
- repo.create_account(
- display_name=display_name,
- venue=venue,
- venue_account_ref=venue_account_ref,
- api_key=api_key,
- api_secret=api_secret,
- description=description,
- enabled=enabled,
- )
- return RedirectResponse(url="/dashboard", status_code=303)
- @app.get("/dashboard/accounts/{account_id}/edit", response_class=HTMLResponse)
- def http_dashboard_edit_account(account_id: str) -> str:
- row = repo.get_account(account_id)
- checked = "checked" if row["enabled"] else ""
- return f"""
- <html>
- <body style="font-family: system-ui, sans-serif; max-width: 700px; margin: 32px auto; padding: 0 16px;">
- <header style="margin-bottom: 24px; border-bottom: 1px solid #e5e7eb; padding-bottom: 12px;"><h1>Edit account</h1></header>
- <p><a href="/dashboard">Back to dashboard</a></p>
- <form method="post" action="/dashboard/accounts/{row['id']}/update" style="display:grid; gap:10px; max-width: 520px;">
- <input name="display_name" value="{row['display_name'] or ''}" placeholder="name" />
- <input value="{row['venue'] or ''}" placeholder="venue" readonly />
- <input value="{row['venue_account_ref'] or ''}" placeholder="exchange account ref" readonly />
- <input name="description" value="{row['description'] or ''}" placeholder="description" />
- <label><input type="checkbox" name="enabled" {checked} /> enabled</label>
- <button type="submit">Save</button>
- </form>
- <footer style="margin-top: 32px; padding-top: 12px; border-top: 1px solid #e5e7eb; color: #6b7280;">exec-mcp</footer>
- </body>
- </html>
- """
- @app.post("/dashboard/accounts/{account_id}/update")
- def http_dashboard_update_account(
- account_id: str,
- display_name: str = Form(""),
- description: str = Form(""),
- enabled: bool = Form(False),
- ) -> RedirectResponse:
- repo.update_account(account_id=account_id, display_name=display_name, description=description or None, enabled=enabled)
- return RedirectResponse(url="/dashboard", status_code=303)
- @app.post("/dashboard/accounts/{account_id}/delete")
- def http_dashboard_delete_account(account_id: str) -> RedirectResponse:
- repo.delete_account(account_id=account_id)
- return RedirectResponse(url="/dashboard", status_code=303)
- @mcp.tool()
- def list_accounts(enabled_only: bool = True, venue: str | None = None) -> list[dict]:
- """list_accounts(enabled_only=True, venue=None)
- Return account metadata only, never secrets. If `venue` is set, filter to
- that exchange. `enabled_only` defaults to true.
- """
- return repo.list_accounts(venue=venue, enabled_only=enabled_only)
- @mcp.tool()
- def list_markets() -> list[dict]:
- """list_markets()
- Return cached Bitstamp market metadata from the local SQLite cache.
- """
- return bitstamp_list_markets()
- @mcp.tool()
- def list_currencies() -> list[dict]:
- """list_currencies()
- Return cached Bitstamp currency metadata from the local SQLite cache.
- """
- return bitstamp_list_currencies()
- @mcp.tool()
- def get_account_info(account_id: str) -> dict:
- """get_account_info(account_id)
- Return account metadata plus venue-specific live account details when
- available.
- """
- account = repo.get_account(account_id)
- if account["venue"] == "bitstamp":
- return fetch_remote_account_info(account_id)
- raise HTTPException(status_code=400, detail="unsupported venue")
- @mcp.tool()
- def get_account_fees(account_id: str, market_symbol: str | None = None) -> dict:
- """get_account_fees(account_id, market_symbol=None)
- Return Bitstamp fee information for one account, optionally scoped to a
- market symbol.
- """
- account = repo.get_account(account_id)
- if account["venue"] == "bitstamp":
- return fetch_remote_account_fees(account_id, market_symbol)
- raise HTTPException(status_code=400, detail="unsupported venue")
- @mcp.tool()
- def place_order(account_id: str, market: str, side: str, order_type: str, amount, price=None, expire_time: int | None = None, client_id: str | None = None, client_order_id: str | None = None) -> dict:
- """place_order(account_id, market, side, order_type, amount, price=None, expire_time=None, client_id=None, client_order_id=None)
- Place a Bitstamp order. `market` is a Bitstamp symbol like `xrpusd`,
- `amount` is base units, and `expire_time` is relative seconds from now.
- `client_id` is optional and must be a string when provided.
- """
- return service_place_order(account_id=account_id, market=market, side=side, order_type=order_type, amount=amount, price=price, expire_time=expire_time, client_id=client_id, client_order_id=client_order_id)
- @mcp.tool()
- def query_order(account_id: str, order_id, client_order_id: str | None = None, omit_transactions: bool | None = None) -> dict:
- """query_order(account_id, order_id, client_order_id=None, omit_transactions=None)
- Query a Bitstamp order by exchange order id. `client_order_id` and
- `omit_transactions` are optional Bitstamp query parameters.
- """
- return service_query_order(account_id=account_id, order_id=order_id, client_order_id=client_order_id, omit_transactions=omit_transactions)
- @mcp.tool()
- def cancel_order(account_id: str, order_id) -> dict:
- """cancel_order(account_id, order_id)
- Cancel one Bitstamp order by exchange order id.
- """
- return service_cancel_order(account_id=account_id, order_id=order_id)
- @mcp.tool()
- def get_open_orders(account_id: str, client_id: str | None = None) -> dict:
- """get_open_orders(account_id, client_id=None)
- List open orders for one account. If `client_id` is provided, only return
- orders recorded with that client identifier.
- """
- return service_get_open_orders(account_id=account_id, client_id=client_id)
- @mcp.tool()
- def cancel_all_orders(account_id: str, client_id: str | None = None) -> dict:
- """cancel_all_orders(account_id, client_id=None)
- Cancel all open orders for one account. If `client_id` is provided, only
- cancel orders recorded with that client identifier.
- """
- return service_cancel_all_orders(account_id=account_id, client_id=client_id)
- @mcp.tool()
- def report_recent_trades(account_id: str, status: str = "finished", client_id: str | None = None, limit: int = 50) -> dict:
- """report_recent_trades(account_id, status="finished", client_id=None, limit=50)
- Return recent order snapshots for reporting, ordered newest first. Status
- may be `all`, `open`, `cancelled`, or `finished`. `client_id` is optional
- and filters to one reporting stream when provided.
- """
- repo.get_account(account_id)
- status = _normalize_report_status(status)
- limit = _normalize_report_limit(limit)
- orders = repo.list_recent_orders(account_id=account_id, client_id=client_id, status=status, limit=limit)
- return {
- "ok": True,
- "account_id": account_id,
- "client_id": client_id,
- "status": status,
- "limit": limit,
- "count": len(orders),
- "orders": orders,
- }
- @mcp.tool()
- def report_balance_snapshots(account_id: str, limit: int = 50) -> list[dict]:
- """report_balance_snapshots(account_id, limit=50)
- Return stored wallet balance snapshots for the account, ordered newest first.
- """
- repo.get_account(account_id)
- limit = _normalize_report_limit(limit)
- return repo.list_account_balance_snapshots(account_id=account_id, limit=limit)
- def main() -> None:
- init_db()
|