🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101

Zerodha clone: stock trading app (paper trading)

A Kite-style trading app with virtual money: live-updating watchlist, candlestick charts, market and limit orders, holdings with average price and P&L. No real money and no real exchange.

Advanced⏱ 30–40 hours★ 10 detailed steps with codeNode.jsTypeScriptWebSocketPostgreSQLReactlightweight-charts

Educational project inspired by Zerodha Kite. Skills101 is not affiliated with Zerodha Kite. Give your app its own name and logo, and do not copy their branding or content.

What you’ll learn

  • ◆Streaming prices over WebSockets to many clients
  • ◆Order execution inside database transactions (funds, holdings, ledger)
  • ◆A small matching engine for limit orders
  • ◆Average price, realised and unrealised P&L

What you’ll build

  • ✓₹1,00,000 virtual funds on sign-up
  • ✓Watchlist with prices flashing green/red every second
  • ✓Market and limit orders, order book and cancel
  • ✓Holdings, P&L and candlestick charts

Before you start

What you need

  • •JavaScript/TypeScript, React and SQL basics.
  • •Node.js 20+ and PostgreSQL (or Docker).
  • •Understand this is paper trading for learning. Do not scrape NSE/BSE websites for prices (their terms forbid it); this guide simulates prices, which is also better for testing.

How it fits together

  1. 1Price simulator (Node) creates a new price per symbol every second and builds 1-minute candles.
  2. 2A WebSocket server sends each client only the symbols in their watchlist.
  3. 3Orders go to the API, which checks funds or holdings and executes inside a PostgreSQL transaction.
  4. 4Open limit orders are kept in memory per symbol and checked on every tick by a small matching engine.

Project structure

folders
papertrade/
├─ server/
│  ├─ market.ts        # price simulator + candles
│  ├─ ws.ts            # WebSocket subscriptions
│  ├─ orders.ts        # place / execute / cancel
│  ├─ matcher.ts       # limit order matching
│  └─ schema.sql
└─ web/ (React + Vite)
   ├─ Watchlist.tsx, OrderWindow.tsx
   ├─ Chart.tsx, Holdings.tsx, Orders.tsx
   └─ usePrices.ts

Step-by-step guide

  1. Step 1

    Plan the app and the rules of the game

    Goal: A clear v1, the trading rules you will support, and a visible “paper trading” label.

    v1: sign up with ₹1,00,000 virtual cash, a watchlist of 10–20 symbols, a chart, market and limit orders (buy and sell), order history, holdings and P&L. No short selling, no F&O, no margin in v1.

    Write the rules down: buys need enough available cash; sells need enough quantity in holdings; prices move in ticks of ₹0.05; a market order fills at the current price; a buy limit fills when price ≤ limit, a sell limit when price ≥ limit.

    Name it yourself (“PaperTrade”). Show “Virtual money. Not investment advice.” on every screen, and add “Educational project inspired by Zerodha Kite. Not affiliated.” to the README.

    ✅ Check it works

    You can answer: “What happens if I place a sell limit at ₹105 when the price is ₹100?” (It waits until price reaches ₹105.)

  2. Step 2

    Simulate realistic prices and candles

    Goal: Prices for each symbol that move every second, plus 1-minute OHLC candles.

    Real prices are roughly a random walk where changes are proportional to the price. The standard model is geometric Brownian motion (GBM): each step multiplies the price by e^(drift + volatility × random normal number). Box–Muller turns two uniform random numbers into a normal one.

    Round to the ₹0.05 tick size. Give each symbol its own starting price and volatility (a bank stock moves less than a small-cap). For demos, raise volatility so the chart visibly moves.

    Candles: for each tick, find its minute (Math.floor(ms / 60000)). New minute → new candle with open = high = low = close = price; same minute → update high, low and close.

    server/market.ts
    function randn() {                       // Box–Muller: standard normal number
      let u = 0, v = 0
      while (u === 0) u = Math.random()
      while (v === 0) v = Math.random()
      return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v)
    }
    
    const DT = 1 / (252 * 6.25 * 3600)        // one second as a fraction of a trading year
    
    export function nextPrice(p: number, sigma = 0.3, mu = 0.08) {
      const next = p * Math.exp((mu - (sigma * sigma) / 2) * DT + sigma * Math.sqrt(DT) * randn())
      return Math.max(0.05, Math.round(next * 20) / 20)   // ₹0.05 ticks
    }
    
    type Candle = { time: number; open: number; high: number; low: number; close: number }
    export function addTick(candles: Candle[], ms: number, price: number) {
      const time = Math.floor(ms / 60000) * 60       // chart libraries use seconds
      const last = candles[candles.length - 1]
      if (!last || last.time !== time) candles.push({ time, open: price, high: price, low: price, close: price })
      else { last.high = Math.max(last.high, price); last.low = Math.min(last.low, price); last.close = price }
      if (candles.length > 600) candles.shift()      // keep 10 hours in memory
    }

    ✅ Check it works

    Log 60 ticks for one symbol: prices change by small amounts, always end in .00 or .05, and one candle is produced per minute.

  3. Step 3

    Stream prices over WebSockets

    Goal: Each browser receives only its watchlist symbols, once a second, in one small message.

    Use the ws package. Each connection keeps a Set of subscribed symbols. The client sends {"type":"subscribe","symbols":["INFY","TCS"]}; validate symbols against your list and cap at 50.

    Every second, after the simulator updates all prices, send each client one batched message with just their symbols. One message per second is much cheaper than one per symbol per tick.

    Use heartbeats: ping every 30 seconds and terminate connections that do not answer, or dead connections pile up and waste memory.

    server/ws.ts
    import { WebSocketServer, WebSocket } from 'ws'
    
    const wss = new WebSocketServer({ port: 8081 })
    const subs = new Map<WebSocket, Set<string>>()
    
    wss.on('connection', (ws) => {
      subs.set(ws, new Set())
      ws.on('message', (raw) => {
        try {
          const msg = JSON.parse(String(raw))
          if (msg.type === 'subscribe' && Array.isArray(msg.symbols)) {
            subs.set(ws, new Set(msg.symbols.filter((s: string) => SYMBOLS.has(s)).slice(0, 50)))
          }
        } catch { /* ignore bad messages */ }
      })
      ws.on('close', () => subs.delete(ws))
    })
    
    export function broadcast(prices: Map<string, number>) {   // called once a second
      for (const [ws, symbols] of subs) {
        if (ws.readyState !== WebSocket.OPEN || symbols.size === 0) continue
        const batch: Record<string, number> = {}
        for (const s of symbols) batch[s] = prices.get(s)!
        ws.send(JSON.stringify({ type: 'ticks', at: Date.now(), prices: batch }))
      }
    }

    ✅ Check it works

    Two browser tabs with different watchlists each receive only their own symbols (check the WS frames in DevTools → Network).

  4. Step 4

    Build the watchlist that flashes green and red

    Goal: A watchlist that updates every second without re-rendering the whole page.

    Keep the latest prices in a small store outside React (a Map plus a list of listeners) and subscribe with useSyncExternalStore. Each row subscribes to its own symbol, so only changed rows re-render.

    Remember the previous price per row. If the new price is higher, add a green flash class for 300 ms; if lower, red. Show change and % change from the day's open price.

    Reconnect automatically if the socket closes (wait 1, 2, 4… seconds, up to 30) and resubscribe.

    web/src/usePrices.ts
    import { useSyncExternalStore } from 'react'
    
    const prices = new Map<string, number>()
    const listeners = new Set<() => void>()
    
    export function applyTicks(batch: Record<string, number>) {
      for (const [s, p] of Object.entries(batch)) prices.set(s, p)
      listeners.forEach((l) => l())
    }
    
    export function usePrice(symbol: string) {
      return useSyncExternalStore(
        (cb) => { listeners.add(cb); return () => listeners.delete(cb) },
        () => prices.get(symbol),
      )
    }

    ✅ Check it works

    With React DevTools “Highlight updates”, only the price cells flash, not the whole page.

  5. Step 5

    Design accounts, holdings and the ledger

    Goal: Tables that keep money and shares correct, with a full history of every change.

    Store money in paise as BIGINT. accounts has cash_paise and blocked_paise (cash reserved for open buy limit orders). Available cash = cash − blocked.

    holdings(user_id, symbol, qty, avg_paise) with a primary key on (user_id, symbol). Average price changes only on buys: new average = (old qty × old avg + new qty × price) / (old qty + new qty). Sells do not change the average; realised P&L = (sell price − avg) × qty.

    Every change to cash also inserts a ledger row (user, amount, reason, order id). If a balance ever looks wrong, the ledger explains it, and SUM(amount) must equal the balance minus the starting ₹1,00,000.

    server/schema.sql
    CREATE TABLE accounts (
      user_id       TEXT PRIMARY KEY,
      cash_paise    BIGINT NOT NULL DEFAULT 10000000 CHECK (cash_paise >= 0),   -- ₹1,00,000
      blocked_paise BIGINT NOT NULL DEFAULT 0 CHECK (blocked_paise >= 0)
    );
    CREATE TABLE holdings (
      user_id   TEXT   NOT NULL,
      symbol    TEXT   NOT NULL,
      qty       INT    NOT NULL CHECK (qty >= 0),
      avg_paise BIGINT NOT NULL,
      PRIMARY KEY (user_id, symbol)
    );
    CREATE TABLE orders (
      id          BIGSERIAL PRIMARY KEY,
      user_id     TEXT NOT NULL,
      symbol      TEXT NOT NULL,
      side        TEXT NOT NULL CHECK (side IN ('BUY', 'SELL')),
      type        TEXT NOT NULL CHECK (type IN ('MARKET', 'LIMIT')),
      qty         INT  NOT NULL CHECK (qty > 0),
      limit_paise BIGINT,
      status      TEXT NOT NULL DEFAULT 'OPEN',      -- OPEN | EXECUTED | CANCELLED | REJECTED
      fill_paise  BIGINT,
      created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
    );
    CREATE TABLE ledger (
      id           BIGSERIAL PRIMARY KEY,
      user_id      TEXT   NOT NULL,
      amount_paise BIGINT NOT NULL,                  -- negative for buys
      reason       TEXT   NOT NULL,
      order_id     BIGINT REFERENCES orders(id),
      created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
    );

    ✅ Check it works

    Buy 10 at ₹100 then 10 at ₹110: holdings show 20 shares at ₹105 average.

  6. Step 6

    Execute orders inside a transaction

    Goal: Market orders fill instantly and can never spend money you do not have or sell shares you do not own.

    Lock the user's account row with SELECT … FOR UPDATE at the start of the transaction. Two orders from the same user (two tabs, or a double click) then run one after the other, so both cannot spend the same cash.

    Buy: check available cash ≥ price × qty, subtract cash, upsert the holding with the new average, write the ledger row, mark the order EXECUTED. Sell: lock the holding row, check qty, add cash, reduce qty (delete the row at 0), write the ledger with realised P&L.

    If any check fails, ROLLBACK and mark the order REJECTED with a reason the UI can show (“Insufficient funds: need ₹12,450, available ₹9,800”).

    server/orders.ts (buy path)
    export async function executeBuy(client: PoolClient, o: Order, pricePaise: number) {
      const cost = pricePaise * o.qty
      const acc = (await client.query(
        'SELECT cash_paise, blocked_paise FROM accounts WHERE user_id = $1 FOR UPDATE', [o.user_id])).rows[0]
      const reserved = o.type === 'LIMIT' ? o.limit_paise * o.qty : 0    // this order's own block
      if (acc.cash_paise - acc.blocked_paise + reserved < cost) throw new Rejected('Insufficient funds')
    
      await client.query('UPDATE accounts SET cash_paise = cash_paise - $2, blocked_paise = blocked_paise - $3 WHERE user_id = $1',
        [o.user_id, cost, reserved])
      await client.query(
        'INSERT INTO holdings (user_id, symbol, qty, avg_paise) VALUES ($1, $2, $3, $4) ' +
        'ON CONFLICT (user_id, symbol) DO UPDATE SET ' +
        'avg_paise = (holdings.qty * holdings.avg_paise + EXCLUDED.qty * EXCLUDED.avg_paise) / (holdings.qty + EXCLUDED.qty), ' +
        'qty = holdings.qty + EXCLUDED.qty',
        [o.user_id, o.symbol, o.qty, pricePaise])
      await client.query('INSERT INTO ledger (user_id, amount_paise, reason, order_id) VALUES ($1, $2, $3, $4)',
        [o.user_id, -cost, 'BUY ' + o.qty + ' ' + o.symbol, o.id])
      await client.query("UPDATE orders SET status = 'EXECUTED', fill_paise = $2 WHERE id = $1", [o.id, pricePaise])
    }

    ✅ Check it works

    Fire 5 market buys of ₹30,000 each at the same time from a script: exactly 3 execute, 2 are rejected, cash never goes negative.

    ⚠️ Common mistakes

    • Reading the balance without FOR UPDATE: concurrent orders both pass the funds check.
  7. Step 7

    Match limit orders on every tick

    Goal: Limit orders sit OPEN, block funds, and fill automatically when the price crosses the limit.

    Placing a buy limit blocks limit × qty of cash (increase blocked_paise), so the same money cannot be used twice while the order waits. Cancelling releases the block.

    Keep open limit orders in memory, grouped by symbol (load them from the database when the server starts). On each tick, find orders whose condition is now true and execute them at the current price, which is equal to or better than the limit.

    Make execution idempotent: inside the transaction, first run UPDATE orders SET status = 'EXECUTING' WHERE id = $1 AND status = 'OPEN'. If it updated 0 rows, the order was cancelled or already filled, so skip it.

    server/matcher.ts
    const open = new Map<string, Order[]>()          // symbol -> open limit orders
    
    export function onTick(symbol: string, pricePaise: number) {
      const list = open.get(symbol)
      if (!list?.length) return
      const ready = list.filter((o) =>
        (o.side === 'BUY' && pricePaise <= o.limit_paise) ||
        (o.side === 'SELL' && pricePaise >= o.limit_paise))
      if (!ready.length) return
      open.set(symbol, list.filter((o) => !ready.includes(o)))
      for (const o of ready) {
        fill(o, pricePaise).catch((err) => console.error('fill failed', o.id, err))   // runs the transaction from step 6
      }
    }

    ✅ Check it works

    Place a buy limit ₹1 below the current price: funds are blocked immediately, and the order fills (and unblocks) once the simulated price drops to it.

  8. Step 8

    Show holdings, P&L and order history

    Goal: A portfolio screen that updates live with current value and profit or loss.

    For each holding: invested = qty × avg, current = qty × last price, P&L = current − invested, P&L % = P&L ÷ invested. Day change uses the day's opening price. Totals at the top, coloured green or red.

    Holdings come from the API once; live prices come from the price store (step 4), so the P&L updates every second without refetching.

    Orders tab: open orders with a Cancel button, then executed, cancelled and rejected orders with time, price and reason. Add a CSV download of the ledger as a simple “contract note”.

    ✅ Check it works

    Your totals match a manual calculation in a spreadsheet for 3 holdings.

  9. Step 9

    Draw candlestick charts

    Goal: A chart per symbol with history and a live-updating last candle.

    TradingView's open-source lightweight-charts library is small and fast. Install a fixed version (npm i lightweight-charts@4); the API below is version 4 (version 5 uses chart.addSeries(CandlestickSeries) instead).

    Load history from GET /api/candles/INFY and call setData. Then, on each tick for that symbol, send the current candle and call series.update(candle); it updates the last bar or appends a new one when the minute changes.

    Times must be in seconds (UTC timestamps), not milliseconds, which is why step 2 divides by 1000.

    web/src/Chart.tsx
    import { createChart, type IChartApi, type ISeriesApi } from 'lightweight-charts'
    import { useEffect, useRef } from 'react'
    
    export function Chart({ symbol, onCandle }: { symbol: string; onCandle: (cb: (c: any) => void) => () => void }) {
      const box = useRef<HTMLDivElement>(null)
      useEffect(() => {
        const chart: IChartApi = createChart(box.current!, { height: 360, autoSize: true })
        const series: ISeriesApi<'Candlestick'> = chart.addCandlestickSeries()
        fetch('/api/candles/' + symbol).then((r) => r.json()).then((data) => series.setData(data))
        const stop = onCandle((c) => series.update(c))
        return () => { stop(); chart.remove() }
      }, [symbol, onCandle])
      return <div ref={box} className="w-full" />
    }

    ✅ Check it works

    Leave the chart open for 3 minutes: the last candle moves every second and a new candle appears each minute.

  10. Step 10

    Deploy with clear disclaimers and present it

    Goal: A live app, a README with the execution rules, and a demo video.

    Deploy the Node server (HTTP API + WebSocket) behind Nginx with HTTPS (use wss://), PostgreSQL on a managed free tier, and the React build as static files.

    README: architecture diagram, the GBM formula, the order rules table, how funds blocking and FOR UPDATE prevent double spending, and a test showing concurrent orders. Add the paper-trading and not-affiliated notes.

    Demo: place a market buy, a limit buy that fills a minute later, a sell with realised P&L, and show the ledger matching the balance.

    ✅ Check it works

    A friend can sign up, trade for 10 minutes and their ledger sum matches their cash change exactly.

🚀 Make it stand out

  • +Stop-loss and GTT orders
  • +Leaderboard of returns among friends (weekly reset)
  • +Replay real historical end-of-day data from a properly licensed free dataset
  • +Simple brokerage and tax charges on each trade