DEV Community

diogenicious
diogenicious

Posted on Fully Autonomous

Realized and unrealized PnL from a list of trades, in TypeScript

A trading history is a list of fills: buys and sells, each with a quantity, a price and a fee. From that list you want two numbers. Realized PnL is the profit or loss on what you already sold. Unrealized PnL is the profit or loss on what you still hold, valued at the current price.

The total is easy. The split between the two is not, because it depends on which coins you say you sold. This post computes both in TypeScript with two common methods, average cost and FIFO, and shows that they agree on the total and disagree on everything else.

Disclosure: I am the founder of copy.top. We publish a free crypto wallet tracker that shows realized PnL and open positions for public traders. The code below is a minimal version written for this article.

The input

type Side = "buy" | "sell";

interface Fill {
  side: Side;
  qty: number;   // coins bought or sold
  price: number; // price per coin
  fee?: number;  // fee paid on this fill, in the same currency as the price
}

const DUST = 1e-9; // below this, treat a quantity as zero

function check(f: Fill, n: number): number {
  if (!(f.qty > 0 && f.price > 0)) throw new RangeError(`fill ${n}: qty and price must be positive`);
  const fee = f.fee ?? 0;
  if (!(fee >= 0)) throw new RangeError(`fill ${n}: fee must be zero or more`);
  return fee;
}

interface Result {
  qty: number;       // coins still held
  costBasis: number; // what the coins still held cost, buy fees included
  realized: number;  // profit or loss on what was sold, fees included
  unrealizedAt: (price: number) => number;
}
Enter fullscreen mode Exit fullscreen mode

Fees are handled the same way in both methods: a buy fee is part of what the coins cost, and a sell fee comes out of what the sale brought in.

Method 1: average cost

Every coin you hold has the same cost: total cost divided by total coins. When you sell, you remove that average cost for each coin sold.

export function pnlAverageCost(fills: Fill[]): Result {
  let qty = 0;
  let cost = 0;
  let realized = 0;

  fills.forEach((f, n) => {
    const fee = check(f, n);
    if (f.side === "buy") {
      qty += f.qty;
      cost += f.qty * f.price + fee;
      return;
    }
    if (f.qty > qty + DUST) throw new RangeError(`fill ${n}: selling more than is held`);
    const sold = Math.min(f.qty, qty);
    const removed = (cost / qty) * sold; // average cost of the coins sold
    realized += sold * f.price - fee - removed;
    qty -= sold;
    cost -= removed;
    if (qty < DUST) { qty = 0; cost = 0; }
  });

  return { qty, costBasis: cost, realized, unrealizedAt: (p) => qty * p - cost };
}
Enter fullscreen mode Exit fullscreen mode

A sell never changes the average cost of the coins left. Only buys do.

Method 2: FIFO

First in, first out: each buy is a lot with its own cost, and a sell uses up the oldest lots first.

export function pnlFifo(fills: Fill[]): Result {
  const lots: { qty: number; unitCost: number }[] = [];
  let realized = 0;

  fills.forEach((f, n) => {
    const fee = check(f, n);
    if (f.side === "buy") {
      lots.push({ qty: f.qty, unitCost: (f.qty * f.price + fee) / f.qty });
      return;
    }
    const held = lots.reduce((s, l) => s + l.qty, 0);
    if (f.qty > held + DUST) throw new RangeError(`fill ${n}: selling more than is held`);

    let left = Math.min(f.qty, held);
    let removed = 0;
    while (left > DUST && lots.length > 0) {
      const lot = lots[0];
      const take = Math.min(left, lot.qty);
      removed += take * lot.unitCost;
      lot.qty -= take;
      left -= take;
      if (lot.qty < DUST) lots.shift(); // oldest lot used up
    }
    realized += f.qty * f.price - fee - removed;
  });

  const qty = lots.reduce((s, l) => s + l.qty, 0);
  const costBasis = lots.reduce((s, l) => s + l.qty * l.unitCost, 0);
  return { qty, costBasis, realized, unrealizedAt: (p) => qty * p - costBasis };
}
Enter fullscreen mode Exit fullscreen mode

Both functions throw when a sell is larger than what is held. Returning a negative position would hide a missing buy in the data, which is the most common reason a PnL looks wrong.

Same trades, two answers

const fills: Fill[] = [
  { side: "buy", qty: 1000, price: 0.1, fee: 1 },
  { side: "buy", qty: 1000, price: 0.2, fee: 2 },
  { side: "sell", qty: 1500, price: 0.25, fee: 3.75 },
];
Enter fullscreen mode Exit fullscreen mode

Valued at a current price of 0.12:

average cost FIFO
coins held 500 500
cost basis 75.75 101
realized 144 169.25
unrealized -15.75 -41
total 128.25 128.25

The total is the same, and it has to be: 303 went in, 371.25 came out of the sale, and the 500 coins left are worth 60. The methods only disagree on which coins were sold. FIFO says the cheap coins from the first buy went first, so more profit is realized and the coins left carry a higher cost.

Neither is wrong. What is wrong is comparing a realized PnL computed one way with another computed the other way, or switching methods halfway through a history.

Why realized PnL alone can mislead

A history where someone sells part of a winner and holds the rest after the price falls:

const h = pnlAverageCost([
  { side: "buy", qty: 1000, price: 1 },
  { side: "buy", qty: 1000, price: 1 },
  { side: "sell", qty: 500, price: 1.2 },
]);

h.realized;          // 100
h.unrealizedAt(0.4); // -900
Enter fullscreen mode Exit fullscreen mode

Realized PnL is positive. The account is down 800. Anyone can make realized PnL look good by selling what went up and holding what went down. When you read someone's results, look at the open positions too.

A note on floating point

const exit = pnlAverageCost([
  { side: "buy", qty: 0.1 + 0.2, price: 3 },
  { side: "sell", qty: 0.3, price: 4 },
]);

exit.qty;      // 0
exit.realized; // 0.30000000000000004
Enter fullscreen mode Exit fullscreen mode

0.1 + 0.2 is 0.30000000000000004, so selling 0.3 leaves a tiny leftover. Without the DUST check that leftover would stay in the position forever, with a cost attached. Real token amounts have many decimals, so this happens all the time. Round only for display.

What these numbers leave out

  • Unrealized PnL uses the current price. On a thin market you may not be able to sell at that price, so the real figure can be lower.
  • Network costs and slippage are only included if they are in the fees or the fill prices.
  • Tax rules decide which method you must use for taxes, and they differ by country. This post is about reading a history, not about tax.

If you want the numbers for a single trade with fees, there is a free crypto profit calculator, with no sign up. Nothing here is financial advice. Trading memecoins is risky, you can lose everything you put in.

Top comments (0)