# How to Track Real-Time Trader Activity on Solana

> A step-by-step guide to watching Solana wallets in real time, decoding their trades from token balance changes, and ranking top traders, with TypeScript code.

- Author: OnChain Team
- Published: 2026-10-18
- Page: https://www.onchain.ro/blog/solana-real-time-trader-activity

To track trader activity on Solana in real time, subscribe to the wallets you care about over a WebSocket, fetch each new transaction they sign, and work out what they traded from the difference between the token balances before and after the transaction. Aggregate those trades per wallet in a rolling window and you have a live "top traders" view. This guide builds that end to end in TypeScript, using only the standard Solana RPC.

## What you will build

- A watcher that gets notified within seconds when a tracked wallet signs a transaction.
- A decoder that turns a raw transaction into trades: which token, which direction, how much.
- A rolling 24-hour leaderboard per wallet.
- A small HTTP endpoint that streams new trades to a browser.

It works for a few dozen to a few hundred wallets. Past that, switch the ingestion step to a streaming source, covered at the end.

```diagram
title: How a wallet's transaction becomes a ranked trade
node wallets at 0,1 user "Tracked wallets" "Addresses you watch"
node ws at 1,1 external "logsSubscribe" "WebSocket ping per transaction"
node skip at 1,2.1 warn "Dropped" "Failed transactions"
node queue at 2,1 default "Fetch queue" "De-duplicated, rate-limited"
node rpc at 2,0 external "RPC node" "getTransaction"
node decode at 3,1 default "Decoder" "Balance deltas become trades"
node board at 4,0.5 store "Leaderboard" "Rolling 24-hour stats"
node sse at 4,1.5 default "SSE stream" "Pushes each new trade"
node browser at 5,1 user "Dashboard" "Live trades and rankings"
edge wallets -> ws "subscribe"
edge ws -> queue "signature"
edge ws -> skip "logs.err" fail
edge queue -> rpc "fetch"
edge rpc -> decode "parsed tx"
edge decode -> board
edge decode -> sse
edge board -> browser "/leaderboard" dashed
edge sse -> browser "/trades"
```

## Step 1: Set up the project

```bash
mkdir trader-activity && cd trader-activity
npm init -y
npm install @solana/web3.js
npm install -D typescript tsx @types/node
```

You need an RPC endpoint that supports both HTTP and WebSocket. The public endpoint is heavily rate-limited, so use a paid provider for anything beyond testing.

```bash
export RPC_HTTP="https://your-rpc-provider.example"
export RPC_WS="wss://your-rpc-provider.example"
```

This guide uses `@solana/web3.js` 1.x, which is still the most widely used client. The newer `@solana/kit` exposes the same RPC methods with a different API.

## Step 2: Subscribe to wallet activity

The [`logsSubscribe`](https://solana.com/docs/rpc/websocket/logssubscribe) RPC method notifies you whenever a transaction mentions a given address. In web3.js it is `connection.onLogs`.

```ts
// watcher.ts
import { Connection, PublicKey } from "@solana/web3.js";

export const connection = new Connection(process.env.RPC_HTTP!, {
  wsEndpoint: process.env.RPC_WS,
  commitment: "confirmed",
});

export type Seen = { signature: string; wallet: string; slot: number };

export function watchWallets(wallets: string[], onSeen: (s: Seen) => void) {
  const ids = wallets.map((wallet) =>
    connection.onLogs(
      new PublicKey(wallet),
      (logs, ctx) => {
        if (logs.err) return; // skip failed transactions
        onSeen({ signature: logs.signature, wallet, slot: ctx.slot });
      },
      "confirmed",
    ),
  );
  return () => ids.forEach((id) => connection.removeOnLogsListener(id));
}
```

Two things to know:

- **Commitment.** `confirmed` arrives fast and is almost always final. If you store data for accounting, re-check it at `finalized` later.
- **One subscription per wallet.** Providers cap the number of subscriptions per connection. Check yours before you add hundreds of wallets.

## Step 3: Fetch each transaction without hitting rate limits

A notification only gives you the signature. Fetch the full transaction with [`getTransaction`](https://solana.com/docs/rpc/http/gettransaction), through a small queue so bursts do not trip the rate limit.

```ts
// fetcher.ts
import type { ParsedTransactionWithMeta } from "@solana/web3.js";
import { connection, type Seen } from "./watcher";

const queue: Seen[] = [];
const seen = new Set<string>(); // the same tx can mention several tracked wallets

export function enqueue(item: Seen) {
  const key = `${item.signature}:${item.wallet}`;
  if (seen.has(key)) return;
  seen.add(key);
  queue.push(item);
}

export async function runFetcher(
  handle: (item: Seen, tx: ParsedTransactionWithMeta) => void,
  perSecond = 8,
) {
  for (;;) {
    const batch = queue.splice(0, perSecond);
    await Promise.all(
      batch.map(async (item) => {
        const tx = await connection.getParsedTransaction(item.signature, {
          maxSupportedTransactionVersion: 0, // required for versioned transactions
          commitment: "confirmed",
        });
        if (tx?.meta) handle(item, tx);
      }),
    );
    await new Promise((r) => setTimeout(r, 1000));
  }
}
```

Leave out `maxSupportedTransactionVersion` and the call fails for versioned transactions, which most DEX swaps now are. In production, also cap the size of `seen`, or keep it in Redis with an expiry.

## Step 4: Decode trades from balance changes

You do not need to understand every DEX program to see what a wallet traded. Each transaction's metadata contains the wallet's token balances before (`preTokenBalances`) and after (`postTokenBalances`), and its SOL balance in `preBalances` and `postBalances`. The differences tell you what went in and what came out.

```ts
// decode.ts
import type { ParsedTransactionWithMeta } from "@solana/web3.js";

export type Trade = {
  signature: string;
  wallet: string;
  time: number;
  side: "buy" | "sell";
  mint: string;
  amount: number; // token units, UI-adjusted
  solDelta: number; // SOL spent (negative) or received (positive)
};

const LAMPORTS = 1e9;

function tokenDeltas(tx: ParsedTransactionWithMeta, owner: string) {
  const deltas = new Map<string, number>();
  const add = (mint: string, v: number) =>
    deltas.set(mint, (deltas.get(mint) ?? 0) + v);
  for (const b of tx.meta!.preTokenBalances ?? []) {
    if (b.owner === owner) add(b.mint, -(b.uiTokenAmount.uiAmount ?? 0));
  }
  for (const b of tx.meta!.postTokenBalances ?? []) {
    if (b.owner === owner) add(b.mint, b.uiTokenAmount.uiAmount ?? 0);
  }
  return deltas;
}

export function decodeTrades(
  signature: string,
  wallet: string,
  tx: ParsedTransactionWithMeta,
): Trade[] {
  const keys = tx.transaction.message.accountKeys.map((k) => k.pubkey.toBase58());
  const i = keys.indexOf(wallet);
  if (i < 0) return [];
  const solDelta = (tx.meta!.postBalances[i] - tx.meta!.preBalances[i]) / LAMPORTS;

  const trades: Trade[] = [];
  for (const [mint, delta] of tokenDeltas(tx, wallet)) {
    if (Math.abs(delta) < 1e-12) continue;
    trades.push({
      signature,
      wallet,
      time: (tx.blockTime ?? Date.now() / 1000) * 1000,
      side: delta > 0 ? "buy" : "sell",
      mint,
      amount: Math.abs(delta),
      solDelta,
    });
  }
  return trades;
}
```

This is a heuristic, so be honest about its limits:

- SOL that the DEX wraps into WSOL shows up as a token balance change, not a SOL change. Treat the WSOL mint (`So11111111111111111111111111111111111111112`) as SOL when you price trades.
- `solDelta` includes the transaction fee and any tips, so small trades look slightly worse than they were.
- Transfers between a trader's own wallets look like a buy on one side and a sell on the other. Group known wallets together if that matters to you.

## Step 5: Keep a rolling leaderboard

Store every trade, then compute per-wallet stats over the last 24 hours. In production this is a database query. Here it is in memory so the logic is visible.

```ts
// leaderboard.ts
import type { Trade } from "./decode";

const DAY = 24 * 60 * 60 * 1000;
const trades: Trade[] = [];

export function record(t: Trade) {
  trades.push(t);
  const cutoff = Date.now() - DAY;
  while (trades.length && trades[0].time < cutoff) trades.shift();
}

export function leaderboard(limit = 20) {
  const byWallet = new Map<
    string,
    { wallet: string; trades: number; solFlow: number; tokens: Set<string> }
  >();
  for (const t of trades) {
    const row = byWallet.get(t.wallet) ?? {
      wallet: t.wallet,
      trades: 0,
      solFlow: 0,
      tokens: new Set(),
    };
    row.trades += 1;
    row.solFlow += t.solDelta;
    row.tokens.add(t.mint);
    byWallet.set(t.wallet, row);
  }
  return [...byWallet.values()]
    .map((r) => ({ ...r, tokens: r.tokens.size }))
    .sort((a, b) => b.trades - a.trades)
    .slice(0, limit);
}
```

Sorting by trade count is a neutral default. "Net SOL flow" is tempting as a profit proxy, but it ignores the value of tokens still held, so label it as flow, not profit.

## Step 6: Stream new trades to a browser

Server-Sent Events are enough for a one-way feed and need no extra library.

```ts
// server.ts
import http from "node:http";
import { watchWallets } from "./watcher";
import { enqueue, runFetcher } from "./fetcher";
import { decodeTrades } from "./decode";
import { record, leaderboard } from "./leaderboard";

const clients = new Set<http.ServerResponse>();
const WALLETS = (process.env.WALLETS ?? "").split(",").filter(Boolean);

watchWallets(WALLETS, enqueue);
runFetcher((item, tx) => {
  for (const trade of decodeTrades(item.signature, item.wallet, tx)) {
    record(trade);
    const line = `data: ${JSON.stringify(trade)}\n\n`;
    clients.forEach((res) => res.write(line));
  }
});

http
  .createServer((req, res) => {
    if (req.url === "/leaderboard") {
      res.setHeader("Content-Type", "application/json");
      return res.end(JSON.stringify(leaderboard()));
    }
    if (req.url === "/trades") {
      res.writeHead(200, {
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache",
      });
      clients.add(res);
      req.on("close", () => clients.delete(res));
      return;
    }
    res.statusCode = 404;
    res.end();
  })
  .listen(3000);
```

Run it with `WALLETS=addr1,addr2 npx tsx server.ts`, then open `http://localhost:3000/trades` to watch trades arrive.

## Step 7: Know when to change the ingestion layer

Per-wallet WebSocket subscriptions are the simplest start and they stop scaling quickly. Your options, roughly in order of effort:

| Approach | Good for | Trade-off |
|---|---|---|
| `logsSubscribe` per wallet (this guide) | Up to a few hundred wallets | Subscription limits, one fetch per transaction |
| Provider webhooks | Hundreds to thousands of wallets, no long-lived connection | Depends on one provider's format |
| Geyser gRPC stream | Whole programs or the whole chain | You run a real streaming pipeline |

If you outgrow this setup, the companion guide on [building a real-time Solana data pipeline](/blog/solana-real-time-data-pipeline) covers the streaming approach.

## What we would do

Start with this design for a fixed list of wallets. It is cheap, easy to debug, and it tells you quickly whether the data is useful. Before you build a large "top traders" product, decide what "top" means, because volume, frequency and realised profit rank very differently, and only realised profit needs historical prices. Store raw transactions alongside your decoded trades so you can re-run a better decoder later without re-fetching.

We build these systems as part of our [Solana data and analytics work](/services/solana-data-scrapers).

---

OnChain · 15 Bld. Iuliu Maniu, 061075 Bucharest, Romania · contact@onchain.ro · https://www.onchain.ro
