Every chart widget rendered only the baked-in 250-bar demo series: no set_series existed in Python despite the docstring naming it, so there was no way to plot real data at all. Now StockWidget holds up to three series slots (primary + two extra for the multi-symbol charts) via set_series (the C API), get_series, add_point, clear / populate, item_count, and load_csv; all 37 draw paths read the widget series through _bars(widget) instead of module DEMO_SERIES, so derived series (Heikin-Ashi, Renko, VWAP, OBV, ...) rebuild from the loaded data and the drawing tools inherit it as background. load_csv reads date,open,high,low,close,volume with the stdlib csv module: header optional (matched by name, any order, extra columns ignored), dates YYYY-MM-DD / YYYY/MM/DD / DD-MM-YYYY / ISO datetime / epoch seconds (validated, not stored -- the x-axis is bar index), ValueError naming the row on bad data. A cleared series draws a no-data placeholder; a one-bar series draws (Price: flat change). Tests: tests/test_stock_csv.py, 27 tests (parsing, API, headless renders of all 24 chart kinds incl. CSV-vs-template pixel diff). Fixture tests/data/ohlcv_30.csv (30 weekday bars). Full suite 311 tests pass; visreg 24/24 stock charts pixel-identical to template goldens. Docs: docs/stock-charts-data.md. Screenshots: tools/stock_csv_shots.py (Xvfb, RMSE 9-35% vs template goldens).
1974 lines
69 KiB
Python
1974 lines
69 KiB
Python
"""Stock Market widgets (37): Cairo drawings in the archetype structure.
|
|
|
|
Ports the C designer (widgets/components/Stock*, docs/stock-market*.md)
|
|
and the Rust port (crates/xframe-indicators/src/{plot,generated}.rs)
|
|
to the Python XFrame archetype model: one StockWidget class,
|
|
parameterised by ``kind``, with kind-specific branches in _draw --
|
|
the same pattern as the other archetypes in lightgui/xframe/core.py.
|
|
|
|
Demo data: every chart renders from ``demo_series()``, an exact port
|
|
of C ``xframe::make_seeded_series(250)`` (StockData.h) -- a
|
|
deterministic xorshift64* random walk starting at 100.0 -- so chart
|
|
colours are visible in the designer without series data, like C
|
|
(seeds 250).
|
|
|
|
Feeding real data: each widget holds up to three series slots
|
|
(primary + two extra for the multi-symbol charts) via
|
|
``StockWidget.set_series(bars, which=1)`` -- the Python port of C
|
|
``set_series`` -- plus ``get_series``, ``add_point``, ``clear`` /
|
|
``populate`` and ``load_csv``. ``load_csv`` reads a
|
|
``date,open,high,low,close,volume`` file with the stdlib ``csv``
|
|
module (see ``docs/stock-charts-data.md`` for the format spec).
|
|
``set_series`` is a data source, not a scalar prop, so it has no
|
|
Inspector row (the C generator SKIPs it). Series data is runtime
|
|
state only: it is NOT saved in .fdj files, so a project reloaded in
|
|
the designer shows the demo series again until the generated program
|
|
loads its data.
|
|
|
|
Template data, per widget: the primary series is ``DEMO_SERIES``
|
|
(250 bars, seed 42); the multi-symbol charts also use
|
|
``DEMO_SERIES_2`` (seed 43) and ``DEMO_SERIES_3`` (seed 44) as their
|
|
second/third symbols. Derived series (Heikin-Ashi, Renko, VWAP, OBV,
|
|
A/D, Money Flow, correlation, indexed, ratio, spread) are rebuilt
|
|
from whatever series the widget currently holds, exactly as C
|
|
``set_series`` rebuilds them.
|
|
|
|
Short-plot guard (the Rust plot.rs:250 clamp class): Rust clamps a
|
|
marker y into ``[area.y + 8, area.y + area.h - 8]``; when the plot is
|
|
shorter than 16px that clamp has min > max and panics. Here
|
|
``_frame()`` returns None for plots shorter than 16px (or with no
|
|
positive plot area) and the widget draws only its border + label.
|
|
|
|
Anchor guard (C flag 13, ddaf4bd): ParallelChannel/Pitchfork
|
|
``draw()`` indexed ``anchors_[2]`` unconditionally while
|
|
``set_anchors()`` can leave only 2 anchors. The Python equivalent
|
|
is ``_anchors()``: only anchors the user has actually set (an
|
|
``anchor-i-bar`` prop present in ``widget.props``) count -- a freshly
|
|
placed tool has 0. Draw code never indexes past ``len(anchors)``:
|
|
with <2 anchors ParallelChannel draws no channel lines and
|
|
Pitchfork draws no fork (only the anchor dots present); with 2
|
|
anchors ParallelChannel draws the main line + the dashed midline
|
|
(the outer line falls back to the midline, so it is not drawn twice)
|
|
and Pitchfork falls back to a trendline through the two anchors
|
|
(the tines need the third anchor); with 3 anchors both draw fully.
|
|
Other tools draw a centred default when they have 0 anchors so the
|
|
widget still reads as its kind in the palette.
|
|
"""
|
|
|
|
import csv
|
|
import datetime
|
|
import math
|
|
|
|
from lightgui.xframe.core import (
|
|
Widget,
|
|
parse_color,
|
|
_bg,
|
|
_box,
|
|
_prop_bool,
|
|
_prop_float,
|
|
_prop_int,
|
|
_rgb,
|
|
_text_width,
|
|
_wtext,
|
|
)
|
|
|
|
# --- demo series: exact port of C make_seeded_series(n, seed) -----------
|
|
_MASK64 = (1 << 64) - 1
|
|
_XOR_MUL = 0x2545F4914F6CDD1D
|
|
_DEMO_N = 250
|
|
|
|
|
|
def _stock_next(state):
|
|
"""xorshift64* step; returns (output, new_state)."""
|
|
x = state
|
|
x ^= x >> 12
|
|
x ^= (x << 25) & _MASK64
|
|
x ^= x >> 27
|
|
x &= _MASK64
|
|
return (x * _XOR_MUL) & _MASK64, x
|
|
|
|
|
|
def _stock_uniform(state):
|
|
"""Uniform double in [0, 1); returns (value, new_state)."""
|
|
out, state = _stock_next(state)
|
|
return (out >> 11) * (1.0 / 9007199254740992.0), state
|
|
|
|
|
|
def demo_series(n=_DEMO_N, seed=42):
|
|
"""Deterministic synthetic OHLCV series: a random walk starting
|
|
at 100.0. Same (n, seed) gives identical bars on every run.
|
|
Each bar is (open, high, low, close, volume); every bar satisfies
|
|
high >= max(open, close) and low <= min(open, close)."""
|
|
out = []
|
|
if n <= 0:
|
|
return out
|
|
state = (0x9E3779B97F4A7C15 ^ (seed * 0xBF58476D1CE4E5B9)) & _MASK64
|
|
if state == 0:
|
|
state = _XOR_MUL
|
|
prev_close = 100.0
|
|
for _i in range(n):
|
|
open_v = prev_close
|
|
shock, state = _stock_uniform(state)
|
|
close = open_v + 0.02 + (shock - 0.5) * 2.4
|
|
if not close > 1.0:
|
|
extra, state = _stock_uniform(state)
|
|
close = 1.0 + extra
|
|
up, state = _stock_uniform(state)
|
|
high = max(open_v, close) + up * 0.9
|
|
down, state = _stock_uniform(state)
|
|
low = min(open_v, close) - down * 0.9
|
|
vol, state = _stock_uniform(state)
|
|
volume = 500000.0 + vol * 1500000.0
|
|
out.append((open_v, high, low, close, volume))
|
|
prev_close = close
|
|
return out
|
|
|
|
|
|
# Cached demo series (250 bars, like C) + a second symbol for the
|
|
# comparison / overlay / correlation charts.
|
|
DEMO_SERIES = demo_series()
|
|
DEMO_SERIES_2 = demo_series(seed=43)
|
|
DEMO_SERIES_3 = demo_series(seed=44)
|
|
_DEMO_BY_SLOT = (DEMO_SERIES, DEMO_SERIES_2, DEMO_SERIES_3)
|
|
|
|
# --- CSV loading -----------------------------------------------------------
|
|
# Format: date,open,high,low,close,volume -- one bar per row. The
|
|
# header row is optional (auto-detected); with a header, columns are
|
|
# matched by name (order-independent, extra columns ignored), without
|
|
# one they are positional. The date is parsed and validated but NOT
|
|
# stored: bars are (open, high, low, close, volume) 5-tuples, the same
|
|
# model demo_series() returns, and the x-axis plots bar index, not
|
|
# dates (like the C demo, whose axis is also index-based).
|
|
|
|
_CSV_COLUMNS = ("date", "open", "high", "low", "close", "volume")
|
|
_CSV_ALIASES = {
|
|
"date": ("date", "timestamp", "time", "datetime"),
|
|
"open": ("open", "o"),
|
|
"high": ("high", "h"),
|
|
"low": ("low", "l"),
|
|
"close": ("close", "c"),
|
|
"volume": ("volume", "vol", "v"),
|
|
}
|
|
_CSV_DATE_FORMATS = (
|
|
"%Y-%m-%d", "%Y/%m/%d", "%d-%m-%Y", "%Y-%m-%d %H:%M:%S",
|
|
"%Y-%m-%dT%H:%M:%S",
|
|
)
|
|
|
|
|
|
def _parse_csv_date(text, row_no):
|
|
"""Parse a CSV date cell; raises ValueError naming the row."""
|
|
text = text.strip()
|
|
if not text:
|
|
raise ValueError("CSV row %d: empty date" % row_no)
|
|
try: # epoch seconds (int or float, e.g. 1767225600)
|
|
epoch = float(text)
|
|
if 946684800 <= epoch <= 4102444800: # 2000-01-01 .. 2100-01-01
|
|
return datetime.datetime.fromtimestamp(
|
|
epoch, datetime.timezone.utc)
|
|
except (ValueError, OverflowError, OSError):
|
|
pass
|
|
for fmt in _CSV_DATE_FORMATS:
|
|
try:
|
|
return datetime.datetime.strptime(text, fmt)
|
|
except ValueError:
|
|
continue
|
|
raise ValueError(
|
|
"CSV row %d: unparsable date %r (expected YYYY-MM-DD, "
|
|
"YYYY/MM/DD, DD-MM-YYYY, an ISO datetime, or epoch seconds)"
|
|
% (row_no, text))
|
|
|
|
|
|
def _parse_csv_float(text, row_no, column):
|
|
try:
|
|
return float(text)
|
|
except (TypeError, ValueError):
|
|
raise ValueError("CSV row %d: %s is not a number: %r"
|
|
% (row_no, column, text))
|
|
|
|
|
|
def _check_bar(bar, row_no):
|
|
"""Validate one (open, high, low, close, volume) bar."""
|
|
open_v, high, low, close, volume = bar
|
|
if high < max(open_v, close):
|
|
raise ValueError(
|
|
"CSV row %d: high %.2f is below open/close (%.2f/%.2f) -- "
|
|
"check the column order" % (row_no, high, open_v, close))
|
|
if low > min(open_v, close):
|
|
raise ValueError(
|
|
"CSV row %d: low %.2f is above open/close (%.2f/%.2f) -- "
|
|
"check the column order" % (row_no, low, open_v, close))
|
|
if volume < 0:
|
|
raise ValueError("CSV row %d: negative volume %.2f"
|
|
% (row_no, volume))
|
|
return bar
|
|
|
|
|
|
def _validate_bars(bars, what="series"):
|
|
"""Normalise *bars* to a list of float (o, h, l, c, v) tuples.
|
|
|
|
Accepts 5-tuples/lists of numbers, or dicts with open/high/low/
|
|
close/volume keys. Raises ValueError on a malformed bar.
|
|
"""
|
|
if bars is None:
|
|
return None
|
|
out = []
|
|
for i, bar in enumerate(bars):
|
|
if isinstance(bar, dict):
|
|
try:
|
|
vals = tuple(float(bar[k]) for k in
|
|
("open", "high", "low", "close", "volume"))
|
|
except (KeyError, TypeError, ValueError):
|
|
raise ValueError(
|
|
"%s bar %d: need open/high/low/close/volume, got %r"
|
|
% (what, i, bar))
|
|
else:
|
|
try:
|
|
vals = tuple(float(v) for v in bar)
|
|
except (TypeError, ValueError):
|
|
raise ValueError(
|
|
"%s bar %d: need 5 numbers, got %r" % (what, i, bar))
|
|
if len(vals) != 5:
|
|
raise ValueError(
|
|
"%s bar %d: need 5 numbers, got %d"
|
|
% (what, i, len(vals)))
|
|
out.append(_check_bar(vals, i + 1))
|
|
return out
|
|
|
|
|
|
def _header_map(first_row):
|
|
"""Column-name -> index for a header row, or None if not a header.
|
|
|
|
A row counts as a header when its cells (lowercased, stripped)
|
|
cover every required column by name/alias. Unknown extra cells
|
|
(e.g. Adj Close) are ignored.
|
|
"""
|
|
cells = [str(c).strip().lower() for c in first_row]
|
|
mapping = {}
|
|
for column, aliases in _CSV_ALIASES.items():
|
|
for alias in aliases:
|
|
if alias in cells:
|
|
mapping[column] = cells.index(alias)
|
|
break
|
|
else:
|
|
return None
|
|
return mapping
|
|
|
|
|
|
def load_csv(source):
|
|
"""Load OHLCV bars from a CSV file.
|
|
|
|
*source* is a path (str / os.PathLike) or a file-like object
|
|
opened for text. Returns a list of (open, high, low, close,
|
|
volume) float tuples, in file order.
|
|
|
|
Expected columns: ``date,open,high,low,close,volume``. A header
|
|
row is optional: when the first row names the columns (matched
|
|
case-insensitively, aliases ``timestamp``/``time`` for date,
|
|
``o``/``h``/``l``/``c``/``vol``/``v`` accepted) the columns are
|
|
read by name in any order and extra columns are ignored;
|
|
otherwise the row must have exactly those six columns in order.
|
|
Dates accept ``YYYY-MM-DD``, ``YYYY/MM/DD``, ``DD-MM-YYYY``, an
|
|
ISO datetime, or epoch seconds; the date is validated but not
|
|
stored (bars carry no timestamp, and the x-axis is bar index).
|
|
Raises ValueError naming the offending row on bad data, and
|
|
ValueError when the file has no data rows.
|
|
"""
|
|
close_after = False
|
|
if hasattr(source, "read"):
|
|
handle = source
|
|
else:
|
|
handle = open(source, "r", encoding="utf-8-sig", newline="")
|
|
close_after = True
|
|
try:
|
|
rows = [r for r in csv.reader(handle)
|
|
if r and any(str(c).strip() for c in r)]
|
|
finally:
|
|
if close_after:
|
|
handle.close()
|
|
if not rows:
|
|
raise ValueError("CSV: no rows found")
|
|
mapping = _header_map(rows[0])
|
|
if mapping is None:
|
|
# A first row that names *some* columns but not all of them is
|
|
# a broken header, not data -- say so instead of failing on
|
|
# "open is not a number: 'open'".
|
|
first_cells = {str(c).strip().lower() for c in rows[0]}
|
|
known = {a for aliases in _CSV_ALIASES.values() for a in aliases}
|
|
if first_cells & known:
|
|
missing = [c for c in _CSV_COLUMNS
|
|
if not (set(_CSV_ALIASES[c]) & first_cells)]
|
|
raise ValueError(
|
|
"CSV header names only some columns; missing: %s"
|
|
% ", ".join(missing))
|
|
for i, r in enumerate(rows):
|
|
if len(r) != 6:
|
|
raise ValueError(
|
|
"CSV row %d: expected 6 columns "
|
|
"(date,open,high,low,close,volume), got %d"
|
|
% (i + 1, len(r)))
|
|
data_rows = rows[1:] if mapping is not None else rows
|
|
bars = []
|
|
for offset, row in enumerate(data_rows):
|
|
row_no = offset + (2 if mapping is not None else 1)
|
|
if mapping is not None:
|
|
try:
|
|
cells = {c: row[mapping[c]] for c in _CSV_COLUMNS}
|
|
except IndexError:
|
|
raise ValueError(
|
|
"CSV row %d: short row, expected %d columns, got %d"
|
|
% (row_no, max(mapping.values()) + 1, len(row)))
|
|
else:
|
|
cells = dict(zip(_CSV_COLUMNS, row))
|
|
_parse_csv_date(cells["date"], row_no)
|
|
bar = tuple(_parse_csv_float(cells[c], row_no, c)
|
|
for c in ("open", "high", "low", "close", "volume"))
|
|
bars.append(_check_bar(bar, row_no))
|
|
if not bars:
|
|
raise ValueError("CSV: no data rows found")
|
|
return bars
|
|
|
|
|
|
def _bars(widget, which=1):
|
|
"""The OHLCV bars a draw function should plot for *widget*.
|
|
|
|
Slot *which* (1, 2 or 3): the widget's own series when one was
|
|
set with ``set_series`` (an empty list stays empty -- a cleared
|
|
widget draws the no-data placeholder), else the built-in demo
|
|
series for that slot (``DEMO_SERIES`` / ``_2`` / ``_3``).
|
|
"""
|
|
if not 1 <= which <= 3:
|
|
raise ValueError("series slot must be 1, 2 or 3, got %r" % (which,))
|
|
own = getattr(widget, "_series", None) or (None, None, None)
|
|
if own[which - 1] is not None:
|
|
return own[which - 1]
|
|
return _DEMO_BY_SLOT[which - 1]
|
|
|
|
|
|
# Kinds that plot two or three series (primary + extras); used by
|
|
# StockWidget._draw to show the no-data placeholder when any series
|
|
# a kind needs is empty.
|
|
_MULTI_KINDS = frozenset((
|
|
"CorrelationView", "IndexedComparison", "MultiSymbolChart",
|
|
"OverlayChart", "RatioChart", "RelativePerformance",
|
|
"SectorComparison", "SpreadChart",
|
|
))
|
|
_THREE_SERIES_KINDS = frozenset((
|
|
"MultiSymbolChart", "RelativePerformance", "SectorComparison",
|
|
))
|
|
|
|
# Palette kinds (stock.py covers the 37 Stock* registry names).
|
|
STOCK_KINDS = frozenset((
|
|
"AccumulationDistribution", "AreaChart", "Arrow", "BaselineChart",
|
|
"Brush", "CandlestickChart", "CorrelationView", "Ellipse",
|
|
"FibExtension", "FibRetracement", "HeikinAshi", "HollowCandles",
|
|
"HorizontalLine", "IndexedComparison", "LineChart", "MeasureTool",
|
|
"MoneyFlowChart", "MultiSymbolChart", "OBVChart", "OHLCBarChart",
|
|
"OverlayChart", "ParallelChannel", "Pitchfork", "Price",
|
|
"RatioChart", "Rectangle", "RelativePerformance", "Renko",
|
|
"SectorComparison", "SpreadChart", "TextAnnotation", "Trendline",
|
|
"VWAP", "VerticalLine", "VolumeBars", "VolumeCandles",
|
|
"VolumeProfile",
|
|
))
|
|
|
|
UP_RGB = (0.0, 150 / 255, 0.0) # corrected up default
|
|
DOWN_RGB = (200 / 255, 30 / 255, 30 / 255) # corrected down default
|
|
CANDLE_UP_RGB = (120 / 255, 190 / 255, 120 / 255)
|
|
CANDLE_DOWN_RGB = (200 / 255, 120 / 255, 120 / 255)
|
|
GRID_RGB = (225 / 255, 225 / 255, 225 / 255)
|
|
AXIS_RGB = (150 / 255, 150 / 255, 150 / 255)
|
|
LINE_RGB = (0.0, 100 / 255, 200 / 255)
|
|
|
|
|
|
def _color(widget, name, default):
|
|
return parse_color(widget.get_prop(name, ""), default)
|
|
|
|
|
|
# --- frame / view / scale --------------------------------------------------
|
|
|
|
def _frame(widget):
|
|
"""Plot rect (px, py, pw, ph), or None when too small to plot.
|
|
|
|
Mirrors C plot_x()/plot_y()/plot_w()/plot_h(): a left axis of
|
|
``axis-width`` (56) and a bottom axis of ``axis-height`` (20) when
|
|
the table has those props, else a 4px margin all round. The
|
|
short-plot guard: height < 16px (or no positive plot area) means
|
|
no plot at all -- the Rust plot.rs:250 clamp (min > max) class.
|
|
"""
|
|
w, h = widget.width, widget.height
|
|
names = widget.prop_names()
|
|
if "axis-width" in names:
|
|
ax_w = _prop_int(widget, "axis-width", 56)
|
|
ax_h = _prop_int(widget, "axis-height", 20)
|
|
px, py = ax_w, 6
|
|
pw, ph = w - ax_w - 8, h - ax_h - 12
|
|
else:
|
|
px, py = 4, 4
|
|
pw, ph = w - 8, h - 8
|
|
if h < 16 or pw <= 0 or ph <= 0:
|
|
return None
|
|
return (px, py, pw, ph)
|
|
|
|
|
|
def _view(widget, total):
|
|
"""(first, count) of the visible window (C effective_count)."""
|
|
names = widget.prop_names()
|
|
if "view-first" not in names:
|
|
return 0.0, float(total)
|
|
first = _prop_float(widget, "view-first", 0.0)
|
|
count = _prop_float(widget, "view-count", 0.0)
|
|
if count <= 0 or count > total:
|
|
count = float(total)
|
|
first = max(0.0, min(max(0.0, total - count), first))
|
|
return first, count
|
|
|
|
|
|
def _y_range(widget, values, i0, i1):
|
|
"""(lo, hi) for *values* over [i0, i1): auto range with the C 6%
|
|
padding, or the manual y-min/y-max when auto-y is off."""
|
|
lo, hi = None, None
|
|
for v in values[i0:i1]:
|
|
if v is None:
|
|
continue
|
|
lo = v if lo is None else min(lo, v)
|
|
hi = v if hi is None else max(hi, v)
|
|
if lo is None or hi is None:
|
|
return 0.0, 1.0
|
|
if "auto-y" in widget.prop_names() \
|
|
and not _prop_bool(widget, "auto-y", True):
|
|
return (_prop_float(widget, "y-min", 0.0),
|
|
_prop_float(widget, "y-max", 1.0))
|
|
pad = (hi - lo) * 0.06 + 1e-9
|
|
return lo - pad, hi + pad
|
|
|
|
|
|
def _nice_step(span, target=6):
|
|
"""C nice_step: 1/2/5/10 x a power of ten."""
|
|
if span <= 0:
|
|
return 1.0
|
|
raw = span / target
|
|
mag = 10.0 ** math.floor(math.log10(raw))
|
|
norm = raw / mag
|
|
step = 1.0 if norm < 1.5 else 2.0 if norm < 3.5 \
|
|
else 5.0 if norm < 7.5 else 10.0
|
|
return step * mag
|
|
|
|
|
|
def _fmt(value):
|
|
"""C fmt(): two decimals, trailing zeroes stripped."""
|
|
text = "%.2f" % value
|
|
return text.rstrip("0").rstrip(".") if "." in text else text
|
|
|
|
|
|
class _Plot:
|
|
"""Plot geometry + scale for one chart draw."""
|
|
|
|
def __init__(self, widget, frame, lo, hi, first, count, total):
|
|
px, py, pw, ph = frame
|
|
self.px, self.py, self.pw, self.ph = px, py, pw, ph
|
|
self.lo, self.hi = (lo, hi) if hi > lo else (lo, lo + 1.0)
|
|
self.first, self.count, self.total = first, count, total
|
|
|
|
def x(self, i):
|
|
"""Centre x of bar *i*."""
|
|
item_w = self.pw / self.count if self.count else self.pw
|
|
return self.px + (i - self.first + 0.5) * item_w
|
|
|
|
def item_w(self):
|
|
return self.pw / self.count if self.count else self.pw
|
|
|
|
def y(self, value):
|
|
return self.py + (self.hi - value) / (self.hi - self.lo) * self.ph
|
|
|
|
def x_at_bar(self, bar):
|
|
return self.x(bar)
|
|
|
|
|
|
def _draw_grid(cr, widget, plot):
|
|
"""Horizontal gridlines + left price labels (C draw loop)."""
|
|
if "grid-color" not in widget.prop_names():
|
|
return
|
|
grid = _color(widget, "grid-color", GRID_RGB)
|
|
axis = _color(widget, "axis-color", AXIS_RGB)
|
|
step = _nice_step(plot.hi - plot.lo, 6)
|
|
start = math.ceil(plot.lo / step) * step
|
|
value = start
|
|
while value <= plot.hi:
|
|
gy = plot.y(value)
|
|
cr.save()
|
|
_rgb(cr, grid)
|
|
cr.set_line_width(1)
|
|
cr.move_to(plot.px, gy)
|
|
cr.line_to(plot.px + plot.pw, gy)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_wtext(cr, widget, _fmt(value), plot.px - 6, gy + 4, size=11,
|
|
rgb=axis, align="right", max_width=plot.px - 8)
|
|
value += step
|
|
|
|
|
|
def _draw_x_axis(cr, widget, plot):
|
|
"""Bottom axis line + index ticks (C draw loop)."""
|
|
if "axis-width" not in widget.prop_names():
|
|
return
|
|
axis = _color(widget, "axis-color", AXIS_RGB)
|
|
bottom = plot.py + plot.ph
|
|
cr.save()
|
|
_rgb(cr, axis)
|
|
cr.set_line_width(1)
|
|
cr.move_to(plot.px, bottom)
|
|
cr.line_to(plot.px + plot.pw, bottom)
|
|
target = max(1, plot.pw // 90)
|
|
istep = int(math.ceil(plot.count / max(1, target)))
|
|
i0 = int(math.floor(plot.first))
|
|
i1 = int(math.ceil(plot.first + plot.count))
|
|
for i in range(i0, i1, max(1, istep)):
|
|
if i < 0 or i >= plot.total:
|
|
continue
|
|
cx = plot.x(i)
|
|
cr.move_to(cx, bottom)
|
|
cr.line_to(cx, bottom + 4)
|
|
cr.stroke()
|
|
cr.restore()
|
|
if plot.ph > 28:
|
|
for i in range(i0, i1, max(1, istep)):
|
|
if i < 0 or i >= plot.total:
|
|
continue
|
|
_wtext(cr, widget, str(i), plot.x(i), bottom + 16, size=11,
|
|
rgb=axis, align="center", max_width=40)
|
|
cr.save()
|
|
_rgb(cr, axis)
|
|
cr.set_line_width(1)
|
|
cr.rectangle(plot.px + 0.5, plot.py + 0.5,
|
|
plot.pw - 1, plot.ph - 1)
|
|
cr.stroke()
|
|
cr.restore()
|
|
|
|
|
|
def _draw_title(cr, widget, plot, suffix=""):
|
|
"""Title text + last close at the top-left of the plot (C)."""
|
|
if plot.ph < 18:
|
|
return
|
|
label = widget.text
|
|
if suffix:
|
|
label = label + " " + suffix
|
|
_wtext(cr, widget, label, plot.px + 8, plot.py + 14, size=12,
|
|
rgb=(0.12, 0.12, 0.12), max_width=plot.pw - 16)
|
|
|
|
|
|
def _chart_base(cr, widget, bars):
|
|
"""Common chart setup: background, frame, view window, y-range
|
|
over the visible bars, grid + x axis. Returns (plot, i0, i1) or
|
|
(None, 0, 0) when too small to plot."""
|
|
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
|
|
frame = _frame(widget)
|
|
if frame is None:
|
|
_wtext(cr, widget, widget.pkind, widget.width / 2,
|
|
widget.height / 2 + 5, size=12, align="center",
|
|
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
|
|
return None, 0, 0
|
|
total = len(bars)
|
|
first, count = _view(widget, total)
|
|
i0 = int(math.floor(first))
|
|
i1 = int(math.ceil(first + count))
|
|
if "auto-y" not in widget.prop_names() or _prop_bool(
|
|
widget, "auto-y", True):
|
|
vis_lo = min((b[2] for b in bars[i0:i1]), default=0.0)
|
|
vis_hi = max((b[1] for b in bars[i0:i1]), default=1.0)
|
|
pad = (vis_hi - vis_lo) * 0.06 + 1e-9
|
|
lo, hi = vis_lo - pad, vis_hi + pad
|
|
else:
|
|
lo = _prop_float(widget, "y-min", 0.0)
|
|
hi = _prop_float(widget, "y-max", 1.0)
|
|
plot = _Plot(widget, frame, lo, hi, first, count, total)
|
|
_draw_grid(cr, widget, plot)
|
|
return plot, i0, i1
|
|
|
|
|
|
def _draw_candles(cr, widget, plot, bars, i0, i1, hollow=False):
|
|
"""Candle bodies + wicks (C StockCandlestickChart draw)."""
|
|
up = _color(widget, "up-color", UP_RGB)
|
|
down = _color(widget, "down-color", DOWN_RGB)
|
|
if "up-color" not in widget.prop_names():
|
|
up = _color(widget, "candle-up-color", CANDLE_UP_RGB)
|
|
down = _color(widget, "candle-down-color", CANDLE_DOWN_RGB)
|
|
bw = max(1, int(plot.item_w() * 0.6))
|
|
for i in range(i0, min(i1, len(bars))):
|
|
if i < 0:
|
|
continue
|
|
open_v, high, low, close, _vol = bars[i]
|
|
cx = plot.x(i)
|
|
is_up = close >= open_v
|
|
colour = up if is_up else down
|
|
cr.save()
|
|
_rgb(cr, colour)
|
|
cr.set_line_width(1)
|
|
cr.move_to(cx, plot.y(high))
|
|
cr.line_to(cx, plot.y(low))
|
|
cr.stroke()
|
|
top = plot.y(max(open_v, close))
|
|
bot = plot.y(min(open_v, close))
|
|
if hollow and is_up:
|
|
cr.set_line_width(1)
|
|
cr.rectangle(cx - bw / 2, top, bw, max(1, bot - top))
|
|
cr.stroke()
|
|
else:
|
|
cr.rectangle(cx - bw / 2, top, bw, max(1, bot - top))
|
|
cr.fill()
|
|
cr.restore()
|
|
|
|
|
|
def _draw_line_values(cr, plot, values, i0, i1, rgb, width=2.0):
|
|
"""Polyline of *values* over [i0, i1) (None gaps break it)."""
|
|
cr.save()
|
|
_rgb(cr, rgb)
|
|
cr.set_line_width(width)
|
|
started = False
|
|
for i in range(i0, min(i1, len(values))):
|
|
if i < 0 or values[i] is None:
|
|
started = False
|
|
continue
|
|
x, y = plot.x(i), plot.y(values[i])
|
|
if not started:
|
|
cr.move_to(x, y)
|
|
started = True
|
|
else:
|
|
cr.line_to(x, y)
|
|
cr.stroke()
|
|
cr.restore()
|
|
|
|
|
|
def _draw_ohlc_bars(cr, widget, plot, bars, i0, i1):
|
|
"""OHLC bars: vertical high-low line with open/close ticks."""
|
|
up = _color(widget, "up-color", UP_RGB)
|
|
down = _color(widget, "down-color", DOWN_RGB)
|
|
tick = max(2, int(plot.item_w() * 0.3))
|
|
for i in range(i0, min(i1, len(bars))):
|
|
if i < 0:
|
|
continue
|
|
open_v, high, low, close, _vol = bars[i]
|
|
cx = plot.x(i)
|
|
cr.save()
|
|
_rgb(cr, up if close >= open_v else down)
|
|
cr.set_line_width(1)
|
|
cr.move_to(cx, plot.y(high))
|
|
cr.line_to(cx, plot.y(low))
|
|
cr.move_to(cx - tick, plot.y(open_v))
|
|
cr.line_to(cx, plot.y(open_v))
|
|
cr.move_to(cx, plot.y(close))
|
|
cr.line_to(cx + tick, plot.y(close))
|
|
cr.stroke()
|
|
cr.restore()
|
|
|
|
|
|
def _anchors(widget):
|
|
"""Anchors the user has set, in order (see module docstring:
|
|
Flag 13 guard). Each is (bar, price); price falls back to the
|
|
table default 100 when only the bar was set."""
|
|
out = []
|
|
for i in (1, 2, 3):
|
|
if "anchor-%d-bar" % i in widget.props:
|
|
bar = _prop_int(widget, "anchor-%d-bar" % i, 0)
|
|
price = _prop_float(widget, "anchor-%d-price" % i, 100.0)
|
|
out.append((bar, price))
|
|
return out
|
|
|
|
|
|
def _draw_anchor_dots(cr, plot, anchors, rgb=(0.12, 0.12, 0.12)):
|
|
"""Filled 8px anchor dots (C draws XFillArc 8x8 per anchor)."""
|
|
cr.save()
|
|
_rgb(cr, rgb)
|
|
for bar, price in anchors:
|
|
cx, cy = plot.x(bar), plot.y(price)
|
|
cr.arc(cx, cy, 4, 0, 2 * math.pi)
|
|
cr.fill()
|
|
cr.restore()
|
|
|
|
|
|
def _line_through(cr, plot, b0, p0, b1, p1, rgb, width=2.0, dashed=False):
|
|
"""Line through (b0, p0)-(b1, p1) extended across the plot."""
|
|
if b1 == b0:
|
|
slope = 0.0
|
|
else:
|
|
slope = (p1 - p0) / (b1 - b0)
|
|
v_left = p0 + slope * (-0.5 - b0 + plot.first)
|
|
v_right = p0 + slope * (plot.first + plot.count - 0.5 - b0)
|
|
cr.save()
|
|
_rgb(cr, rgb)
|
|
cr.set_line_width(width)
|
|
if dashed:
|
|
cr.set_dash([6.0, 4.0])
|
|
cr.move_to(plot.px, plot.y(v_left))
|
|
cr.line_to(plot.px + plot.pw, plot.y(v_right))
|
|
cr.stroke()
|
|
cr.restore()
|
|
|
|
|
|
# --- chart kinds -------------------------------------------------------------
|
|
# Each _draw_<kind> takes (cr, widget); the series is _bars(widget)
|
|
# unless noted. Derived series (Heikin-Ashi, Renko, VWAP, OBV, ...)
|
|
# are rebuilt from the demo bars, like C set_series does.
|
|
|
|
def _closes(bars):
|
|
return [b[3] for b in bars]
|
|
|
|
|
|
def _line_chart_base(cr, widget, values, line_rgb=None):
|
|
"""Frame + y-range over *values* + grid + line + title. Used by
|
|
the derived-line charts (OBV, A/D, correlation, ...)."""
|
|
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
|
|
frame = _frame(widget)
|
|
if frame is None:
|
|
_wtext(cr, widget, widget.pkind, widget.width / 2,
|
|
widget.height / 2 + 5, size=12, align="center",
|
|
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
|
|
return None, 0, 0
|
|
total = len(values)
|
|
first, count = _view(widget, total)
|
|
i0 = int(math.floor(first))
|
|
i1 = int(math.ceil(first + count))
|
|
lo, hi = _y_range(widget, values, i0, i1)
|
|
plot = _Plot(widget, frame, lo, hi, first, count, total)
|
|
_draw_grid(cr, widget, plot)
|
|
_draw_x_axis(cr, widget, plot)
|
|
if line_rgb is not None:
|
|
width = _prop_int(widget, "line-width", 2) \
|
|
if "line-width" in widget.prop_names() else 2
|
|
_draw_line_values(cr, plot, values, i0, i1, line_rgb, width)
|
|
return plot, i0, i1
|
|
|
|
|
|
def _draw_candlestick(cr, widget):
|
|
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
|
|
if plot is None:
|
|
return
|
|
_draw_candles(cr, widget, plot, _bars(widget), i0, i1)
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
|
|
|
|
|
|
def _draw_hollow(cr, widget):
|
|
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
|
|
if plot is None:
|
|
return
|
|
_draw_candles(cr, widget, plot, _bars(widget), i0, i1, hollow=True)
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
|
|
|
|
|
|
def _heikin_ashi(bars):
|
|
"""Heikin-Ashi candles from OHLC bars (C StockHeikinAshi)."""
|
|
out = []
|
|
ha_open = bars[0][0]
|
|
for open_v, high, low, close, vol in bars:
|
|
ha_close = (open_v + high + low + close) / 4.0
|
|
ha_high = max(high, ha_open, ha_close)
|
|
ha_low = min(low, ha_open, ha_close)
|
|
out.append((ha_open, ha_high, ha_low, ha_close, vol))
|
|
ha_open = (ha_open + ha_close) / 2.0
|
|
return out
|
|
|
|
|
|
def _draw_heikin_ashi(cr, widget):
|
|
bars = _heikin_ashi(_bars(widget))
|
|
plot, i0, i1 = _chart_base(cr, widget, bars)
|
|
if plot is None:
|
|
return
|
|
_draw_candles(cr, widget, plot, bars, i0, i1)
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, _fmt(bars[-1][3]))
|
|
|
|
|
|
def _draw_ohlc(cr, widget):
|
|
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
|
|
if plot is None:
|
|
return
|
|
_draw_ohlc_bars(cr, widget, plot, _bars(widget), i0, i1)
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
|
|
|
|
|
|
def _draw_line(cr, widget):
|
|
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
|
|
if plot is None:
|
|
return
|
|
line = _color(widget, "line-color", LINE_RGB)
|
|
width = _prop_int(widget, "line-width", 2)
|
|
_draw_line_values(cr, plot, _closes(_bars(widget)), i0, i1, line,
|
|
width)
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
|
|
|
|
|
|
def _draw_area(cr, widget):
|
|
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
|
|
if plot is None:
|
|
return
|
|
line = _color(widget, "line-color", LINE_RGB)
|
|
fill = _color(widget, "fill-color", (180 / 255, 210 / 255, 240 / 255))
|
|
width = _prop_int(widget, "line-width", 2)
|
|
closes = _closes(_bars(widget))
|
|
bottom = plot.py + plot.ph
|
|
cr.save()
|
|
_rgb(cr, fill, 0.55)
|
|
started = False
|
|
for i in range(i0, min(i1, len(closes))):
|
|
if i < 0:
|
|
continue
|
|
x, y = plot.x(i), plot.y(closes[i])
|
|
if not started:
|
|
cr.move_to(x, bottom)
|
|
cr.line_to(x, y)
|
|
started = True
|
|
else:
|
|
cr.line_to(x, y)
|
|
if started:
|
|
cr.line_to(plot.x(min(i1, len(closes)) - 1), bottom)
|
|
cr.close_path()
|
|
cr.fill()
|
|
cr.restore()
|
|
_draw_line_values(cr, plot, closes, i0, i1, line, width)
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
|
|
|
|
|
|
def _draw_baseline(cr, widget):
|
|
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
|
|
if plot is None:
|
|
return
|
|
baseline = _prop_float(widget, "baseline", 100.0)
|
|
up_fill = _color(widget, "up-fill-color",
|
|
(170 / 255, 220 / 255, 170 / 255))
|
|
down_fill = _color(widget, "down-fill-color",
|
|
(240 / 255, 180 / 255, 180 / 255))
|
|
line = _color(widget, "line-color", LINE_RGB)
|
|
base_rgb = _color(widget, "baseline-color",
|
|
(120 / 255, 120 / 255, 120 / 255))
|
|
closes = _closes(_bars(widget))
|
|
base_y = plot.y(baseline)
|
|
bottom = plot.py + plot.ph
|
|
cr.save()
|
|
_rgb(cr, up_fill, 0.6)
|
|
cr.rectangle(plot.px, plot.py, plot.pw, max(0, base_y - plot.py))
|
|
cr.fill()
|
|
_rgb(cr, down_fill, 0.6)
|
|
cr.rectangle(plot.px, base_y, plot.pw, max(0, bottom - base_y))
|
|
cr.fill()
|
|
_rgb(cr, base_rgb)
|
|
cr.set_line_width(1)
|
|
cr.set_dash([6.0, 4.0])
|
|
cr.move_to(plot.px, base_y)
|
|
cr.line_to(plot.px + plot.pw, base_y)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_draw_line_values(cr, plot, closes, i0, i1, line,
|
|
_prop_int(widget, "line-width", 2))
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
|
|
|
|
|
|
def _renko_bricks(bars, brick_size):
|
|
"""Renko bricks from closes (C StockRenko): +1 up / -1 down."""
|
|
closes = _closes(bars)
|
|
bricks = []
|
|
level = math.floor(closes[0] / brick_size) * brick_size
|
|
for close in closes[1:]:
|
|
while close >= level + brick_size:
|
|
level += brick_size
|
|
bricks.append(1)
|
|
while close <= level - brick_size:
|
|
level -= brick_size
|
|
bricks.append(-1)
|
|
return bricks
|
|
|
|
|
|
def _draw_renko(cr, widget):
|
|
brick_size = max(0.01, _prop_float(widget, "brick-size", 1.0))
|
|
bricks = _renko_bricks(_bars(widget), brick_size)
|
|
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
|
|
frame = _frame(widget)
|
|
if frame is None:
|
|
_wtext(cr, widget, widget.pkind, widget.width / 2,
|
|
widget.height / 2 + 5, size=12, align="center",
|
|
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
|
|
return
|
|
total = len(bricks)
|
|
first, count = _view(widget, total)
|
|
i0 = int(math.floor(first))
|
|
i1 = int(math.ceil(first + count))
|
|
levels = []
|
|
level = 0
|
|
for brick in bricks:
|
|
level += brick
|
|
levels.append(level)
|
|
lo = min([0] + levels[i0:i1]) - 1
|
|
hi = max([0] + levels[i0:i1]) + 1
|
|
plot = _Plot(widget, frame, lo, hi, first, count, total)
|
|
_draw_grid(cr, widget, plot)
|
|
up = _color(widget, "up-color", UP_RGB)
|
|
down = _color(widget, "down-color", DOWN_RGB)
|
|
bw = max(1, int(plot.item_w() * 0.8))
|
|
for i in range(i0, min(i1, total)):
|
|
if i < 0:
|
|
continue
|
|
level = levels[i]
|
|
prev = levels[i - 1] if i > 0 else 0
|
|
cx = plot.x(i)
|
|
top = plot.y(max(level, prev))
|
|
bot = plot.y(min(level, prev))
|
|
cr.save()
|
|
_rgb(cr, up if bricks[i] > 0 else down)
|
|
cr.rectangle(cx - bw / 2, top, bw, max(1, bot - top))
|
|
cr.fill_preserve()
|
|
_rgb(cr, (0.12, 0.12, 0.12))
|
|
cr.set_line_width(0.5)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, "%d bricks" % total)
|
|
|
|
|
|
def _volume_values(bars):
|
|
return [b[4] for b in bars]
|
|
|
|
|
|
def _draw_volume_bars(cr, widget):
|
|
volumes = _volume_values(_bars(widget))
|
|
plot, i0, i1 = _line_chart_base(
|
|
cr, widget, volumes, line_rgb=None)
|
|
if plot is None:
|
|
return
|
|
up = _color(widget, "up-color", UP_RGB)
|
|
down = _color(widget, "down-color", DOWN_RGB)
|
|
vmax = max(volumes[i0:i1], default=1.0) or 1.0
|
|
bw = max(1, int(plot.item_w() * 0.6))
|
|
bottom = plot.py + plot.ph
|
|
for i in range(i0, min(i1, len(volumes))):
|
|
if i < 0:
|
|
continue
|
|
h = volumes[i] / vmax * plot.ph
|
|
cx = plot.x(i)
|
|
cr.save()
|
|
_rgb(cr, up if _bars(widget)[i][3] >= _bars(widget)[i][0] else down)
|
|
cr.rectangle(cx - bw / 2, bottom - h, bw, h)
|
|
cr.fill()
|
|
cr.restore()
|
|
_draw_title(cr, widget, plot, "")
|
|
|
|
|
|
def _draw_volume_candles(cr, widget):
|
|
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
|
|
if plot is None:
|
|
return
|
|
# Candles on the top 2/3, volume bars on the bottom 1/3.
|
|
top_h = plot.ph * 2 / 3
|
|
sub = _Plot(widget, (plot.px, plot.py, plot.pw, top_h),
|
|
plot.lo, plot.hi, plot.first, plot.count, plot.total)
|
|
_draw_candles(cr, widget, sub, _bars(widget), i0, i1)
|
|
volumes = _volume_values(_bars(widget))
|
|
vmax = max(volumes[i0:i1], default=1.0) or 1.0
|
|
up = _color(widget, "up-color", UP_RGB)
|
|
down = _color(widget, "down-color", DOWN_RGB)
|
|
bw = max(1, int(plot.item_w() * 0.6))
|
|
bottom = plot.py + plot.ph
|
|
vol_h = plot.ph / 3
|
|
for i in range(i0, min(i1, len(volumes))):
|
|
if i < 0:
|
|
continue
|
|
h = volumes[i] / vmax * vol_h
|
|
cx = plot.x(i)
|
|
cr.save()
|
|
_rgb(cr, up if _bars(widget)[i][3] >= _bars(widget)[i][0] else down)
|
|
cr.rectangle(cx - bw / 2, bottom - h, bw, h)
|
|
cr.fill()
|
|
cr.restore()
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
|
|
|
|
|
|
def _draw_volume_profile(cr, widget):
|
|
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
|
|
if plot is None:
|
|
return
|
|
_draw_candles(cr, widget, plot, _bars(widget), i0, i1)
|
|
bins = max(2, _prop_int(widget, "bins", 20))
|
|
poc_rgb = _color(widget, "poc-color", DOWN_RGB)
|
|
line = _color(widget, "line-color", LINE_RGB)
|
|
vis = _bars(widget)[i0:i1]
|
|
if vis:
|
|
lo = min(b[2] for b in vis)
|
|
hi = max(b[1] for b in vis)
|
|
span = (hi - lo) or 1.0
|
|
counts = [0.0] * bins
|
|
for _o, _h, _l, _c, vol in vis:
|
|
idx = min(bins - 1, int((_c - lo) / span * bins))
|
|
counts[idx] += vol
|
|
vmax = max(counts) or 1.0
|
|
poc = counts.index(vmax)
|
|
prof_w = plot.pw * 0.3
|
|
for idx, count in enumerate(counts):
|
|
w = count / vmax * prof_w
|
|
y_top = plot.y(lo + (idx + 1) / bins * span)
|
|
y_bot = plot.y(lo + idx / bins * span)
|
|
cr.save()
|
|
_rgb(cr, line, 0.45)
|
|
cr.rectangle(plot.px + plot.pw - w, y_top, w,
|
|
max(1, y_bot - y_top))
|
|
cr.fill()
|
|
cr.restore()
|
|
poc_y = plot.y(lo + (poc + 0.5) / bins * span)
|
|
cr.save()
|
|
_rgb(cr, poc_rgb)
|
|
cr.set_line_width(2)
|
|
cr.move_to(plot.px, poc_y)
|
|
cr.line_to(plot.px + plot.pw, poc_y)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, _fmt(_bars(widget)[-1][3]))
|
|
|
|
|
|
def _vwap_values(bars):
|
|
out = []
|
|
cum_tp_vol = 0.0
|
|
cum_vol = 0.0
|
|
for open_v, high, low, close, vol in bars:
|
|
tp = (high + low + close) / 3.0
|
|
cum_tp_vol += tp * vol
|
|
cum_vol += vol
|
|
out.append(cum_tp_vol / cum_vol if cum_vol else close)
|
|
return out
|
|
|
|
|
|
def _draw_vwap(cr, widget):
|
|
values = _vwap_values(_bars(widget))
|
|
closes = _closes(_bars(widget))
|
|
plot, i0, i1 = _line_chart_base(cr, widget, values, line_rgb=None)
|
|
if plot is None:
|
|
return
|
|
line = _color(widget, "line-color", LINE_RGB)
|
|
vwap = _color(widget, "vwap-color", (230 / 255, 126 / 255, 34 / 255))
|
|
_draw_line_values(cr, plot, closes, i0, i1, line, 1.5)
|
|
_draw_line_values(cr, plot, values, i0, i1, vwap, 2.5)
|
|
_draw_title(cr, widget, plot, _fmt(values[-1]))
|
|
|
|
|
|
def _obv_values(bars):
|
|
out = []
|
|
obv = 0.0
|
|
prev = None
|
|
for open_v, high, low, close, vol in bars:
|
|
if prev is not None:
|
|
if close > prev:
|
|
obv += vol
|
|
elif close < prev:
|
|
obv -= vol
|
|
out.append(obv)
|
|
prev = close
|
|
return out
|
|
|
|
|
|
def _draw_obv(cr, widget):
|
|
line = _color(widget, "line-color", LINE_RGB)
|
|
plot, i0, i1 = _line_chart_base(cr, widget, _obv_values(_bars(widget)),
|
|
line_rgb=line)
|
|
if plot is None:
|
|
return
|
|
_draw_title(cr, widget, plot, "")
|
|
|
|
|
|
def _accum_dist_values(bars):
|
|
out = []
|
|
ad = 0.0
|
|
for open_v, high, low, close, vol in bars:
|
|
if high != low:
|
|
mult = ((close - low) - (high - close)) / (high - low)
|
|
else:
|
|
mult = 0.0
|
|
ad += mult * vol
|
|
out.append(ad)
|
|
return out
|
|
|
|
|
|
def _draw_accum_dist(cr, widget):
|
|
line = _color(widget, "line-color", (0.0, 150 / 255, 0.0))
|
|
plot, i0, i1 = _line_chart_base(
|
|
cr, widget, _accum_dist_values(_bars(widget)), line_rgb=line)
|
|
if plot is None:
|
|
return
|
|
_draw_title(cr, widget, plot, "")
|
|
|
|
|
|
def _money_flow_values(bars):
|
|
out = []
|
|
flow = 0.0
|
|
prev = None
|
|
for open_v, high, low, close, vol in bars:
|
|
tp = (high + low + close) / 3.0
|
|
raw = tp * vol
|
|
if prev is not None:
|
|
flow += raw if close > prev else -raw if close < prev else 0.0
|
|
out.append(flow)
|
|
prev = close
|
|
return out
|
|
|
|
|
|
def _draw_money_flow(cr, widget):
|
|
values = _money_flow_values(_bars(widget))
|
|
plot, i0, i1 = _line_chart_base(cr, widget, values, line_rgb=None)
|
|
if plot is None:
|
|
return
|
|
zero = _color(widget, "zero-line-color",
|
|
(120 / 255, 120 / 255, 120 / 255))
|
|
up = _color(widget, "up-color", UP_RGB)
|
|
down = _color(widget, "down-color", DOWN_RGB)
|
|
zero_y = plot.y(0.0)
|
|
cr.save()
|
|
_rgb(cr, zero)
|
|
cr.set_line_width(1)
|
|
cr.set_dash([6.0, 4.0])
|
|
cr.move_to(plot.px, zero_y)
|
|
cr.line_to(plot.px + plot.pw, zero_y)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_draw_line_values(cr, plot, values, i0, i1,
|
|
up if values[-1] >= 0 else down, 2.0)
|
|
_draw_title(cr, widget, plot, "")
|
|
|
|
|
|
def _rolling_corr(a, b, window):
|
|
out = []
|
|
for i in range(len(a)):
|
|
if i + 1 < window:
|
|
out.append(0.0)
|
|
continue
|
|
wa, wb = a[i - window + 1:i + 1], b[i - window + 1:i + 1]
|
|
ma, mb = sum(wa) / window, sum(wb) / window
|
|
num = sum((x - ma) * (y - mb) for x, y in zip(wa, wb))
|
|
den = math.sqrt(sum((x - ma) ** 2 for x in wa)
|
|
* sum((y - mb) ** 2 for y in wb))
|
|
out.append(num / den if den else 0.0)
|
|
return out
|
|
|
|
|
|
def _draw_correlation(cr, widget):
|
|
window = max(2, _prop_int(widget, "window", 20))
|
|
values = _rolling_corr(_closes(_bars(widget)),
|
|
_closes(_bars(widget, 2)), window)
|
|
plot, i0, i1 = _line_chart_base(cr, widget, values, line_rgb=None)
|
|
if plot is None:
|
|
return
|
|
zero = _color(widget, "zero-line-color",
|
|
(120 / 255, 120 / 255, 120 / 255))
|
|
corr = _color(widget, "corr-color", LINE_RGB)
|
|
scatter = _color(widget, "scatter-color", DOWN_RGB)
|
|
zero_y = plot.y(0.0)
|
|
cr.save()
|
|
_rgb(cr, zero)
|
|
cr.set_line_width(1)
|
|
cr.move_to(plot.px, zero_y)
|
|
cr.line_to(plot.px + plot.pw, zero_y)
|
|
cr.stroke()
|
|
_rgb(cr, scatter)
|
|
for i in range(i0, min(i1, len(values)), 5):
|
|
if i >= 0:
|
|
cr.arc(plot.x(i), plot.y(values[i]), 2, 0, 2 * math.pi)
|
|
cr.fill()
|
|
cr.restore()
|
|
_draw_line_values(cr, plot, values, i0, i1, corr, 2.0)
|
|
_draw_title(cr, widget, plot, _fmt(values[-1]))
|
|
|
|
|
|
def _indexed(bars, base_value=100.0):
|
|
first = bars[0][3]
|
|
return [c / first * base_value for c in _closes(bars)]
|
|
|
|
|
|
def _draw_indexed(cr, widget):
|
|
base = _prop_float(widget, "base-value", 100.0)
|
|
first, count = _view(widget, len(_bars(widget)))
|
|
i0, i1 = int(math.floor(first)), int(math.ceil(first + count))
|
|
series = [_indexed(_bars(widget), base),
|
|
_indexed(_bars(widget, 2), base)]
|
|
lo = min(min(s[i0:i1]) for s in series)
|
|
hi = max(max(s[i0:i1]) for s in series)
|
|
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
|
|
frame = _frame(widget)
|
|
if frame is None:
|
|
_wtext(cr, widget, widget.pkind, widget.width / 2,
|
|
widget.height / 2 + 5, size=12, align="center",
|
|
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
|
|
return
|
|
plot = _Plot(widget, frame, lo - 1, hi + 1, first, count,
|
|
len(_bars(widget)))
|
|
_draw_grid(cr, widget, plot)
|
|
base_rgb = _color(widget, "base-line-color",
|
|
(180 / 255, 180 / 255, 180 / 255))
|
|
base_y = plot.y(base)
|
|
cr.save()
|
|
_rgb(cr, base_rgb)
|
|
cr.set_line_width(1)
|
|
cr.set_dash([6.0, 4.0])
|
|
cr.move_to(plot.px, base_y)
|
|
cr.line_to(plot.px + plot.pw, base_y)
|
|
cr.stroke()
|
|
cr.restore()
|
|
for values, rgb in ((series[0], LINE_RGB),
|
|
(series[1], DOWN_RGB)):
|
|
_draw_line_values(cr, plot, values, i0, i1, rgb, 2.0)
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, "")
|
|
|
|
|
|
def _draw_relative_perf(cr, widget):
|
|
first, count = _view(widget, len(_bars(widget)))
|
|
i0, i1 = int(math.floor(first)), int(math.ceil(first + count))
|
|
series = []
|
|
for bars in (_bars(widget), _bars(widget, 2), _bars(widget, 3)):
|
|
base = bars[0][3]
|
|
series.append([(c - base) / base * 100.0
|
|
for c in _closes(bars)])
|
|
lo = min(min(s[i0:i1]) for s in series)
|
|
hi = max(max(s[i0:i1]) for s in series)
|
|
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
|
|
frame = _frame(widget)
|
|
if frame is None:
|
|
_wtext(cr, widget, widget.pkind, widget.width / 2,
|
|
widget.height / 2 + 5, size=12, align="center",
|
|
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
|
|
return
|
|
plot = _Plot(widget, frame, lo - 1, hi + 1, first, count,
|
|
len(_bars(widget)))
|
|
_draw_grid(cr, widget, plot)
|
|
zero = _color(widget, "zero-line-color",
|
|
(180 / 255, 180 / 255, 180 / 255))
|
|
zero_y = plot.y(0.0)
|
|
cr.save()
|
|
_rgb(cr, zero)
|
|
cr.set_line_width(1)
|
|
cr.move_to(plot.px, zero_y)
|
|
cr.line_to(plot.px + plot.pw, zero_y)
|
|
cr.stroke()
|
|
cr.restore()
|
|
for values, rgb in ((series[0], LINE_RGB),
|
|
(series[1], DOWN_RGB),
|
|
(series[2], (0.0, 150 / 255, 0.0))):
|
|
_draw_line_values(cr, plot, values, i0, i1, rgb, 2.0)
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, "")
|
|
|
|
|
|
def _draw_ratio(cr, widget):
|
|
a, b = _closes(_bars(widget)), _closes(_bars(widget, 2))
|
|
values = [x / y if y else 0.0 for x, y in zip(a, b)]
|
|
line = _color(widget, "line-color", (120 / 255, 60 / 255, 180 / 255))
|
|
plot, i0, i1 = _line_chart_base(cr, widget, values, line_rgb=line)
|
|
if plot is None:
|
|
return
|
|
_draw_title(cr, widget, plot, _fmt(values[-1]))
|
|
|
|
|
|
def _draw_spread(cr, widget):
|
|
a, b = _closes(_bars(widget)), _closes(_bars(widget, 2))
|
|
values = [x - y for x, y in zip(a, b)]
|
|
plot, i0, i1 = _line_chart_base(cr, widget, values, line_rgb=None)
|
|
if plot is None:
|
|
return
|
|
zero = _color(widget, "zero-line-color",
|
|
(120 / 255, 120 / 255, 120 / 255))
|
|
line = _color(widget, "line-color", LINE_RGB)
|
|
zero_y = plot.y(0.0)
|
|
cr.save()
|
|
_rgb(cr, zero)
|
|
cr.set_line_width(1)
|
|
cr.set_dash([6.0, 4.0])
|
|
cr.move_to(plot.px, zero_y)
|
|
cr.line_to(plot.px + plot.pw, zero_y)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_draw_line_values(cr, plot, values, i0, i1, line, 2.0)
|
|
_draw_title(cr, widget, plot, _fmt(values[-1]))
|
|
|
|
|
|
def _draw_sector(cr, widget):
|
|
labels = [s for s in widget.get_prop("labels", "Tech|Tech|Energy")
|
|
.split("|") if s]
|
|
seen = []
|
|
for label in labels:
|
|
if label not in seen:
|
|
seen.append(label)
|
|
series = [_indexed(_bars(widget)), _indexed(_bars(widget, 2)),
|
|
_indexed(_bars(widget, 3))]
|
|
first, count = _view(widget, len(_bars(widget)))
|
|
i0, i1 = int(math.floor(first)), int(math.ceil(first + count))
|
|
lo = min(min(s[i0:i1]) for s in series)
|
|
hi = max(max(s[i0:i1]) for s in series)
|
|
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
|
|
frame = _frame(widget)
|
|
if frame is None:
|
|
_wtext(cr, widget, widget.pkind, widget.width / 2,
|
|
widget.height / 2 + 5, size=12, align="center",
|
|
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
|
|
return
|
|
plot = _Plot(widget, frame, lo - 1, hi + 1, first, count,
|
|
len(_bars(widget)))
|
|
_draw_grid(cr, widget, plot)
|
|
colours = (LINE_RGB, DOWN_RGB, (0.0, 150 / 255, 0.0))
|
|
for values, rgb in zip(series, colours):
|
|
_draw_line_values(cr, plot, values, i0, i1, rgb, 2.0)
|
|
_draw_x_axis(cr, widget, plot)
|
|
x = plot.px + 8
|
|
for label, rgb in zip(seen, colours):
|
|
cr.save()
|
|
_rgb(cr, rgb)
|
|
cr.rectangle(x, plot.py + 6, 10, 4)
|
|
cr.fill()
|
|
cr.restore()
|
|
_wtext(cr, widget, label, x + 14, plot.py + 14, size=11,
|
|
max_width=80)
|
|
x += _text_width(cr, widget, label, size=11) + 34
|
|
_draw_title(cr, widget, plot, "")
|
|
|
|
|
|
def _draw_multi_symbol(cr, widget):
|
|
series = [_indexed(_bars(widget)), _indexed(_bars(widget, 2)),
|
|
_indexed(_bars(widget, 3))]
|
|
first, count = _view(widget, len(_bars(widget)))
|
|
i0, i1 = int(math.floor(first)), int(math.ceil(first + count))
|
|
lo = min(min(s[i0:i1]) for s in series)
|
|
hi = max(max(s[i0:i1]) for s in series)
|
|
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
|
|
frame = _frame(widget)
|
|
if frame is None:
|
|
_wtext(cr, widget, widget.pkind, widget.width / 2,
|
|
widget.height / 2 + 5, size=12, align="center",
|
|
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
|
|
return
|
|
plot = _Plot(widget, frame, lo - 1, hi + 1, first, count,
|
|
len(_bars(widget)))
|
|
_draw_grid(cr, widget, plot)
|
|
for values, rgb in zip(series, (LINE_RGB, DOWN_RGB,
|
|
(0.0, 150 / 255, 0.0))):
|
|
_draw_line_values(cr, plot, values, i0, i1, rgb, 2.0)
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, "")
|
|
|
|
|
|
def _draw_overlay(cr, widget):
|
|
first, count = _view(widget, len(_bars(widget)))
|
|
i0, i1 = int(math.floor(first)), int(math.ceil(first + count))
|
|
main = _closes(_bars(widget))
|
|
other = _closes(_bars(widget, 2))
|
|
lo = min(min(main[i0:i1]), min(other[i0:i1]))
|
|
hi = max(max(main[i0:i1]), max(other[i0:i1]))
|
|
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
|
|
frame = _frame(widget)
|
|
if frame is None:
|
|
_wtext(cr, widget, widget.pkind, widget.width / 2,
|
|
widget.height / 2 + 5, size=12, align="center",
|
|
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
|
|
return
|
|
plot = _Plot(widget, frame, lo - 1, hi + 1, first, count,
|
|
len(_bars(widget)))
|
|
_draw_grid(cr, widget, plot)
|
|
_draw_line_values(cr, plot, main, i0, i1, LINE_RGB, 2.0)
|
|
cr.save()
|
|
_rgb(cr, DOWN_RGB)
|
|
cr.set_line_width(1.5)
|
|
cr.set_dash([5.0, 3.0])
|
|
started = False
|
|
for i in range(i0, min(i1, len(other))):
|
|
if i < 0:
|
|
continue
|
|
x, y = plot.x(i), plot.y(other[i])
|
|
if not started:
|
|
cr.move_to(x, y)
|
|
started = True
|
|
else:
|
|
cr.line_to(x, y)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, _fmt(main[-1]))
|
|
|
|
|
|
def _draw_price(cr, widget):
|
|
"""Price label: big last close + day change (kind "Price")."""
|
|
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
|
|
bars = _bars(widget)
|
|
last = bars[-1][3]
|
|
# A one-bar series has no previous close: show a flat change.
|
|
prev = bars[-2][3] if len(bars) >= 2 else last
|
|
change = last - prev
|
|
rgb = UP_RGB if change >= 0 else DOWN_RGB
|
|
sign = "+" if change >= 0 else ""
|
|
_wtext(cr, widget, widget.text, 8, 16, size=12, bold=True,
|
|
max_width=widget.width - 16)
|
|
_wtext(cr, widget, _fmt(last), 8, widget.height / 2 + 12, size=20,
|
|
rgb=rgb, bold=True, max_width=widget.width - 16)
|
|
_wtext(cr, widget, "%s%s (%s%.2f%%)" % (sign, _fmt(change), sign,
|
|
change / prev * 100.0),
|
|
8, widget.height - 8, size=11, rgb=rgb,
|
|
max_width=widget.width - 16)
|
|
|
|
|
|
# --- drawing tools -----------------------------------------------------------
|
|
# Tools draw over the candle chart. Anchors come from _anchors()
|
|
# (only user-set ones count); see the module docstring for the
|
|
# Flag 13 (ddaf4bd) guard semantics.
|
|
|
|
def _tool_base(cr, widget):
|
|
"""Candle background + plot for a tool; (plot, i0, i1)."""
|
|
plot, i0, i1 = _chart_base(cr, widget, _bars(widget))
|
|
if plot is None:
|
|
return None, 0, 0
|
|
_draw_candles(cr, widget, plot, _bars(widget), i0, i1)
|
|
return plot, i0, i1
|
|
|
|
|
|
def _tool_finish(cr, widget, plot, anchors):
|
|
_draw_anchor_dots(cr, plot, anchors)
|
|
_draw_x_axis(cr, widget, plot)
|
|
_draw_title(cr, widget, plot, "")
|
|
|
|
|
|
def _draw_trendline(cr, widget):
|
|
plot, i0, i1 = _tool_base(cr, widget)
|
|
if plot is None:
|
|
return
|
|
anchors = _anchors(widget)
|
|
colour = _color(widget, "color", DOWN_RGB)
|
|
width = _prop_int(widget, "line-width", 2)
|
|
if len(anchors) >= 2:
|
|
(b0, p0), (b1, p1) = anchors[0], anchors[1]
|
|
_line_through(cr, plot, b0, p0, b1, p1, colour, width)
|
|
elif len(anchors) == 1:
|
|
bar, price = anchors[0]
|
|
cr.save()
|
|
_rgb(cr, colour)
|
|
cr.set_line_width(width)
|
|
cr.move_to(plot.px, plot.y(price))
|
|
cr.line_to(plot.px + plot.pw, plot.y(price))
|
|
cr.stroke()
|
|
cr.restore()
|
|
else:
|
|
_line_through(cr, plot, 0, plot.lo + (plot.hi - plot.lo) * 0.25,
|
|
len(_bars(widget)) - 1,
|
|
plot.lo + (plot.hi - plot.lo) * 0.75, colour, width)
|
|
_tool_finish(cr, widget, plot, anchors)
|
|
|
|
|
|
def _draw_horizontal_line(cr, widget):
|
|
plot, i0, i1 = _tool_base(cr, widget)
|
|
if plot is None:
|
|
return
|
|
anchors = _anchors(widget)
|
|
colour = _color(widget, "color", LINE_RGB)
|
|
width = _prop_int(widget, "line-width", 2)
|
|
price = anchors[0][1] if anchors \
|
|
else (plot.lo + plot.hi) / 2.0
|
|
cr.save()
|
|
_rgb(cr, colour)
|
|
cr.set_line_width(width)
|
|
cr.move_to(plot.px, plot.y(price))
|
|
cr.line_to(plot.px + plot.pw, plot.y(price))
|
|
cr.stroke()
|
|
cr.restore()
|
|
_tool_finish(cr, widget, plot, anchors)
|
|
|
|
|
|
def _draw_vertical_line(cr, widget):
|
|
plot, i0, i1 = _tool_base(cr, widget)
|
|
if plot is None:
|
|
return
|
|
anchors = _anchors(widget)
|
|
colour = _color(widget, "color", (120 / 255, 60 / 255, 180 / 255))
|
|
width = _prop_int(widget, "line-width", 2)
|
|
bar = anchors[0][0] if anchors else len(_bars(widget)) // 2
|
|
cr.save()
|
|
_rgb(cr, colour)
|
|
cr.set_line_width(width)
|
|
cr.move_to(plot.x(bar), plot.py)
|
|
cr.line_to(plot.x(bar), plot.py + plot.ph)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_tool_finish(cr, widget, plot, anchors)
|
|
|
|
|
|
def _draw_rectangle(cr, widget):
|
|
plot, i0, i1 = _tool_base(cr, widget)
|
|
if plot is None:
|
|
return
|
|
anchors = _anchors(widget)
|
|
colour = _color(widget, "color", LINE_RGB)
|
|
fill = _color(widget, "fill-color",
|
|
(200 / 255, 220 / 255, 255 / 255))
|
|
width = _prop_int(widget, "line-width", 2)
|
|
if len(anchors) >= 2:
|
|
(b0, p0), (b1, p1) = anchors[0], anchors[1]
|
|
x0, x1 = sorted((plot.x(b0), plot.x(b1)))
|
|
y0, y1 = sorted((plot.y(p0), plot.y(p1)))
|
|
else:
|
|
x0 = plot.px + plot.pw * 0.25
|
|
x1 = plot.px + plot.pw * 0.75
|
|
y0 = plot.py + plot.ph * 0.25
|
|
y1 = plot.py + plot.ph * 0.75
|
|
cr.save()
|
|
_rgb(cr, fill, 0.5)
|
|
cr.rectangle(x0, y0, x1 - x0, y1 - y0)
|
|
cr.fill_preserve()
|
|
_rgb(cr, colour)
|
|
cr.set_line_width(width)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_tool_finish(cr, widget, plot, anchors)
|
|
|
|
|
|
def _draw_ellipse(cr, widget):
|
|
plot, i0, i1 = _tool_base(cr, widget)
|
|
if plot is None:
|
|
return
|
|
anchors = _anchors(widget)
|
|
colour = _color(widget, "color", (0.0, 140 / 255, 120 / 255))
|
|
fill = _color(widget, "fill-color",
|
|
(220 / 255, 235 / 255, 255 / 255))
|
|
width = _prop_int(widget, "line-width", 2)
|
|
if len(anchors) >= 2:
|
|
(b0, p0), (b1, p1) = anchors[0], anchors[1]
|
|
x0, x1 = sorted((plot.x(b0), plot.x(b1)))
|
|
y0, y1 = sorted((plot.y(p0), plot.y(p1)))
|
|
else:
|
|
x0 = plot.px + plot.pw * 0.25
|
|
x1 = plot.px + plot.pw * 0.75
|
|
y0 = plot.py + plot.ph * 0.25
|
|
y1 = plot.py + plot.ph * 0.75
|
|
cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
|
|
rx, ry = max(1, (x1 - x0) / 2), max(1, (y1 - y0) / 2)
|
|
cr.save()
|
|
cr.translate(cx, cy)
|
|
cr.scale(rx, ry)
|
|
cr.arc(0, 0, 1, 0, 2 * math.pi)
|
|
cr.restore()
|
|
cr.save()
|
|
_rgb(cr, fill, 0.5)
|
|
cr.fill_preserve()
|
|
_rgb(cr, colour)
|
|
cr.set_line_width(width)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_tool_finish(cr, widget, plot, anchors)
|
|
|
|
|
|
def _draw_arrow(cr, widget):
|
|
plot, i0, i1 = _tool_base(cr, widget)
|
|
if plot is None:
|
|
return
|
|
anchors = _anchors(widget)
|
|
colour = _color(widget, "color", DOWN_RGB)
|
|
width = _prop_int(widget, "line-width", 3)
|
|
if len(anchors) >= 2:
|
|
(b0, p0), (b1, p1) = anchors[0], anchors[1]
|
|
x0, y0 = plot.x(b0), plot.y(p0)
|
|
x1, y1 = plot.x(b1), plot.y(p1)
|
|
else:
|
|
x0, y0 = plot.px + plot.pw * 0.2, plot.py + plot.ph * 0.7
|
|
x1, y1 = plot.px + plot.pw * 0.8, plot.py + plot.ph * 0.3
|
|
angle = math.atan2(y1 - y0, x1 - x0)
|
|
head = 12
|
|
cr.save()
|
|
_rgb(cr, colour)
|
|
cr.set_line_width(width)
|
|
cr.move_to(x0, y0)
|
|
cr.line_to(x1, y1)
|
|
cr.stroke()
|
|
cr.move_to(x1, y1)
|
|
cr.line_to(x1 - head * math.cos(angle - 0.45),
|
|
y1 - head * math.sin(angle - 0.45))
|
|
cr.line_to(x1 - head * math.cos(angle + 0.45),
|
|
y1 - head * math.sin(angle + 0.45))
|
|
cr.close_path()
|
|
cr.fill()
|
|
cr.restore()
|
|
_tool_finish(cr, widget, plot, anchors)
|
|
|
|
|
|
def _fib_levels(cr, widget, plot, anchors, ratios, colour, level_rgb):
|
|
"""Horizontal fib lines between the two anchor prices."""
|
|
if len(anchors) >= 2:
|
|
(b0, p0), (b1, p1) = anchors[0], anchors[1]
|
|
else:
|
|
p0, p1 = plot.hi, plot.lo
|
|
lo_p, hi_p = min(p0, p1), max(p0, p1)
|
|
span = hi_p - lo_p
|
|
for ratio in ratios:
|
|
price = hi_p - ratio * span
|
|
y = plot.y(price)
|
|
cr.save()
|
|
_rgb(cr, colour if ratio in (0.0, 1.0) else level_rgb)
|
|
cr.set_line_width(1)
|
|
if ratio not in (0.0, 1.0):
|
|
cr.set_dash([5.0, 3.0])
|
|
cr.move_to(plot.px, y)
|
|
cr.line_to(plot.px + plot.pw, y)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_wtext(cr, widget, "%.1f%%" % (ratio * 100), plot.px + 4,
|
|
y - 3, size=11, rgb=level_rgb, max_width=60)
|
|
|
|
|
|
def _draw_fib_retracement(cr, widget):
|
|
plot, i0, i1 = _tool_base(cr, widget)
|
|
if plot is None:
|
|
return
|
|
anchors = _anchors(widget)
|
|
colour = _color(widget, "color", (180 / 255, 120 / 255, 0.0))
|
|
level_rgb = _color(widget, "level-color",
|
|
(120 / 255, 120 / 255, 120 / 255))
|
|
_fib_levels(cr, widget, plot, anchors,
|
|
(0.0, 0.236, 0.382, 0.5, 0.618, 1.0), colour, level_rgb)
|
|
_tool_finish(cr, widget, plot, anchors)
|
|
|
|
|
|
def _draw_fib_extension(cr, widget):
|
|
plot, i0, i1 = _tool_base(cr, widget)
|
|
if plot is None:
|
|
return
|
|
anchors = _anchors(widget)
|
|
colour = _color(widget, "color", (180 / 255, 80 / 255, 0.0))
|
|
level_rgb = _color(widget, "level-color",
|
|
(120 / 255, 120 / 255, 120 / 255))
|
|
if len(anchors) >= 2:
|
|
(b0, p0), (b1, p1) = anchors[0], anchors[1]
|
|
else:
|
|
p0, p1 = plot.hi, plot.lo
|
|
span = abs(p1 - p0)
|
|
base = min(p0, p1)
|
|
for ratio in (1.0, 1.272, 1.618):
|
|
price = base + ratio * span if p1 >= p0 \
|
|
else base - ratio * span
|
|
y = plot.y(price)
|
|
cr.save()
|
|
_rgb(cr, colour if ratio == 1.0 else level_rgb)
|
|
cr.set_line_width(1)
|
|
if ratio != 1.0:
|
|
cr.set_dash([5.0, 3.0])
|
|
cr.move_to(plot.px, y)
|
|
cr.line_to(plot.px + plot.pw, y)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_wtext(cr, widget, "%.1f%%" % (ratio * 100), plot.px + 4,
|
|
y - 3, size=11, rgb=level_rgb, max_width=60)
|
|
_tool_finish(cr, widget, plot, anchors)
|
|
|
|
|
|
def _draw_parallel_channel(cr, widget):
|
|
"""Flag 13 (ddaf4bd): with 2 anchors the outer line falls back
|
|
to the midline (so it is not drawn twice); with <2 anchors no
|
|
channel lines at all -- only the dots present."""
|
|
plot, i0, i1 = _tool_base(cr, widget)
|
|
if plot is None:
|
|
return
|
|
anchors = _anchors(widget)
|
|
colour = _color(widget, "color", LINE_RGB)
|
|
width = _prop_int(widget, "line-width", 2)
|
|
if len(anchors) >= 2:
|
|
(b0, p0), (b1, p1) = anchors[0], anchors[1]
|
|
mid = (p0 + p1) / 2.0
|
|
_line_through(cr, plot, b0, p0, b1, p1, colour, width)
|
|
_line_through(cr, plot, b0, mid, b1, mid, colour, 1.0,
|
|
dashed=True)
|
|
if len(anchors) > 2:
|
|
_b2, off = anchors[2]
|
|
_line_through(cr, plot, b0, off, b1, off, colour, width)
|
|
_tool_finish(cr, widget, plot, anchors)
|
|
|
|
|
|
def _draw_pitchfork(cr, widget):
|
|
"""Flag 13 (ddaf4bd): with 2 anchors the fork falls back to a
|
|
trendline through them (the handle); the tines need the third
|
|
anchor. With <2 anchors no fork lines at all."""
|
|
plot, i0, i1 = _tool_base(cr, widget)
|
|
if plot is None:
|
|
return
|
|
anchors = _anchors(widget)
|
|
colour = _color(widget, "color", (120 / 255, 60 / 255, 180 / 255))
|
|
width = _prop_int(widget, "line-width", 2)
|
|
if len(anchors) >= 2:
|
|
(b0, p0), (b1, p1) = anchors[0], anchors[1]
|
|
x0, y0 = plot.x(b0), plot.y(p0)
|
|
x1, y1 = plot.x(b1), plot.y(p1)
|
|
if len(anchors) > 2:
|
|
b2, p2 = anchors[2]
|
|
x2, y2 = plot.x(b2), plot.y(p2)
|
|
else:
|
|
x2, y2 = x1, y1
|
|
mx, my = (x1 + x2) / 2, (y1 + y2) / 2
|
|
run = max(1, mx - x0)
|
|
slope = (my - y0) / run
|
|
end_x = plot.px + plot.pw
|
|
cr.save()
|
|
_rgb(cr, colour)
|
|
cr.set_line_width(width)
|
|
cr.move_to(x0, y0)
|
|
cr.line_to(end_x, my + (end_x - x0) * slope)
|
|
cr.stroke()
|
|
cr.set_line_width(1)
|
|
cr.set_dash([5.0, 3.0])
|
|
if len(anchors) > 2:
|
|
cr.move_to(x1, y1)
|
|
cr.line_to(end_x, y1 + (end_x - x1) * slope)
|
|
cr.move_to(x2, y2)
|
|
cr.line_to(end_x, y2 + (end_x - x2) * slope)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_tool_finish(cr, widget, plot, anchors)
|
|
|
|
|
|
def _draw_measure(cr, widget):
|
|
plot, i0, i1 = _tool_base(cr, widget)
|
|
if plot is None:
|
|
return
|
|
anchors = _anchors(widget)
|
|
colour = _color(widget, "color", (0.0, 140 / 255, 120 / 255))
|
|
width = _prop_int(widget, "line-width", 2)
|
|
if len(anchors) >= 2:
|
|
(b0, p0), (b1, p1) = anchors[0], anchors[1]
|
|
x0, y0 = plot.x(b0), plot.y(p0)
|
|
x1, y1 = plot.x(b1), plot.y(p1)
|
|
cr.save()
|
|
_rgb(cr, colour)
|
|
cr.set_line_width(width)
|
|
cr.set_dash([6.0, 3.0])
|
|
cr.move_to(x0, y0)
|
|
cr.line_to(x1, y1)
|
|
cr.stroke()
|
|
cr.restore()
|
|
label = "%+d bars %s" % (b1 - b0, _fmt(p1 - p0))
|
|
_wtext(cr, widget, label, (x0 + x1) / 2, (y0 + y1) / 2 - 6,
|
|
size=12, align="center", rgb=colour, max_width=160)
|
|
_tool_finish(cr, widget, plot, anchors)
|
|
|
|
|
|
def _draw_brush(cr, widget):
|
|
plot, i0, i1 = _tool_base(cr, widget)
|
|
if plot is None:
|
|
return
|
|
anchors = _anchors(widget)
|
|
colour = _color(widget, "color", (200 / 255, 30 / 255, 200 / 255))
|
|
width = _prop_int(widget, "line-width", 4)
|
|
cr.save()
|
|
_rgb(cr, colour)
|
|
cr.set_line_width(width)
|
|
cr.set_line_cap(1)
|
|
steps = 24
|
|
for s in range(steps + 1):
|
|
frac = s / steps
|
|
x = plot.px + frac * plot.pw
|
|
y = plot.py + plot.ph * (0.5 + 0.3 * math.sin(frac * 9.0))
|
|
if s == 0:
|
|
cr.move_to(x, y)
|
|
else:
|
|
cr.line_to(x, y)
|
|
cr.stroke()
|
|
cr.restore()
|
|
_tool_finish(cr, widget, plot, anchors)
|
|
|
|
|
|
def _draw_text_annotation(cr, widget):
|
|
plot, i0, i1 = _tool_base(cr, widget)
|
|
if plot is None:
|
|
return
|
|
anchors = _anchors(widget)
|
|
colour = _color(widget, "color", (160 / 255, 90 / 255, 0.0))
|
|
fill = _color(widget, "fill-color",
|
|
(255 / 255, 248 / 255, 200 / 255))
|
|
text_rgb = _color(widget, "text-color", (20 / 255, 20 / 255, 20 / 255))
|
|
note = widget.get_prop("annotation-text", "Note")
|
|
if anchors:
|
|
x = plot.x(anchors[0][0])
|
|
y = plot.y(anchors[0][1])
|
|
else:
|
|
x, y = plot.px + plot.pw * 0.3, plot.py + plot.ph * 0.3
|
|
w = _text_width(cr, widget, note, size=12) + 16
|
|
h = 24
|
|
_box(cr, x, y, w, h, fill, colour)
|
|
_wtext(cr, widget, note, x + 8, y + 17, size=12, rgb=text_rgb,
|
|
max_width=w - 16)
|
|
_tool_finish(cr, widget, plot, anchors)
|
|
|
|
|
|
# --- widget class ------------------------------------------------------------
|
|
|
|
_CHART_DRAW = {
|
|
"AccumulationDistribution": _draw_accum_dist,
|
|
"AreaChart": _draw_area,
|
|
"Arrow": _draw_arrow,
|
|
"BaselineChart": _draw_baseline,
|
|
"Brush": _draw_brush,
|
|
"CandlestickChart": _draw_candlestick,
|
|
"CorrelationView": _draw_correlation,
|
|
"Ellipse": _draw_ellipse,
|
|
"FibExtension": _draw_fib_extension,
|
|
"FibRetracement": _draw_fib_retracement,
|
|
"HeikinAshi": _draw_heikin_ashi,
|
|
"HollowCandles": _draw_hollow,
|
|
"HorizontalLine": _draw_horizontal_line,
|
|
"IndexedComparison": _draw_indexed,
|
|
"LineChart": _draw_line,
|
|
"MeasureTool": _draw_measure,
|
|
"MoneyFlowChart": _draw_money_flow,
|
|
"MultiSymbolChart": _draw_multi_symbol,
|
|
"OBVChart": _draw_obv,
|
|
"OHLCBarChart": _draw_ohlc,
|
|
"OverlayChart": _draw_overlay,
|
|
"ParallelChannel": _draw_parallel_channel,
|
|
"Pitchfork": _draw_pitchfork,
|
|
"Price": _draw_price,
|
|
"RatioChart": _draw_ratio,
|
|
"Rectangle": _draw_rectangle,
|
|
"RelativePerformance": _draw_relative_perf,
|
|
"Renko": _draw_renko,
|
|
"SectorComparison": _draw_sector,
|
|
"SpreadChart": _draw_spread,
|
|
"TextAnnotation": _draw_text_annotation,
|
|
"Trendline": _draw_trendline,
|
|
"VWAP": _draw_vwap,
|
|
"VerticalLine": _draw_vertical_line,
|
|
"VolumeBars": _draw_volume_bars,
|
|
"VolumeCandles": _draw_volume_candles,
|
|
"VolumeProfile": _draw_volume_profile,
|
|
}
|
|
|
|
|
|
def _no_data(cr, widget):
|
|
"""Border + 'no data' placeholder for a widget whose series was
|
|
cleared (see StockWidget._draw)."""
|
|
_bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
|
|
_wtext(cr, widget, widget.pkind, widget.width / 2,
|
|
widget.height / 2 - 4, size=12, align="center",
|
|
rgb=(0.4, 0.4, 0.4), max_width=widget.width - 12)
|
|
_wtext(cr, widget, "No data -- call set_series() or load_csv()",
|
|
widget.width / 2, widget.height / 2 + 14, size=11,
|
|
align="center", rgb=(0.4, 0.4, 0.4),
|
|
max_width=widget.width - 12)
|
|
|
|
|
|
class StockWidget(Widget):
|
|
"""One of the 37 Stock Market widgets (archetype Chart/Label in
|
|
the palette, drawn here instead of the generic panel)."""
|
|
|
|
ARCHETYPE = "Chart"
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
# Own series per slot (1, 2, 3): None means "use the built-in
|
|
# demo series for that slot"; a list (possibly empty) is data
|
|
# the user fed in. Runtime state only -- never saved in .fdj.
|
|
self._series = [None, None, None]
|
|
|
|
# --- data ingestion (set_series is the C API; load_csv is new) -----
|
|
def set_series(self, bars, which=1):
|
|
"""Replace the series in slot *which* (1, 2 or 3).
|
|
|
|
*bars* is a list of (open, high, low, close, volume) tuples
|
|
(or dicts with those keys), or None to revert the slot to the
|
|
built-in demo series. Resets the view window (like C
|
|
``set_series``) and marks the widget dirty so the host
|
|
redraws. The multi-symbol charts read slots 2/3 as their
|
|
second/third symbols.
|
|
"""
|
|
if not 1 <= which <= 3:
|
|
raise ValueError("series slot must be 1, 2 or 3, got %r"
|
|
% (which,))
|
|
self._series[which - 1] = _validate_bars(bars)
|
|
if "view-first" in self.prop_names():
|
|
self.props.pop("view-first", None)
|
|
if "view-count" in self.prop_names():
|
|
self.props.pop("view-count", None)
|
|
self._mark_dirty()
|
|
|
|
def populate(self, bars, which=1):
|
|
"""Alias for ``set_series``: fill the widget with *bars*.
|
|
|
|
The clear/populate pair: ``widget.clear()`` empties the
|
|
series, ``widget.populate(bars)`` (or ``set_series``) refills
|
|
it.
|
|
"""
|
|
self.set_series(bars, which=which)
|
|
|
|
def get_series(self, which=1):
|
|
"""The bars slot *which* currently plots: the widget's own
|
|
series when set, else the built-in demo series for that slot.
|
|
Returns a copy, so callers cannot mutate the plotted data.
|
|
"""
|
|
return list(_bars(self, which))
|
|
|
|
def add_point(self, bar):
|
|
"""Append one (open, high, low, close, volume) bar to the
|
|
primary series and return the new bar count.
|
|
|
|
If no own series was set yet, this starts a fresh series
|
|
(it does NOT extend the demo series)."""
|
|
bar = _validate_bars([bar], what="add_point")[0]
|
|
if self._series[0] is None:
|
|
self._series[0] = []
|
|
self._series[0].append(bar)
|
|
self._mark_dirty()
|
|
return len(self._series[0])
|
|
|
|
def clear(self, which=0):
|
|
"""Empty the series: *which* 0 clears all three slots, 1..3
|
|
clears one slot. A cleared widget draws the no-data
|
|
placeholder until ``populate`` / ``set_series`` refills it
|
|
(or ``set_series(None)`` restores the demo series).
|
|
"""
|
|
if which == 0:
|
|
self._series = [[], [], []]
|
|
elif 1 <= which <= 3:
|
|
self._series[which - 1] = []
|
|
else:
|
|
raise ValueError("series slot must be 0..3, got %r"
|
|
% (which,))
|
|
self._mark_dirty()
|
|
|
|
def load_csv(self, source, which=1):
|
|
"""Load OHLCV bars from a CSV file into slot *which*.
|
|
|
|
*source* is a path or a file-like object; see module
|
|
``load_csv`` for the format. Returns the number of bars
|
|
loaded. Raises ValueError naming the offending row on bad
|
|
data, and leaves the previous series untouched in that case.
|
|
"""
|
|
bars = load_csv(source)
|
|
self.set_series(bars, which=which)
|
|
return len(bars)
|
|
|
|
def item_count(self, which=1):
|
|
"""Number of bars slot *which* currently plots (C parity)."""
|
|
return len(_bars(self, which))
|
|
|
|
def _draw(self, cr):
|
|
# A cleared series draws the no-data placeholder instead of a
|
|
# chart: every _draw_<kind> indexes bars[-1]/bars[0], so the
|
|
# check has to happen before dispatch, not inside each kind.
|
|
# Multi-symbol kinds need their extra slots too.
|
|
own = self._series
|
|
if own[0] is not None and len(own[0]) == 0:
|
|
_no_data(cr, self)
|
|
return
|
|
if self.pkind in _MULTI_KINDS:
|
|
if own[1] is not None and len(own[1]) == 0:
|
|
_no_data(cr, self)
|
|
return
|
|
if (self.pkind in _THREE_SERIES_KINDS
|
|
and own[2] is not None and len(own[2]) == 0):
|
|
_no_data(cr, self)
|
|
return
|
|
draw = _CHART_DRAW.get(self.pkind)
|
|
if draw is not None:
|
|
draw(cr, self)
|
|
return
|
|
_bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
|
|
_wtext(cr, self, self.pkind, self.width / 2,
|
|
self.height / 2 + 5, size=12, align="center",
|
|
rgb=(0.4, 0.4, 0.4), max_width=self.width - 12)
|