How to calculate unrealized profit and loss (PnL) for crypto

GoldRush TeamUpdated 15 min read

Unrealized PnL is what the crypto you still hold is worth now minus what it cost. The formula, how FIFO or average cost changes it, an example and code.

Unrealized profit and loss (PnL) is the gain or loss on crypto you still hold: what those units are worth at today's price minus what you paid for them (their cost basis). Selling turns it into realized PnL. When you bought in several lots and have sold some, the answer depends on which lots you count as sold, so FIFO and average cost give different figures. This guide covers the formula, works an example by hand, and then computes it in code from a wallet's onchain history with the GoldRush Foundational API.

This is not tax or investment advice: unrealized PnL is an accounting figure, and whether it matters for tax where you live is a question for a tax professional.

Unrealized vs realized profit and loss

  • Realized PnL is locked in. You sold or swapped the units, and the gain or loss is the amount you received minus the cost basis of the units you gave up. Under the IRS virtual currency FAQ, that is when a gain or loss arises: on a sale (A7) or an exchange for other property, including another crypto asset (A16).
  • Unrealized PnL is on paper. It is the same calculation for units you still hold, using today's price as if you sold now. It moves with the market and is zero again once you sell, when it becomes realized.

Add the two and you get your total PnL on the token. The total doesn't depend on the cost basis method; the method only decides how much of it counts as realized and how much is still unrealized. The cost basis and capital gains guide covers the realized side. This one covers what you still hold.

The unrealized PnL formula

Unrealized PnL   = current value of the units held − cost basis of the units heldcurrent value    = quantity held × current priceUnrealized PnL % = Unrealized PnL ÷ cost basis of the units held × 100
  • Cost basis is what you paid to acquire the units, including fees. The IRS FAQ defines basis that way for crypto bought with dollars (A8).
  • With one purchase, the cost basis is that purchase. Buy 2 tokens at $1,000 each, and at $1,800 the unrealized PnL is 2 × $1,800 − $2,000 = +$1,600, or +80%.
  • With average cost, the formula becomes quantity × (current price − average cost per unit), because every unit carries the same cost.
  • A positive result is an unrealized gain, a negative one an unrealized loss. Some portfolio trackers also subtract the estimated fee to sell; say so if yours does.

How the cost basis method changes unrealized PnL

Once you have sold part of a holding, you have to decide which units the sale used up. Whatever is left is what unrealized PnL is measured on:

Method The sale used up So the units still held are
FIFO (first in, first out) The oldest units The newest purchases
LIFO (last in, first out) The newest units The oldest purchases
HIFO (highest in, first out) The most expensive units The cheapest purchases
Average cost Units at the average cost Units at the average cost

If prices rose while you were buying, FIFO leaves you holding the expensive recent lots (smaller unrealized gain), while LIFO and HIFO leave you holding the cheap early lots (bigger unrealized gain, smaller realized one). Under the IRS FAQ, FIFO is what applies when you don't identify which units you sold (A41). For portfolio tracking you can use any method, but use the same one your tax figures use, or the realized and unrealized numbers won't add up to the same total.

Unrealized PnL example: FIFO vs LIFO vs average cost

These numbers are hypothetical, chosen to make the arithmetic easy to follow. You buy a token four times and sell once:

Date Trade Units Price Amount
January Buy 2 $1,000 $2,000
March Buy 1 $1,600 $1,600
June Buy 1 $2,200 $2,200
August Sell 1 $2,000 $2,000
Today Still held 3 $1,800 $5,400

You paid $5,800 for 4 units and still hold 3, worth 3 × $1,800 = $5,400. What those 3 units cost depends on the method:

Method Cost basis of the 3 units held Unrealized PnL Unrealized % Realized PnL (August) Total
FIFO $4,800 ($1,000 + $1,600 + $2,200) +$600 +12.5% +$1,000 +$1,600
LIFO $3,600 ($1,000 + $1,000 + $1,600) +$1,800 +50.0% −$200 +$1,600
HIFO $3,600 (same as LIFO here) +$1,800 +50.0% −$200 +$1,600
Average cost $4,350 (3 × $5,800 ÷ 4) +$1,050 +24.1% +$550 +$1,600

Under FIFO, the August sale used one of the January units ($1,000), so you still hold one January unit and both later ones. Under average cost, every unit costs $5,800 ÷ 4 = $1,450, the sale took out $1,450, and the 3 units left carry $4,350. The total is +$1,600 every time: $2,000 received plus $5,400 still held, minus $5,800 paid.

Data needed to compute unrealized PnL

For one token in one wallet, you need the units held and today's price, plus every lot that came in and what it was worth that day. GoldRush gives you both from three endpoints:

  • Token balances (balances_v2): every token the wallet holds, with the raw balance, contract_decimals, quote_rate (the current price in your quote currency) and quote (the balance times that price).
  • ERC-20 token transfers (transfers_v2): every transfer of one token in or out of the wallet, with transfer_type (IN or OUT), the raw amount in delta and quote_rate, the token's price on the day of the transfer.
  • Historical token prices (historical_by_addresses_v2): the daily price for a date range, to fill in a transfer that came back without a quote_rate.

Prerequisites: Node.js 18 or later (for the built-in fetch), and a GoldRush API key from the free trial in the GOLDRUSH_API_KEY environment variable. The five code blocks in steps 1 to 4 and "Run the unrealized PnL script" make one script: save them, in order, in one file named pnl.mjs (the .mjs extension lets the last block use top-level await), then run node pnl.mjs.

GoldRush's Streaming API also has a Wallet PnL by Token GraphQL query, which returns realized and unrealized PnL, the current balance and transaction details for each token a wallet holds, on Base, Ethereum, BNB Smart Chain (BSC), Polygon, Gnosis, Optimism, MegaETH and Robinhood Chain. Computing it yourself from the Foundational API, as below, lets you choose the cost basis method and check every lot behind the number.

Step 1: Get the current balance and price

balances_v2 returns every token in the wallet. Keep the one you want: its raw balance, decimals and current price.

const API = "https://api.covalenthq.com/v1";const headers = { Authorization: `Bearer ${process.env.GOLDRUSH_API_KEY}` }; async function get(url) {    const res = await fetch(url, { headers });    if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);    return (await res.json()).data;} // The wallet's current balance of one token, in raw units, and the token's price now.async function getHolding(chain, wallet, token) {    const data = await get(`${API}/${chain}/address/${wallet}/balances_v2/?quote-currency=USD`);    const item = data.items.find((i) => i.contract_address === token.toLowerCase());    if (!item) throw new Error(`${data.address} holds no ${token} on ${chain}`);    if (item.quote_rate == null) throw new Error(`No current price for ${item.contract_ticker_symbol}`);    return {        symbol: item.contract_ticker_symbol,        balance: BigInt(item.balance), // raw units: divide by 10^decimals for tokens        decimals: item.contract_decimals,        price: item.quote_rate, // USD per token now    };}

Each item looks like this, from a balances_v2 response for an eth-mainnet wallet, recorded on 3 November 2026 and trimmed to one token:

{    "data": {        "address": "0x5227f603c1ee34ce3c06efe6477003bdfccb2f8c",        "chain_name": "eth-mainnet",        "quote_currency": "USD",        "items": [            {                "contract_decimals": 6,                "contract_name": "Tether USD",                "contract_ticker_symbol": "USDT",                "contract_address": "0xdac17f958d2ee523a2206206994597c13d831ec7",                "type": "stablecoin",                "is_spam": false,                "balance": "1175464712876362",                "balance_24h": "1175464712876362",                "quote_rate": 0.99606574,                "quote_rate_24h": 0.99569386,                "quote": 1170840000,                "quote_24h": 1170403000,                "is_native_token": false            }        ]    },    "error": false,    "error_message": null,    "error_code": null}

A token can come back with quote_rate set to null when there is no price for it, which is common for spam and very illiquid tokens. Without a current price there is no unrealized PnL to compute, so the function stops there.

Step 2: Rebuild the lots from transfers

This is the same approach as the cost basis guide: page through transfers_v2 for the token, keep each movement with its price that day and any gas the wallet paid, and fill in missing prices from historical token prices. Add this to the same file:

// Every movement of one token in or out of a wallet, oldest first, with the token's price// that day and the gas the wallet paid.async function getTransfers(chain, wallet, token) {    const transfers = [];    for (let page = 0; ; page++) {        const data = await get(            `${API}/${chain}/address/${wallet}/transfers_v2/` +                `?contract-address=${token}&quote-currency=USD&page-size=100&page-number=${page}`        );        for (const tx of data.items) {            if (!tx.successful) continue;            // Gas is the wallet's cost only when it sent the transaction; count it once.            // gas_quote can be null (gas with no price) or missing: count either as no fee.            let fee = tx.from_address === data.address ? (tx.gas_quote ?? 0) : 0;            for (const t of tx.transfers) {                if (t.contract_address !== token.toLowerCase()) continue;                transfers.push({                    date: t.block_signed_at,                    type: t.transfer_type, // "IN" or "OUT"                    amount: BigInt(t.delta),                    decimals: t.contract_decimals,                    price: t.quote_rate, // USD per token on the day of the transfer                    fee,                });                fee = 0;            }        }        if (!data.pagination?.has_more) break;    }    return transfers.sort((a, b) => a.date.localeCompare(b.date));} // The token's USD price on one day (YYYY-MM-DD), cached.const prices = new Map(); async function priceOn(chain, token, day) {    const key = `${chain}:${token}:${day}`;    if (!prices.has(key)) {        const data = await get(            `${API}/pricing/historical_by_addresses_v2/${chain}/USD/${token}/?from=${day}&to=${day}`        );        // API keys created since 1 April 2026 get the daily prices in `items`; older keys in `prices`.        prices.set(key, (data[0]?.items ?? data[0]?.prices)?.[0]?.price ?? null);    }    return prices.get(key);} async function fillMissingPrices(chain, token, transfers) {    for (const t of transfers) {        t.price ??= await priceOn(chain, token, t.date.slice(0, 10));        if (t.price == null) throw new Error(`No price for ${token} on ${t.date}`);    }    return transfers;}

getTransfers reads pages like this one, a transfers_v2 response for USDT on eth-mainnet, recorded on 3 November 2026 and trimmed to one transaction and the fields the code reads:

{    "data": {        "address": "0x77edef23fbd05921c26fe29fcc3a65e14d2ac3eb",        "chain_name": "eth-mainnet",        "items": [            {                "block_signed_at": "2026-10-29T21:06:47.000Z",                "tx_hash": "0x279d12e9a7f594eeaf0eb83fe649f7f2cdf82ced156a82f85014dc56369b36d8",                "successful": true,                "from_address": "0x77edef23fbd05921c26fe29fcc3a65e14d2ac3eb",                "gas_quote": 19.88923567251063,                "transfers": [                    {                        "block_signed_at": "2026-10-29T21:06:47.000Z",                        "tx_hash": "0x279d12e9a7f594eeaf0eb83fe649f7f2cdf82ced156a82f85014dc56369b36d8",                        "contract_decimals": 6,                        "contract_ticker_symbol": "USDT",                        "contract_address": "0xdac17f958d2ee523a2206206994597c13d831ec7",                        "transfer_type": "OUT",                        "delta": "80000000000000",                        "quote_rate": 1.011037826538086                    }                ]            }        ],        "pagination": { "has_more": false, "page_number": 0, "page_size": 100, "total_count": null }    },    "error": false,    "error_message": null,    "error_code": null}

priceOn reads the first entry of a list like this one. API keys created since 1 April 2026 get the daily prices in that entry's items; older keys get them in prices, with items set to null (the GoldRush changelog entry "API Schema Improvements for New API Keys", 19 March 2026). priceOn reads either. This is a historical_by_addresses_v2 response for WETH on 29 October 2026 from an older key, recorded on 3 November 2026 and trimmed of its metadata:

{    "data": [        {            "contract_decimals": 18,            "contract_ticker_symbol": "WETH",            "contract_address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",            "quote_currency": "USD",            "prices": [{ "date": "2026-10-29", "price": 2252.9236 }],            "items": null        }    ],    "error": false,    "error_message": null,    "error_code": null}

Both endpoints give one price per day, so a lot's cost is the day's price, not the price at the minute of the trade. If you bought on an exchange, the fill price from its records is more exact.

Step 3: Work out what is still held

Replay the transfers in order. Each IN adds a lot with its cost: amount times price, plus any gas the wallet paid. Each OUT removes units, and the method decides which: the oldest lot for FIFO, the newest for LIFO, or a share of one pooled lot for average cost. What remains is the units you still hold and their cost basis. Add this to the same file:

const units = (raw, decimals) => Number(raw) / 10 ** decimals; // Replays every transfer and returns the lots still held, each with its remaining cost basis.// method: "fifo" (oldest lots leave first), "lifo" (newest first) or "average" (one pooled lot).function openLots(transfers, method = "fifo") {    const lots = [];    for (const t of transfers) {        if (t.type === "IN") {            const cost = units(t.amount, t.decimals) * t.price + t.fee;            if (method === "average" && lots.length) {                lots[0].amount += t.amount;                lots[0].cost += cost;            } else {                lots.push({ acquired: t.date, amount: t.amount, cost });            }            continue;        }        let left = t.amount;        while (left > 0n) {            const i = method === "lifo" ? lots.length - 1 : 0;            const lot = lots[i];            if (!lot) throw new Error(`${t.date}: more went out than came in`);            const take = lot.amount < left ? lot.amount : left;            lot.cost -= (lot.cost * Number(take)) / Number(lot.amount);            lot.amount -= take;            left -= take;            if (lot.amount === 0n) lots.splice(i, 1);        }    }    return lots;}

For HIFO, take the lot with the highest cost per unit instead. Amounts stay as BigInt raw units, so matching lots never leaves rounding dust.

Step 4: Compute unrealized PnL

Compare the lots with the balance, then apply the formula. Add this to the same file:

function unrealizedPnl(holding, lots) {    const held = lots.reduce((sum, l) => sum + l.amount, 0n);    if (held !== holding.balance) {        // A transfer the history doesn't show (or a rebasing token): the lots don't explain the balance.        console.warn(`lots add up to ${held} raw units, the balance is ${holding.balance}`);    }    const amount = units(holding.balance, holding.decimals);    const costBasis = lots.reduce((sum, l) => sum + l.cost, 0);    const value = amount * holding.price;    const pnl = value - costBasis;    return { amount, price: holding.price, value, costBasis, pnl, pct: costBasis ? (pnl / costBasis) * 100 : null };}

If the lots don't add up to the balance, the PnL is measured on the wrong units. The usual causes are tokens that changed hands outside a Transfer event (rebasing tokens) or a history you have only part of.

Run the unrealized PnL script

This puts the four steps together for one token in one wallet and prints the result under each method. Add it at the end of pnl.mjs, and change WALLET and TOKEN to your own; WALLET can be an address or an ENS name.

const CHAIN = "eth-mainnet";const WALLET = "vitalik.eth";const TOKEN = "0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE"; // SHIB const holding = await getHolding(CHAIN, WALLET, TOKEN);const transfers = await fillMissingPrices(CHAIN, TOKEN, await getTransfers(CHAIN, WALLET, TOKEN)); const usd = (n) => n.toFixed(2);console.log(`${holding.symbol}: ${units(holding.balance, holding.decimals)} held at $${holding.price}`);for (const method of ["fifo", "lifo", "average"]) {    const r = unrealizedPnl(holding, openLots(transfers, method));    console.log(        method.padEnd(8),        "cost",        usd(r.costBasis),        "value",        usd(r.value),        "PnL",        usd(r.pnl),        `${r.pct?.toFixed(1)}%`    );}

We ran this code with responses in the documented shape that reproduce the hypothetical worked example above (not live data). It printed the same figures as the table:

TKN: 3 held at $1800fifo     cost 4800.00 value 5400.00 PnL 600.00 12.5%lifo     cost 3600.00 value 5400.00 PnL 1800.00 50.0%average  cost 4350.00 value 5400.00 PnL 1050.00 24.1%

Handle errors from the GoldRush API

When a request fails, the API answers with a non-2xx status and the same envelope as a success, with data set to null. The docs show this body for a chain name it doesn't recognize, with HTTP status 501:

{    "data": null,    "error": true,    "error_message": "Chain nosuchchain-mainnet not supported.",    "error_code": 501}

get() throws the status and the body, so the script stops with 501 {"data":null,"error":true,…} instead of printing a PnL from partial data. error_code always equals the HTTP status, and error_message says what went wrong:

  • 501: the chain name is misspelled or not supported. Fix it; the same request keeps returning 501.
  • 401: the API key is missing or wrong. A request with no Authorization header at all gets an HTML 401 page instead of JSON, which is why get() reads the body as text before throwing.
  • 429 or a 5xx: rate limit or a busy backend. Retry after a pause, with backoff.

Failed requests cost no credits. The error handling page lists every code and what to do about it.

Limits of computing unrealized PnL from transfers

The result is only as good as the lots you feed it:

  • Moves between your own wallets. An IN from a wallet you own is not a purchase: it carries the lots it had there. Merge the histories of all your wallets before replaying them, and treat moves between them as transfers, not trades.
  • Airdrops, rewards and payments. These come in as IN transfers at the day's price, which is how the IRS FAQ values crypto received for services (A13). If yours are treated differently, adjust their cost.
  • Native tokens. ETH and other native coins aren't in transfers_v2, so their lots come from the wallet's transaction history instead.
  • A whole portfolio. Run it per token and add up the results. balances_v2 already lists every token the wallet holds, so it is the list to loop over; skip the ones with is_spam set or no quote_rate.

For the products built on this data, see the crypto wallet API page for portfolio trackers and the crypto tax and accounting API page for tax software.

Credit cost of an unrealized PnL check

Reading the current balance costs 1 per call. Rebuilding the lots costs 0.05 per item for ERC-20 token transfers, one item per transaction: 50 credits for a token with 1,000 transactions. Price look-ups (1 per call) run only for transfers that came back without a price. To estimate a month of portfolio refreshes, use the pricing calculator.

Frequently asked questions

How do you calculate unrealized profit and loss?

Multiply the units you still hold by the current price, then subtract what those units cost you, including fees. A positive result is an unrealized gain, a negative one an unrealized loss. Divide it by the cost and multiply by 100 for a percentage.

What is the difference between realized and unrealized PnL?

Realized PnL comes from units you sold or swapped: what you received minus their cost. Unrealized PnL is the same calculation for units you still hold, at today's price. Selling turns unrealized PnL into realized PnL, and the two add up to your total PnL on the asset.

Does FIFO or average cost change unrealized PnL?

Yes, once you have sold part of a holding. The method decides which units the sale used up, so it decides the cost of the units left. Your total PnL is the same under every method; only the split between realized and unrealized changes.

Do you pay tax on unrealized gains in crypto?

Under the IRS virtual currency FAQ, a gain or loss arises when you sell crypto or exchange it for other property, including another crypto asset, not while you hold it. Other countries have their own rules, so check where you file. This guide is not tax advice.

Can I get unrealized PnL from an API?

The Foundational API gives you the inputs: current balances and prices, every transfer of a token with its price that day, and historical prices. You apply the cost basis method, as in the code above. GoldRush's Streaming API also has a Wallet PnL by Token query that returns realized and unrealized PnL per token on Base, Ethereum, BNB Smart Chain (BSC), Polygon, Gnosis, Optimism, MegaETH and Robinhood Chain.

Next steps

Get new guides by email

New tutorials and best practices for building with blockchain data, sent as they're published.