Esta página ainda não foi traduzida, por isso aparece em inglês.

Drawing tools

76 built-in drawing tools. Each one snaps to the bars with the magnet, takes undo and redo, keeps its own settings, and is saved with the layout.

Drawing with the pointer

chart.setDrawingTool('trendLine')   // the next clicks draw a trend line
chart.setDrawingTool(null)          // back to the cursor
chart.setStayInDrawingMode(true)    // keep the tool after each drawing

A tool is drawn one of three ways:

  • Clicks — one click per point (two for a trend line, five for an XABCD pattern).
  • Freehand — press and drag; brush and highlighter.
  • Path — one click per point, then a double-click, Enter, or a click on the last point ends it; path and polyline.

Escape drops a drawing that is not finished yet.

Adding drawings from code

const id = chart.addDrawing({
  type: 'fibRetracement',
  anchors: [{ time: t1, price: 101.2 }, { time: t2, price: 96.4 }],
  style: { color: '#f2a93b' },
  options: { reversed: true, extendRight: true },
})

chart.autoFib()   // a retracement over the dominant swing in view, or null

On indicator panes

A drawing begun on an indicator pane (RSI, MACD…) is made on that pane: its anchors’ prices are the pane’s values, the magnet snaps to the pane’s lines, and it follows the pane’s scale. It stays inside its pane. Side panes and folded ones take no drawings, and the tools that read the bars’ prices (Anchored VWAP, Volume Profile, Long/Short Position) stay on the price pane. A pane’s drawing takes no price alert.

const rsi = chart.addIndicator('rsi')
chart.addDrawing({
  type: 'horizontalLine',
  anchors: [{ time: t1, price: 70 }],   // 70 on the RSI scale
  paneId: rsi,                          // a pane’s id, as getIndicatorPanes() lists them
})

When the indicator that owns the pane is removed and another in the pane takes it over, its drawings go with the pane. When the pane goes, its drawings are hidden and come back with it on undo. A saved layout puts them back on their panes.

Text

The text tools (Text, Note, Callout, Price Label, Arrow Mark) share one text style: size, bold, italics and a colour of their own. A Text, a Note and a Callout also line their lines up left, centre or right, can have a background and a border, and wrap at a width. A Text keeps its own line breaks and runs on unless it is given one; a Note and a Callout wrap at 240 px. A Note, a Callout, a Signpost and a Balloon write in a bubble filled with their colour, in the ink that reads on it, so the bars under them do not show through the words; a fillColor or a textColor of their own is kept. A Callout's pointer is its bubble's tail: it leaves the side facing the point.

Without a size of their own, words are set at 14 px and figures (a level's price, a ratio, a stats box) at 12 px, both a step or more over the axis type and growing with it (chart.setFont, and the widget on a wide screen). A size of 12 saved by an earlier version reads as none. Words people write are set in the system's sans face, figures in the chart's face; font: { textFamily } (or chart.setFont({ textFamily })) gives the words a face of your own, and the widget gives them its look's.

chart.addDrawing({
  type: 'text',
  anchors: [{ time: t1, price: 101.2 }],
  style: {
    text: 'Breakout\nretest here',     // its own line breaks are kept
    fontSize: 14, bold: true, italic: false,
    textAlign: 'center',              // 'left' | 'center' | 'right'
    textColor: '#f2a93b',
    textBackground: true, fillColor: '#1e222d', fillOpacity: 0.8,
    textBorder: true, borderColor: '#f2a93b',
    textWrap: 200,                    // px; 0: only where the text breaks
  },
})

In the widget, a text, a note, a callout, a signpost, a balloon or an anchored text or note opens a box over its words as soon as it is drawn and on a double-click: type over them, Enter or a click away keeps them, Shift+Enter starts a new line, and Escape puts them back (a text just drawn goes, with no words too). One undo takes a text just drawn and its words away. Its settings stay a click away, on the toolbar over it or its menu. The toolbar over a selection sets the fill and the text colour of the tools that have them. chart.getDrawingTextRect(id) says where a text's box is, to lay an editor of your own over it.

Text on lines and boxes

A trend line, a ray, an extended, info or angle line, an arrow, a horizontal or vertical line and a rectangle take a text too, in the same style. textAlign puts it at the line's left end, its middle or its right end, and textVAlign above the line, on it or under it; in a rectangle they place it inside, at its top, middle or bottom. The text follows the line's slope and always reads left to right, and bottom to top along a vertical line. In the widget the Text tab has the two rows. Its words are typed in place too: the Text button on the toolbar over the selected drawing, Text in its menu, or a double-click on the words opens the box (a double-click on the line itself opens its settings). Enter or a click away keeps them, Escape puts them back, and a line left with no words is a line again.

chart.addDrawing({
  type: 'trendLine',
  anchors: [{ time: t1, price: 98 }, { time: t2, price: 104 }],
  style: { color: '#4c8dff', lineWidth: 2, lineStyle: 'solid',
    text: 'Breakout', textAlign: 'right', textVAlign: 'top' },  // 'top' | 'middle' | 'bottom'
})
chart.addDrawing({ type: 'verticalLine', anchors: [{ time: t3, price: 0 }], options: { showTime: true } })
chart.addDrawing({ type: 'fibRetracement', anchors: [a, b], options: { trendLine: false, oneColor: true } })

A horizontal line and a horizontal ray hide their price with showPrice: false. A vertical line shows its bar's time with showTime: true, written as the crosshair writes it. A rectangle has eight handles: one at each corner and one in the middle of each side, which moves that side alone. A Fibonacci retracement and extension draw a dashed line through their points (trendLine, on by default) and draw all their levels in the drawing's colour with oneColor. A click on the words picks the line or the box too. A retracement puts 0 where the move ends, at its second point, so 38.2% is the price that gives back 38.2% of it; reversed: true measures from the first point. Its levels and an extension's stay between their points unless extendLeft or extendRight is set, each label beside its line's end. A parallel channel has its middle line unless middleLine: false. A horizontal line's price and a vertical line's time are tagged on the axes, selected or not. A drawing saved before these were the defaults is loaded as it was drawn.

How drawings look

Every tool is drawn the same way:

  • A selected drawing's handles are rings in its colour, filled with the chart's background (the drawings.handleColor style key fills them with a colour of yours), a size over its line: 9 px across on a 1 px line, more on a thicker one. The handle under the pointer grows, and the one in hand fills with the colour. Only the drawing a drag would reshape shows rings; the others of a selection, and a locked drawing, show small dots.
  • A drawing under the pointer glows a little, so it is plain which one a click takes.
  • While a drawing is made, the points placed show as handles.
  • Dashes and dots grow with the line, dots are round, and a solid line's ends are round. Arrowheads grow with the line too.
  • A fill is the line's colour, tinted, unless it was set on its own: a drawing turned red fills red. A label on a coloured tag is written in black or white, whichever reads; a stats box is the chart's own surface and text colour, in both themes; words in a drawing's colour are deepened where they would not read on a light background.
  • A tool's own lines follow its line style; its grids, guides and secondary angles are 1 px and lighter. A level, an angle or a division whose label would cover another's is left unlabelled, never the 0 and 1 levels. Percentages are written whole when they are (50%, not 50.0%), and each Fibonacci ratio drawn with others has a colour of its own.
  • Rises and falls (a price range, a Long/Short position's target and stop, a forecast's outcome) take the theme's profit and loss colours (the trading.profitColor and trading.lossColor style keys), green and red without them.
  • A text, an icon or an arrow mark shows no handle, which would sit on its letters or its glyph: selected, it is framed, and a press anywhere on it moves it.

Settings

Besides its style (colour, width, line style, fill, text), a tool can offer settings of its own: Fibonacci levels, extending a line left or right, labels, a background, an icon, a wave degree. The settings dialog of the widget is built from them.

chart.getDrawingOptionDefs('fibRetracement')  // what the tool offers
chart.getDrawingOptions(id)                   // its values, defaults filled in
chart.setDrawingOptions(id, {
  levels: [{ value: 0.5, visible: true }, { value: 0.618, visible: true, color: '#e8505b' }],
})

// several changes as one undo step
chart.updateDrawing(id, { style: { lineWidth: 2 }, options: { extendLeft: true } })

// a dialog previewing changes: one undo step, or put back on cancel
chart.beginDrawingEdit(id)
chart.updateDrawing(id, { style: { color: '#26a69a' } })
chart.endDrawingEdit(id, { cancel: false })

// what every new Fibonacci retracement starts with
chart.setDrawingToolDefaults('fibRetracement', { showPrices: false })

Settings from a saved layout or a pasted drawing are checked against the tool; values it does not take are dropped.

The settings dialog

In the widget, a double-click on a drawing (or Settings on its toolbar, its menu or the object tree) opens its settings in tabs. Style: the line (colour, width, dash) in one row, its ends, the fill, then the tool's switches and choices, and its levels. Text, for the tools that write: the text and its size. Coordinates: each point's price, date and time, in the chart's time zone. Visibility: the intervals it shows on. Every change shows at once; OK keeps them as one undo step, Cancel (or Escape) puts the drawing back. The Template menu applies or deletes a saved template, saves the drawing's look as one, keeps the options as the tool's default, and resets them.

Shown on some intervals

A drawing can be kept to some intervals, with the rules an indicator takes: a unit off (minutes: false), or a range of it (hours: [1, 4]). On the other intervals it is not drawn, not hit and not selected. The rules are saved with the layout.

chart.updateDrawing(id, { intervals: { minutes: false } })  // not on minute charts
chart.isDrawingShown(id)                                    // false on a 5m chart
chart.updateDrawing(id, { intervals: null })                // every interval again

chart.addDrawing({ type: 'horizontalLine', anchors: [{ time: t, price: 100 }], intervals: { days: false, weeks: false } })

On a bare Chart without a stream, give the interval of your bars with chart.setDataTimeframe('5m').

A line's ends, middle and stats

Trend lines, rays and extended lines can show their middle point, and stats between their two points: the price's change and its percentage, the bars and the time between them, the angle. The stats show while the line is selected, or all the time, by its right end, its middle or its left end. A trend line's ends can be arrows. All of it is off until asked for.

chart.setDrawingOptions(id, {
  showPriceRange: true, showBarsRange: true, showDateRange: true, showAngle: true,
  alwaysShowStats: true, statsPosition: 'right',   // 'left' | 'center' | 'right'
  showMiddlePoint: true,
  rightEnd: 'arrow',                                // trend lines: leftEnd, rightEnd
})

The toolbar over a selection

In the widget, clicking a drawing shows a small toolbar right over it: colour, line width and line style, then settings, an alert on its line, lock, the full drawing menu (the same as a right-click) and delete. With several drawings selected it sits over all of them, and its changes go to each. It follows the drawing while it is moved, panned or zoomed, steps aside while a drawing tool, the eraser or the zoom area is on, and is one tab stop that the arrow keys move along.

On a chart too narrow for all of its buttons (a phone) it stays on one line and gives up buttons instead: first those the drawing's menu holds too (the alert, the lock, the words, the settings, each only while the menu has its entry), then the figure beside the line width, then the colours the settings hold. The line's colour, width and style, the menu and delete stay. On a phone it waits at the foot of the plot, beside the drawing tools' button. Menus and panels open over it.

new ChartWidget(host, { features: { selectionToolbar: false } })  // turn it off
widget.setFeatures({ selectionToolbar: true })

// Your own controls over a drawing, on a bare Chart:
chart.on('drawingSelect', ({ payload }) => {
  const rect = payload.primary ? chart.getDrawingRect(payload.primary) : null
  // { x, y, width, height } in px from the chart container's top-left, or null
})

Long/Short Position

riskReward: drag from the entry to the stop. The target sits the reward:risk ratio away. From the account size and the risk (a percent of the account, or an amount) it works out the quantity, and shows each line's price, distance and profit or loss.

Selected, it has four handles: the entry, the stop and the target on the entry's edge, and its other edge on the entry line. The entry moves in time and price, the stop changes its price, the target the reward:risk ratio, and the other edge how long the trade runs.

Over the bars in that span it plays the trade out. The trade is entered on the first bar at or after the entry. Each bar after it is checked for the stop and the target; one that reaches both is taken as the stop, since which came first is not in the bar, and one that opens past a level closes the trade at its open. The part the trade went through is tinted in the colour of what it made, with a dashed line from the entry to where it closed and a tag there: Target hit, Stop hit, Closed at the right edge, or Open at the last bar, with the profit or loss. It is played on the series' own prices (under Heikin Ashi too), and left out for a box drawn back from its entry and on chart types whose bars are not the series' (Renko, Kagi, line break, point & figure). showOutcome: false turns it off.

chart.setDrawingOptions(id, { accountSize: 25_000, riskMode: 'percent', risk: 1, rewardRatio: 3 })
chart.setDrawingOptions(id, { showOutcome: false })   // the zones and their tags only

positionLevels(drawing) reads one as a trade, for an app that places an order from it: its side ('buy' for a long), entry, stop-loss, take-profit and the quantity its risk buys, unrounded, with the decimals the drawing writes it in. It gives null for any other drawing, for a position whose stop is still on its entry, for one with no risk set (no quantity), and for prices that are not finite numbers.

In the widget, a selected Long/Short Position shows Create order in its toolbar while trading is on: it opens the order ticket filled with these levels (side, entry as the price, stop-loss, take-profit and the quantity its risk buys), which you adjust and place. An order is never one click away.

Round the quantity down to what your broker takes, so the order risks no more than the drawing says. Whether the entry is a limit or a stop order depends on where it is against the price now. placeOrderIntent needs the trading feature on: it emits orderPlace, which a connected execution adapter places (see Trading).

import { positionLevels } from '@tradecanvas/chart'

const levels = positionLevels(chart.getDrawings().find((d) => d.id === id))
if (levels) {
  const { side, entry, stopLoss, takeProfit, quantity, quantityDecimals } = levels
  const step = 10 ** quantityDecimals
  const last = chart.getData().at(-1)?.close ?? entry
  // A buy below the price now waits as a limit, one above it as a stop; a sell the other way round.
  const type = (side === 'buy') === (entry <= last) ? 'limit' : 'stop'
  chart.placeOrderIntent({
    side, type, price: entry, stopPrice: type === 'stop' ? entry : undefined,
    quantity: Math.floor(quantity * step) / step, stopLoss, takeProfit,
  })
}

Alerts on drawings

An alert can follow a trend line, ray, extended or horizontal line, or the lines of a parallel channel: it fires when the price crosses the line where it is at the latest bar, as drawn on the chart (straight across bars, and in log price on a log scale).

if (chart.canAddDrawingAlert(id)) {
  chart.createAlert({ with: { drawing: id }, condition: 'crossingUp', trigger: 'oncePerBarClose', message: 'Broke the trend line' })
}

The alert goes with its drawing, comes back with it on undo, and is saved with the layout.

Order and groups

chart.moveDrawing(id, 'front')       // 'front' | 'forward' | 'backward' | 'back'
chart.moveDrawing(id, 0)              // or a place in the order: 0 the bottom, as getDrawings() lists them
chart.updateDrawing(id, { name: 'Weekly support' })  // its name in the object tree; null: its tool's
const group = chart.groupDrawings([a, b, c], 'Weekly levels')
chart.setDrawingGroupVisible(group, false)
chart.setDrawingGroupLocked(group, true)
chart.ungroupDrawings(group)

chart.getSelectedDrawingIds()
chart.removeDrawings(ids)            // one undo step
chart.removeAll('drawings')         // every drawing; 'indicators', or 'all' for both: one undo step, locked drawings stay
chart.setDrawingsVisible(ids, false)
chart.setDrawingsLocked(ids, true)

chart.copyDrawings()                 // the selected ones (Ctrl+C)
chart.pasteDrawings()                // Ctrl+V, here or on another chart of the page
chart.canPasteDrawings()             // whether there is something to paste

Clicking one drawing of a group selects the whole group.

In the widget's object tree the drawings are listed as they stack, the one on top first. A click on a drawing's name selects it and a double-click renames it. Its row clones it, and its grip drags it onto another row's place; the arrow keys on the grip move it one row up or down the list and the stack together.

Eraser, zoom and magnet

chart.setEraserMode(true)          // each click on a drawing removes it, until Escape
chart.setZoomAreaMode(true)        // the next drag zooms to the bars in its box
chart.setDrawingMagnetMode('strong') // 'off' | 'weak' | 'strong'

The weak magnet snaps a point to the bar's open, high, low or close when the pointer is near one; the strong magnet always does. In the widget the magnet starts off: a drawing goes where it is placed until the magnet button turns it on.

Cursors, and a drawing's span on the axes

new Chart(el, { crosshair: { mode: 'magnet', cursor: 'dot' } })
chart.setCrosshairCursor('arrow')        // 'cross' | 'dot' | 'arrow'
chart.on('crosshairCursorChange', (e) => e.payload)  // { cursor }
widget.setCrosshairCursor('dot')         // the widget's, a Chart Setting
chart.setDrawingAxisSpansVisible(false)  // or features: { drawingAxisSpans: false }

Cross draws the crosshair's lines with a crosshair cursor. Dot draws the same lines with a small dot in the crosshair's colour for a cursor. Arrow draws no lines and keeps the arrow cursor, while the price and the time still follow the pointer on the axes. In the widget, the cursor button at the top of the drawing tools opens a menu of the three, and the Chart Settings have the row. The kind is the viewer's own: persistSettings keeps it, and a layout or a shared link never carries it.

While a drawing is selected, moved or being drawn, the price axis is tinted from its lowest to its highest price and the time axis from its first to its last time, and each end is labelled in the drawing's colour. A horizontal line marks only its price and a vertical line only its time; a drawing kept to the screen marks neither. The eraser glows the drawing a click would remove.

Editing with the pointer and the keys

  • The magnet works on a dragged handle and on a moved drawing too: the point nearest where it was grabbed lands on a price, and the rest keep their place to it. The weak magnet reaches 50 px.
  • Hold Ctrl/⌘ while drawing or dragging to turn the magnet over for that moment: on when it is off, off when it is on.
  • Hold Shift while drawing or dragging a handle to keep the line flat, upright or at 45° on screen. On empty chart, Shift + drag still measures. It holds for lines and paths; a box, a channel's width or a pitchfork's point stays free.
  • ← → ↑ ↓ move the selected drawings a bar across or a pixel up or down; with Shift, ten. A run of presses is one undo step, and locked drawings stay.
  • Ctrl/⌘ + drag on a drawing drags out a copy (of the whole selection when the drawing is in it), one undo step. A Ctrl/⌘ + click still adds it to the selection or takes it out, and Ctrl/⌘ + drag on empty chart draws a selection box. On a handle of the selected drawing, Ctrl/⌘ + drag reshapes it with the magnet turned over instead.
  • Escape while a drawing is dragged calls the drag off: a moved or reshaped drawing goes back where it was, and a copy being dragged out goes, with nothing left to undo.

Keyboard

  • Ctrl/⌘ + Z undo, Ctrl + Shift + Z or Ctrl + Y redo.
  • Ctrl + C / V copy and paste drawings, Ctrl + D duplicate, Delete remove.
  • Ctrl + G group the selection, Ctrl + Shift + G ungroup.
  • Ctrl + ] / [ bring forward / send backward; with Shift, to the front / back.
  • Enter ends a path; Escape drops the tool, the eraser, or the selection.

Events

chart.on('drawingCreate', (e) => e.payload)       // { id, type, drawing }
chart.on('drawingUpdate', (e) => e.payload)       // { id }
chart.on('drawingRemove', (e) => e.payload)       // { id }
chart.on('drawingDoubleClick', (e) => e.payload)  // { id, x, y }: where on the chart it was
chart.on('drawingContextMenu', (e) => e.payload)  // { id, x, y }
chart.on('toolModeChange', (e) => e.payload)      // { eraser } or { zoomArea }

Undo and redo send drawingCreate, drawingRemove and drawingUpdate for the drawings they bring back, take away or change.

Catalog

Lines

  • trendLine — extends left or right when asked.
  • ray, extendedLine
  • horizontalLine, horizontalRay (forward in time from its point), verticalLine, crossLine
  • infoLine — with a box of price change, bars, time and angle.
  • trendAngle — with its on-screen angle.

Channels

  • parallelChannel — the line through its first two points moved straight up or down to its third (as its alerts read it), with an optional middle line, extending either way.
  • regressionChannel — the least-squares line through the closes between its two points, with bands two standard deviations either side; its points set the bars, and its handles sit on the line.
  • disjointChannel — two lines over the same bars that lean opposite ways: the first through its two points, the second through the third point's price halfway along. A wedge that narrows or widens; it extends either way and gives both prices to alerts.
  • flatTopBottom — a sloping line through two points and a level one at the third point's price, over the same bars: a flat top over rising lows, or a flat bottom under falling highs.

Fibonacci

  • fibRetracement, fibExtension — editable levels, prices and percentages, labels left or right, background, reversed.
  • fibChannel, fibSpeedResistanceFan — the fan's rays in their levels' colours, the time rays dashed, both labelled.
  • fibTimeZones — from the zone's start (0) on; its handles, and those of cyclicLines, sit on their lines halfway up the plot.
  • fibArcs — arcs around the start of a move, half or full circles.
  • fibCircles — circles at Fibonacci multiples of a radius.
  • fibSpiral — a golden spiral from its centre.
  • fibWedge — arcs between two lines from an apex.

Gann and pitchforks

  • pitchfork, schiffPitchfork, modifiedSchiffPitchfork — the B–C line joins the tines, and the fork is tinted between them to the plot's edge.
  • pitchfan — rays from a pivot through levels between two points.
  • gannFan — each angle labelled where it leaves the plot; gannBox — its divisions labelled in price and in time; gannSquare

Shapes

  • rectangle, circle, ellipse, triangle — an ellipse's handles sit on its curve, each moving one side.
  • rotatedRectangle — a rectangle at any angle: one side through its first two points, as deep as the third point is far from that side. It is square on the screen, so its far side follows the scale as the chart is zoomed.
  • polyline — a closed shape, a point per click.
  • curve — bent through a third point; arc — a circle arc through three points.

Brushes

  • brush, highlighter — freehand; selected, a stroke is framed as a text is, and moved by a press anywhere on it.
  • path — a line through points, with an arrow at the end.

Patterns

  • xabcdPattern, cypherPattern, abcdPattern, threeDrives — with their ratios. Point names sit outside their points, clear of the handles; each ratio sits on its guide, or just off it where the line is taken, never over a name, a handle or another ratio.
  • headAndShoulders — with the neckline, its peaks named over them, shortened to LS, H and RS where the full names would meet.

Elliott waves

  • elliottWave (1–5, A–C), elliottImpulse, elliottCorrection, elliottTriangle, elliottDoubleCombo, elliottTripleCombo — labels in the style of the wave degree: a figure in a ring, (1), 1 or i, outside their points.

Cycles

  • cyclicLines, timeCycles, sineLine

Measuring

  • priceRange — a box in the rise or fall colour (or the colour you pick for it) with an arrow up or down it and the change on a tag past its end.
  • dateRange — the bars between two times, an arrow across and the bars and time on a tag; its handles at the ends of its arrow, halfway up the plot.
  • dateAndPriceRange — both at once, with an arrow on each measure and the volume inside; measure — the change and the bars between two points.

Notes and marks

  • text, note (a pin with its text), callout, priceLabel
  • arrow, arrowMark (up, down, left or right, with a label), flag, icon (star, heart, tick, cross, circle, triangles, bolt)
  • signpost (its text on a board atop a post on a bar), balloon (its text in a bubble pointing at a bar)
  • anchoredText, anchoredNote: kept to a place on the screen, they stay put as the chart scrolls, zooms or changes symbol. Their points are shares of the plot ({ time: 0.5, price: 0.25 } is halfway across, a quarter down), and the settings have no Coordinates tab.

Forecasting

  • riskReward — Long/Short Position (above).
  • forecast — in the rise colour once the price reaches the target, the fall colour when its time runs out first.
  • projection — a move carried over from a third point.
  • barsPattern — a copy of some bars, as bars, a line or high-low, mirrored or flipped; the bars it copies under a light band.
  • anchoredVWAP — its handle on the VWAP where it starts; volumeProfileRange — the volume at each price as a histogram inside the range's box, the value area (70% of the volume) shaded, the point of control across; its handles on the box's corners.

Saving

const json = chart.saveState()   // drawings, their settings and groups, indicators, alerts…
chart.loadState(json)            // checks every drawing; malformed ones are left out

Your own tools

A tool is a DrawingPlugin registered with chart.registerDrawingTool(plugin). Its descriptor lists its settings (options), how it is drawn (creation), and whether it has a fill or text; it may give the prices of its lines (priceAt, for alerts), move handles that are not anchors (moveHandle), and receive the chart's bars (setDataGetter). See Plugins.