# Calendar (/vela-pro/modules/catalog/calendar)



The Calendar module (`@luxalgo/vela-pro-calendar`) adds a side panel displaying scheduled macroeconomic releases, corporate events, and market holidays by date. It is an opt-in module that bundles no static event dataset; instead, you connect a `CalendarSource` adapter backed by your API. When no source is configured, the panel renders `"No calendar connected"`.

Key features include:

* Six event categories: Economic (macro releases displaying actual, forecast, and previous figures color-coded for beats and misses, impact badges, live speech indicators, and a current-time marker), Earnings, Dividends, Splits, IPO, and Holidays.
* A four-week date strip with a Today button, weekly navigation arrows, and indicator dots on dates with scheduled events.
* Time-zone normalization that places timestamped economic releases on the viewer's local calendar date and local clock time, while keeping corporate events and market holidays anchored to their nominal `YYYY-MM-DD` date.
* Active-chart integration where clicking an earnings, dividend, split, or IPO row loads that symbol on the active chart, and rows matching the active chart's ticker are highlighted.

## Configuration [#configuration]

See [Installation](/vela-pro/get-started/setup) for adding `@luxalgo/vela-pro-calendar` to your project, then pass `calendar({ source })` in the `plugins` array of `enableVelaPro()`:

```ts
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro } from '@luxalgo/vela-pro';
import { calendar, type CalendarData, type CalendarSource } from '@luxalgo/vela-pro-calendar';

const source: CalendarSource = {
    async load({ from, to }, signal) {
        const res = await fetch(`/api/calendar?from=${from}&to=${to}`, { signal });
        if (!res.ok) throw new Error(`Calendar: HTTP ${res.status}`);
        return (await res.json()) as Partial<CalendarData>;
    },
};

enableVelaPro({
    plugins: [
        calendar({
            source,
            tabs: ['economic', 'earnings', 'dividends', 'holidays'],
            minImpact: 'medium',
        }),
    ],
});

const workspace = new VelaWorkspace('#chart', {
    layout: false,
    symbol: 'BTCUSDT',
    providers: { binance: () => new BinanceProvider() },
    persist: true,
});
```

### Options [#options]

| Option         | Default           | Description                                                                                                             |
| -------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `source`       | `null`            | `CalendarSource` adapter supplying calendar events.                                                                     |
| `timeZone`     | Browser time zone | Viewer's IANA time zone identifier.                                                                                     |
| `tabs`         | All six tabs      | Visible category tabs in display order (`'economic'`, `'earnings'`, `'dividends'`, `'splits'`, `'ipos'`, `'holidays'`). |
| `minImpact`    | `'low'`           | Initial minimum impact filter on the Economic tab (`'low'` shows all events, `'medium'`, or `'high'`).                  |
| `settings`     | None              | Initial `{ tab, minImpact }` state.                                                                                     |
| `selectSymbol` | `true`            | Loads the symbol on the active chart when the user clicks a corporate event row.                                        |
| `onItemClick`  | None              | Callback invoked with `(item, ctx)` whenever the user clicks any calendar row.                                          |
| `width`        | `400`             | Initial side panel width in pixels. Users can resize the panel between 300 and 640 pixels.                              |
| `order`        | `5`               | Sort order among side rail panel buttons.                                                                               |

When workspace persistence is enabled, the user's selected tab and impact filter are saved in the workspace state document and take precedence over `minImpact` and `settings` on reload.

Use `onItemClick` to handle custom actions per event category by narrowing on `item.kind`:

```ts
import { enableVelaPro } from '@luxalgo/vela-pro';
import { calendar, type CalendarSource } from '@luxalgo/vela-pro-calendar';

declare const source: CalendarSource;

enableVelaPro({
    plugins: [
        calendar({
            source,
            onItemClick: (item, ctx) => {
                if (item.kind === 'economic') ctx.toast(`${item.event.currency}: ${item.event.event}`);
            },
        }),
    ],
});
```

## CalendarSource port [#calendarsource-port]

`CalendarSource` defines a single asynchronous `load` method:

```typescript
interface CalendarSource {
    load(range: { from: string; to: string }, signal: AbortSignal): Promise<Partial<CalendarData>>;
}

interface CalendarData {
    economic: EconomicRelease[];
    earnings: EarningsReport[];
    dividends: DividendEvent[];
    splits: SplitEvent[];
    ipos: IpoEvent[];
    holidays: MarketHoliday[];
}
```

`from` and `to` are inclusive `YYYY-MM-DD` date strings. The module fetches four-week windows starting on the Monday of the week preceding the selected date, caching each window so navigating within the same period reuses the loaded data. You can return any subset of `CalendarData`; omitted keys default to empty arrays. Forward `signal` to `fetch` so superseded requests abort cleanly. If `load` rejects, the panel displays `"The calendar could not load"` along with `error.message` and a Try again button.

| Category    | Event fields                                                                                                                                                                                                                                |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `economic`  | `id`, `at` (release timestamp in epoch ms), `country` (such as `US` or `EU`), `currency`, `event`, `impact` (`'high'`, `'medium'`, or `'low'`), `previous`, `forecast`, `actual` (`null` until published), and optional `period` and `unit` |
| `earnings`  | `id`, `symbol`, `date`, `epsActual`, `epsEstimate`, `revenueActual`, `revenueEstimate`, and optional `hour` (`'bmo'` before market open or `'amc'` after market close)                                                                      |
| `dividends` | `id`, `symbol`, `date` (ex-dividend date), `amount`, and optional `yield` (annualized percentage) and `paymentDate`                                                                                                                         |
| `splits`    | `id`, `symbol`, `date`, `numerator`, `denominator`                                                                                                                                                                                          |
| `ipos`      | `id`, `symbol`, `date`, and optional `company`, `exchange`, `priceRange`, `shares`                                                                                                                                                          |
| `holidays`  | `id`, `date`, `market`, `name`, and optional `earlyClose` (such as `'13:00'` for partial sessions)                                                                                                                                          |

All `date` fields use `YYYY-MM-DD` format, and unavailable numeric figures should be set to `null`.

Map your API's response format to `CalendarData` inside `load`:

```ts
import type { CalendarSource, EconomicRelease } from '@luxalgo/vela-pro-calendar';

/** Upstream API record format. */
interface MacroRow {
    id: string;
    releasedAt: string; // ISO 8601
    country: string;
    currency: string;
    title: string;
    importance: 1 | 2 | 3;
    prior: number | null;
    consensus: number | null;
    actual: number | null;
}

const IMPACT = { 1: 'low', 2: 'medium', 3: 'high' } as const;

const toRelease = (row: MacroRow): EconomicRelease => ({
    id: row.id,
    at: Date.parse(row.releasedAt),
    country: row.country,
    currency: row.currency,
    event: row.title,
    impact: IMPACT[row.importance],
    previous: row.prior,
    forecast: row.consensus,
    actual: row.actual,
});

export const source: CalendarSource = {
    async load({ from, to }, signal) {
        const res = await fetch(`/api/macro?from=${from}&to=${to}`, { signal });
        if (!res.ok) throw new Error(`Calendar: HTTP ${res.status}`);
        const rows = (await res.json()) as MacroRow[];
        return { economic: rows.map(toRelease) }; // omitted categories default to empty
    },
};
```

Keep two display rules in mind when mapping payloads:

* **Corporate event symbols:** Clicking a corporate event passes `event.symbol` to the chart, so populate `symbol` with tickers recognized by your `DataProvider`. Rows highlight automatically when `symbol` matches the active chart's base ticker (excluding any venue prefix).
* **Economic release status:** Release state is derived from `at` and `actual`. Before `at`, an event displays as upcoming; after `at` while `actual` is `null`, it displays as awaiting release; once `actual` is non-null, it displays as released. Events whose title indicates a speech, testimony, or press conference display a live badge for 45 minutes starting at `at`.

## Controller API [#controller-api]

`calendarController()` returns the `CalendarController` instance after `enableVelaPro()` installs the module, or `null` beforehand. Because the controller caches fetched date ranges, call `refresh()` when new figures are published on your backend:

```ts
import { calendarController } from '@luxalgo/vela-pro-calendar';

// Invalidate cached ranges and reload open calendar views when new macro figures arrive.
const updates = new EventSource('/api/calendar/updates');
updates.onmessage = () => calendarController()?.refresh();
```

| Member                | Description                                                                                         |
| --------------------- | --------------------------------------------------------------------------------------------------- |
| `refresh()`           | Clears cached date ranges and triggers open calendar panels to reload.                              |
| `setSource(source)`   | Attaches or replaces the active `CalendarSource` (for example, after user authentication).          |
| `hasSource`, `source` | Indicates whether a `CalendarSource` is attached and returns the current instance.                  |
| `onChange(listener)`  | Subscribes to source replacements, completed loads, and refreshes. Returns an unsubscribe function. |

## Widgets [#widgets]

`createCalendar(props)` mounts the Calendar as a standalone component outside a workspace (see [Standalone widgets](/vela-pro/modules/widgets)). All props are optional. `controller` and `tabs` are read once on creation, while the remaining props can be updated via `update(props)`.

| Prop               | Description                                                                                                       |
| ------------------ | ----------------------------------------------------------------------------------------------------------------- |
| `source`           | `CalendarSource` used when no shared `controller` is passed.                                                      |
| `controller`       | Shared `CalendarController` instance allowing multiple calendar widgets to share one cache and `refresh()` cycle. |
| `symbol`           | Active symbol highlighted across corporate event tabs.                                                            |
| `timeZone`         | Viewer's IANA time zone identifier. Defaults to the browser time zone.                                            |
| `tabs`             | Visible tabs in display order. Defaults to all six tabs.                                                          |
| `minImpact`        | Minimum impact filter on the Economic tab. Defaults to `'low'`.                                                   |
| `settings`         | Initial `{ tab, minImpact }` preferences.                                                                         |
| `host`             | Portal container for menus. Defaults to the widget's root element.                                                |
| `active`           | Controls data loading and live clock updates. Defaults to `true`.                                                 |
| `onSelectSymbol`   | Callback invoked with `symbol` when the user clicks a corporate event row.                                        |
| `onItemClick`      | Callback invoked with the clicked event item on any row click.                                                    |
| `onSettingsChange` | Callback invoked whenever the user changes the active tab or impact filter.                                       |

The widget's `tools` element contains the impact filter menu and refresh button. Use `settings()` and `applySettings(settings)` to read and restore user preferences across sessions.

## Related [#related]

* [Timeframes and sessions](/vela-pro/data/symbols/sessions)
* [Standalone widgets](/vela-pro/modules/widgets)
* [API reference: Calendar](/vela-pro/api/calendar)
