# Price alerts

Create, list, update, and cancel alerts that fire when a market's price crosses a level.

`client.priceAlerts` manages the caller's price alerts. Alerts belong to the root account, not a trading account: a session and the root account's API keys see the same alerts. No call changes balances, orders, or account settings. Errors carry `detail: { service: "alerts", code }`. Tree-shaken builds reach the same service with `priceAlertsService(core)` from `@polyester/sdk/services/price-alerts`.

API keys need `read-price-alerts` for `list` and `manage-price-alerts` for `create`, `update`, and `cancel`. A key whose policy lacks the permission gets `PermissionError` with `detail.code === "AUTH_API_KEY_ACCESS_DENIED"`. Both are main-account permissions: sub-account policies reject them, and a key scoped to a subaccount is refused with `PermissionError` and `detail.code === "SUBACCOUNT_KEY_REFUSED"`.

An alert fires at most once, and only on a crossing it observes. It records the price when it is created or set again as its `referencePrice`. An alert whose condition already holds at that price has `armed: false` and first waits for the price to move to the other side: a `below` alert created while the price is already below fires only after the price rises above it and falls back. Prices that arrive late, or a feed that stops updating, never fire an alert. `update` sets a fired alert again.

## Methods

| Method   | Summary                                                           |
| -------- | ----------------------------------------------------------------- |
| `create` | Create an active alert.                                           |
| `list`   | Page through alerts, newest first.                                |
| `update` | Change an alert's direction, price, or channels, or set it again. |
| `cancel` | Cancel an active alert.                                           |

### `create(input, options?)`

Creates an active alert and returns it, with the price it watches and its `referencePrice`.

```ts
const symbolId = client.catalog.market.requireSymbolIdByPairSymbol("BTC-USDT");

const alert = await client.priceAlerts.create({
	symbolId,
	direction: "above",
	price: "90000",
	channels: ["in_app"],
	idempotencyKey: crypto.randomUUID(),
});
console.log(alert.alertId, alert.priceSource, alert.referencePrice, alert.armed);
```

| Field            | Type                            | Required | Notes                                                                   |
| ---------------- | ------------------------------- | -------- | ----------------------------------------------------------------------- |
| `symbolId`       | `number`                        | yes      | Spot market ID.                                                         |
| `direction`      | `"above" \| "below"`            | yes      | `above` fires at or above `price`, `below` at or below it.              |
| `price`          | `string`                        | yes      | Positive decimal, at most 9 decimal places, e.g. `"90000"`.             |
| `channels`       | `("in_app" \| "telegram")[]`    | yes      | One or two distinct delivery channels.                                  |
| `priceSource`    | `"last_price" \| "index_price"` | no       | Omit for the index price on markets that have one, else the last price. |
| `idempotencyKey` | `string`                        | no       | Reusing it with the same request returns the alert it created.          |

`index_price` on a market without an index price throws `PreconditionFailedError` with `detail.code === "PRICE_SOURCE_UNSUPPORTED"`; use `last_price`. A market with no current price yet throws a retryable `ServiceUnavailableError` (`PRICE_UNAVAILABLE`).

`"telegram"` delivers the fired alert as a direct message to the Telegram account linked to the caller's account. Asking for it without a linked Telegram account throws `PreconditionFailedError` with `detail.code === "TELEGRAM_NOT_LINKED"`, and while Telegram delivery is disabled, with `detail.code === "TELEGRAM_UNAVAILABLE"`. Neither is retryable: link Telegram through [social verification](https://testnet.polyester.com/docs/sdk/typescript/reference/social-verification), or ask for `"in_app"` only. `update` throws them too when the alert keeps `"telegram"` among its channels; set `channels: ["in_app"]` to change such an alert.

### `list(input?, options?)`

Returns `{ alerts, nextPageToken }`, newest first. Pass the previous `nextPageToken` as `pageToken` with the same filters; an empty `nextPageToken` means there are no more.

```ts
let pageToken = "";
do {
	const page = await client.priceAlerts.list({ statuses: ["active"], limit: 200, pageToken });
	for (const alert of page.alerts) {
		console.log(alert.alertId, alert.symbolId, alert.direction, alert.price);
	}
	pageToken = page.nextPageToken;
} while (pageToken !== "");
```

| Field       | Type                                        | Notes                                              |
| ----------- | ------------------------------------------- | -------------------------------------------------- |
| `statuses`  | `("active" \| "triggered" \| "canceled")[]` | Only alerts in these states. Omit or `[]` for all. |
| `symbolId`  | `number`                                    | Only alerts on this market.                        |
| `limit`     | `number`                                    | 1 to 200, default 50.                              |
| `pageToken` | `string`                                    | The previous `nextPageToken`.                      |

### `update(input, options?)`

Changes an alert's `direction`, `price`, or `channels` and returns `{ alert, outcome }`. Omitted fields stay as they are, and `channels` replaces the whole list. A new direction or price records a new reference price. Updating a `triggered` alert sets it again, `active` with a new reference price, even with no field given. An update that changes nothing on an `active` alert returns it unchanged.

```ts
const { alert: updated, outcome } = await client.priceAlerts.update({
	alertId: alert.alertId,
	expectedRevision: alert.revision,
	price: "95000",
});
```

| Field              | Type                         | Notes                                                             |
| ------------------ | ---------------------------- | ----------------------------------------------------------------- |
| `alertId`          | `string`                     | The alert to change.                                              |
| `expectedRevision` | `string`                     | The alert's `revision` from the last read.                        |
| `direction`        | `"above" \| "below"`         | New crossing to wait for.                                         |
| `price`            | `string`                     | Positive decimal, at most 9 decimal places.                       |
| `channels`         | `("in_app" \| "telegram")[]` | One or two distinct channels, replacing the current ones.         |
| `idempotencyKey`   | `string`                     | Optional. Reusing it with the same request applies nothing again. |

`outcome` says what the call did:

| `outcome`   | Meaning                                                                                      |
| ----------- | -------------------------------------------------------------------------------------------- |
| `applied`   | The alert changed.                                                                           |
| `unchanged` | The alert was already as requested.                                                          |
| `replayed`  | The `idempotencyKey` was already used for this request. Nothing changed; `alert` is current. |

A replayed update never sets an alert again, however late it comes. An alert keeps at most 1,000 update keys: a new key beyond that throws `PreconditionFailedError` with `detail.code === "ALERT_UPDATE_LIMIT_REACHED"`, while updates without a key and repeats of a stored key still work.

A stale `expectedRevision` throws `RevisionConflictError`: read the alert again and retry. A canceled alert throws `PreconditionFailedError` with `detail.code === "ALERT_CANCELLED"`.

### `cancel(input, options?)`

Cancels an active alert by `alertId` and returns it. Canceling a canceled alert returns it unchanged. A `triggered` alert already fired, so there is nothing to cancel: it throws `PreconditionFailedError` with `detail.code === "ALERT_TRIGGERED"`. Update it to set it again.

```ts
const canceled = await client.priceAlerts.cancel({ alertId: alert.alertId });
```

## The `PriceAlert` shape

```ts
import type { PriceAlert } from "@polyester/sdk";

interface PriceAlert {
	alertId: string;
	symbolId: number;
	direction: "above" | "below" | "unspecified";
	priceSource: "last_price" | "index_price" | "unspecified"; // the price it watches
	price: string; // alert price, a decimal string
	referencePrice: string; // price when created or last set again; it fires on a crossing from here
	armed: boolean; // false while an alert created past its price waits for the price to move back
	status: "active" | "triggered" | "canceled" | "unspecified";
	channels: ("in_app" | "telegram" | "unspecified")[];
	revision: string; // pass as expectedRevision to update
	createdAt: number | null; // epoch ms
	updatedAt: number | null; // epoch ms, the caller's last change
	triggeredAt: number | null; // epoch ms, set only once the alert fired
	triggeredPrice: string | null; // price that fired it; null unless triggered
}
```

`active` waits for its crossing, `triggered` fired once and stopped, and `canceled` never fires again.

## Errors

Invalid input, such as a zero price or a repeated channel, throws `ValidationError` before the request is sent. The service's refusals:

| `detail.code`                | Error                     | Methods            | What to do                                                      |
| ---------------------------- | ------------------------- | ------------------ | --------------------------------------------------------------- |
| `UNKNOWN_SYMBOL`             | `ValidationError`         | `create`           | The market is not listed.                                       |
| `ALERT_NOT_FOUND`            | `ResourceNotFoundError`   | `update`, `cancel` | No alert of the caller has this ID.                             |
| `PRICE_SOURCE_UNSUPPORTED`   | `PreconditionFailedError` | `create`, `update` | The market has no index price. Use `last_price`.                |
| `ALERT_LIMIT_REACHED`        | `PreconditionFailedError` | `create`, `update` | The root account has 100 active alerts. Cancel one first.       |
| `ALERT_CANCELLED`            | `PreconditionFailedError` | `update`           | The alert is canceled and can no longer change.                 |
| `ALERT_UPDATE_LIMIT_REACHED` | `PreconditionFailedError` | `update`           | Update without a key, or create a new alert.                    |
| `ALERT_TRIGGERED`            | `PreconditionFailedError` | `cancel`           | The alert already fired. Update it to set it again.             |
| `TELEGRAM_NOT_LINKED`        | `PreconditionFailedError` | `create`, `update` | No Telegram account is linked. Link one, or use `in_app` only.  |
| `TELEGRAM_UNAVAILABLE`       | `PreconditionFailedError` | `create`, `update` | Telegram delivery is disabled. Use `in_app` only.               |
| `REVISION_CONFLICT`          | `RevisionConflictError`   | `update`           | Read the alert again and retry.                                 |
| `IDEMPOTENCY_CONFLICT`       | `AlreadyExistsError`      | `create`, `update` | The key was used with a different request. The original stands. |
| `SUBACCOUNT_KEY_REFUSED`     | `PermissionError`         | all                | Use a session or an API key of the root account.                |
| `PRICE_UNAVAILABLE`          | `ServiceUnavailableError` | `create`, `update` | The market has no current price yet. Retry the same request.    |
| `SERVICE_UNAVAILABLE`        | `ServiceUnavailableError` | all                | Retry the same request.                                         |

## Related

- [Notifications](https://testnet.polyester.com/docs/sdk/typescript/reference/notifications) for the `price_alert` notices of fired alerts.
- [API keys](https://testnet.polyester.com/docs/sdk/typescript/reference/api-keys#account-permissions) for the `read-price-alerts` and `manage-price-alerts` permissions.
- [Catalog](https://testnet.polyester.com/docs/sdk/typescript/reference/catalog) for resolving `symbolId`.
- [Errors](https://testnet.polyester.com/docs/sdk/typescript/reference/errors) for the error type reference.
