Files
alpaca-llm-bot-v1/bot.py

56 lines
2.0 KiB
Python

from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
import json
from config import settings
from db import SessionLocal, BotDecision, TradeExecution
from services import searx_news, ollama_decide, place_order
scheduler = BackgroundScheduler(timezone=settings.timezone)
def run_cycle():
db = SessionLocal()
try:
for symbol in settings.symbols:
news = searx_news(symbol)
decision = ollama_decide(symbol, news)
drow = BotDecision(
symbol=symbol,
action=decision["action"],
confidence=decision["confidence"],
reason=decision["reason"],
market_context=json.dumps(news)[:60000],
order_usd=decision["order_usd"],
status="planned",
)
db.add(drow)
db.commit()
db.refresh(drow)
if decision["action"] in {"buy", "sell"} and decision["confidence"] >= 0.55:
res = place_order(symbol, decision["action"], min(settings.max_order_usd, decision["order_usd"]))
ok = bool(res and res.get("ok"))
drow.status = "executed" if ok else "failed"
db.add(drow)
db.add(TradeExecution(
symbol=symbol,
side=decision["action"],
qty=float((res or {}).get("json", {}).get("qty", 0) or 0),
notional=min(settings.max_order_usd, decision["order_usd"]),
alpaca_order_id=(res or {}).get("json", {}).get("id", ""),
raw=json.dumps(res)[:60000],
))
db.commit()
else:
drow.status = "skipped"
db.add(drow)
db.commit()
finally:
db.close()
def start_scheduler():
scheduler.add_job(run_cycle, "interval", hours=settings.trade_interval_hours, id="trade_cycle", replace_existing=True)
scheduler.start()