cfg.initial_capital * len(assets) = $16 * 7 = $112, но реальный депозит $114. Добавлен capital.total в конфиг. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
295 lines
9.8 KiB
Python
295 lines
9.8 KiB
Python
"""FastAPI web dashboard with Jinja2 + HTMX."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.responses import HTMLResponse
|
|
from fastapi.staticfiles import StaticFiles
|
|
from fastapi.templating import Jinja2Templates
|
|
|
|
from ..config import Config
|
|
from fastapi.responses import StreamingResponse
|
|
|
|
from ..state import (
|
|
get_db, init_db, get_all_assets, get_open_position,
|
|
get_trade_history, get_equity_history, get_signal_log,
|
|
close_position, get_asset, update_asset,
|
|
)
|
|
|
|
TEMPLATES_DIR = Path(__file__).parent / "templates"
|
|
STATIC_DIR = Path(__file__).parent / "static"
|
|
|
|
|
|
def create_app(cfg: Config) -> FastAPI:
|
|
app = FastAPI(title="RemizovTrader", version="0.1.0")
|
|
templates = Jinja2Templates(directory=str(TEMPLATES_DIR))
|
|
|
|
if STATIC_DIR.exists():
|
|
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
|
|
|
|
@app.get("/", response_class=HTMLResponse)
|
|
async def dashboard(request: Request):
|
|
conn = get_db()
|
|
init_db(conn)
|
|
|
|
assets = get_all_assets(conn)
|
|
positions = {}
|
|
for a in assets:
|
|
pos = get_open_position(conn, a["ticker"])
|
|
if pos:
|
|
positions[a["ticker"]] = dict(pos)
|
|
|
|
total_equity = sum(a["equity"] for a in assets)
|
|
total_initial = cfg.total_capital if cfg.total_capital > 0 else cfg.initial_capital * len(cfg.assets)
|
|
total_pnl = total_equity - total_initial
|
|
total_ret = (total_equity / total_initial - 1) * 100 if total_initial > 0 else 0
|
|
|
|
equity_data = get_equity_history(conn)
|
|
recent_trades = get_trade_history(conn, limit=10)
|
|
|
|
conn.close()
|
|
|
|
return templates.TemplateResponse("dashboard.html", {
|
|
"request": request,
|
|
"cfg": cfg,
|
|
"assets": assets,
|
|
"positions": positions,
|
|
"total_equity": total_equity,
|
|
"total_pnl": total_pnl,
|
|
"total_ret": total_ret,
|
|
"equity_data": equity_data,
|
|
"recent_trades": recent_trades,
|
|
})
|
|
|
|
@app.get("/positions", response_class=HTMLResponse)
|
|
async def positions_page(request: Request):
|
|
conn = get_db()
|
|
init_db(conn)
|
|
|
|
assets = get_all_assets(conn)
|
|
positions = []
|
|
for a in assets:
|
|
pos = get_open_position(conn, a["ticker"])
|
|
if pos:
|
|
positions.append({**dict(pos), "equity": a["equity"]})
|
|
|
|
conn.close()
|
|
|
|
return templates.TemplateResponse("positions.html", {
|
|
"request": request,
|
|
"cfg": cfg,
|
|
"positions": positions,
|
|
})
|
|
|
|
@app.get("/history", response_class=HTMLResponse)
|
|
async def history_page(request: Request):
|
|
conn = get_db()
|
|
init_db(conn)
|
|
trades = get_trade_history(conn, limit=200)
|
|
conn.close()
|
|
|
|
return templates.TemplateResponse("history.html", {
|
|
"request": request,
|
|
"cfg": cfg,
|
|
"trades": trades,
|
|
})
|
|
|
|
@app.get("/signals", response_class=HTMLResponse)
|
|
async def signals_page(request: Request):
|
|
conn = get_db()
|
|
init_db(conn)
|
|
signals = get_signal_log(conn, limit=200)
|
|
conn.close()
|
|
|
|
return templates.TemplateResponse("signals.html", {
|
|
"request": request,
|
|
"cfg": cfg,
|
|
"signals": signals,
|
|
})
|
|
|
|
@app.get("/settings", response_class=HTMLResponse)
|
|
async def settings_page(request: Request):
|
|
return templates.TemplateResponse("settings.html", {
|
|
"request": request,
|
|
"cfg": cfg,
|
|
})
|
|
|
|
# HTMX partial endpoints
|
|
@app.get("/api/equity-chart", response_class=HTMLResponse)
|
|
async def equity_chart_data(request: Request):
|
|
conn = get_db()
|
|
init_db(conn)
|
|
data = get_equity_history(conn)
|
|
conn.close()
|
|
|
|
return templates.TemplateResponse("partials/equity_chart.html", {
|
|
"request": request,
|
|
"equity_data": data,
|
|
})
|
|
|
|
@app.get("/api/positions-table", response_class=HTMLResponse)
|
|
async def positions_table(request: Request):
|
|
conn = get_db()
|
|
init_db(conn)
|
|
|
|
assets = get_all_assets(conn)
|
|
positions = []
|
|
for a in assets:
|
|
pos = get_open_position(conn, a["ticker"])
|
|
if pos:
|
|
positions.append({**dict(pos), "equity": a["equity"]})
|
|
|
|
conn.close()
|
|
|
|
return templates.TemplateResponse("partials/positions_table.html", {
|
|
"request": request,
|
|
"positions": positions,
|
|
})
|
|
|
|
@app.post("/api/run-cycle", response_class=HTMLResponse)
|
|
async def run_cycle_api(request: Request):
|
|
from ..core.executor import run_cycle
|
|
|
|
conn = get_db()
|
|
init_db(conn)
|
|
logs = run_cycle(conn, cfg)
|
|
conn.close()
|
|
|
|
return templates.TemplateResponse("partials/cycle_result.html", {
|
|
"request": request,
|
|
"logs": logs,
|
|
})
|
|
|
|
@app.post("/api/close-position/{pos_id}", response_class=HTMLResponse)
|
|
async def close_position_api(pos_id: int, request: Request):
|
|
from ..core import risk
|
|
|
|
conn = get_db()
|
|
init_db(conn)
|
|
|
|
row = conn.execute(
|
|
"SELECT * FROM positions WHERE id=? AND status='open'", (pos_id,),
|
|
).fetchone()
|
|
if not row:
|
|
conn.close()
|
|
return HTMLResponse("<p>Position not found or already closed.</p>")
|
|
|
|
pos = dict(row)
|
|
from ..core.signals import fetch_prices
|
|
# Find per-asset timeframe
|
|
_tf = cfg.timeframe
|
|
for a in cfg.assets:
|
|
if a.ticker == pos["ticker"]:
|
|
_tf = a.timeframe or cfg.timeframe
|
|
break
|
|
prices, dates = fetch_prices(pos["ticker"], _tf,
|
|
"max" if _tf == "1d" else "730d")
|
|
last_price = float(prices[-1]) if prices is not None else pos["entry_price"]
|
|
last_date = str(dates[-1]) if dates is not None else ""
|
|
|
|
pnl_net, pnl_pct = risk.calculate_pnl(
|
|
pos["entry_price"], last_price, pos["direction"],
|
|
pos["pos_size"], pos["pos_value"],
|
|
)
|
|
close_position(conn, pos_id,
|
|
exit_price=last_price, exit_date=last_date,
|
|
exit_reason="manual", pnl_net=pnl_net, pnl_pct=pnl_pct)
|
|
|
|
asset = get_asset(conn, pos["ticker"])
|
|
if asset:
|
|
new_equity = asset["equity"] + pnl_net
|
|
new_peak = max(asset["peak_equity"], new_equity)
|
|
win = pnl_net > 0
|
|
update_asset(conn, pos["ticker"],
|
|
equity=new_equity, peak_equity=new_peak,
|
|
trades_count=asset["trades_count"] + 1,
|
|
wins=asset["wins"] + (1 if win else 0),
|
|
losses=asset["losses"] + (0 if win else 1),
|
|
total_pnl=asset["total_pnl"] + pnl_net)
|
|
|
|
conn.close()
|
|
dir_str = "LONG" if pos["direction"] == 1 else "SHORT"
|
|
result = "WIN" if pnl_net > 0 else "LOSS"
|
|
return HTMLResponse(
|
|
f"<p>Closed {dir_str} {pos['ticker']} @ ${last_price:,.2f} "
|
|
f"PnL ${pnl_net:+,.2f} [{result}]</p>"
|
|
)
|
|
|
|
@app.get("/api/export-csv")
|
|
async def export_csv():
|
|
import csv
|
|
import io
|
|
|
|
conn = get_db()
|
|
init_db(conn)
|
|
trades = get_trade_history(conn, limit=10000)
|
|
conn.close()
|
|
|
|
output = io.StringIO()
|
|
writer = csv.writer(output)
|
|
writer.writerow([
|
|
"ticker", "direction", "entry_date", "entry_price",
|
|
"exit_date", "exit_price", "exit_reason",
|
|
"pnl_net", "pnl_pct", "pos_size", "pos_value",
|
|
"correlation", "k_used",
|
|
])
|
|
for t in trades:
|
|
writer.writerow([
|
|
t["ticker"],
|
|
"LONG" if t["direction"] == 1 else "SHORT",
|
|
t["entry_date"], t["entry_price"],
|
|
t.get("exit_date", ""), t.get("exit_price", ""),
|
|
t.get("exit_reason", ""),
|
|
t.get("pnl_net", ""), t.get("pnl_pct", ""),
|
|
t["pos_size"], t["pos_value"],
|
|
t.get("correlation", ""), t.get("k_used", ""),
|
|
])
|
|
|
|
output.seek(0)
|
|
return StreamingResponse(
|
|
iter([output.getvalue()]),
|
|
media_type="text/csv",
|
|
headers={"Content-Disposition": "attachment; filename=trades.csv"},
|
|
)
|
|
|
|
@app.get("/backtest-signals", response_class=HTMLResponse)
|
|
async def backtest_signals_page(request: Request, file: str = ""):
|
|
import json as _json
|
|
|
|
signals_dir = Path(__file__).parent.parent.parent.parent / "data" / "backtest_signals"
|
|
files = []
|
|
if signals_dir.exists():
|
|
for p in sorted(signals_dir.glob("*.json"), reverse=True):
|
|
try:
|
|
meta = _json.loads(p.read_text())
|
|
files.append({
|
|
"name": p.name,
|
|
"ticker": meta.get("ticker", "?"),
|
|
"date": p.name.split("_", 1)[1].replace(".json", "") if "_" in p.name else "",
|
|
"sharpe": meta.get("sharpe", 0),
|
|
"total_signals": meta.get("total_signals", 0),
|
|
})
|
|
except Exception:
|
|
pass
|
|
|
|
report = None
|
|
signals_json = "[]"
|
|
if file:
|
|
fp = signals_dir / file
|
|
if fp.exists():
|
|
report = _json.loads(fp.read_text())
|
|
signals_json = _json.dumps(report.get("signals", []))
|
|
|
|
return templates.TemplateResponse("backtest_signals.html", {
|
|
"request": request,
|
|
"cfg": cfg,
|
|
"files": files,
|
|
"selected": file,
|
|
"report": report,
|
|
"signals_json": signals_json,
|
|
})
|
|
|
|
return app
|