feat: live spot trading через Bybit + двойной источник данных
- SpotExecutor (spot.py): buy/sell через ccxt с проверкой баланса, минимумов, dry-run - signals.py: dual-source (ccxt + yfinance) с пагинацией по времени - executor.py: live-хуки (buy/sell на бирже), откат phantom позиций, skip SHORT на спот - config: binance → bybit, binance_symbol → symbol, data_source, LLM config - .gitignore: защита .env с API ключами Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -7,3 +7,4 @@ build/
|
||||
data/models/
|
||||
data/trades.db
|
||||
.DS_Store
|
||||
.env
|
||||
|
||||
+16
-8
@@ -13,31 +13,31 @@ risk:
|
||||
|
||||
assets:
|
||||
- ticker: BTC-USD
|
||||
binance_symbol: BTC/USDT
|
||||
symbol: BTC/USDT
|
||||
K: 2
|
||||
corr_thresh: 0.5
|
||||
trailing_stop: true
|
||||
|
||||
- ticker: ETH-USD
|
||||
binance_symbol: ETH/USDT
|
||||
symbol: ETH/USDT
|
||||
K: 2
|
||||
corr_thresh: 0.5
|
||||
trailing_stop: true
|
||||
|
||||
- ticker: AVAX-USD
|
||||
binance_symbol: AVAX/USDT
|
||||
symbol: AVAX/USDT
|
||||
K: 2
|
||||
corr_thresh: 0.5
|
||||
trailing_stop: true
|
||||
|
||||
- ticker: LINK-USD
|
||||
binance_symbol: LINK/USDT
|
||||
symbol: LINK/USDT
|
||||
K: 2
|
||||
corr_thresh: 0.5
|
||||
trailing_stop: true
|
||||
|
||||
- ticker: SOL-USD
|
||||
binance_symbol: SOL/USDT
|
||||
symbol: SOL/USDT
|
||||
K: 2
|
||||
corr_thresh: 0.5
|
||||
trailing_stop: true
|
||||
@@ -58,9 +58,10 @@ circuit_breaker:
|
||||
dd_reset: 0.10 # 10% DD → resume
|
||||
|
||||
exchange:
|
||||
name: binance
|
||||
api_key: "" # set via REMIZOV_API_KEY env var
|
||||
api_secret: "" # set via REMIZOV_API_SECRET env var
|
||||
name: bybit
|
||||
data_source: exchange # "exchange" (ccxt/Bybit) or "yfinance"
|
||||
api_key: "" # set via REMIZOV_API_KEY env var
|
||||
api_secret: "" # set via REMIZOV_API_SECRET env var
|
||||
testnet: true
|
||||
|
||||
web:
|
||||
@@ -72,6 +73,13 @@ telegram:
|
||||
bot_token: "" # set via REMIZOV_TG_TOKEN env var
|
||||
chat_id: ""
|
||||
|
||||
llm:
|
||||
enabled: false
|
||||
base_url: "https://api.z.ai/api/anthropic"
|
||||
model: "glm-4.5-air"
|
||||
api_key: "" # set via REMIZOV_LLM_TOKEN env var
|
||||
sentiment_threshold: -0.3
|
||||
|
||||
schedule:
|
||||
timeframe: 4h # 1d | 4h
|
||||
check_time: "22:00" # UTC (used for daily, ignored for 4h)
|
||||
|
||||
@@ -15,7 +15,7 @@ DATA_DIR = Path(__file__).parent.parent.parent / "data"
|
||||
@dataclass
|
||||
class AssetConfig:
|
||||
ticker: str
|
||||
binance_symbol: str
|
||||
symbol: str # ccxt format, e.g. "BTC/USDT"
|
||||
K: int = 2
|
||||
corr_thresh: float = 0.5
|
||||
trailing_stop: bool = True
|
||||
@@ -50,7 +50,8 @@ class CircuitBreakerConfig:
|
||||
|
||||
@dataclass
|
||||
class ExchangeConfig:
|
||||
name: str = "binance"
|
||||
name: str = "bybit"
|
||||
data_source: str = "exchange" # "exchange" (ccxt) or "yfinance"
|
||||
api_key: str = ""
|
||||
api_secret: str = ""
|
||||
testnet: bool = True
|
||||
@@ -62,6 +63,15 @@ class WebConfig:
|
||||
port: int = 8080
|
||||
|
||||
|
||||
@dataclass
|
||||
class LLMConfig:
|
||||
enabled: bool = False
|
||||
base_url: str = "https://api.z.ai/api/anthropic"
|
||||
api_key: str = ""
|
||||
model: str = "glm-4.5-air"
|
||||
sentiment_threshold: float = -0.3
|
||||
|
||||
|
||||
@dataclass
|
||||
class TelegramConfig:
|
||||
enabled: bool = False
|
||||
@@ -83,6 +93,7 @@ class Config:
|
||||
exchange: ExchangeConfig = field(default_factory=ExchangeConfig)
|
||||
web: WebConfig = field(default_factory=WebConfig)
|
||||
telegram: TelegramConfig = field(default_factory=TelegramConfig)
|
||||
llm: LLMConfig = field(default_factory=LLMConfig)
|
||||
|
||||
|
||||
def load_config(path: Path | None = None) -> Config:
|
||||
@@ -94,9 +105,12 @@ def load_config(path: Path | None = None) -> Config:
|
||||
with open(path) as f:
|
||||
raw = yaml.safe_load(f) or {}
|
||||
|
||||
assets = [
|
||||
AssetConfig(**a) for a in raw.get("assets", [])
|
||||
]
|
||||
assets_raw = raw.get("assets", [])
|
||||
for a in assets_raw:
|
||||
# Backward compat: binance_symbol → symbol
|
||||
if "binance_symbol" in a and "symbol" not in a:
|
||||
a["symbol"] = a.pop("binance_symbol")
|
||||
assets = [AssetConfig(**a) for a in assets_raw]
|
||||
|
||||
model_raw = raw.get("model", {})
|
||||
risk_raw = raw.get("risk", {})
|
||||
@@ -115,17 +129,22 @@ def load_config(path: Path | None = None) -> Config:
|
||||
telegram = TelegramConfig(**tg_raw)
|
||||
telegram.bot_token = os.environ.get("REMIZOV_TG_TOKEN", telegram.bot_token)
|
||||
|
||||
llm_raw = raw.get("llm", {})
|
||||
llm = LLMConfig(**llm_raw)
|
||||
llm.api_key = os.environ.get("REMIZOV_LLM_TOKEN", llm.api_key)
|
||||
|
||||
return Config(
|
||||
mode=raw.get("mode", "paper"),
|
||||
initial_capital=capital_raw.get("initial", 100.0),
|
||||
currency=capital_raw.get("currency", "USDT"),
|
||||
timeframe=schedule_raw.get("timeframe", "1d"),
|
||||
check_time=schedule_raw.get("check_time", "22:00"),
|
||||
assets=assets or [AssetConfig(ticker="BTC-USD", binance_symbol="BTC/USDT")],
|
||||
assets=assets or [AssetConfig(ticker="BTC-USD", symbol="BTC/USDT")],
|
||||
model=ModelConfig(**model_raw),
|
||||
risk=RiskConfig(**risk_raw),
|
||||
circuit_breaker=CircuitBreakerConfig(**cb_raw),
|
||||
exchange=exchange,
|
||||
web=WebConfig(**web_raw),
|
||||
telegram=telegram,
|
||||
llm=llm,
|
||||
)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""Trade executor — paper mode (SQLite) and live mode (ccxt, future)."""
|
||||
"""Trade executor — paper mode (SQLite) and live mode (Bybit spot via ccxt)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sqlite3
|
||||
from datetime import date
|
||||
|
||||
@@ -15,6 +16,20 @@ from ..state import (
|
||||
from . import model as model_mod
|
||||
from . import risk, signals
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# Singleton spot executor (created once on first live trade)
|
||||
_spot_executor = None
|
||||
|
||||
|
||||
def _get_spot(cfg: Config):
|
||||
"""Get or create SpotExecutor singleton."""
|
||||
global _spot_executor
|
||||
if _spot_executor is None:
|
||||
from .spot import SpotExecutor
|
||||
_spot_executor = SpotExecutor(cfg.exchange)
|
||||
return _spot_executor
|
||||
|
||||
|
||||
def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
"""Run one trading cycle: check stops, generate signals.
|
||||
@@ -24,6 +39,10 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
logs = []
|
||||
today = str(date.today())
|
||||
|
||||
if cfg.mode == "live" and len(cfg.assets) > 1:
|
||||
log.warning(f"Live mode with {len(cfg.assets)} assets — "
|
||||
f"exchange balance is shared, not per-asset")
|
||||
|
||||
for asset_cfg in cfg.assets:
|
||||
ticker = asset_cfg.ticker
|
||||
asset = _get_or_skip(conn, ticker)
|
||||
@@ -34,7 +53,11 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
# Fetch prices
|
||||
interval = cfg.timeframe
|
||||
period = "max" if interval == "1d" else "730d"
|
||||
prices, dates = signals.fetch_prices(ticker, interval, period)
|
||||
source = cfg.exchange.data_source
|
||||
symbol = asset_cfg.symbol if source == "exchange" else ticker
|
||||
prices, dates = signals.fetch_prices(
|
||||
symbol, interval, period, cfg.exchange, source=source,
|
||||
)
|
||||
if prices is None or len(prices) < cfg.model.window_size + cfg.model.shift:
|
||||
logs.append(f"{ticker}: not enough data")
|
||||
continue
|
||||
@@ -208,8 +231,20 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
|
||||
|
||||
dir_str = "LONG" if direction == 1 else "SHORT"
|
||||
win_str = "WIN" if win else "LOSS"
|
||||
return (f"CLOSED {dir_str} ${entry_price:,.2f}→${exit_price:,.2f} "
|
||||
f"({exit_reason}) PnL ${pnl_net:+,.2f} [{win_str}]")
|
||||
msg = (f"CLOSED {dir_str} ${entry_price:,.2f}→${exit_price:,.2f} "
|
||||
f"({exit_reason}) PnL ${pnl_net:+,.2f} [{win_str}]")
|
||||
|
||||
# Live execution: sell on exchange
|
||||
if cfg.mode == "live" and direction == 1:
|
||||
spot = _get_spot(cfg)
|
||||
order = spot.sell(asset_cfg.symbol)
|
||||
if order:
|
||||
msg += " [LIVE SELL OK]"
|
||||
else:
|
||||
msg += " [LIVE SELL FAILED]"
|
||||
log.error(f"{asset_cfg.ticker}: live sell failed on close")
|
||||
|
||||
return msg
|
||||
|
||||
return None
|
||||
|
||||
@@ -260,6 +295,13 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
|
||||
if direction is None:
|
||||
return "indeterminate direction"
|
||||
|
||||
# Live spot mode: skip SHORT signals (can't short on spot)
|
||||
if cfg.mode == "live" and direction == -1:
|
||||
log_signal(conn, ticker=ticker, date=str(dates[-1]),
|
||||
correlation=corr, direction=direction, action="skip_spot_short",
|
||||
details="SHORT not available in live spot mode")
|
||||
return f"SHORT signal — SKIP (spot mode, corr={corr:.3f})"
|
||||
|
||||
# Correlation filter
|
||||
conflict = _check_correlation_conflict(conn, ticker, direction)
|
||||
if conflict:
|
||||
@@ -309,8 +351,25 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
|
||||
correlation=corr, direction=direction, action="open")
|
||||
|
||||
dir_str = "LONG" if direction == 1 else "SHORT"
|
||||
return (f"SIGNAL {dir_str} @ ${entry_price:,.2f} "
|
||||
f"stop ${stop_price:,.2f} corr={corr:.3f} size=${pos_value:,.2f}")
|
||||
msg = (f"SIGNAL {dir_str} @ ${entry_price:,.2f} "
|
||||
f"stop ${stop_price:,.2f} corr={corr:.3f} size=${pos_value:,.2f}")
|
||||
|
||||
# Live execution: buy on exchange
|
||||
if cfg.mode == "live" and direction == 1:
|
||||
spot = _get_spot(cfg)
|
||||
order = spot.buy(asset_cfg.symbol, pos_value)
|
||||
if order:
|
||||
msg += " [LIVE BUY OK]"
|
||||
else:
|
||||
# Rollback paper position — no phantom positions
|
||||
close_position(conn, pos_id,
|
||||
exit_price=entry_price, exit_date=str(dates[-1]),
|
||||
exit_reason="live_buy_failed", pnl_net=0, pnl_pct=0)
|
||||
msg = (f"SIGNAL {dir_str} @ ${entry_price:,.2f} "
|
||||
f"[LIVE BUY FAILED — position rolled back]")
|
||||
log.error(f"{ticker}: live buy failed, paper position rolled back")
|
||||
|
||||
return msg
|
||||
|
||||
|
||||
def _retrain(conn, ticker, prices, cfg):
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Sentiment analysis via LLM API (Anthropic-compatible)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
|
||||
from ..config import LLMConfig
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
SENTIMENT_PROMPT = """You are a crypto market sentiment analyzer.
|
||||
Analyze the following market data for {ticker} and return a sentiment score.
|
||||
|
||||
Current price: ${price:,.2f}
|
||||
24h change: {change_24h:+.2f}%
|
||||
7d change: {change_7d:+.2f}%
|
||||
30d change: {change_30d:+.2f}%
|
||||
Recent price action (last 20 bars, 4H): {recent_prices}
|
||||
|
||||
Return ONLY a JSON object:
|
||||
{{"score": <float from -1.0 to 1.0>, "reason": "<one sentence>"}}
|
||||
|
||||
Score guide:
|
||||
- -1.0: extreme fear, crash, capitulation
|
||||
- -0.5: bearish, declining momentum
|
||||
- 0.0: neutral, consolidation
|
||||
- +0.5: bullish, growing momentum
|
||||
- +1.0: extreme greed, parabolic move"""
|
||||
|
||||
|
||||
def get_sentiment(cfg: LLMConfig, ticker: str, prices: list[float],
|
||||
) -> tuple[float, str]:
|
||||
"""Get sentiment score from LLM. Returns (score, reason)."""
|
||||
if not cfg.enabled or not cfg.api_key:
|
||||
return 0.0, "llm_disabled"
|
||||
|
||||
n = len(prices)
|
||||
if n < 30:
|
||||
return 0.0, "not_enough_data"
|
||||
|
||||
price = prices[-1]
|
||||
change_24h = (prices[-1] / prices[-7] - 1) * 100 if n >= 7 else 0 # 6 bars = 24h on 4H
|
||||
change_7d = (prices[-1] / prices[-42] - 1) * 100 if n >= 42 else 0 # 42 bars = 7d on 4H
|
||||
change_30d = (prices[-1] / prices[-180] - 1) * 100 if n >= 180 else 0
|
||||
|
||||
recent = [round(float(p), 2) for p in prices[-20:]]
|
||||
|
||||
prompt = SENTIMENT_PROMPT.format(
|
||||
ticker=ticker, price=price,
|
||||
change_24h=change_24h, change_7d=change_7d, change_30d=change_30d,
|
||||
recent_prices=recent,
|
||||
)
|
||||
|
||||
try:
|
||||
resp = httpx.post(
|
||||
f"{cfg.base_url}/v1/messages",
|
||||
headers={
|
||||
"x-api-key": cfg.api_key,
|
||||
"anthropic-version": "2023-06-01",
|
||||
"content-type": "application/json",
|
||||
},
|
||||
json={
|
||||
"model": cfg.model,
|
||||
"max_tokens": 150,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
if resp.status_code != 200:
|
||||
log.warning("LLM API error %d: %s", resp.status_code, resp.text[:200])
|
||||
return 0.0, f"api_error_{resp.status_code}"
|
||||
|
||||
data = resp.json()
|
||||
text = data.get("content", [{}])[0].get("text", "")
|
||||
|
||||
# Parse JSON from response
|
||||
text = text.strip()
|
||||
if text.startswith("```"):
|
||||
text = text.split("\n", 1)[-1].rsplit("```", 1)[0]
|
||||
|
||||
result = json.loads(text)
|
||||
score = float(result.get("score", 0))
|
||||
reason = str(result.get("reason", ""))
|
||||
|
||||
# Clamp to [-1, 1]
|
||||
score = max(-1.0, min(1.0, score))
|
||||
return score, reason
|
||||
|
||||
except (httpx.HTTPError, json.JSONDecodeError, KeyError, ValueError) as e:
|
||||
log.warning("Sentiment analysis failed: %s", e)
|
||||
return 0.0, f"error: {e}"
|
||||
|
||||
|
||||
def momentum_sentiment_proxy(prices: list[float]) -> float:
|
||||
"""Simple momentum-based sentiment proxy for backtesting.
|
||||
|
||||
Uses price momentum as a stand-in for news sentiment.
|
||||
Returns score from -1.0 to 1.0.
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
n = len(prices)
|
||||
if n < 30:
|
||||
return 0.0
|
||||
|
||||
p = np.array(prices)
|
||||
|
||||
# Short-term momentum (6 bars = 24h on 4H)
|
||||
mom_short = (p[-1] / p[-7] - 1) if n >= 7 else 0
|
||||
|
||||
# Medium-term momentum (42 bars = 7d on 4H)
|
||||
mom_med = (p[-1] / p[-42] - 1) if n >= 42 else 0
|
||||
|
||||
# RSI-like overbought/oversold
|
||||
changes = np.diff(p[-15:])
|
||||
gains = changes[changes > 0].sum()
|
||||
losses = -changes[changes < 0].sum()
|
||||
rs = gains / losses if losses > 0 else 10.0
|
||||
rsi = 100 - 100 / (1 + rs)
|
||||
|
||||
# Combine: normalize to [-1, 1]
|
||||
# RSI: 30→-0.5, 50→0, 70→+0.5
|
||||
rsi_score = (rsi - 50) / 50
|
||||
|
||||
# Momentum: clip to [-0.1, 0.1] range, scale to [-1, 1]
|
||||
mom_score = np.clip(mom_short * 10 + mom_med * 5, -1, 1)
|
||||
|
||||
# Average
|
||||
score = 0.5 * rsi_score + 0.5 * mom_score
|
||||
return float(np.clip(score, -1, 1))
|
||||
@@ -2,14 +2,86 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import numpy as np
|
||||
import yfinance as yf
|
||||
|
||||
from ..config import AssetConfig, ModelConfig
|
||||
from ..config import AssetConfig, ExchangeConfig, ModelConfig
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# Singleton exchange instance
|
||||
_exchange = None
|
||||
|
||||
|
||||
def fetch_prices(ticker: str, interval: str = "1d", period: str = "max"):
|
||||
"""Fetch close prices and dates from yfinance."""
|
||||
def _get_exchange(exchange_cfg: ExchangeConfig | None = None):
|
||||
"""Get or create ccxt exchange instance."""
|
||||
global _exchange
|
||||
if _exchange is not None:
|
||||
return _exchange
|
||||
|
||||
import ccxt
|
||||
name = exchange_cfg.name if exchange_cfg else "bybit"
|
||||
exchange_class = getattr(ccxt, name)
|
||||
_exchange = exchange_class({"enableRateLimit": True})
|
||||
log.info(f"Initialized {name} exchange for market data")
|
||||
return _exchange
|
||||
|
||||
|
||||
def fetch_prices_ccxt(symbol: str, interval: str = "1d", period: str = "max",
|
||||
exchange_cfg: ExchangeConfig | None = None):
|
||||
"""Fetch close prices and dates from exchange via ccxt (Bybit etc).
|
||||
|
||||
Args:
|
||||
symbol: ccxt symbol format, e.g. "BTC/USDT"
|
||||
interval: timeframe, e.g. "4h", "1d"
|
||||
period: "max" or "730d" etc.
|
||||
"""
|
||||
exchange = _get_exchange(exchange_cfg)
|
||||
|
||||
if period == "max":
|
||||
days = 1000
|
||||
else:
|
||||
days = int(period.rstrip("d"))
|
||||
since = int((datetime.now(timezone.utc) - timedelta(days=days)).timestamp() * 1000)
|
||||
|
||||
all_ohlcv = []
|
||||
batch_size = 1000
|
||||
now_ms = int(datetime.now(timezone.utc).timestamp() * 1000)
|
||||
prev_since = None
|
||||
while since < now_ms:
|
||||
try:
|
||||
ohlcv = exchange.fetch_ohlcv(symbol, interval, since=since, limit=batch_size)
|
||||
except Exception as e:
|
||||
log.error(f"Failed to fetch {symbol} from {exchange.id}: {e}")
|
||||
return None, None
|
||||
if not ohlcv:
|
||||
break
|
||||
all_ohlcv.extend(ohlcv)
|
||||
since = ohlcv[-1][0] + 1
|
||||
if since == prev_since:
|
||||
break
|
||||
prev_since = since
|
||||
|
||||
if not all_ohlcv:
|
||||
return None, None
|
||||
|
||||
closes = np.array([c[4] for c in all_ohlcv], dtype=np.float64)
|
||||
dates = [datetime.fromtimestamp(c[0] / 1000, tz=timezone.utc).date()
|
||||
for c in all_ohlcv]
|
||||
return closes, dates
|
||||
|
||||
|
||||
def fetch_prices_yfinance(ticker: str, interval: str = "1d", period: str = "max"):
|
||||
"""Fetch close prices and dates from yfinance.
|
||||
|
||||
Args:
|
||||
ticker: yfinance ticker format, e.g. "BTC-USD"
|
||||
interval: timeframe, e.g. "4h", "1d"
|
||||
period: "max" or "730d" etc.
|
||||
"""
|
||||
import yfinance as yf
|
||||
hist = yf.Ticker(ticker).history(period=period, interval=interval)
|
||||
if hist.empty:
|
||||
return None, None
|
||||
@@ -18,6 +90,23 @@ def fetch_prices(ticker: str, interval: str = "1d", period: str = "max"):
|
||||
return close, dates
|
||||
|
||||
|
||||
def fetch_prices(symbol: str, interval: str = "1d", period: str = "max",
|
||||
exchange_cfg: ExchangeConfig | None = None,
|
||||
source: str = "exchange"):
|
||||
"""Fetch close prices and dates.
|
||||
|
||||
Args:
|
||||
symbol: ticker/symbol (format depends on source)
|
||||
interval: timeframe
|
||||
period: data period
|
||||
exchange_cfg: exchange config (for ccxt source)
|
||||
source: "exchange" (ccxt/Bybit) or "yfinance"
|
||||
"""
|
||||
if source == "yfinance":
|
||||
return fetch_prices_yfinance(symbol, interval, period)
|
||||
return fetch_prices_ccxt(symbol, interval, period, exchange_cfg)
|
||||
|
||||
|
||||
def prepare_windows(prices: np.ndarray, window_size: int, shift: int) -> list[dict]:
|
||||
"""Create normalized windows from price array."""
|
||||
data = []
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
"""Spot trading executor for Bybit via ccxt.
|
||||
|
||||
Safety-first design:
|
||||
- Balance checks before every trade
|
||||
- Min order validation
|
||||
- Dry-run mode (testnet=true in config)
|
||||
- No retries on failure (prevents double orders)
|
||||
- Comprehensive logging
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from ..config import ExchangeConfig
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SpotExecutor:
|
||||
"""Execute spot trades on Bybit."""
|
||||
|
||||
def __init__(self, exchange_cfg: ExchangeConfig):
|
||||
import ccxt
|
||||
self.exchange = ccxt.bybit({
|
||||
"apiKey": exchange_cfg.api_key,
|
||||
"secret": exchange_cfg.api_secret,
|
||||
"enableRateLimit": True,
|
||||
})
|
||||
self.dry_run = exchange_cfg.testnet
|
||||
self._markets_loaded = False
|
||||
|
||||
if self.dry_run:
|
||||
log.info("SpotExecutor: DRY RUN mode (testnet=true)")
|
||||
else:
|
||||
log.info("SpotExecutor: LIVE mode")
|
||||
|
||||
def _ensure_markets(self):
|
||||
if not self._markets_loaded:
|
||||
self.exchange.load_markets()
|
||||
self._markets_loaded = True
|
||||
|
||||
def get_balance(self, coin: str) -> float:
|
||||
"""Get free balance for a coin."""
|
||||
try:
|
||||
b = self.exchange.fetch_balance()
|
||||
return float(b.get(coin, {}).get("free", 0) or 0)
|
||||
except Exception as e:
|
||||
log.error(f"Balance fetch failed: {e}")
|
||||
return 0.0
|
||||
|
||||
def get_price(self, symbol: str) -> float | None:
|
||||
"""Get current market price."""
|
||||
try:
|
||||
ticker = self.exchange.fetch_ticker(symbol)
|
||||
return float(ticker["last"])
|
||||
except Exception as e:
|
||||
log.error(f"Price fetch {symbol} failed: {e}")
|
||||
return None
|
||||
|
||||
def buy(self, symbol: str, usdt_amount: float) -> dict | None:
|
||||
"""Market buy with specified USDT amount.
|
||||
|
||||
Returns order dict or None on failure.
|
||||
Does NOT retry on failure (prevents double orders).
|
||||
"""
|
||||
self._ensure_markets()
|
||||
coin = symbol.split("/")[0]
|
||||
|
||||
# 1. Get price
|
||||
price = self.get_price(symbol)
|
||||
if price is None:
|
||||
return None
|
||||
|
||||
# 2. Calculate amount
|
||||
market = self.exchange.market(symbol)
|
||||
amount = usdt_amount / price
|
||||
amount = float(self.exchange.amount_to_precision(symbol, amount))
|
||||
|
||||
# 3. Validate minimums
|
||||
min_amount = float(market["limits"]["amount"]["min"] or 0)
|
||||
min_cost = float(market["limits"]["cost"]["min"] or 5.0)
|
||||
|
||||
if amount < min_amount:
|
||||
log.error(f"BUY {symbol}: amount {amount} < min {min_amount}")
|
||||
return None
|
||||
if usdt_amount < min_cost:
|
||||
log.error(f"BUY {symbol}: cost ${usdt_amount:.2f} < min ${min_cost}")
|
||||
return None
|
||||
|
||||
# 4. Check balance (strict)
|
||||
usdt_free = self.get_balance("USDT")
|
||||
if usdt_free < usdt_amount:
|
||||
# Try to buy what we can afford
|
||||
if usdt_free >= min_cost:
|
||||
log.warning(f"BUY {symbol}: USDT {usdt_free:.2f} < requested {usdt_amount:.2f}, "
|
||||
f"reducing to {usdt_free:.2f}")
|
||||
usdt_amount = usdt_free
|
||||
amount = usdt_amount / price
|
||||
amount = float(self.exchange.amount_to_precision(symbol, amount))
|
||||
else:
|
||||
log.error(f"BUY {symbol}: USDT {usdt_free:.2f} < min ${min_cost}")
|
||||
return None
|
||||
|
||||
# 5. Execute
|
||||
ts = datetime.now(timezone.utc).isoformat()
|
||||
if self.dry_run:
|
||||
log.info(f"[DRY RUN] BUY {amount} {coin} @ ~${price:,.2f} "
|
||||
f"(${usdt_amount:.2f}) at {ts}")
|
||||
return {"dry_run": True, "side": "buy", "symbol": symbol,
|
||||
"amount": amount, "price": price, "cost": usdt_amount}
|
||||
|
||||
try:
|
||||
order = self.exchange.create_market_buy_order(symbol, amount)
|
||||
filled = float(order.get("filled", 0))
|
||||
avg_price = float(order.get("average", price))
|
||||
cost = float(order.get("cost", usdt_amount))
|
||||
log.info(f"BUY OK: {filled} {coin} @ ${avg_price:,.2f} "
|
||||
f"(${cost:.2f}) order={order['id']}")
|
||||
return order
|
||||
except Exception as e:
|
||||
log.error(f"BUY {symbol} FAILED: {e}")
|
||||
return None
|
||||
|
||||
def sell(self, symbol: str, amount: float | None = None) -> dict | None:
|
||||
"""Market sell. If amount is None, sell entire balance.
|
||||
|
||||
Returns order dict or None on failure.
|
||||
Does NOT retry on failure (prevents double orders).
|
||||
"""
|
||||
self._ensure_markets()
|
||||
coin = symbol.split("/")[0]
|
||||
|
||||
# 1. Determine amount
|
||||
if amount is None:
|
||||
amount = self.get_balance(coin)
|
||||
|
||||
if amount <= 0:
|
||||
log.warning(f"SELL {symbol}: nothing to sell ({coin} balance=0)")
|
||||
return None
|
||||
|
||||
# 2. Precision
|
||||
amount = float(self.exchange.amount_to_precision(symbol, amount))
|
||||
|
||||
# 3. Validate minimum
|
||||
market = self.exchange.market(symbol)
|
||||
min_amount = float(market["limits"]["amount"]["min"] or 0)
|
||||
|
||||
if amount < min_amount:
|
||||
log.warning(f"SELL {symbol}: amount {amount} < min {min_amount}")
|
||||
return None
|
||||
|
||||
# 4. Check balance
|
||||
coin_free = self.get_balance(coin)
|
||||
if coin_free < amount:
|
||||
log.warning(f"SELL {symbol}: balance {coin_free} < requested {amount}, "
|
||||
f"selling available")
|
||||
amount = float(self.exchange.amount_to_precision(symbol, coin_free))
|
||||
if amount < min_amount:
|
||||
return None
|
||||
|
||||
# 5. Execute
|
||||
price = self.get_price(symbol)
|
||||
ts = datetime.now(timezone.utc).isoformat()
|
||||
if self.dry_run:
|
||||
cost = amount * (price or 0)
|
||||
log.info(f"[DRY RUN] SELL {amount} {coin} @ ~${price:,.2f} "
|
||||
f"(~${cost:.2f}) at {ts}")
|
||||
return {"dry_run": True, "side": "sell", "symbol": symbol,
|
||||
"amount": amount, "price": price, "cost": cost}
|
||||
|
||||
try:
|
||||
order = self.exchange.create_market_sell_order(symbol, amount)
|
||||
filled = float(order.get("filled", 0))
|
||||
avg_price = float(order.get("average", price or 0))
|
||||
cost = float(order.get("cost", 0))
|
||||
log.info(f"SELL OK: {filled} {coin} @ ${avg_price:,.2f} "
|
||||
f"(${cost:.2f}) order={order['id']}")
|
||||
return order
|
||||
except Exception as e:
|
||||
log.error(f"SELL {symbol} FAILED: {e}")
|
||||
return None
|
||||
@@ -62,13 +62,13 @@
|
||||
<header>Assets</header>
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Ticker</th><th>Binance</th><th>K</th><th>Corr Thresh</th><th>Trailing</th></tr>
|
||||
<tr><th>Ticker</th><th>Symbol</th><th>K</th><th>Corr Thresh</th><th>Trailing</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for a in cfg.assets %}
|
||||
<tr>
|
||||
<td>{{ a.ticker }}</td>
|
||||
<td>{{ a.binance_symbol }}</td>
|
||||
<td>{{ a.symbol }}</td>
|
||||
<td>{{ a.K }}</td>
|
||||
<td>{{ a.corr_thresh }}</td>
|
||||
<td>{{ 'Yes' if a.trailing_stop else 'No' }}</td>
|
||||
|
||||
Reference in New Issue
Block a user