From 3288f27e37cb60095c9ff39f1b63218d5fd1b5f8 Mon Sep 17 00:00:00 2001 From: Femi John Date: Thu, 25 Jun 2026 14:09:30 +0100 Subject: [PATCH] feat: add GET /spreads/:asset route to calculate bid-ask spreads for given assets --- src/routes/spreads.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/routes/spreads.ts diff --git a/src/routes/spreads.ts b/src/routes/spreads.ts new file mode 100644 index 0000000..b1c92d7 --- /dev/null +++ b/src/routes/spreads.ts @@ -0,0 +1,32 @@ +import type { FastifyInstance } from 'fastify'; +import { pgPool } from '../db'; + +/** + * GET /spreads/:asset - Return current bid, ask, and spread (bps) for the given asset. + * The bid is taken as the highest price among price points where the asset appears. + * The ask is the lowest price among those points. + * Spread basis points = ((ask - bid) / ask) * 10_000. + */ +export async function registerSpreadsRoutes(app: FastifyInstance) { + app.get('/spreads/:asset', async (req, reply) => { + const { asset } = req.params as { asset: string }; + if (!asset) { + return reply.status(400).send({ error: 'Asset parameter is required' }); + } + + const result = await pgPool.query( + `SELECT MAX(price::numeric) AS bid, MIN(price::numeric) AS ask + FROM price_points + WHERE assetA = $1 OR assetB = $1`, + [asset] + ); + const row = result.rows[0]; + const bid = row.bid !== null ? parseFloat(row.bid) : null; + const ask = row.ask !== null ? parseFloat(row.ask) : null; + let spreadBps: number | null = null; + if (bid !== null && ask !== null && ask !== 0) { + spreadBps = ((ask - bid) / ask) * 10_000; + } + return { asset, bid, ask, spreadBps }; + }); +}