# Custom drawing tools (/vela-pro/charts/drawings/custom-tools)



Interactive drawing tools are implemented inside Vela's open-source core (`@luxalgo/vela`) and cannot be registered dynamically from host application code. However, most product requirements for domain-specific tools can be met through the public API by combining built-in tools with custom style templates, custom descriptions, and dedicated toolbar groups. When you require new geometry or anchor behavior, contribute a new tool class directly to the core.

| Requirement                                                            | Recommended approach                                                                                                      |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| A branded zone, level, or line that users place and edit interactively | Configure tool defaults or style templates on a built-in tool ([Customizing built-in tools](#customizing-built-in-tools)) |
| A dedicated toolbar group with a custom name and curated tool list     | Pass `drawings.groups` to `VelaWorkspace` ([Customizing built-in tools](#customizing-built-in-tools))                     |
| Data-driven chart annotations that users do not edit interactively     | Render primitives from an indicator (see [Custom indicators](/vela-pro/indicators/custom-indicators))                     |
| An interactive tool with new geometry or placement rules               | Add a drawing class to the core ([Core implementation steps](#core-implementation-steps))                                 |

## Customizing built-in tools [#customizing-built-in-tools]

The following example configures a workspace with custom toolbar groups, registers two named zone presets on the Rectangle tool, and customizes the tool's hover card description:

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

enableVelaPro();
registerDrawingToolDescription('Rectangle', 'Mark a zone, then pick Desk demand or Desk supply from its styles.');

const workspace = new VelaWorkspace('#chart', {
    layout: false,
    symbol: 'BTCUSDT',
    timeframe: '60',
    live: true,
    providers: { binance: () => new BinanceProvider() },
    persist: true,
    drawings: {
        groups: [
            { id: 'desk', label: 'Desk tools', tools: ['box', 'hline', 'position'] },
            { id: 'lines', label: 'Lines', tools: ['trendline', 'ray', 'parallelchannel'] },
        ],
    },
});

const drawings = workspace.chart.drawings;
const saved = drawings.toolTemplates();
const house = [
    { name: 'Desk demand', settings: { style: { lineColor: '#0e9f6e', fillColor: '#0e9f6e26' } } },
    { name: 'Desk supply', settings: { style: { lineColor: '#e02424', fillColor: '#e0242426' } } },
];
const own = (saved.box ?? []).filter((style) => !house.some((h) => h.name === style.name));
drawings.setToolTemplates({ ...saved, box: [...house, ...own] });
```

`drawings.groups` replaces the default toolbar layout with the specified groups in array order. Each group's `label` sets its accessible name on the desktop toolbar and its tab title in the mobile drawings sheet, while the toolbar button displays the icon of the last-used tool in that group.

`setToolTemplates()` adds the `Desk demand` and `Desk supply` presets to the Rectangle tool's style menu inside its settings dialog, alongside the built-in **Demand** and **Supply** presets and any styles saved by the user. Templates are shared across all charts in the workspace and persisted in the workspace state document. To change the default appearance of newly placed shapes without adding a named preset, use `setToolDefaults()` instead (see [Tool defaults and saved styles](/vela-pro/charts/drawings/editing#tool-defaults-and-saved-styles)).

`registerDrawingToolDescription()` sets the description copy shown on the tool's hover card in Vela Pro's drawing menus and toolbar tooltips, keyed by the display name shown on the toolbar.

## Architectural constraints [#architectural-constraints]

Although the root `@luxalgo/vela` package exports `registerDrawingType` and the abstract `Drawing` class (while `@luxalgo/vela/plugin` exposes only the read-only `drawingTypes` and `getDrawingType` functions), host applications cannot register custom drawing tools at runtime for three reasons:

* **Closed type key union:** `registerDrawingType` requires a `DrawingTypeKey`, which is a closed union of the 79 built-in string keys. Adding a new key requires editing the core's TypeScript source.
* **Internal base classes:** Shared base classes such as `SegmentDrawing`, `FibRatios`, and `PatternDrawing` provide the geometry projection, hit-testing, and settings schemas shared across built-in tools, whereas only the root `Drawing` class is exported publicly.
* **Fixed renderer dispatch:** The native renderer selects painting routines based on the core's known base classes and type keys. Even if a custom `Drawing` subclass is registered with a type assertion, the renderer has no corresponding painter for it.

## Core implementation steps [#core-implementation-steps]

Because the core is open source, new interactive drawing tools are contributed to the [LuxAlgo/Vela repository](https://github.com/LuxAlgo/Vela) and reach downstream applications in the next core release. All drawing model changes take place under `src/core/drawings/`.

<Steps>
  <Step title="Add the type key">
    Add the new string literal to the `DrawingTypeKey` union in `Drawing.ts`. This key serves as the public identifier accepted by `chart.drawings.add()`, `chart.drawings.setTool()`, and the workspace `drawings` option.
  </Step>

  <Step title="Implement the drawing class">
    Create the tool class under `types/` extending the closest shared base class so the implementation only specifies what is unique to the tool.
  </Step>

  <Step title="Register the tool">
    Call `registerDrawingType` in `registry.ts` with the `type` key, `group`, localized `label`, inline SVG `icon`, default style, and `create` factory. Registration powers `chart.drawings.add()`, saved-drawing deserialization, and the tool's label and icon across the UI.
  </Step>

  <Step title="Place the key on the toolbar">
    Add the type key to the appropriate section array in `toolbar.ts` (such as `HARMONIC_TYPES` or `SHAPE_TYPES`). Without an entry in `toolbar.ts`, the tool is registered for programmatic use but omitted from the default toolbar. The `lines`, `channels`, and `pitchforks` groups are an exception because their toolbar sections automatically include every type registered under those group names.
  </Step>

  <Step title="Export the class">
    Re-export the class from `src/core/drawings/index.ts`, the barrel module imported by the native renderer.
  </Step>

  <Step title="Add custom rendering if needed">
    Subclasses of `SegmentDrawing`, `FibRatios`, `RadialFib`, `PatternDrawing`, and `GlyphStamp` render automatically because `DrawingPainter` handles those families generically. Tools built on `CalloutBase` or introducing custom visual elements require a dedicated rendering branch in `src/renderers/native/drawings/DrawingPainter.ts`.
  </Step>
</Steps>

The following example adds a harmonic pattern using `HarmonicPattern` (replace the sample ratio bands with your target validation thresholds):

```typescript
// Drawing.ts: add the new member to the union
export type DrawingTypeKey = /* existing keys */ | 'altbat';

// types/AltBat.ts
import { msg } from '../../i18n/message';
import type { MessageLike } from '../../i18n/types';
import { HarmonicPattern, type HarmonicRanges } from './HarmonicPattern';

export class AltBat extends HarmonicPattern {
    readonly type = 'altbat' as const;

    patternName(): MessageLike {
        return msg('drawing.altbat.patternName', 'Alt Bat');
    }

    protected ranges(): HarmonicRanges {
        return { ab: { min: 0.33, max: 0.42 }, bc: { min: 0.382, max: 0.886 }, cd: { min: 2, max: 3.618 }, ad: { min: 1.08, max: 1.18 } };
    }
}

// registry.ts: `harmonic` provides the shared group, icon, and default style
registerDrawingType({ type: 'altbat', label: msg('drawing.altbat.label', 'Alt Bat'), ...harmonic, create: (init) => new AltBat(init) });

// toolbar.ts
const HARMONIC_TYPES: DrawingTypeKey[] = ['gartley', 'bat', 'butterfly', 'crab', 'shark', 'cypher', 'altbat'];

// index.ts
export { AltBat } from './types/AltBat';
```

`HarmonicPattern` provides the five anchor points, leg ratio calculations, and pattern validation, and `DrawingPainter` already renders all `PatternDrawing` subclasses without renderer changes. Contributions to the core should also include unit tests alongside `test/drawings-*.test.ts`, a row in the core's tool catalogue documentation, and extracted translation keys via `npm run i18n:extract` for all `msg()` strings.

### Base classes [#base-classes]

| Base class        | Typical use case                                         | Methods to implement                                     |
| ----------------- | -------------------------------------------------------- | -------------------------------------------------------- |
| `SegmentDrawing`  | Multi-segment line tools such as channels and pitchforks | `geometry(proj)` returning segments and an optional fill |
| `FibRatios`       | Fibonacci retracement and extension tools                | `defaultLevels()` and `entryLines(proj)`                 |
| `RadialFib`       | Fibonacci circles, arcs, and wedges                      | `radial(proj)` returning a center with radii and angles  |
| `PatternDrawing`  | Multi-point patterns with labeled vertices               | `vertexLabels()`                                         |
| `HarmonicPattern` | Named ratio-validated harmonic patterns                  | `patternName()` and `ranges()`                           |
| `CalloutBase`     | Two-point callout boxes with an anchor pointer           | `type` property and an optional default label            |
| `PinnedLabel`     | Single-point labels pinned to a price coordinate         | `type` property and `schema()`                           |
| `GlyphStamp`      | Single-point glyph or icon stamps                        | `type` property and `defaultGlyph()`                     |
| `Drawing`         | Custom shapes that do not fit an existing base class     | Full geometry projection methods and `schema()`          |

Keep drawing classes free of renderer imports and pixel coordinates. Anchor points are stored in data space (time and price), and screen geometry is computed through the `Projector` argument passed to projection methods. See [Adding a Drawing Tool](/vela/contributing/adding-a-drawing-tool) and [Pick a base](/vela/contributing/adding-a-drawing-tool#pick-a-base) in the core contributor docs for the full contract.

## UI and API integration [#ui-and-api-integration]

Once shipped in a core release, a registered drawing tool integrates across every Vela and Vela Pro surface automatically:

* **Drawing toolbar:** Appears in its group menu under the configured section with its registered label and icon, and is accepted in `drawings.tools` and `drawings.groups`.
* **Searchable drawing menus:** Included automatically in Vela Pro's group menus, section counts, and search index. Hover cards appear once a description is configured.
* **Radial wheel:** Appears when starred by a user or when listed in `radialWheel.fallbackTools`.
* **Programmatic API:** Accepted by `chart.drawings.add('altbat')` and `chart.drawings.setTool('altbat')`.

Menu card descriptions remain configured in your Vela Pro host application:

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

enableVelaPro({
    drawingMenus: { descriptions: { 'Alt Bat': 'An Alternate Bat harmonic pattern, validated leg by leg.' } },
});
```

## Built-in capabilities [#built-in-capabilities]

Because a drawing class declaratively defines its anchors, projected geometry, and settings schema, the core and Vela Pro provide interactive behaviors automatically without per-tool UI or state code:

* **Placement modes:** `placementMode()` selects click-by-click, press-drag-release, or freehand input, and `anchorSchema()` defines anchor counts and movement axes.
* **Selection and handles:** Drag handles, body dragging, multi-selection, and keyboard nudging work automatically.
* **Floating toolbar and settings dialog:** Controls are generated directly from the tool's `schema()` definition.
* **Persistence:** Drawings serialize to plain JSON for workspace state documents and per-symbol storage. Additional per-drawing fields serialize through `writeProps()` and `readProps()`.
* **History and clipboard:** Undo, redo, copy, paste, and duplication work automatically.
* **Workspace features:** Z-order stacking, favorites, tool defaults, saved style templates, and multi-chart drawing sync work across any registered type.

## Related [#related]

* [Drawing tools](/vela-pro/charts/drawings/tools)
* [Managing drawings](/vela-pro/charts/drawings/editing)
* [Adding a Drawing Tool (core)](/vela/contributing/adding-a-drawing-tool)
