diff options
Diffstat (limited to 'server')
-rw-r--r-- | server/api/bids.py | 88 |
1 files changed, 77 insertions, 11 deletions
diff --git a/server/api/bids.py b/server/api/bids.py index 24e2fa0..9da6825 100644 --- a/server/api/bids.py +++ b/server/api/bids.py @@ -1,16 +1,82 @@ -from fastapi import APIRouter -from models.bid import Bid -from typing import List +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session +from db import SessionLocal +from models.bid import Bid as BidModel +from pydantic import BaseModel +from datetime import datetime, timezone +from zoneinfo import ZoneInfo +from typing import List, Optional router = APIRouter() +NEW_ENGLAND_TZ = ZoneInfo("America/New_York") -fake_bid_store: List[Bid] = [] +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() -@router.get("/", response_model=List[Bid]) -def get_bids(): - return fake_bid_store +class BidBase(BaseModel): + timestamp: datetime + quantity: float + price: float + user_id: int # In production the user_id should be obtained from the authenticated user -@router.post("/", response_model=Bid) -def submit_bid(bid: Bid): - fake_bid_store.append(bid) - return bid +class BidCreate(BidBase): + pass + +class BidResponse(BidBase): + id: int + status: str + pnl: Optional[float] + + class Config: + from_atrributes = True + +@router.get("/", response_model=List[BidResponse]) +def get_bids(db: Session = Depends(get_db)): + return db.query(BidModel).all() + +@router.post("/", response_model=BidResponse) +def submit_bid(bid: BidCreate, db: Session = Depends(get_db)): + # TODO: Can you submit a bid for 2AM the next day after 11AM? + now = datetime.now(NEW_ENGLAND_TZ) + bid_timestamp_local = bid.timestamp.astimezone(NEW_ENGLAND_TZ) + bid_day = bid_timestamp_local.date() + today = now.date() + + print(f"Received bid for {bid_day} at {bid.timestamp}") + + if bid.timestamp < now: + raise HTTPException(status_code=400, detail="Cannot submit bids in the past.") + + cutoff_time = now.replace(hour=11, minute=0, second=0, microsecond=0) + + if bid_day == today: + if now > cutoff_time: + raise HTTPException(status_code=400, detail="Cannot submit bids for today after 11am.") + + start_of_hour = bid.timestamp.replace(minute=0, second=0, microsecond=0) + end_of_hour = start_of_hour.replace(minute=59, second=59, microsecond=999999) + + bid_count = db.query(BidModel).filter( + BidModel.timestamp >= start_of_hour, + BidModel.timestamp <= end_of_hour + ).count() + + if bid_count >= 10: + raise HTTPException(status_code=400, detail="Cannot submit more than 10 bids for this hour.") + + db_bid = BidModel( + timestamp=bid.timestamp, + quantity=bid.quantity, + price=bid.price, + user_id=bid.user_id, + status="Submitted", + pnl=None + ) + db.add(db_bid) + db.commit() + db.refresh(db_bid) + return db_bid |