# Journal (/vela-pro/modules/catalog/journal)



The Journal module (`@luxalgo/vela-pro-journal`) records trade executions and computes performance analytics, equity curves, and trade reviews. It requires the [Trading](/vela-pro/modules/trading/overview) module and is skipped if Trading is not installed. When both modules are registered, broker fills are recorded into the journal automatically as they occur, and round-trip trades and statistics are derived from those fills.

Key features include:

* A compact side panel displaying an account selector, date-range filter (`today`, `7d`, `30d`, `365d`, `ytd`, `all`), net PnL with an inline equity curve, win rate, profit factor, drawdown, recent trades, and session notes.
* A full-screen analytics view covering the chart column with period-over-period KPIs, daily PnL, drawdown charts, a monthly performance calendar, risk and behavioral metrics, dimensional breakdowns, a searchable trades table, daily notes, and side-by-side account or period comparisons.
* Trade and day review workflows to correct or exclude individual fills, rate setups, attach tags and mistake labels, and record planned stop-loss and profit-target levels.
* Manual trade logging via Add trade for recording executions placed outside the workspace.

## Configuration [#configuration]

See [Installation](/vela-pro/get-started/setup) for adding `@luxalgo/vela-pro-journal` to your project, then pass `journal()` alongside `trading()` 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 { journal } from '@luxalgo/vela-pro-journal';
import { trading } from '@luxalgo/vela-pro-trading';

enableVelaPro({
    plugins: [trading(), journal({ timeZone: 'America/New_York' })],
});

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

Array order in `plugins` does not matter because Vela Pro guarantees that `trading` installs before `journal`.

### Options [#options]

| Option        | Default                   | Description                                                                                                       |
| ------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `store`       | `new LocalJournalStore()` | `JournalStore` adapter used to persist journal data. Defaults to `localStorage` under the key `vela-pro.journal`. |
| `timeZone`    | Browser time zone         | IANA time zone identifier used to bucket executions into calendar days.                                           |
| `syncTrading` | `true`                    | Automatically records fills emitted by the Trading module's `Broker`.                                             |
| `width`       | `400`                     | Initial side panel width in pixels. Users can resize the panel between 300 and 720 pixels.                        |
| `order`       | `4`                       | Sort order among side rail panel buttons.                                                                         |

## Trade reconstruction [#trade-reconstruction]

The journal stores raw `JournalFill` records rather than precomputed trades. Closed and open round-trip trades, daily calendar totals, and performance statistics are derived from fills and recomputed automatically whenever fills are added, edited, or excluded. User-authored review metadata (trade notes, tags, mistakes, star ratings, planned stop/target levels, and daily notes) is stored separately by trade key so annotations persist across rebuilds.

During reconstruction, fills are grouped by account and symbol and processed chronologically. Same-side fills scale into the open position, opposite-side fills close exposure, and an opposite-side fill exceeding current size closes the active trade and opens a new trade in the reverse direction. Lot matching follows each account's `profitMethod`: `'fifo'` (default), `'lifo'`, or `'wavg'` (weighted average cost).

Each journal account has a `kind` indicating how its executions are populated:

| Kind       | Behavior                                                                                                                                   |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `'sync'`   | Mirrors the active `Broker` from the Trading module. Created automatically when the first fill arrives and named after `broker.info.name`. |
| `'import'` | Populated programmatically by application code via `addFills`.                                                                             |
| `'manual'` | Populated manually by the user via Add trade (default `kind` when calling `addAccount`).                                                   |

When `syncTrading: true` is active, broker executions are deduplicated by `fill.id`. Custom adapters built via [Broker integration](/vela-pro/modules/trading/broker) must assign stable, non-changing IDs to every `Fill`.

## Controller API [#controller-api]

`journalController()` returns the `JournalController` instance once `enableVelaPro()` installs the module, or `null` beforehand. A common integration pattern is importing historical executions from external broker statements or APIs:

```ts
import { journalController } from '@luxalgo/vela-pro-journal';

const journal = journalController();
if (journal) {
    await journal.ready(); // wait for JournalStore.load() to finish

    const account =
        journal.accounts().find((a) => a.broker === 'Broker X') ??
        journal.addAccount({ name: 'Broker X', broker: 'Broker X', kind: 'import', currency: 'USD', initialBalance: 10_000 });

    const { inserted, duplicates } = journal.addFills(account.id, [
        { id: 'x-1001', symbol: 'AAPL', side: 'buy', quantity: 10, price: 190.5, fee: 1, executedAt: Date.parse('2026-11-02T14:31:00Z') },
        { id: 'x-1002', symbol: 'AAPL', side: 'sell', quantity: 10, price: 193.2, fee: 1, executedAt: Date.parse('2026-11-03T15:02:00Z') },
    ]);
    console.info(`${inserted} fills imported, ${duplicates} already there`);

    journal.setRange('ytd');
    for (const trade of journal.trades()) console.info(trade.symbol, trade.direction, trade.netPnl);
}
```

Assign each imported fill a deterministic `id` such as your venue's execution ID. `addFills` skips any fill whose `id` already exists on the account and reports the count in `duplicates`, making repeated imports idempotent.

Additional controller methods manage accounts, fills, annotations, and filters:

| Member                                                             | Description                                                                                                                     |
| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| `trades(range?)`, `allTrades()`, `trade(key)`                      | Returns reconstructed trades in the active range, all trades on the selected account, or a single trade by key.                 |
| `selectAccount(id)`, `setRange(range)`, `setCustomRange(from, to)` | Selects the active account or date filter (`'today'`, `'7d'`, `'30d'`, `'365d'`, `'ytd'`, `'all'`, or `YYYY-MM-DD` bounds).     |
| `addAccount`, `updateAccount`, `removeAccount`                     | Creates, updates, or deletes journal accounts.                                                                                  |
| `addFills`, `updateFill`, `removeFill`, `restoreFill`              | Inserts, edits, excludes, or restores fills. Imported and synchronized fills are soft-excluded rather than permanently deleted. |
| `annotate(tradeKey, patch)`                                        | Updates a trade's `notes`, `tags`, `mistakes`, `rating`, `stopLoss`, or `profitTarget`.                                         |
| `addNote(body, date?)`, `editNote`, `deleteNote`                   | Creates, edits, or removes daily journal notes.                                                                                 |
| `syncBroker(broker)`                                               | Subscribes to fills from a `Broker` instance and returns an unsubscribe function.                                               |
| `onChange(listener)`                                               | Subscribes to `'data'` or `'selection'` updates.                                                                                |

`@luxalgo/vela-pro-journal` also exports pure calculation helpers (`computeMetrics`, `dayStats`, `equityCurve`, `breakdown`, and related functions) that accept reconstructed trade arrays returned by the controller.

## JournalStore port [#journalstore-port]

Implement `JournalStore` to persist journal accounts, executions, annotations, and notes on your backend.

```typescript
interface JournalStore {
    load(): Promise<JournalData | null>;
    save(data: JournalData): Promise<void>;
}

interface JournalData {
    accounts: JournalAccount[];
    fills: JournalFill[];
    /** User review metadata keyed by reconstructed trade key. */
    annotations: Record<string, TradeAnnotation>;
    notes: JournalNote[];
}

interface JournalAccount {
    id: string;
    name: string;
    broker: string;
    kind: 'manual' | 'import' | 'sync';
    currency: string;
    initialBalance: number | null; // enables percentage drawdown metrics when set
    profitMethod: 'fifo' | 'lifo' | 'wavg';
    createdAt: number;
}

interface JournalFill {
    id: string;
    accountId: string;
    symbol: string;
    source: 'manual' | 'import' | 'sync';
    side: 'buy' | 'sell';
    quantity: number;
    price: number;
    fee: number;
    executedAt: number; // epoch ms
    reported?: FillValues | null; // original broker/import values preserved when edited by the user
    excluded?: boolean; // soft-hidden from trade reconstruction
}
```

Resolve `null` from `load()` when the user has no saved journal data yet. `save(data)` is debounced and receives the complete `JournalData` document after mutations; reconstructed trades are omitted from storage and rebuilt on load.

```ts
import { enableVelaPro } from '@luxalgo/vela-pro';
import { journal, type JournalData, type JournalStore } from '@luxalgo/vela-pro-journal';
import { trading } from '@luxalgo/vela-pro-trading';

let loaded = false;

const store: JournalStore = {
    async load() {
        const res = await fetch('/api/journal', { credentials: 'include' });
        if (!res.ok && res.status !== 404) throw new Error(`Journal: HTTP ${res.status}`);
        loaded = true;
        return res.status === 404 ? null : ((await res.json()) as JournalData);
    },
    async save(data) {
        if (!loaded) return;
        await fetch('/api/journal', {
            method: 'PUT',
            credentials: 'include',
            headers: { 'content-type': 'application/json' },
            body: JSON.stringify(data),
        });
    },
};

enableVelaPro({ plugins: [trading(), journal({ store })] });
```

<Warning>
  If `load()` rejects, the journal starts empty and calls `save()` on the next edit. Guarding `save()` with a `loaded` flag prevents a failed initial request from overwriting stored journal records on your server.
</Warning>

## Widgets [#widgets]

Both the compact journal panel and the full-screen analytics view can be mounted outside a workspace as standalone components (see [Standalone widgets](/vela-pro/modules/widgets)).

`createJournalPanel(props)` creates the compact side panel widget. Its `tools` element contains the account selector, Add trade button, and Maximize button.

| Prop          | Description                                                                                                                |
| ------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `controller`  | Required. `JournalController` managing journal data and selection state.                                                   |
| `symbol`      | Default symbol prefilled when opening Add trade.                                                                           |
| `host`        | Portal container for menus and dialogs. Defaults to the widget's root element.                                             |
| `icons`       | Accessor returning a symbol icon source (`() => chart.data` or any object implementing `symbolIcon(symbol)`).              |
| `onMaximize`  | Callback invoked to open the full journal view, passing an optional target (`trade` key or `date`). Omit to hide Maximize. |
| `onShowTrade` | Callback invoked with a reconstructed trade so host code can frame it on a chart. Omit to hide per-trade chart buttons.    |
| `onNotify`    | Callback invoked with `(message, kind)` for status feedback.                                                               |

`createJournalView(props)` creates the full-screen analytics dashboard. It accepts `controller`, `symbol`, `host`, `icons`, `onShowTrade`, and `onNotify`, along with `onMinimize` and `onClose` (each button renders only when its callback is provided). Call `view.open(target)` to navigate directly to a specific trade or date.

When running outside a workspace, connect a `TradingController`'s broker manually by calling `journal.syncBroker(trading.broker)`.

## Keyboard shortcuts [#keyboard-shortcuts]

| Keys   | Action                                                                                       |
| ------ | -------------------------------------------------------------------------------------------- |
| Escape | Closes the maximized journal view and returns to the chart (ignored when typing in an input) |

## Related [#related]

* [Trading](/vela-pro/modules/trading/overview)
* [Broker integration](/vela-pro/modules/trading/broker)
* [API reference: Journal](/vela-pro/api/journal)
