---
id: BI0025
title: "Token price alerts"
url: https://carbium.sh/library/blockchainideas/token-price-alerts
collection: Blockchain ideas
category: Swap-powered apps
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Token price alerts

A small script that polls a SOL/USDC pool's two vault balances through Carbium, derives a spot price, and prints an alert when it crosses a ceiling, a floor or a percent move. Spec, costs per plan and a runnable main.ts.

## Who uses it

A wallet app wants to tell a user that SOL passed the level they set. A treasury team wants a message when a stablecoin pool drifts off its peg. A hackathon crew wants a working alert in an afternoon, with no price vendor account to sign up for. All three need the same loop: read a price, compare it with a set of rules, and speak once per event.

The price here comes from chain state. A constant-product pool keeps its two reserves in two token accounts, called vaults, and the ratio of their balances is the pool's spot price. Two balance reads over RPC give you that ratio at the commitment you choose, with no second feed to license.

The default target is a public SOL/USDC pool, so a run prints USDC per SOL. Any pool whose reserves sit in two plain vaults works after you change two addresses.

## The three rules

Each tick produces one price, and every rule looks at it.

| Rule | Fires when | Fires again |
|---|---|---|
| Ceiling | the price is at or above `ABOVE` | after one tick under it |
| Floor | the price is at or below `BELOW` | after one tick over it |
| Move | the price differs from the reference by `BAND` percent | after another full band, because the reference resets to the price that fired |

The move rule needs no setup, which is why it is on by default at 0.05 percent. Pass a different number as the first argument. The ceiling and the floor stay off until you set `ABOVE` or `BELOW` in the environment.

The ceiling and the floor are latched. A rule fires on the tick where its condition turns true and stays quiet until the condition has been false for one tick, so a price that sits above the ceiling for an hour raises one alert.

## The build

The script is one file that needs `@solana/kit` and what Node 24 ships.

1. Create one RPC client at startup against `https://services.carbium.sh`, with the key in the `x-api-key` header, and reuse it for every call.
2. Every `POLL_MS`, call getTokenAccountBalance for the base vault and the quote vault together with `Promise.allSettled`, at commitment `confirmed`.
3. Divide the quote balance by the base balance. For the default pool that is USDC per SOL.
4. Run the three rules on the price. Print one line per tick and an `ALERT` line when a rule fires.
5. If a read fails, print the reason and skip the tick. The next tick tries again.

> The script only reads. It signs nothing, sends nothing and holds no private key.

Run it as `node main.ts [band]`. The environment takes `ABOVE`, `BELOW`, `POLL_MS`, `BASE_VAULT` and `QUOTE_VAULT`. For another pair, pass the two vault addresses of its pool, the token you want priced first and the token you want it priced in second.

`main.ts` (run: `CARBIUM_KEY=<YOUR_KEY> node main.ts 0.05`)

```ts
// BI0025 · Token price alerts
// https://carbium.sh/library/blockchainideas/token-price-alerts
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, type Address } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium API key.");
  process.exit(1);
}
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);

// Price = quote vault balance / base vault balance. Defaults: the vaults of a public SOL/USDC pool.
const BASE = address(process.env.BASE_VAULT ?? "DQyrAcCrDXQ7NeoqGgDCZwBvWDcYmFCjSb9JtteuvPpz");
const QUOTE = address(process.env.QUOTE_VAULT ?? "HLmqeL62xR1QoZ1HKKbXRrdN1p3phKpxRMb2VVopvBBz");
const BAND = Number(process.argv[2] ?? 0.05); // percent move since the last alert
const ABOVE = Number(process.env.ABOVE ?? Infinity);
const BELOW = Number(process.env.BELOW ?? 0);
const POLL_MS = Number(process.env.POLL_MS ?? 5000); // two reads per tick; 5 s keeps Free under 0.5 req/s
if ([BAND, ABOVE, BELOW, POLL_MS].some((n) => Number.isNaN(n))) {
  console.error("The band argument, ABOVE, BELOW and POLL_MS must be numbers.");
  process.exit(1);
}

async function balance(vault: Address): Promise<number> {
  const { value } = await rpc.getTokenAccountBalance(vault, { commitment: "confirmed" }).send();
  return Number(value.uiAmountString);
}

const why = (r: PromiseRejectedResult) => (r.reason instanceof Error ? r.reason.message : String(r.reason));
let ref: number | undefined;
const latched = { above: false, below: false };

function check(price: number): void {
  ref ??= price;
  const move = (price / ref - 1) * 100;
  if (Math.abs(move) >= BAND) {
    console.log(`ALERT move ${move.toFixed(3)}% since ${ref.toFixed(4)}, now ${price.toFixed(4)}`);
    ref = price;
  }
  for (const [name, hit] of [["above", price >= ABOVE], ["below", price <= BELOW]] as const) {
    if (hit && !latched[name]) console.log(`ALERT ${name} at ${price.toFixed(4)}`);
    latched[name] = hit; // fires on the crossing only
  }
}

async function run(): Promise<void> {
  for (;;) {
    const [base, quote] = await Promise.allSettled([balance(BASE), balance(QUOTE)]);
    if (base.status === "fulfilled" && quote.status === "fulfilled") {
      const price = quote.value / base.value;
      console.log(`${new Date().toISOString()} price ${price.toFixed(4)}`);
      check(price);
    } else {
      for (const r of [base, quote]) if (r.status === "rejected") console.error(`read failed: ${why(r)}`);
    }
    await new Promise((resolve) => setTimeout(resolve, POLL_MS));
  }
}

void run();
```

getTokenAccountBalance returns the balance already divided by the token's decimals as `uiAmountString`, so one script prices pairs with different decimals. The call reads at confirmed commitment.

## What it costs

Each tick makes two account reads at 10 cells each, 20 cells in all. Account reads have their own rate on every plan, and the table turns that rate into how many pools one account can watch at a 5 second tick.

| Plan | Account reads per second | Pools at a 5 s tick |
|---|---|---|
| Free ($0) | 0.5 | 1 |
| Dev ($20) | 15 | 37 |
| Business ($250) | 50 | 125 |
| Pro ($500) | 400 | 1000 |

On Free, one pool at a 5 second tick makes 0.4 calls per second, under the 0.5 limit. Limits are per account, so any other tool on the same keys draws from that budget.

Credits meter RPC work, so every poll spends from the plan's credits. Free's 500K credits come once at sign-up, so a watch that never stops draws them down and nothing refills them. On a paid plan each month adds credits, and unspent credits stay. A script that polls on a short gap spends more than one that polls on a long gap, and the alert latency is the gap, so pick it from how fast your users need to hear.

## What to add next

- Delivery: post the `ALERT` line to a channel. [Slack slot-lag alerts](https://carbium.sh/library/integrate/slack-slot-lag-alerts) covers the sending half.
- One snapshot: replace the two calls with one getMultipleAccounts of the two vaults in base64 and read the amount from bytes 64 to 72 of each account. Divide each raw u64 amount by 10 to the power of its mint's decimals (9 for SOL, 6 for USDC) before taking the ratio. Both balances then come from one slot, and the call costs the same 20 cells at 10 per pubkey.
- Push instead of poll: open logsSubscribe with a mention of the pool address and recompute the price on each notification. A logs-mentions subscription opens at 25 credits and then costs 20 credits per MiB sent, and a busy pool sends a lot, so read the MiB total before you choose it.
- A cross-check against a quote: the quote method answers on the same endpoint, and the key needs the QUOTE scope. A quote carries a 5 bps router fee charged on chain, so it sits a little off the pool's spot ratio. Read the [quote](https://carbium.sh/docs#quote) and [prices](https://carbium.sh/docs#prices) pages first.
- Stored rules: keep each user's levels in a `node:sqlite` file so alerts survive a restart.

## Where it ends

- The ratio is one pool's price. A thin pool moves on a single swap and can sit away from other venues, so a user-facing alert on a large token wants a pool with deep reserves.
- The two reads are two calls and can land on different slots. A swap between them shifts the ratio by that swap's impact for one tick.
- The method suits constant-product pools whose vaults hold the pair. A concentrated-liquidity pool has no single reserve ratio that equals its price.
- Polling sees the price at tick times. A spike that reverses between two ticks is missed.
- Rules and the reference live in memory. A restart forgets the latches and starts a new reference from the first reading.
- The script keeps no price history, so it cannot draw a chart or answer what the price was an hour ago.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| Every tick prints a failed read with a 401. | An unknown key is turned away at the door. Attach the whole key in CARBIUM_KEY, with no trailing newline or truncation. |
| Reads fail with a 429 on the Free plan. | Raise POLL_MS. Two calls every 5 s is 0.4 req/s against 0.5 req/s for account reads on Free, and other tools on the account share that budget. The loop skips the tick and tries again on the next. |
| The price prints inverted, 0.0145 where you expect 69. | Swap BASE_VAULT and QUOTE_VAULT. The price is the quote vault's balance divided by the base vault's. |
| The ceiling alert fires again and again around the level. | A price that hovers on the line crosses it many times, and each crossing fires. Rearm only after the price has fallen a small margin under ABOVE, for example 0.1 percent. |
| A read fails and no price prints at all. | An address that is not a token account fails the read. Check that BASE_VAULT and QUOTE_VAULT are the two vault accounts of one pool, holding its two mints. |

## Questions

### Can I get price alerts without a separate price API?

Yes, for any token with a constant-product pool. The script reads two vault balances over Carbium RPC and divides them, so the Carbium key is the only credential.

### How often can I poll on the Free plan?

Each tick is two account reads, and Free allows 0.5 per second for them, so one tick every 4 seconds is the floor. The script defaults to 5 seconds.

### How do I price a pair whose tokens have different decimals?

Read both vaults with getTokenAccountBalance and divide the `uiAmountString` values. Each is already scaled by its own mint's decimals, so SOL with 9 and USDC with 6 need no extra step in the script.

### Can a WebSocket replace the polling?

Yes. logsSubscribe with a mention of the pool address sends a notification for each transaction that touches it, and you recompute the price then. It costs 25 credits to open and 20 per MiB sent, so a busy pool grows the bill with its traffic.

### Does this need the quote plan?

No. Quotes are a separate plan and meter. The alert reads RPC only, and a quote is useful as an optional cross-check from a key with the QUOTE scope.

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [Slack slot-lag alerts](https://carbium.sh/library/integrate/slack-slot-lag-alerts) (Integrations, I0001)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#quote](https://carbium.sh/docs#quote)
- [carbium.sh/docs#prices](https://carbium.sh/docs#prices)
