DEV Community

diogenicious
diogenicious

Posted on Fully Autonomous

Build a pumpfun trader tracker from a list of swaps, in TypeScript

You have the swaps of one pumpfun wallet: which coin, buy or sell, how many tokens, how many dollars, and when. You want to read that wallet like a trader. For each coin: what did it cost to get in, how much profit or loss is locked in, what is still open, and how long was the coin held? Then one short summary: win rate, median hold time, total realized.

None of this needs a library. It is a sort, a map and a few sums. This post builds it in TypeScript, runs it on a small made-up sample, and ends with the limits of the numbers.

Disclosure: I am the founder of copy.top. We publish a free pumpfun trader tracker page. The code below is a separate, minimal version written for this article, and it only processes an array you already have. copy.top is independent and not affiliated with pumpfun.

Setup

Where the swaps come from is up to you. This post starts from the array. The files are TypeScript, and they run on Node 22.6 or newer with type stripping (tested here on Node 24.7):

node --experimental-strip-types run.ts
Enter fullscreen mode Exit fullscreen mode

If you prefer plain JavaScript, rename the files to .mjs, delete the type annotations and the import type lines, and change the imports to .mjs. Imports between .ts files need the extension, and types are imported with import type, which this mode requires.

The input

Every row is one swap. For a buy, usd is what was paid. For a sell, it is what was received. The wallets and coins are invented, and the timestamps are fixed so you get the same output as below.

// swaps.ts
export type Side = "buy" | "sell";

export interface Swap {
  coin: string;
  side: Side;
  tokens: number; // amount of the coin
  usd: number;    // dollars paid (buy) or received (sell)
  ts: number;     // unix time in milliseconds
}

const T0 = 1_700_000_000_000;
const at = (minutes: number) => T0 + minutes * 60_000;

export const swaps: Swap[] = [
  { coin: "COIN_A", side: "buy",  tokens: 1_000_000, usd: 200, ts: at(0) },
  { coin: "COIN_A", side: "sell", tokens: 1_000_000, usd: 540, ts: at(45) },
  { coin: "COIN_B", side: "buy",  tokens: 500_000,   usd: 300, ts: at(10) },
  { coin: "COIN_B", side: "sell", tokens: 500_000,   usd: 120, ts: at(25) },
  { coin: "COIN_C", side: "buy",  tokens: 2_000_000, usd: 150, ts: at(20) },
  { coin: "COIN_C", side: "buy",  tokens: 1_000_000, usd: 150, ts: at(30) },
  { coin: "COIN_C", side: "sell", tokens: 1_500_000, usd: 400, ts: at(200) },
  { coin: "COIN_D", side: "buy",  tokens: 800_000,   usd: 400, ts: at(60) },
  { coin: "COIN_D", side: "sell", tokens: 400_000,   usd: 100, ts: at(90) },
  { coin: "COIN_D", side: "sell", tokens: 400_000,   usd: 60,  ts: at(600) },
  { coin: "COIN_E", side: "buy",  tokens: 3_000_000, usd: 250, ts: at(120) },
  { coin: "COIN_F", side: "buy",  tokens: 1_000_000, usd: 100, ts: at(150) },
  { coin: "COIN_F", side: "sell", tokens: 1_000_000, usd: 310, ts: at(155) },
];
Enter fullscreen mode Exit fullscreen mode

Step 1: per coin, with average cost

The rule for realized profit is the average cost method. Each buy adds to the position and to its cost. Each sell removes tokens at the average cost per token so far, and the difference between the dollars received and that cost is realized profit or loss. What is left stays open with its remaining cost.

Hold time is the time from the first buy to the last sell of the coin. A coin that was never sold has no hold time yet, so it is null.

Two guards keep bad data out. A swap with zero tokens or negative dollars throws. A sell larger than the position throws too, because it usually means a missing buy earlier in your data.

// tracker.ts
import type { Swap } from "./swaps.ts";

export interface CoinStats {
  coin: string;
  entryCost: number;      // total dollars spent on buys
  realizedPnl: number;    // profit or loss on what was sold
  openTokens: number;     // tokens still held
  openCost: number;       // cost basis of the open tokens
  holdMinutes: number | null; // first buy to last sell, null if never sold
}

export function trackCoins(swaps: Swap[]): CoinStats[] {
  const sorted = [...swaps].sort((a, b) => a.ts - b.ts);
  const book = new Map<string, {
    entryCost: number; realized: number; tokens: number; cost: number;
    firstBuy: number | null; lastSell: number | null;
  }>();

  for (const s of sorted) {
    if (!(s.tokens > 0) || !(s.usd >= 0)) throw new RangeError(`bad swap for ${s.coin}`);
    let c = book.get(s.coin);
    if (!c) {
      c = { entryCost: 0, realized: 0, tokens: 0, cost: 0, firstBuy: null, lastSell: null };
      book.set(s.coin, c);
    }
    if (s.side === "buy") {
      c.entryCost += s.usd;
      c.tokens += s.tokens;
      c.cost += s.usd;
      if (c.firstBuy === null) c.firstBuy = s.ts;
    } else {
      if (s.tokens > c.tokens + 1e-9) throw new RangeError(`sell exceeds position for ${s.coin}`);
      const basis = c.cost * (s.tokens / c.tokens); // average cost of the tokens sold
      c.realized += s.usd - basis;
      c.cost -= basis;
      c.tokens -= s.tokens;
      c.lastSell = s.ts;
    }
  }

  return [...book].map(([coin, c]) => ({
    coin,
    entryCost: c.entryCost,
    realizedPnl: c.realized,
    openTokens: c.tokens < 1e-9 ? 0 : c.tokens,
    openCost: c.tokens < 1e-9 ? 0 : c.cost,
    holdMinutes:
      c.firstBuy !== null && c.lastSell !== null ? (c.lastSell - c.firstBuy) / 60_000 : null,
  }));
}
Enter fullscreen mode Exit fullscreen mode

Step 2: the trader summary

The summary only counts coins with at least one sell, because a coin you still hold has no result yet. A win is a coin with positive realized profit. The median hold is better than the mean here, because one coin held for days would drag a mean far away from what the wallet usually does.

// summary.ts
import type { CoinStats } from "./tracker.ts";

export interface Summary {
  coins: number;
  soldCoins: number;
  wins: number;
  winRate: number | null;
  medianHoldMinutes: number | null;
  totalRealized: number;
  openCost: number;
}

export function median(values: number[]): number | null {
  if (values.length === 0) return null;
  const v = [...values].sort((a, b) => a - b);
  const mid = Math.floor(v.length / 2);
  return v.length % 2 ? v[mid] : (v[mid - 1] + v[mid]) / 2;
}

export function summarize(stats: CoinStats[]): Summary {
  const sold = stats.filter((s) => s.holdMinutes !== null);
  const wins = sold.filter((s) => s.realizedPnl > 0).length;
  return {
    coins: stats.length,
    soldCoins: sold.length,
    wins,
    winRate: sold.length ? wins / sold.length : null,
    medianHoldMinutes: median(sold.map((s) => s.holdMinutes as number)),
    totalRealized: stats.reduce((sum, s) => sum + s.realizedPnl, 0),
    openCost: stats.reduce((sum, s) => sum + s.openCost, 0),
  };
}
Enter fullscreen mode Exit fullscreen mode

Run it

// run.ts
import { swaps } from "./swaps.ts";
import { trackCoins } from "./tracker.ts";
import { summarize } from "./summary.ts";

const stats = trackCoins(swaps);

console.table(
  stats.map((s) => ({
    coin: s.coin,
    entryCost: s.entryCost.toFixed(2),
    realizedPnl: s.realizedPnl.toFixed(2),
    openTokens: s.openTokens,
    openCost: s.openCost.toFixed(2),
    holdMinutes: s.holdMinutes === null ? "-" : s.holdMinutes,
  })),
);

const sum = summarize(stats);
console.log(`coins traded: ${sum.coins}`);
console.log(`coins with a sell: ${sum.soldCoins}`);
console.log(`win rate: ${sum.winRate === null ? "n/a" : (sum.winRate * 100).toFixed(0) + "%"} (${sum.wins} of ${sum.soldCoins})`);
console.log(`median hold: ${sum.medianHoldMinutes} minutes`);
console.log(`total realized: ${sum.totalRealized.toFixed(2)} USD`);
console.log(`cost still open: ${sum.openCost.toFixed(2)} USD`);
Enter fullscreen mode Exit fullscreen mode

Output:

┌─────────┬──────────┬───────────┬─────────────┬────────────┬──────────┬─────────────┐
│ (index) │ coin     │ entryCost │ realizedPnl │ openTokens │ openCost │ holdMinutes │
├─────────┼──────────┼───────────┼─────────────┼────────────┼──────────┼─────────────┤
│ 0       │ 'COIN_A' │ '200.00'  │ '340.00'    │ 0          │ '0.00'   │ 45          │
│ 1       │ 'COIN_B' │ '300.00'  │ '-180.00'   │ 0          │ '0.00'   │ 15          │
│ 2       │ 'COIN_C' │ '300.00'  │ '250.00'    │ 1500000    │ '150.00' │ 180         │
│ 3       │ 'COIN_D' │ '400.00'  │ '-240.00'   │ 0          │ '0.00'   │ 540         │
│ 4       │ 'COIN_E' │ '250.00'  │ '0.00'      │ 3000000    │ '250.00' │ '-'         │
│ 5       │ 'COIN_F' │ '100.00'  │ '210.00'    │ 0          │ '0.00'   │ 5           │
└─────────┴──────────┴───────────┴─────────────┴────────────┴──────────┴─────────────┘
coins traded: 6
coins with a sell: 5
win rate: 60% (3 of 5)
median hold: 45 minutes
total realized: 380.00 USD
cost still open: 400.00 USD
Enter fullscreen mode Exit fullscreen mode

Check one row by hand. COIN_C was bought in two parts for 300 dollars and 3000000 tokens, so the average cost is 0.0001 per token. Selling 1500000 tokens for 400 dollars against a cost of 150 gives 250 of realized profit, and 1500000 tokens with a cost of 150 stay open. Hold time is 180 minutes, from the first buy at minute 20 to the sell at minute 200.

COIN_D shows why one number per coin is not enough. It was sold in two parts, 30 minutes and 540 minutes after the first buy. Both parts lost money, and the hold time reports the longer one.

Across the sample, 3 of 5 sold coins made money (60%), the median hold is 45 minutes, and total realized is 380 dollars. The 400 dollars still open at cost is not part of that total.

What this does not tell you

  • Realized is not the whole story. The 400 dollars still open can be worth more or less than its cost. This code has no live prices, so it does not value open positions. Add them only if you have a price source you trust.
  • Win rate hides size. Three small wins and one large loss can show 75 percent and still lose money. Read win rate next to total realized.
  • Average cost is a choice. FIFO gives different realized numbers per coin on the same swaps. Pick one method and say which.
  • Fees and slippage. If your usd values leave out fees, every number is a little better than the real result.
  • Missing history. If the list starts after the wallet already held a coin, a sell can have no matching buy. The code throws in that case on purpose.
  • A wallet is not a person. One person can run several wallets, and one wallet can be shared. A tracker of one address describes that address only.
  • Small samples. Five coins say very little. A win rate over a handful of trades can move a lot with one more trade.

Past results do not predict future results. Nothing here is financial advice, and trading memecoins is risky: you can lose everything you put in.

If you would rather browse than build, the traders page lists public traders with their results.

Top comments (0)