aboutsummaryrefslogtreecommitdiff
path: root/server/api/bids.py
blob: 9da68250dd274fa941dca8d5829731c559322b4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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")

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

class BidBase(BaseModel):
    timestamp: datetime
    quantity: float
    price: float
    user_id: int # In production the user_id should be obtained from the authenticated user

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