Risk controls, alerts, API token, more exchanges, presets
CI/CD / backend (pull_request) Successful in 6m18s
CI/CD / frontend (pull_request) Successful in 4m55s
CI/CD / build (pull_request) Skipped
CI/CD / deploy (pull_request) Skipped
CI/CD / cleanup (pull_request) Skipped

- RiskManager halts + flattens on max daily loss / drawdown, caps position
  size and trades per day; adds a manual kill switch (POST /api/bot/kill).
- Telegram and webhook notifications on trades, errors and halts.
- Optional API bearer token on /api, injected server-side by the frontend
  nginx so the browser never sees it.
- Kraken and Coinbase market data (public); Coinbase live broker. Live on an
  unsupported exchange now errors instead of silently falling back to paper.
- Strategy presets backed by the StrategyConfig table (CRUD API + UI).
- Idempotent additive-column migration so existing SQLite databases upgrade in
  place (fixes the new strategy_configs.name column).
This commit is contained in:
matitos committed 2026-09-18 19:26:29 +00:00
1 parent 9c3bee87ac
commit 03dfa369e5
35 files changed
+1409 -45

No files matched your search

+21 -5
View File
@@ -3,14 +3,30 @@ from __future__ import annotations
from app.config import Settings
from app.market.base import MarketData
from app.market.binance import BinanceMarketData
from app.market.coinbase import CoinbaseMarketData
from app.market.fake import FakeMarketData
from app.market.kraken import KrakenMarketData
_FEEDS: dict[str, type[MarketData]] = {
"binance": BinanceMarketData,
"binanceus": BinanceMarketData,
"kraken": KrakenMarketData,
"coinbase": CoinbaseMarketData,
}
def build_market_data(settings: Settings) -> MarketData:
exchange = settings.exchange.lower()
if exchange in {"binance", "binanceus"}:
return BinanceMarketData()
raise ValueError(f"unsupported exchange: {settings.exchange}")
try:
feed_cls = _FEEDS[settings.exchange.lower()]
except KeyError:
raise ValueError(
f"unsupported exchange: {settings.exchange}. available: {sorted(_FEEDS)}"
) from None
return feed_cls()
__all__ = ["FakeMarketData", "MarketData", "build_market_data"]
__all__ = [
"FakeMarketData",
"MarketData",
"build_market_data",
]
+72
View File
@@ -0,0 +1,72 @@
from __future__ import annotations
import httpx
from app.market.base import MarketData
from app.schemas import Candle
BASE_URL = "https://api.exchange.coinbase.com"
# Coinbase granularities are in seconds.
GRANULARITIES: dict[str, int] = {
"1m": 60,
"5m": 300,
"15m": 900,
"1h": 3600,
"6h": 21600,
"1d": 86400,
}
def to_product_id(symbol: str) -> str:
return symbol.replace("/", "-").upper()
class CoinbaseMarketData(MarketData):
"""Public Coinbase Exchange market data over REST (no API key required)."""
def __init__(self, base_url: str = BASE_URL, timeout: float = 10.0) -> None:
self._client = httpx.AsyncClient(
base_url=base_url,
timeout=timeout,
headers={"User-Agent": "crypto_trading/0.1"},
)
@staticmethod
def _granularity(timeframe: str) -> int:
try:
return GRANULARITIES[timeframe]
except KeyError:
raise ValueError(
f"unsupported timeframe '{timeframe}' for Coinbase; "
f"use one of {sorted(GRANULARITIES)}"
) from None
async def fetch_candles(self, symbol: str, timeframe: str, limit: int) -> list[Candle]:
response = await self._client.get(
f"/products/{to_product_id(symbol)}/candles",
params={"granularity": self._granularity(timeframe)},
)
response.raise_for_status()
# Coinbase returns newest-first rows: [time, low, high, open, close, volume].
rows = sorted(response.json(), key=lambda row: row[0])
candles = [
Candle(
ts=int(row[0]) * 1000,
open=float(row[3]),
high=float(row[2]),
low=float(row[1]),
close=float(row[4]),
volume=float(row[5]),
)
for row in rows
]
return candles[-limit:]
async def fetch_price(self, symbol: str) -> float:
response = await self._client.get(f"/products/{to_product_id(symbol)}/ticker")
response.raise_for_status()
return float(response.json()["price"])
async def close(self) -> None:
await self._client.aclose()
+74
View File
@@ -0,0 +1,74 @@
from __future__ import annotations
import httpx
from app.market.base import MarketData
from app.schemas import Candle
BASE_URL = "https://api.kraken.com"
# Kraken intervals are in minutes; map our timeframe strings to them.
INTERVALS: dict[str, int] = {
"1m": 1,
"5m": 5,
"15m": 15,
"30m": 30,
"1h": 60,
"4h": 240,
"1d": 1440,
"1w": 10080,
}
class KrakenMarketData(MarketData):
"""Public Kraken spot market data over REST (no API key required)."""
def __init__(self, base_url: str = BASE_URL, timeout: float = 10.0) -> None:
self._client = httpx.AsyncClient(base_url=base_url, timeout=timeout)
@staticmethod
def _interval(timeframe: str) -> int:
try:
return INTERVALS[timeframe]
except KeyError:
raise ValueError(
f"unsupported timeframe '{timeframe}' for Kraken; use one of {sorted(INTERVALS)}"
) from None
@staticmethod
def _result(payload: dict) -> dict:
errors = payload.get("error") or []
if errors:
raise ValueError(f"kraken error: {errors}")
return payload.get("result", {})
async def fetch_candles(self, symbol: str, timeframe: str, limit: int) -> list[Candle]:
response = await self._client.get(
"/0/public/OHLC",
params={"pair": symbol, "interval": self._interval(timeframe)},
)
response.raise_for_status()
result = self._result(response.json())
rows = next((value for key, value in result.items() if key != "last"), [])
candles = [
Candle(
ts=int(row[0]) * 1000,
open=float(row[1]),
high=float(row[2]),
low=float(row[3]),
close=float(row[4]),
volume=float(row[6]),
)
for row in rows
]
return candles[-limit:]
async def fetch_price(self, symbol: str) -> float:
response = await self._client.get("/0/public/Ticker", params={"pair": symbol})
response.raise_for_status()
result = self._result(response.json())
ticker = next(iter(result.values()))
return float(ticker["c"][0])
async def close(self) -> None:
await self._client.aclose()