First commit
This commit is contained in:
+110
@@ -0,0 +1,110 @@
|
||||
"""Broker adapters. Both expose the same small interface so the rest of the
|
||||
bot doesn't care where an order goes."""
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .store import Store
|
||||
|
||||
|
||||
@dataclass
|
||||
class Position:
|
||||
symbol: str
|
||||
qty: float
|
||||
avg_price: float
|
||||
market_value: float
|
||||
|
||||
|
||||
class Broker:
|
||||
name = "base"
|
||||
|
||||
def equity(self) -> float: ...
|
||||
def positions(self) -> list[Position]: ...
|
||||
def has_position(self, symbol: str) -> bool:
|
||||
return any(p.symbol.replace("/", "") == symbol.replace("/", "") for p in self.positions())
|
||||
def market_open(self) -> bool:
|
||||
return True
|
||||
def buy_notional(self, symbol: str, amount: float, price: float, asset_class: str = "stock") -> dict: ...
|
||||
def close(self, symbol: str, price: float) -> dict: ...
|
||||
|
||||
|
||||
class PaperBroker(Broker):
|
||||
"""Built-in simulated broker (used for AEX stocks). Fills at the alert price
|
||||
with a 0.15% fee, so results are slightly pessimistic rather than flattering."""
|
||||
name = "paper"
|
||||
FEE = 0.0015
|
||||
|
||||
def __init__(self, store: Store):
|
||||
self.s = store
|
||||
|
||||
def _cash(self) -> float:
|
||||
return self.s.q("SELECT cash FROM paper_account WHERE id=1")[0]["cash"]
|
||||
|
||||
def positions(self) -> list[Position]:
|
||||
return [Position(r["symbol"], r["qty"], r["avg_price"], r["qty"] * r["last_price"])
|
||||
for r in self.s.q("SELECT * FROM paper_positions")]
|
||||
|
||||
def equity(self) -> float:
|
||||
return self._cash() + sum(p.market_value for p in self.positions())
|
||||
|
||||
def mark(self, symbol: str, price: float):
|
||||
self.s.q("UPDATE paper_positions SET last_price=? WHERE symbol=?", (price, symbol))
|
||||
|
||||
def buy_notional(self, symbol, amount, price, asset_class="stock"):
|
||||
cash = self._cash()
|
||||
amount = min(amount, cash / (1 + self.FEE))
|
||||
if amount <= 1:
|
||||
raise ValueError("not enough paper cash")
|
||||
qty = amount / price
|
||||
fee = amount * self.FEE
|
||||
self.s.q("UPDATE paper_account SET cash = cash - ? WHERE id=1", (amount + fee,))
|
||||
self.s.q("INSERT INTO paper_positions (symbol, qty, avg_price, last_price) VALUES (?,?,?,?)",
|
||||
(symbol, qty, price, price))
|
||||
return {"broker": "paper", "side": "buy", "qty": round(qty, 6), "price": price,
|
||||
"fee": round(fee, 2)}
|
||||
|
||||
def close(self, symbol, price):
|
||||
rows = self.s.q("SELECT * FROM paper_positions WHERE symbol=?", (symbol,))
|
||||
if not rows:
|
||||
raise ValueError("no open position")
|
||||
qty, avg = rows[0]["qty"], rows[0]["avg_price"]
|
||||
proceeds = qty * price
|
||||
fee = proceeds * self.FEE
|
||||
self.s.q("UPDATE paper_account SET cash = cash + ? WHERE id=1", (proceeds - fee,))
|
||||
self.s.q("DELETE FROM paper_positions WHERE symbol=?", (symbol,))
|
||||
pnl = proceeds - fee - qty * avg * (1 + self.FEE)
|
||||
return {"broker": "paper", "side": "sell", "qty": round(qty, 6), "price": price,
|
||||
"fee": round(fee, 2), "pnl": round(pnl, 2)}
|
||||
|
||||
|
||||
class AlpacaBroker(Broker):
|
||||
"""Alpaca, paper account by default. Used for crypto."""
|
||||
name = "alpaca"
|
||||
|
||||
def __init__(self, key: str, secret: str, live: bool = False):
|
||||
from alpaca.trading.client import TradingClient
|
||||
self.client = TradingClient(key, secret, paper=not live)
|
||||
|
||||
def equity(self) -> float:
|
||||
return float(self.client.get_account().equity)
|
||||
|
||||
def positions(self) -> list[Position]:
|
||||
return [Position(p.symbol, float(p.qty), float(p.avg_entry_price), float(p.market_value))
|
||||
for p in self.client.get_all_positions()]
|
||||
|
||||
def market_open(self) -> bool:
|
||||
return bool(self.client.get_clock().is_open)
|
||||
|
||||
def buy_notional(self, symbol, amount, price, asset_class="crypto"):
|
||||
from alpaca.trading.enums import OrderSide, TimeInForce
|
||||
from alpaca.trading.requests import MarketOrderRequest
|
||||
# Crypto trades 24/7 (GTC). Fractional/notional stock orders must be DAY orders.
|
||||
tif = TimeInForce.GTC if asset_class == "crypto" else TimeInForce.DAY
|
||||
order = self.client.submit_order(MarketOrderRequest(
|
||||
symbol=symbol, notional=round(amount, 2), side=OrderSide.BUY,
|
||||
time_in_force=tif))
|
||||
return {"broker": "alpaca", "side": "buy", "order_id": str(order.id),
|
||||
"notional": round(amount, 2), "status": str(order.status)}
|
||||
|
||||
def close(self, symbol, price):
|
||||
order = self.client.close_position(symbol.replace("/", ""))
|
||||
return {"broker": "alpaca", "side": "sell", "order_id": str(order.id),
|
||||
"status": str(order.status)}
|
||||
Reference in New Issue
Block a user