fix: 3 корневые причины расхождения БД/биржа
1. reconcile: для futures использует Bybit closedPnl (реальный PnL с учётом fees/slippage) вместо calculate_pnl 2. open: перед открытием futures проверяет что на бирже нет orphan-позиции — предотвращает случайное добавление к существующей 3. _open: fetch_order после market order для реальных fill данных (filled, average, cost) — исправляет qty=0 в orders таблице Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -93,17 +93,34 @@ def reconcile_positions(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
min_threshold = pos["pos_size"] * 0.1 # <10% of position = closed
|
||||
|
||||
if coin_balance < min_threshold:
|
||||
# Position was closed externally (user sold on exchange)
|
||||
# Position was closed externally (SL, user, or liquidation)
|
||||
current_price = executor.get_price(asset_cfg.symbol)
|
||||
if current_price is None:
|
||||
current_price = pos["entry_price"] # fallback
|
||||
|
||||
commission = cfg.commission_for(asset_cfg)
|
||||
pnl_net, pnl_pct = risk.calculate_pnl(
|
||||
pos["entry_price"], current_price, pos["direction"],
|
||||
pos["pos_size"], pos["pos_value"],
|
||||
commission=commission,
|
||||
)
|
||||
# For futures: use Bybit's actual closed PnL (includes fees, slippage)
|
||||
if cfg.is_futures(asset_cfg):
|
||||
closed = executor.get_closed_pnl(asset_cfg.symbol)
|
||||
if closed and abs(closed["entryPrice"] - pos["entry_price"]) < pos["entry_price"] * 0.02:
|
||||
pnl_net = closed["closedPnl"]
|
||||
current_price = closed["exitPrice"]
|
||||
pnl_pct = pnl_net / pos["pos_value"] if pos["pos_value"] else 0
|
||||
log.info(f"{ticker}: using Bybit closedPnl=${pnl_net:+.4f} "
|
||||
f"exit=${current_price:.4f}")
|
||||
else:
|
||||
commission = cfg.commission_for(asset_cfg)
|
||||
pnl_net, pnl_pct = risk.calculate_pnl(
|
||||
pos["entry_price"], current_price, pos["direction"],
|
||||
pos["pos_size"], pos["pos_value"],
|
||||
commission=commission,
|
||||
)
|
||||
else:
|
||||
commission = cfg.commission_for(asset_cfg)
|
||||
pnl_net, pnl_pct = risk.calculate_pnl(
|
||||
pos["entry_price"], current_price, pos["direction"],
|
||||
pos["pos_size"], pos["pos_value"],
|
||||
commission=commission,
|
||||
)
|
||||
|
||||
close_position(conn, pos["id"],
|
||||
exit_price=current_price,
|
||||
@@ -691,6 +708,13 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
|
||||
executor = _get_executor(cfg, asset_cfg)
|
||||
|
||||
if cfg.is_futures(asset_cfg):
|
||||
# Safety: check no orphan position exists on exchange
|
||||
existing = executor.get_position(asset_cfg.symbol)
|
||||
if isinstance(existing, dict) and existing["size"] > 0:
|
||||
log.error(f"{ticker}: ABORT — exchange already has "
|
||||
f"{existing['side']} {existing['size']} position!")
|
||||
msg += " [ABORT: existing exchange position]"
|
||||
return msg
|
||||
# Futures: open_long or open_short
|
||||
if direction == 1:
|
||||
order = executor.open_long(asset_cfg.symbol, pos_value)
|
||||
|
||||
@@ -108,6 +108,34 @@ class FuturesExecutor:
|
||||
log.error(f"Fetch position {symbol} failed: {e}")
|
||||
return self.API_ERROR
|
||||
|
||||
def get_closed_pnl(self, symbol: str, limit: int = 5) -> dict | None:
|
||||
"""Get most recent closed PnL for symbol from Bybit.
|
||||
|
||||
Returns dict with: exitPrice, closedPnl, qty, side, or None.
|
||||
"""
|
||||
self._ensure_markets()
|
||||
try:
|
||||
market = self.exchange.market(symbol)
|
||||
result = self.exchange.privateGetV5PositionClosedPnl({
|
||||
"symbol": market["id"],
|
||||
"category": "linear",
|
||||
"limit": limit,
|
||||
})
|
||||
pnl_list = result.get("result", {}).get("list", [])
|
||||
if pnl_list:
|
||||
latest = pnl_list[0]
|
||||
return {
|
||||
"exitPrice": float(latest.get("avgExitPrice", 0)),
|
||||
"entryPrice": float(latest.get("avgEntryPrice", 0)),
|
||||
"closedPnl": float(latest.get("closedPnl", 0)),
|
||||
"qty": float(latest.get("qty", 0)),
|
||||
"side": latest.get("side", ""),
|
||||
}
|
||||
return None
|
||||
except Exception as e:
|
||||
log.warning(f"Closed PnL fetch {symbol} failed: {e}")
|
||||
return None
|
||||
|
||||
def get_price(self, symbol: str) -> float | None:
|
||||
"""Get current market price."""
|
||||
try:
|
||||
@@ -159,10 +187,23 @@ class FuturesExecutor:
|
||||
|
||||
try:
|
||||
order = self.exchange.create_order(symbol, "market", side, amount)
|
||||
# Bybit market orders may return filled=0 initially — fetch for real data
|
||||
order_id = order.get("id")
|
||||
if order_id and not float(order.get("filled") or 0):
|
||||
import time
|
||||
time.sleep(0.5)
|
||||
try:
|
||||
order = self.exchange.fetch_order(order_id, symbol)
|
||||
except Exception:
|
||||
pass # use original order data
|
||||
filled = float(order.get("filled") or amount)
|
||||
avg = float(order.get("average") or price)
|
||||
cost = float(order.get("cost") or filled * avg)
|
||||
order["filled"] = filled
|
||||
order["average"] = avg
|
||||
order["cost"] = cost
|
||||
log.info(f"{side.upper()} OK: {filled} {symbol} @ ${avg:,.2f} "
|
||||
f"order={order.get('id')}")
|
||||
f"cost=${cost:.2f} order={order_id}")
|
||||
return order
|
||||
except Exception as e:
|
||||
log.error(f"{side.upper()} {symbol} FAILED: {e}")
|
||||
|
||||
Reference in New Issue
Block a user