Chapter 32: Exercises — Building a Platform from Scratch

These exercises progress from conceptual understanding through calculation, programming, analysis, and research. They are designed to reinforce every major concept from the chapter and to extend your platform-building skills.


Part A: Conceptual Questions (8 problems)

A.1 ⭐ Layered Architecture

Explain the purpose of each layer in our platform architecture (routers, services, engines, models). Why do we avoid putting database queries directly in route handlers?

A.2 ⭐ Order Book Matching Priority

In our order book implementation, we use price-time priority. Describe what this means. If three sell orders exist at the same price—placed at 10:01, 10:02, and 10:03 respectively—and a buy order arrives that can only fill one of them, which sell order gets filled and why?

A.3 ⭐⭐ LMSR Price Interpretation

The LMSR price function produces values between 0 and 1 that sum to 1 across all outcomes. Explain why these prices can be interpreted as probabilities. Under what conditions might the LMSR prices fail to reflect true probabilities?

A.4 ⭐⭐ Market vs. Limit Orders

A trader wants to buy shares in a prediction market. Compare the advantages and disadvantages of using a market order versus a limit order. When would each be appropriate?

A.5 ⭐⭐ JWT Statelessness

Explain why JWT authentication is called "stateless." What is the primary advantage of stateless authentication for a prediction market platform? What is the main disadvantage?

A.6 ⭐⭐⭐ Market Resolution Trust

Our implementation allows only the market creator to resolve a market. Describe three alternative resolution mechanisms and their trade-offs in terms of trust, speed, and cost.

A.7 ⭐⭐⭐ LMSR Liquidity Parameter

A prediction market operator is deciding on the liquidity parameter $b$ for a new binary market. The operator has a budget of $500 for market-making subsidy. What is the maximum $b$ they can use? What is the trade-off of using a higher $b$ within this budget?

A.8 ⭐⭐⭐⭐ Hybrid Market Design

Propose a design that combines both an order book and an LMSR AMM in the same market. The AMM should provide baseline liquidity, while the order book allows traders to offer better prices. Describe the order routing logic: when does a trade go to the AMM vs. the order book?


Part B: Calculation Problems (5 problems)

B.1 ⭐ LMSR Cost Calculation

A binary LMSR market has $b = 50$, and the current share vector is $\mathbf{q} = (20, 10)$. Compute: 1. The current cost function value $C(\mathbf{q})$. 2. The prices $p_1$ and $p_2$. 3. The cost of buying 5 additional shares of outcome 1.

B.2 ⭐⭐ Order Book Execution

Consider an order book for outcome "Yes" with the following state:

Bids (buy orders): | Price | Quantity | Timestamp | |-------|----------|-----------| | 0.65 | 20 | 10:01 | | 0.60 | 15 | 10:00 | | 0.55 | 30 | 10:02 |

Asks (sell orders): | Price | Quantity | Timestamp | |-------|----------|-----------| | 0.70 | 10 | 10:01 | | 0.75 | 25 | 10:03 |

A market sell order for 25 shares arrives. Describe the sequence of trades that occur, including the price and quantity of each trade and the final state of the order book.

B.3 ⭐⭐ Maximum Loss Calculation

An LMSR market has 4 outcomes and a liquidity parameter $b = 200$. Compute the maximum loss for the market maker. If the market is currently in a state where $\mathbf{q} = (100, 50, 30, 20)$, what is the current cost function value? How much of the maximum loss has been "used up" so far?

B.4 ⭐⭐⭐ Position P&L

Alice bought 50 shares of outcome "Yes" in an LMSR market (b=100, binary). Her trades were: - 20 shares when the price was at 0.45 (cost: $9.58) - 30 shares when the price was at 0.55 (cost: $17.39)

The current price of "Yes" is 0.70. Calculate: 1. Alice's average cost per share. 2. Her unrealized profit/loss. 3. Her return on investment (ROI).

B.5 ⭐⭐⭐ Spread and Slippage

In an order book market, the best bid is $0.60 (quantity 10) and the best ask is $0.65 (quantity 10). The next ask is $0.70 (quantity 20).

  1. What is the quoted spread?
  2. If a trader submits a market buy order for 5 shares, what is their execution price and slippage relative to the midpoint?
  3. If a trader submits a market buy order for 15 shares, what is their volume-weighted average price (VWAP)?

Part C: Programming Exercises (8 problems)

Extend the markets router to support searching markets by title keyword. Add a search query parameter to the GET /api/v1/markets endpoint that filters markets whose title contains the search string (case-insensitive).

# Starter code
@router.get("/", response_model=list[MarketResponse])
async def list_markets(
    status: Optional[str] = None,
    search: Optional[str] = None,  # Add this
    skip: int = 0,
    limit: int = 20,
    db: Session = Depends(get_db),
):
    # Your implementation here
    pass

C.2 ⭐⭐ Implement Order Book Depth Chart Data

Write a function that returns data suitable for rendering a depth chart. The function should return cumulative bid and ask quantities at each price level.

def get_depth_chart_data(
    order_book: OrderBook, outcome_id: int
) -> dict[str, list[tuple[float, float]]]:
    """Return cumulative depth chart data.

    Args:
        order_book: The order book instance.
        outcome_id: The outcome to chart.

    Returns:
        Dictionary with 'bids' and 'asks', each a list of
        (price, cumulative_quantity) tuples sorted appropriately.
    """
    # Your implementation here
    pass

C.3 ⭐⭐ Add Trade History Endpoint

Implement a GET /api/v1/markets/{market_id}/trades endpoint that returns the recent trade history for a specific market. Support pagination and a since parameter that filters trades after a given timestamp.

C.4 ⭐⭐ Implement LMSR with Multiple Shares Purchase

Extend the LMSR implementation to support a buy_to_price method that calculates how many shares a trader needs to buy to move the price to a target level.

def buy_to_price(
    self, outcome_index: int, target_price: float
) -> tuple[float, float]:
    """Calculate shares needed to reach a target price.

    Args:
        outcome_index: The outcome to buy.
        target_price: The desired price (between 0 and 1).

    Returns:
        Tuple of (shares_needed, total_cost).
    """
    # Your implementation here
    pass

C.5 ⭐⭐⭐ Add Rate Limiting

Implement a simple rate limiter for the trading endpoint. Users should be limited to 10 orders per minute. Use an in-memory dictionary to track request counts per user. Return HTTP 429 (Too Many Requests) when the limit is exceeded.

from fastapi import Request
from collections import defaultdict
import time

# Your RateLimiter class and dependency here

C.6 ⭐⭐⭐ Implement Stop-Loss Orders

Extend the order book engine to support stop-loss orders. A stop-loss order becomes a market order when the price reaches a specified trigger price. Implement the StopOrder class and modify the OrderBook to monitor prices and trigger stops.

C.7 ⭐⭐⭐⭐ Build a Market Activity Feed

Create a WebSocket endpoint that streams market activity (new trades, price changes, order book updates) in real-time. Implement a publish-subscribe pattern where clients can subscribe to specific markets.

from fastapi import WebSocket, WebSocketDisconnect
from typing import Dict, Set

class MarketFeed:
    """Manages WebSocket connections for real-time market updates."""

    def __init__(self):
        self.connections: Dict[int, Set[WebSocket]] = defaultdict(set)

    async def subscribe(self, market_id: int, websocket: WebSocket):
        # Your implementation here
        pass

    async def broadcast(self, market_id: int, event: dict):
        # Your implementation here
        pass

C.8 ⭐⭐⭐⭐ Implement a Full Test Suite

Write a comprehensive test suite for the trading service that covers: - Placing a buy order on an LMSR market - Placing a sell order on an order book market - Attempting to place an order with insufficient balance - Cancelling an order - Verifying positions after a trade - Resolution and payout

Use pytest with fixtures for database setup and teardown. Create at least 8 test functions.


Part D: Analysis Problems (5 problems)

D.1 ⭐⭐ Latency Analysis

Our order book implementation uses Python's heapq module. Analyze the time complexity of the following operations: 1. Submitting a limit order (no match). 2. Submitting a market order that fills against a single resting order. 3. Cancelling an order. 4. Getting the best bid/ask.

For each operation, state the Big-O complexity and explain whether it would be acceptable for a platform handling 1,000 orders per second.

D.2 ⭐⭐ LMSR Sensitivity Analysis

Using the LMSR implementation from the chapter, create a table or chart showing how the cost of buying 10 shares of one outcome in a binary market varies as the current price of that outcome ranges from 0.1 to 0.9 (in steps of 0.1). Use $b = 100$. Explain the pattern you observe and its implications for trader behavior.

D.3 ⭐⭐⭐ Database Schema Critique

Review the database schema presented in the chapter. Identify at least three potential issues or improvements related to: 1. Data integrity constraints that are missing. 2. Performance optimizations (indexes, denormalization). 3. Audit trail completeness.

For each issue, propose a specific solution and explain the trade-off.

D.4 ⭐⭐⭐ Security Audit

Perform a security review of the authentication and trading code presented in the chapter. Identify at least five security vulnerabilities or weaknesses. For each, describe the potential attack vector and propose a mitigation.

D.5 ⭐⭐⭐⭐ Scalability Bottleneck Analysis

Our trading service uses in-memory dictionaries (_order_books and _lmsr_instances) to store engine state. Analyze what happens in the following scenarios: 1. The server process restarts. 2. Multiple server instances run behind a load balancer. 3. A market has 10,000 active orders.

For each scenario, describe the problem and propose an architectural solution.


Part E: Research Problems (4 problems)

E.1 ⭐⭐ Alternative AMMs

Research the Constant Product Market Maker (CPMM) used by Uniswap and compare it to the LMSR. Write a one-page summary covering: - How the CPMM cost function works. - Why it requires a liquidity pool instead of a subsidy. - Advantages and disadvantages compared to LMSR for prediction markets. - Whether CPMM prices can be interpreted as probabilities.

E.2 ⭐⭐⭐ Real-World Platform Architectures

Research the technical architecture of one of the following platforms: Polymarket, Kalshi, or Metaculus. Write a two-page analysis covering: - Their choice of pricing mechanism. - How they handle settlement and resolution. - Their technology stack (to the extent publicly known). - Key differences from our implementation and why those choices were made.

E.3 ⭐⭐⭐ Regulatory Considerations

Research the regulatory landscape for prediction markets in the United States as of 2025. Address: - Which agencies have jurisdiction (CFTC, SEC, state regulators). - The legal distinction between prediction markets and gambling. - How platforms like Kalshi obtained regulatory approval. - What technical requirements regulators impose (KYC, reporting, audit trails).

E.4 ⭐⭐⭐⭐ Sybil Resistance and Market Manipulation

Research techniques for preventing market manipulation on prediction market platforms. Focus on: - Sybil attacks (one person creating many accounts). - Wash trading (trading with yourself to inflate volume). - Information-based manipulation (placing large bets to mislead others).

For each attack type, describe a detection method and a prevention mechanism that could be implemented in our platform.