# Build a pricing function that says "not enough data" when it should (Node.js)

*Disclosure: we build CompsAPI, the sold-price API used in this tutorial. It was drafted with AI assistance, and the parameters and response fields were checked against CompsAPI's documentation. A free key needs no card.*

Most pricing code has one failure mode in common: it returns a number whether or not there is anything behind it. A median of two sales looks exactly like a median of two hundred, and nothing downstream can tell them apart.

This post builds a small Node.js function that returns one of four honest answers for a search: a price, a range, a direction, or "not enough data". It widens the date window before it ever loosens the query, and it flags the one spread pattern that makes a median misleading.

## What you need

- Node 18 or newer (it uses the built-in `fetch`, so nothing to install)
- A free CompsAPI key (100 requests a month, no card), saved as an environment variable:

```bash
export COMPSAPI_KEY="your-key-here"
```

## The rules it follows

These come from how thin markets behave, and they are worth writing down before any code:

1. **An empty 90-day window is a measurement problem, not a price signal.** Zero sales in 90 days means zero sales in 90 days. It says something about how often the item sells, not what it is worth.
2. **Widen the window before you loosen the query.** Keep every filter and go from 90 days to 365, then to 1,095. If you drop the grade from a card search or the model suffix from a lens search, you are pricing a different item.
3. **How thin is too thin** is a rule of thumb, not statistics: 0 to 2 clean sales is not a price, 3 to 7 is a direction (quote a range, never a figure), 8 to 20 is a usable median if the spread is tight, and 20 or more is a real distribution.
4. **A wide upper quartile is a warning.** If the 75th percentile sits several times above the median, the search may be mixing two markets, for example a machine and its manual.

## The function

Save this as `thin.mjs`:

```js
// thin.mjs: a price, a range, or "not enough data" for one eBay search
const KEY = process.env.COMPSAPI_KEY;
const BASE = process.env.COMPSAPI_BASE ?? "https://api.compsapi.com";
const QUERY = process.argv.slice(2).join(" ");
const WINDOWS = [90, 365, 1095]; // widen the window before you loosen the query
const ENOUGH = 8; // below this a median is a direction, not a figure
const TWO_MARKETS = 3; // my threshold: p75 this many times the median looks bimodal

if (!QUERY) {
  console.error('usage: node thin.mjs "item name"');
  process.exit(1);
}

async function statsFor(days) {
  const url = new URL("/v1/comps", BASE);
  url.search = new URLSearchParams({ q: QUERY, days: String(days), exclude: "ai_junk" });
  const res = await fetch(url, { headers: { "X-API-Key": KEY } });
  if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
  const data = await res.json();
  return data.stats ?? null;
}

function verdict(stats) {
  const n = stats?.used_for_stats ?? 0;
  if (n <= 2) return { kind: "none", n };
  const band = { p25: stats.p25, p75: stats.p75 };
  if (n < ENOUGH) return { kind: "direction", n, ...band };
  return {
    kind: n >= 20 ? "distribution" : "usable",
    n,
    median: stats.median,
    ...band,
    twoMarkets: stats.p75 / stats.median >= TWO_MARKETS,
  };
}

let result;
for (const days of WINDOWS) {
  result = { days, ...verdict(await statsFor(days)) };
  if (result.n >= ENOUGH) break;
}

const usd = (x) => `$${x.toFixed(2)}`;
const { kind, days, n } = result;
if (kind === "none") {
  console.log(`Not a price: ${n} clean sales in ${days} days. Step to a comparable item.`);
} else if (kind === "direction") {
  console.log(`A direction, not a figure: ${usd(result.p25)} to ${usd(result.p75)} from ${n} sales in ${days} days.`);
} else {
  console.log(`Median ${usd(result.median)}, band ${usd(result.p25)} to ${usd(result.p75)}, from ${n} sales in ${days} days.`);
  if (result.twoMarkets) console.log("Warning: the upper quartile is far above the median. Look for two markets mixed together.");
}
```

Run it with an item name:

```bash
node thin.mjs "panzer dragoon saga saturn"
```

## What each part does

- `/v1/comps` returns summary statistics for a search. The function reads `stats.used_for_stats` (the number of sales behind the numbers), `median`, `p25` and `p75`.
- `days` is the lookback. Every plan, including the free one, reads up to 1,095 days.
- `exclude=ai_junk` leaves out sales that an AI model labels as lots, parts, accessories, empty boxes and the like, so the count reflects the item, not the pile of add-ons around it.
- **The loop** tries 90, 365 and 1,095 days and stops at the first window with at least 8 clean sales. It never changes the query.
- `twoMarkets` is my own rule, not something the API reports: when the 75th percentile is three or more times the median, the function says so. It is a prompt to look at the cheap rows, not a verdict.

## Why the spread check exists

In a ten-item estate lot priced from completed sales, a Singer Featherweight sewing machine had a median of $39.99 but a 75th percentile of $237.50. The cheap end was a record book, a bobbin and an instruction manual, all titled with the machine's name. Every automatic check passed, because the search returned 152 sales. A count alone cannot catch that. A spread ratio can at least point at it.

## What it costs

At most 3 requests per item, because the loop stops as soon as a window has enough sales. On the free plan (100 requests a month, 10 a minute) that is at least 33 items a month.

## Limits to know about

- **The thresholds are rules of thumb.** 8 and 20 come from a published rule of thumb, and the 3x spread ratio is mine. Tune them for your own category.
- **A match is not a model.** The AI filter removes things that are not a single normal item. It does not check that what is left is the exact model you searched for, and on eBay it agreed with CompsAPI's own labels on about 92% of 690 test listings.
- **Gross prices only.** These are sold prices before fees and shipping.
- **Accepted offers:** prices on accepted Best Offer sales are the amount actually paid, not the asking price that eBay's public page shows.
- **I have not run this script.** It follows the documented parameters and response fields, but it has not been run against a live key or a test server. Treat it as a starting point and check it on an item you know first.

CompsAPI is not affiliated with eBay.

## Get a key

A free key is enough to try this on a few items you know well: [get one here](https://compsapi.com/?utm_source=hashnode&utm_medium=article&utm_campaign=thin-market-pricing). If it returns something that looks wrong, tell us in the comments and we'll look.
