# Webhook delivery

When a webhook fires and what reaches your endpoint. Create one with the subscribe call on Scan, Signals, Tickers, Events or News; manage it under Webhooks (https://tickerbot.io/docs/endpoints/webhooks.md).

## When a webhook fires

We track each ticker's match state per webhook and deliver only when a ticker goes from not matching to matching. A ticker that flickers true → false → true inside a minute fires once; one that stays matched for three days fires once, when it first matched. To fire again it has to leave the match set first. Event and news triggers have no match state: each new event or article fires once.

A webhook fires as soon as your data shows the match. Cadence sets the granularity: the match state is captured each time the webhook runs, on `realtime` at every refresh of your data (below) and on `nyse_open` once a day at the market open. The flicker window is the gap between two runs: a ticker that enters and exits entirely inside it never fires at all, and repeated flicker inside it collapses to at most one event.

Every webhook (scan, signal, ticker, event and news) runs each time your data refreshes. On real-time data that is every live refresh, about once a minute. On data 15 minutes delayed it is every minute, 15 minutes behind live, and event and news webhooks deliver each item once it is 15 minutes old. At end of day it is once each market's close lands (stocks and rates at the NYSE close, FX 5:00 PM ET, crypto 00:00 UTC), and again when a stock's closing price is corrected to the official close (it settles that evening and the next morning), and event and news webhooks deliver everything up to the NYSE close (4:00 PM ET) in the run when that close lands. Scan, signal and ticker deliveries carry `as_of`, the time the data is from.

Polling is different: Run a scan (`POST /v2/scan`), Get a signal and List tickers always return current state with no deduplication. To get edge-triggered behavior from a poll, diff the result set yourself between calls.

## Delivery channels

One discriminator, set when you subscribe. Each subscription delivers to one of: an HTTPS endpoint, a Discord channel, the Tickerbot mobile app or only the dashboard.

- `webhook`: POST a signed JSON payload (`webhook.fired`, `events.fired` or `news.fired`; see Delivery payloads) to your `target_url`.
- `discord`: post a formatted embed to a Discord channel via an incoming-webhook URL. No HMAC: the URL *is* the credential.
- `in_app`: record fires in the dashboard's deliveries timeline only. No outbound request.
- `mobile_push`: push a notification to a phone signed in to the Tickerbot app; the app registers itself.

If you omit `channel`, it's inferred: `discord` when `discord_url` is set, else `mobile_push` when `device_id` is set, else `webhook` when `target_url` is set, otherwise `in_app`. To switch channels later, send `channel` to Update a webhook (https://tickerbot.io/docs/endpoints/webhooks/update.md).

### Discord

Post embeds to a channel with two extra fields.

In Discord, open **Server Settings → Integrations → Webhooks → New Webhook**, pick a channel, and **Copy Webhook URL**. Pass it as `discord_url` with `channel: "discord"` on any subscribe endpoint.

Each fire posts a single embed with the subscription name. A screen lists up to the first dozen matching tickers with price and day change, plus an "…and N more" line; an event webhook lists up to 12 events and a news webhook up to 10 linked headlines. Discord embed limits apply: long lists are truncated, not split.

The URL is a credential, so we store it as one: the create response echoes it once, and every read after omits it (`channel_config_present: true`). To rotate it, send a new `discord_url` to Update a webhook (https://tickerbot.io/docs/endpoints/webhooks/update.md).

## What a delivery sends

The headers and JSON body POSTed to a target_url. X-Tickerbot-Event names which body it is.

### Headers

| Header | Meaning |
| --- | --- |
| `Content-Type` | Always `application/json`. |
| `User-Agent` | Always `Tickerbot-Webhooks/1.0`. |
| `X-Tickerbot-Event` | The event name: `webhook.fired` for scan, signal and ticker webhooks, `events.fired` for event webhooks, `news.fired` for news webhooks. Route on it in your handler. |
| `X-Tickerbot-Delivery-Id` | Identifies the delivery. It stays the same across retries and resends (`POST /v2/webhooks/{webhook}/deliveries/{delivery}/redeliver` sends the original id), so use it to drop duplicates. |
| `X-Tickerbot-Webhook-Id` | The webhook that produced the delivery. |
| `X-Tickerbot-Signature` | HMAC-SHA256 signature, `t=<unix-timestamp>,v1=<hex-digest>`. The signed payload is `<timestamp>.<raw-body>`, keyed with the webhook’s `signing_secret`. |
| `X-Tickerbot-Test` | `true` on deliveries sent by `POST /v2/webhooks/{webhook}/test`, and absent on real fires. A test is the same shape as a real fire, with the same headers and signature, and carries one sample match, event or article (ticker `TBOT`; each signal a sample value of its type: text, an ISO timestamp, a number or `true`), so a receiver can filter tests on this header. |

### `webhook.fired`

Scan, signal and ticker webhooks. One or more tickers started matching since the last evaluation. One delivery per evaluation that has a new match; a ticker that stays matched does not fire again.

| Field | Type | Description |
| --- | --- | --- |
| `event` | string | `webhook.fired`. |
| `webhook_id` | string | The webhook that fired. |
| `name` | string | The webhook’s name. |
| `q` | string | The webhook’s rule. |
| `universe` | string or null | The webhook’s universe, or `null` when it is not scoped to one. |
| `as_of` | timestamp | When the evaluation ran (ISO 8601); on data served behind live, the time of that data. |
| `matches` | object[] | The tickers that started matching, up to 100, in the webhook’s `order` and `dir` (default `market_cap`, descending). Each is a scan row: the default row (`ticker`, `name`, `asset_class`, `asset_type`, `price`, `change_1d_pct`, `gap_pct`, `relative_volume`, `market_cap`) plus the signals in `q` and `order`. A webhook with `select` gets `ticker` plus exactly those signals. |
| `matches[].ticker` | string |  |
| `matches[].name` | string | company / security name |
| `matches[].asset_class` | string | Asset class of the ticker: stocks | rates | crypto | fx. Matches asset_class.slug exactly — the registry and the column share one vocabulary. |
| `matches[].asset_type` | string | security type (CS/ETF/…) |
| `matches[].price` | number | The current price: the first available source in a fixed order (fair value, a newer minute bar, trade, quote, minute bar, day bar, previous close); price_source names it and price_asof carries its time. In history: the bar's close. |
| `matches[].change_1d_pct` | number | Percent change vs `previous_close`, as a whole percent (0.5 = 0.5%, not a fraction). Signed. Percent scale on every read (live, `asof` by date, `asof` by timestamp) since the 2026-09-07 cutover; before it, this signal was `day_change_pct`, a fraction. |
| `matches[].gap_pct` | number | Gap at the open vs the previous close, in whole percent. |
| `matches[].relative_volume` | number | Today's volume over the mean daily volume of the 10 sessions before today; intraday, volume so far. |
| `matches[].market_cap` | number | market capitalization |
| `current_matches` | object[] | Every ticker matching now, new and old, up to 100, in the same order and row shape. |
| `current_matches[].ticker` | string |  |
| `current_matches[].name` | string | company / security name |
| `current_matches[].asset_class` | string | Asset class of the ticker: stocks | rates | crypto | fx. Matches asset_class.slug exactly — the registry and the column share one vocabulary. |
| `current_matches[].asset_type` | string | security type (CS/ETF/…) |
| `current_matches[].price` | number | The current price: the first available source in a fixed order (fair value, a newer minute bar, trade, quote, minute bar, day bar, previous close); price_source names it and price_asof carries its time. In history: the bar's close. |
| `current_matches[].change_1d_pct` | number | Percent change vs `previous_close`, as a whole percent (0.5 = 0.5%, not a fraction). Signed. Percent scale on every read (live, `asof` by date, `asof` by timestamp) since the 2026-09-07 cutover; before it, this signal was `day_change_pct`, a fraction. |
| `current_matches[].gap_pct` | number | Gap at the open vs the previous close, in whole percent. |
| `current_matches[].relative_volume` | number | Today's volume over the mean daily volume of the 10 sessions before today; intraday, volume so far. |
| `current_matches[].market_cap` | number | market capitalization |
| `matched_count` | integer | How many tickers started matching, counted in full when `matches` is cut. |
| `current_match_count` | integer | How many tickers match now, counted in full when `current_matches` is cut. |
| `matches_truncated` | boolean | Present and `true` when `matches` was cut at 100. |
| `current_matches_truncated` | boolean | Present and `true` when `current_matches` was cut at 100. |
| `order` | string | Present when a list was cut: the signal the 100 were taken by. |
| `dir` | string enum | Present when a list was cut: the direction the 100 were taken in. One of the `dir` values below. |

`dir` values:

| Value | Meaning |
|-------|---------|
| `asc` | Ascending: smallest or earliest first. |
| `desc` | Descending: largest or most recent first. |


### `events.fired`

Event webhooks (Subscribe to events). New events of the watched kinds landed for the watched tickers. Each event fires once; only events from the last 7 days fire.

| Field | Type | Description |
| --- | --- | --- |
| `event` | string | `events.fired`. |
| `webhook_id` | string | The webhook that fired. |
| `name` | string | The webhook’s name. |
| `kind` | string[] enum | The event kinds the webhook watches. One of the `kind` values below. |
| `q` | string or null | The webhook’s filter, or `null` when it has none. |
| `ticker` | string[] or null | The webhook’s tickers, or `null`. |
| `universe` | string or null | The webhook’s universe, or `null`. |
| `as_of` | timestamp | When the delivery was built (ISO 8601); on data served behind live, the time of that data. |
| `events` | object[] | The new events, up to 2,000, each a Query events row: `id`, `ticker`, `ts`, `kind` and `payload`; `id` tells a re-delivered event from a new one. A webhook with `select` gets `id`, `ticker`, `ts` and `kind` plus the named fields. |
| `events[].id` | string | The event's stable id, `<kind>:<key>`. Stable across reads; use it to drop duplicates. The key per kind: **earnings** ticker|reported date; **dividend** ticker|ex-date|dividend_type|amount (a regular and a special dividend on one ex-date are two events); **split** ticker|execution date; **filing** the SEC accession number; **insider** ticker|transaction date|executive|security_type (the filing's key: one executive can file several rows a day); **analyst** the vendor's event id; **estimate_revision** ticker|fiscal_date|horizon|observed instant; **news** article id|ticker (one article mentioning three tickers is three events); **signal** signal|ticker|ts|transition|grain. One flip is one event at one grain; the same signal read at 1d and at 1h gives different events. |
| `events[].ticker` | string | The symbol the event is about. |
| `events[].ts` | string | Its position on the timeline (ISO 8601), by kind: report date, ex-date, execution date, filing date, transaction date, rating-change time, publish time, when the nightly refresh observed the revision, or the flip at its grain (the session close at `1d`). List event kinds gives each kind's `ts`. |
| `events[].kind` | string | Which kind this result is: the key into `payload` below. |
| `events[].payload` | object | The kind's own fields, one shape per kind: [All event kinds](/docs/events) lists each kind's. |
| `event_count` | integer | How many new events, counted in full when `events` is cut. |
| `events_truncated` | boolean | Present and `true` when `events` was cut at 2,000. |

`kind` values:

| Value | Meaning |
|-------|---------|
| `earnings` | Fires on each quarterly earnings report: reported vs estimated EPS and the surprise. |
| `dividend` | Fires on each cash-dividend declaration. |
| `split` | Fires on each stock split or reverse split. |
| `filing` | Fires when a 10-K, 20-F, 40-F or 10-Q lands, from the next morning’s EDGAR index read. |
| `insider` | Fires on each reported Form 4 transaction by an officer or director. |
| `analyst` | Fires on each upgrade, downgrade, initiation or price-target change. |
| `estimate_revision` | Fires when the nightly consensus refresh moves an EPS estimate, one event per fiscal period and horizon that moved (about 1,000 a night across the market). |


### `news.fired`

News webhooks (Subscribe to news). New articles matching the webhook’s filter landed. Each article fires once; only articles from the last 2 days fire. More than 100 new articles go out as several deliveries.

| Field | Type | Description |
| --- | --- | --- |
| `event` | string | `news.fired`. |
| `webhook_id` | string | The webhook that fired. |
| `name` | string | The webhook’s name. |
| `search` | string or null | The webhook’s `search`, or `null`. |
| `ticker` | string[] or null | The webhook’s tickers, or `null`. |
| `universe` | string or null | The webhook’s universe, or `null`. |
| `min_relevance` | number or null | The webhook’s `min_relevance`, or `null`. |
| `q` | string or null | The webhook’s filter, or `null`. |
| `as_of` | timestamp | When the delivery was built (ISO 8601); on data served behind live, the time of that data. |
| `articles` | object[] | Up to 100 new articles, oldest first, each a Query news row with its `mentions`. A webhook with `select` gets `id`, the named fields and `mentions`. |
| `articles[].id` | number | The article's id. Stable; use it to drop duplicates. |
| `articles[].time_published` | string | When the article was published (ISO 8601). |
| `articles[].title` | string | Headline. |
| `articles[].summary` | string | The publisher's summary. Not in the default row: name it in `select`. |
| `articles[].source` | string | Publisher name. |
| `articles[].source_domain` | string | Publisher's domain. |
| `articles[].category` | string | The feed's category for the source. |
| `articles[].authors` | array | Bylines. |
| `articles[].topics` | array | Topics the article is tagged with, each `topic` and `relevance_score`. |
| `articles[].overall_sentiment_score` | number | The article's overall sentiment, -1 to 1. |
| `articles[].overall_sentiment_label` | string enum | The article's overall sentiment label, from `overall_sentiment_score`. One of the `articles[].overall_sentiment_label` values below. |
| `articles[].tickers` | array | Every ticker the article mentions. |
| `articles[].mentions` | array | How the article treats each ticker it mentions, in the order of `tickers`. |
| `articles[].mentions[].ticker` | string | The ticker mentioned. |
| `articles[].mentions[].sentiment_score` | number | The article's sentiment toward this ticker, -1 to 1. `null` on articles that carry a label only. |
| `articles[].mentions[].sentiment` | string enum | The sentiment label for this ticker, from `sentiment_score`. One of the `articles[].mentions[].sentiment` values below. |
| `articles[].mentions[].relevance` | number | How much the article is about this ticker, 0 to 1 (1 = it is the subject). `q=relevance >= 0.8` keeps the articles about it. |
| `articles[].banner_image` | string | Image URL, when the publisher gives one. |
| `articles[].url` | string | Link to the article. |
| `articles[].created_at` | string | When the article entered the archive (ISO 8601). A time in the data, so ISO like `time_published`, not the epoch seconds of a webhook's or universe's own `created_at`. |
| `article_count` | integer | How many articles this delivery carries. |

`articles[].overall_sentiment_label` values:

| Value | Meaning |
|-------|---------|
| `Bearish` | Score from -1 to -0.35. |
| `Somewhat-Bearish` | Score from -0.35 to -0.15. |
| `Neutral` | Score from -0.15 to 0.15. |
| `Somewhat-Bullish` | Score from 0.15 to 0.35. |
| `Bullish` | Score from 0.35 to 1. |

`articles[].mentions[].sentiment` values:

| Value | Meaning |
|-------|---------|
| `Bearish` | Score from -1 to -0.35. |
| `Somewhat-Bearish` | Score from -0.35 to -0.15. |
| `Neutral` | Score from -0.15 to 0.15. |
| `Somewhat-Bullish` | Score from 0.15 to 0.35. |
| `Bullish` | Score from 0.35 to 1. |


## Verifying deliveries

Every delivery to a `target_url` carries an `X-Tickerbot-Signature` header. Check it before you trust the body: a valid signature proves the request came from Tickerbot and the body arrived unchanged.

The key is the webhook’s `signing_secret` (`whsec_…`), returned in the response of the subscribe call that created the webhook. Store it then: the create response is the one place it appears. Each webhook has its own.

1. Split the header on commas and read `t` (the Unix time the delivery was signed) and `v1` (the hex signature).
2. Compute HMAC-SHA256 over `<t>.<raw-body>` with the `signing_secret` as the key, and hex-encode it. Use the body bytes exactly as received: parsing and re-serializing the JSON changes them.
3. Compare your digest with `v1` in constant time (`crypto.timingSafeEqual` in Node, `hmac.compare_digest` in Python). Reject the delivery on a mismatch.
4. Reject a delivery whose `t` is more than 5 minutes from your clock, so a captured request cannot be replayed. Each attempt is signed when it is sent, retries and resends included.

Node.js (Express):

```javascript
const crypto = require('crypto')
const express = require('express')
const app = express()

// express.raw keeps the body as the exact bytes we signed.
app.post('/webhooks/tickerbot', express.raw({ type: 'application/json' }), (req, res) => {
  const header = req.get('X-Tickerbot-Signature') || ''
  const parts = Object.fromEntries(header.split(',').map((p) => p.trim().split('=')))
  const t = parts.t
  const sig = parts.v1 || ''
  if (!t || !sig) return res.status(400).send('missing signature')

  const expected = crypto
    .createHmac('sha256', process.env.TICKERBOT_SIGNING_SECRET)
    .update(`${t}.`)
    .update(req.body)
    .digest('hex')
  const ok = sig.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))
  if (!ok) return res.status(401).send('bad signature')
  if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return res.status(401).send('stale')

  const delivery = JSON.parse(req.body)
  // ... handle delivery.event
  res.sendStatus(200)
})
```

Python (Flask):

```python
import hashlib, hmac, os, time
from flask import Flask, request

app = Flask(__name__)
SECRET = os.environ['TICKERBOT_SIGNING_SECRET'].encode()

@app.post('/webhooks/tickerbot')
def tickerbot_webhook():
    header = request.headers.get('X-Tickerbot-Signature', '')
    parts = dict(p.strip().split('=', 1) for p in header.split(',') if '=' in p)
    t, sig = parts.get('t'), parts.get('v1', '')
    if not t or not sig:
        return 'missing signature', 400

    body = request.get_data()  # the raw bytes, before any JSON parsing
    expected = hmac.new(SECRET, t.encode() + b'.' + body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(sig, expected):
        return 'bad signature', 401
    if abs(time.time() - int(t)) > 300:
        return 'stale', 401

    delivery = request.get_json()
    # ... handle delivery['event']
    return '', 200
```

## When delivery fails

A delivery that doesn't get a `2xx` is retried 7 times: 30s → 2m → 10m → 1h → 3h → 6h → 12h, about 22 hours in all. After that it is `permanent_failure`. Each attempt times out after 10 seconds.

Discord deliveries ride the same retry ladder, with one twist. A `2xx` (Discord returns `204`) is a success. A `429` is retried, honoring Discord's `Retry-After`. Other `4xx` responses (e.g. a deleted webhook → `404`) are `permanent_failure`, with no retry. `5xx` and network errors retry on the standard ladder.

The first time a delivery fails for good, we email you; one email per failure streak. `failing_since` on the webhook says when the streak began. If deliveries have kept failing for 72 hours (since `failing_since`) with none getting through, the next delivery that fails for good disables the webhook. Any delivered or failed delivery can be resent (not a test fire; the webhook must be on) with `POST /v2/webhooks/{webhook}/deliveries/{delivery}/redeliver`.

### When a webhook is disabled

The record says why, in `disabled_reason`.

- `user_disabled`: you turned it off with `PATCH` and `enabled: false`.
- `delivery_failure`: deliveries kept failing for 72 hours with none getting through. We email you when it happens. Fix the endpoint, re-enable, then resend what failed from the delivery log.
- `evaluation_failure`: the trigger can no longer run, for example it names a signal that has since been renamed. We disable it on the first failed evaluation and email you the replacement; `disabled_explanation` says what changed. Correct the trigger with `PATCH /v2/webhooks/{webhook}`, then turn it back on.
- `plan_downgrade`: your webhook limit went down. Your oldest webhooks stay on up to the new limit and the newest are turned off; we email you how many. Delete webhooks to get within the limit, then turn them back on.
- `subscription_canceled`: your subscription ended. Resubscribe to turn them back on.

Turning a webhook back on (`PATCH` with `enabled: true`) re-checks the trigger first and returns `400` with the reason if it still can't run.
