Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,22 @@ All notable changes to Vela, newest first.

### Added

- **Magnifier drawing tool — see a finer timeframe inside an area.** Drag a
rectangle over the chart (Measurements group) and its interior redraws the
same market at a lower timeframe, in the chart's own style and colors —
candles subdivide into finer candles, a line chart magnifies into a finer
line, and Heikin Ashi stays Heikin Ashi — at their true time and price
positions. The timeframe chip riding the rectangle's bottom-left corner is
itself a dropdown: click it to switch, or use the same pick on the drawing's
toolbar — both offer only timeframes below the chart's own. Auto picks a
sensible subdivision of the chart's timeframe (a 1-hour chart magnifies into
15-minute candles); the up/down colors and the border style stay editable
when you want the inset to stand apart. The finer bars load in the
background and the area keeps up with live data; if the area is too wide
for the chosen timeframe, or the chart is already at the finest one, the
tool says so inside the rectangle instead of guessing. Like every drawing
it moves, resizes, clones, and persists with the document.

- **Scroll the price axis to rescale it.** The mouse wheel over the right
price-axis strip now zooms that pane's scale the same way dragging it does —
scroll up compresses the visible span, scroll down expands it, each notch a
Expand Down
9 changes: 6 additions & 3 deletions docs/user/drawing-tools.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Drawing tools

Vela™ ships an interactive **drawing-tools** layer: a docked toolbar and ~66 on-chart
Vela™ ships an interactive **drawing-tools** layer: a docked toolbar and ~67 on-chart
tools — trend lines, channels, Fibonacci, harmonic patterns, annotations, and more — that a user
draws, edits, and keeps on the chart. Drawings are anchored in **data space** (time + price), so
they stay locked to the bars across pan, zoom, timeframe changes, and reload — the same durability
Expand Down Expand Up @@ -122,7 +122,9 @@ A new drawing starts **just under the price** — the candles read on top of it,
on top of the indicators — so it behaves like annotation on the chart's background: a zone, a
session band, a shaded area you see *through* the candles rather than across them. From there it
can take **any position in the pane's draw order**: over everything, between two indicators, or
at the very back.
at the very back. (The one exception is a tool whose body *replaces* the series pixels inside its
area — the Magnifier's opaque inset — which starts **above** the whole stack instead, since under
the candles its content would be buried; it can still be reordered afterwards.)

- **From the object tree.** Each pane is one column, read top to bottom as front to back: its
drawings, its indicators and (in the main pane) the price series, all together. Drag a drawing
Expand Down Expand Up @@ -153,7 +155,7 @@ drawings among themselves, and the tree keeps them in one block above the series

## Tool catalogue

**66 tools across 9 groups.** The **Type key** is the string you pass to
**67 tools across 9 groups.** The **Type key** is the string you pass to
`chart.drawings.setTool('…')` or [`chart.drawings.add('…')`](#driving-drawings-from-code). Eraser,
Magnet, Measure, and Stay in drawing mode are toolbar *modes*, not placeable types, so they have no key.

Expand Down Expand Up @@ -275,6 +277,7 @@ whether it falls in that pattern's ideal Fibonacci band.
|---|---|---|
| Date & Price Range | `datepricerange` | A box reporting the time span + price/% change it covers. |
| Long/Short Position | `position` | An entry/stop/target box: click the entry, then drag in the profit direction (up for a long, down for a short). Shows risk:reward, percentages, dollar loss, and position size from your risk % and account balance (size is editable and back-solves the risk %). The gear panel has a long/short switch (mirrors the levels across the entry), exact level values in price or points, and per-label display toggles; zone colors and label styling sit on the quick bar. |
| Magnifier | `magnifier` | A press-drag-release rectangle whose interior shows the same market at a **lower timeframe**, rendered in the chart's own price style *and colors* (candles, bars, line, area, Heikin Ashi; custom chart types fall back to candles) at true time/price positions. The timeframe chip on the rectangle's bottom-left corner is a dropdown — click it to switch — and the same pick leads the quick bar, beside the up/down color overrides and the border style; **Auto** subdivides the chart's timeframe, and both pickers offer only timeframes below the chart's own. The finer bars load in the background and follow live data; when the chart is already at the finest timeframe, or the area needs more bars than the tool will fetch, a notice inside the rectangle says so. Needs a market with a ranged data source (offline `data` arrays have nothing to fetch). |

---

Expand Down
1 change: 1 addition & 0 deletions src/core/drawings/Drawing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export type DrawingTypeKey =
| 'goldensupersonic'
| 'datepricerange'
| 'position'
| 'magnifier'
| 'xabcd'
| 'abcd'
| 'elliottimpulse'
Expand Down
17 changes: 12 additions & 5 deletions src/core/drawings/DrawingController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { IChartRenderer } from '../ports/IChartRenderer';
import type { TypedEventBus } from '../events/EventBus';
import type { VelaEventMap } from '../events/types';
import type { IDrawingsRendererPort, DrawingIntent, DrawingMode } from './port';
import type { DrawingSeriesGateway } from './series';
import type { DrawingsOption } from './toolbar';
import { getDrawingType } from './registry';
import { buildToolbar } from './toolbar';
Expand Down Expand Up @@ -58,13 +59,15 @@ export class DrawingController {
renderer: IChartRenderer,
private readonly events: TypedEventBus<VelaEventMap>,
option: DrawingsOption | undefined,
seriesGateway?: DrawingSeriesGateway,
) {
this.enabled = !!renderer.capabilities.userDrawings && !!renderer.userDrawingsPort;
this.port = this.enabled ? renderer.userDrawingsPort! : null;
if (this.port) {
const { definition, visible } = buildToolbar(option);
this.port.setToolbar(definition);
this.port.showToolbar(visible);
if (seriesGateway) this.port.setSeriesGateway?.(seriesGateway);
this.subs.push(this.port.onDrawingIntent((i) => this.onIntent(i)));
this.subs.push(this.store.onChange(() => this.sync()));
}
Expand Down Expand Up @@ -193,7 +196,7 @@ export class DrawingController {
style,
text: init.text,
props: init.props,
zIndex: init.zIndex ?? this.startZ(init.paneId ?? 'price'),
zIndex: init.zIndex ?? this.startZ(type, init.paneId ?? 'price'),
});
if (!d) return null;
this.history.record(this.store.serialize());
Expand Down Expand Up @@ -283,10 +286,14 @@ export class DrawingController {
* (falling back to just under the pane's top series where there is no price — a study
* pane). Half a key down never ties a series; drawings tying each other paint in insertion
* order, so consecutive new drawings still stack newest-in-front. Undefined without a
* shared z space — the store then places it over the other drawings, its own layer's top. */
private startZ(paneId: string): number | undefined {
* shared z space — the store then places it over the other drawings, its own layer's top.
* A type that COVERS the series (an opaque inset, `coversSeries`) instead starts just
* above the whole stack — under the candles its content would be buried. */
private startZ(type: DrawingTypeKey, paneId: string): number | undefined {
const range = this.port?.stackRange?.(paneId);
return range ? (range.price ?? range.front) - 0.5 : undefined;
if (!range) return undefined;
if (getDrawingType(type)?.coversSeries) return range.front + 0.5;
return (range.price ?? range.front) - 0.5;
}

/** Programmatically select drawings (host UI → chart): shows the on-chart handles + toolbar.
Expand Down Expand Up @@ -457,7 +464,7 @@ export class DrawingController {
const style = last ? { ...i.doc.style, ...last } : i.doc.style;
const d = deserializeDrawing({ ...i.doc, id: this.store.nextId(), style });
if (!d) return;
if (!d.zIndex) d.zIndex = this.startZ(d.paneId) ?? 0; // a freshly placed drawing starts under the price
if (!d.zIndex) d.zIndex = this.startZ(d.type, d.paneId) ?? 0; // a freshly placed drawing starts under the price (or over the stack when it covers the series)
this.history.record(before);
this.store.add(d);
this.captureStyle(d.id);
Expand Down
10 changes: 10 additions & 0 deletions src/core/drawings/geometry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
* same invariant Pine drawings get from `xloc:'bar_time'`.
*/

import type { DrawingSeriesState } from './series';

/** A drawing anchor in DATA space (epoch-ms time + data-space price). */
export interface DrawingPoint {
/** Epoch ms — resolved to a fractional logical bar index by the time scale. */
Expand Down Expand Up @@ -69,6 +71,14 @@ export interface Projector {
* then degrade gracefully to an anchor-only fallback.
*/
barsInRange?(from: number, to: number): ReadonlyArray<{ time: number; open: number; high: number; low: number; close: number; volume?: number }>;
/**
* Bars of a FINER timeframe than the chart's, for the same symbol — the async sibling
* of {@link barsInRange} (see {@link DrawingSeriesGateway}): a cache read that reports
* `loading` while the background fetch runs, after which the renderer repaints.
* Optional: renderers without a series gateway omit it, and such drawings degrade to
* an anchors-only rendering.
*/
seriesInRange?(timeframe: string, from: number, to: number): DrawingSeriesState;
/** Plot width in media px (excludes the right price-axis strip). */
readonly width: number;
/** Plot height in media px (excludes the bottom time-axis strip). */
Expand Down
2 changes: 2 additions & 0 deletions src/core/drawings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ export { HeadShoulders } from './types/HeadShoulders';
export { MeasureBox, formatDuration } from './types/MeasureBox';
export { DatePriceRange } from './types/DatePriceRange';
export { PositionTool, DIRECTION_OPTIONS, type PositionLevelMode } from './types/PositionTool';
export { Magnifier, MAGNIFIER_TIMEFRAME_OPTIONS, magnifierTimeframeLabel, type MagnifierStyle } from './types/Magnifier';
export type { DrawingSeriesBar, DrawingSeriesState, DrawingSeriesGateway } from './series';
export {
registerDrawingType,
getDrawingType,
Expand Down
5 changes: 5 additions & 0 deletions src/core/drawings/port.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Unsubscribe } from '../util/types';
import type { DrawingTypeKey, SerializedDrawing } from './Drawing';
import type { SnapMode } from './geometry';
import type { DrawingSeriesGateway } from './series';
import type { ToolbarDefinition } from './toolbar';

/**
Expand Down Expand Up @@ -85,6 +86,10 @@ export interface IDrawingsRendererPort {
* renderer keeps owning the mutual exclusion (with armed tools too) and reports
* every actual change back through the `mode` intent. Optional. */
setMode?(mode: DrawingMode): void;
/** Hand the renderer the core's series gateway so data-driven drawings can read bars
* of a finer timeframe (exposed to them as `Projector.seriesInRange`). Optional — a
* renderer without it simply never resolves lower-timeframe series. */
setSeriesGateway?(gateway: DrawingSeriesGateway): void;
/** Open a drawing's settings popup (selecting it too) — the programmatic twin of a click on it. */
openSettings(id: string): void;
/** Display another chart's in-progress placement as a GHOST at reduced opacity
Expand Down
26 changes: 26 additions & 0 deletions src/core/drawings/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ import { Shark } from './types/Shark';
import { Cypher } from './types/Cypher';
import { DatePriceRange } from './types/DatePriceRange';
import { PositionTool } from './types/PositionTool';
import { Magnifier } from './types/Magnifier';

/** What a drawing type contributes to the toolbar + factory (renderer-neutral). */
export interface DrawingTypeMeta {
Expand All @@ -84,6 +85,13 @@ export interface DrawingTypeMeta {
/** Inline SVG markup for the toolbar button — no DOM, renderer paints it. */
icon: string;
defaultStyle: DrawingStyle;
/** The tool's body REPLACES the series pixels inside its area (an opaque inset): a fresh
* instance then starts ABOVE the pane's series stack instead of just under the candles —
* under them its content would be buried. The user can still reorder it afterwards. */
coversSeries?: boolean;
/** One short sentence prompting the placement gesture, shown by the renderer at the
* bottom of the chart while the tool is armed and no placement has started yet. */
placementHint?: string;
/** Build an instance from a (partial) serialized record. Serves create + deserialize. */
create(init: Partial<SerializedDrawing> & { paneId: string }): Drawing;
}
Expand Down Expand Up @@ -923,6 +931,24 @@ registerDrawingType({
create: (init) => new PositionTool(init),
});

// ── magnifier (lower-timeframe inset) ──
const MAGNIFIER_ICON = svg24(
'<circle cx="10.5" cy="10.5" r="6.5"/><path d="m15.3 15.3 5.2 5.2"/><path d="M8 12.5v-3M10.5 13.5v-5.5M13 12v-2"/>',
);

registerDrawingType({
type: 'magnifier',
group: 'measure',
label: 'Magnifier',
icon: MAGNIFIER_ICON,
// An empty border color means the THEME's contrast ink (white on dark, black on
// light), resolved at paint time so it follows theme switches; a user pick wins.
defaultStyle: { lineColor: '', lineWidth: 1, lineStyle: 'solid' },
coversSeries: true, // the inset's backdrop must sit over the base candles it replaces
placementHint: 'Drag an area on the chart to view it at a lower timeframe',
create: (init) => new Magnifier(init),
});

// ── anchored VWAP ──
const VWAP_ICON =
svg24('<line x1="5" y1="3" x2="5" y2="21"/><path d="M5 16c4 0 5-9 8-9s3 5 8 3"/>');
Expand Down
53 changes: 53 additions & 0 deletions src/core/drawings/series.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import type { Unsubscribe } from '../util/types';

/**
* Async series access for data-driven drawings — the ranged, any-timeframe sibling
* of {@link Projector.barsInRange}. Painting stays synchronous: a read either serves
* bars from cache or reports `loading` while a fetch runs in the background; the
* gateway then fires {@link DrawingSeriesGateway.onUpdate} so the renderer repaints
* and the next read finds the bars. Neutral by design — any drawing that needs bars
* of a finer timeframe than the chart's reads through this seam.
*/

/** One OHLC(V) bar as the gateway returns it (`time` = bar open, epoch ms). */
export interface DrawingSeriesBar {
time: number;
open: number;
high: number;
low: number;
close: number;
volume?: number;
}

/**
* The synchronous answer to a series read. `ready` and `loading` carry the RESOLVED
* timeframe (an `'auto'` request comes back concrete) and its bar duration so consumers
* never re-derive timeframe math. `loading` may carry best-effort PARTIAL bars from
* previously fetched overlapping windows, so a resize keeps painting what it already
* has while the widened fetch runs; `unavailable` is a terminal state for this
* request — no fetch was started.
*/
export type DrawingSeriesState =
| { state: 'loading'; timeframe: string; barMs: number; bars?: ReadonlyArray<DrawingSeriesBar> }
| { state: 'ready'; bars: ReadonlyArray<DrawingSeriesBar>; timeframe: string; barMs: number }
| {
state: 'unavailable';
/** `no-source` = the market has no ranged feed (inline data); `none-lower` = NO
* offered timeframe is below the chart's (the chart is already at the finest);
* `not-lower` = the explicit pick does not subdivide the chart's (lower picks
* exist); `too-wide` = the range would need more bars than the gateway's cap. */
reason: 'no-source' | 'none-lower' | 'not-lower' | 'too-wide';
};

/**
* The core-owned gateway the renderer hands drawings via {@link Projector.seriesInRange}.
* `timeframe` accepts a canonical value (`'5'`, `'60'`, `'D'`) or `'auto'` — the gateway
* resolves `'auto'` against the chart's own timeframe and refuses anything not strictly
* lower than it.
*/
export interface DrawingSeriesGateway {
/** Synchronous cache read for the CHART's OWN symbol; kicks a background fetch on a miss. */
seriesInRange(timeframe: string, from: number, to: number): DrawingSeriesState;
/** Fires when a background fetch lands new bars (the renderer repaints on it). */
onUpdate(listener: () => void): Unsubscribe;
}
2 changes: 1 addition & 1 deletion src/core/drawings/toolbar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ const PATTERN_TYPES: DrawingTypeKey[] = ['xabcd', 'abcd', 'headshoulders'];
const ELLIOTT_TYPES: DrawingTypeKey[] = ['elliottimpulse', 'elliottcorrection'];
const HARMONIC_TYPES: DrawingTypeKey[] = ['gartley', 'bat', 'butterfly', 'crab', 'shark', 'cypher'];

const MEASUREMENT_TYPES: DrawingTypeKey[] = ['position', 'datepricerange'];
const MEASUREMENT_TYPES: DrawingTypeKey[] = ['position', 'datepricerange', 'magnifier'];
const VOLUME_TYPES: DrawingTypeKey[] = ['anchoredvwap', 'fixedrangevp'];

const BRUSH_TYPES: DrawingTypeKey[] = ['freehand', 'highlighter'];
Expand Down
Loading
Loading