From 442c6d549892e4a7f93ce6803ca620b64ab07b46 Mon Sep 17 00:00:00 2001 From: vybie <168300406+vybie@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:33:27 -0800 Subject: [PATCH 1/4] Prepare TradeCraft 0.4.0 release candidate --- .github/workflows/dimmoff-pine-upstream.yml | 45 + ARCHITECTURE.md | 1 + ATTRIBUTION.md | 6 +- CHANGELOG.md | 4 + Cargo.lock | 13 +- Cargo.toml | 2 +- README.md | 8 +- RELEASE-CHECKLIST.md | 32 +- RELEASE-NOTES-0.4.0.md | 25 + crates/providers/src/lib.rs | 1 + crates/providers/src/options.rs | 168 + crates/ui-egui/src/lib.rs | 11 +- crates/ui-egui/src/options_view.rs | 1002 +++++ crates/ui-egui/src/pine_engine/ast.rs | 133 + crates/ui-egui/src/pine_engine/builtins.rs | 2 - crates/ui-egui/src/pine_engine/lexer.rs | 9 +- crates/ui-egui/src/pine_engine/parser.rs | 2 + crates/ui-egui/src/pine_engine/runtime.rs | 695 ++- crates/ui-egui/src/pine_engine/study.rs | 37 +- crates/ui-egui/src/terminal_app.rs | 45 +- docs/DIMMOFF-PINE-UPSTREAM.md | 25 + licenses/dependency-baseline.json | 40 +- scripts/license-audit.py | 2 +- scripts/pine/bb-levels.pine | 2 + vendor/DIMMOFF-PINE-UPSTREAM | 1 + vendor/EGUI-CHARTS-UPSTREAM | 2 +- vendor/egui-charts/ROADMAP.md | 72 +- vendor/egui-charts/THIRD-PARTY-NOTICES.md | 2 +- .../benches/check-regressions-test.py | 8 + .../egui-charts/benches/check-regressions.sh | 44 +- vendor/egui-charts/benches/frame_time.rs | 20 +- vendor/egui-charts/benches/stream.rs | 1 - vendor/egui-charts/docs/capture/Cargo.lock | 295 +- vendor/egui-charts/docs/capture/Cargo.toml | 5 + vendor/egui-charts/docs/host-data-services.md | 10 +- vendor/egui-charts/docs/progress/features.csv | 212 +- vendor/egui-charts/docs/site/astro.config.mjs | 2 +- .../egui-charts/docs/site/package-lock.json | 735 +++- vendor/egui-charts/docs/site/package.json | 2 +- .../site/src/content/docs/accessibility.mdx | 4 +- .../site/src/content/docs/chart-types.mdx | 11 +- .../content/docs/chart-types/transforms.mdx | 17 +- .../docs/site/src/content/docs/migration.mdx | 2 +- .../docs/site/src/content/docs/own-data.mdx | 440 ++ .../docs/site/src/content/docs/panes.mdx | 16 +- .../site/src/content/docs/price-scale.mdx | 9 +- .../docs/site/src/content/docs/theming.mdx | 5 +- .../docs/site/src/content/docs/time-zones.mdx | 17 +- vendor/egui-charts/examples/demo/Cargo.lock | 299 +- vendor/egui-charts/examples/demo/Cargo.toml | 8 +- vendor/egui-charts/examples/demo/commands.rs | 302 +- .../egui-charts/examples/demo/comparison.rs | 6 + .../egui-charts/examples/demo/controller.rs | 982 ++++- vendor/egui-charts/examples/demo/feeds.rs | 71 +- vendor/egui-charts/examples/demo/interval.rs | 14 +- vendor/egui-charts/examples/demo/layouts.rs | 94 +- vendor/egui-charts/examples/demo/live.rs | 50 +- vendor/egui-charts/examples/demo/marks.rs | 3 + .../egui-charts/examples/demo/owndata/app.rs | 342 ++ .../egui-charts/examples/demo/owndata/bars.rs | 517 +++ .../examples/demo/owndata/dialog.rs | 3917 +++++++++++++++++ .../egui-charts/examples/demo/owndata/feed.rs | 1596 +++++++ .../egui-charts/examples/demo/owndata/http.rs | 147 + .../egui-charts/examples/demo/owndata/mod.rs | 154 + .../examples/demo/owndata/profile.rs | 579 +++ .../demo/owndata/ready/binance-spot.json | 200 + .../examples/demo/owndata/shape.rs | 253 ++ .../examples/demo/owndata/socket.rs | 491 +++ .../examples/demo/owndata/store.rs | 92 + .../examples/demo/owndata/stream.rs | 1179 +++++ .../egui-charts/examples/demo/owndata/time.rs | 385 ++ .../egui-charts/examples/demo/owndata/tree.rs | 132 + vendor/egui-charts/examples/demo/replay.rs | 7 + .../egui-charts/examples/demo/sampledata.rs | 7 +- vendor/egui-charts/examples/demo/storage.rs | 99 +- vendor/egui-charts/examples/demo/strategy.rs | 8 +- .../egui-charts/examples/demo/study_editor.rs | 6 + vendor/egui-charts/examples/docs/Cargo.toml | 2 +- vendor/egui-charts/examples/docs/main.rs | 16 +- .../examples/docs/scenes/order_flow.rs | 6 +- vendor/egui-charts/src/chart/coords/mod.rs | 3 +- .../src/chart/overlays/footprint.rs | 386 +- .../src/chart/overlays/liquidity_heatmap.rs | 8 + vendor/egui-charts/src/chart/primitives.rs | 22 + .../src/chart/rendering/axes/labels.rs | 36 +- .../src/chart/rendering/axes/mod.rs | 34 +- .../src/chart/rendering/axes/study_scale.rs | 27 +- .../src/chart/rendering/candles/area.rs | 89 +- .../src/chart/rendering/candles/japanese.rs | 21 +- .../src/chart/rendering/candles/mod.rs | 24 +- .../chart/rendering/candles/price_based.rs | 288 +- .../src/chart/rendering/candles/range.rs | 4 +- .../src/chart/rendering/context.rs | 8 + .../src/chart/rendering/legend/mod.rs | 87 +- .../src/chart/rendering/legend/quotes.rs | 2 +- .../chart/rendering/legend/study_controls.rs | 23 +- .../src/chart/rendering/overlays/tooltip.rs | 6 + .../src/chart/rendering/trading_lines/mod.rs | 3 +- vendor/egui-charts/src/chart/selection/mod.rs | 1 + .../egui-charts/src/chart/series/hit_test.rs | 1 + .../egui-charts/src/chart/series/settings.rs | 1 + vendor/egui-charts/src/config/chart.rs | 5 +- vendor/egui-charts/src/config/crosshair.rs | 2 + .../config/drawing_tool/interaction_mode.rs | 1 + .../src/config/drawing_tool/mod.rs | 11 +- vendor/egui-charts/src/config/kinetic.rs | 25 +- vendor/egui-charts/src/config/timescale.rs | 4 +- vendor/egui-charts/src/data/financials.rs | 62 + vendor/egui-charts/src/data/footprint.rs | 37 +- vendor/egui-charts/src/data/http/mod.rs | 8 + vendor/egui-charts/src/data/inbox/mod.rs | 9 + vendor/egui-charts/src/data/inbox/sink.rs | 8 + vendor/egui-charts/src/data/metrics.rs | 2 +- vendor/egui-charts/src/data/mod.rs | 13 + vendor/egui-charts/src/data/option_chain.rs | 17 +- vendor/egui-charts/src/data/options_volume.rs | 2 +- vendor/egui-charts/src/data/order_flow.rs | 118 +- vendor/egui-charts/src/data/recording.rs | 2 + vendor/egui-charts/src/data/replay.rs | 6 + vendor/egui-charts/src/data/study.rs | 1 + vendor/egui-charts/src/data/trades.rs | 93 +- .../src/drawings/domain/alert_levels.rs | 37 + .../src/drawings/domain/drawing.rs | 22 +- .../src/drawings/domain/ghost_feed.rs | 2 + vendor/egui-charts/src/drawings/domain/mod.rs | 2 +- .../src/drawings/domain/options.rs | 68 +- .../src/drawings/domain/template.rs | 1 + .../egui-charts/src/drawings/domain/vwap.rs | 216 +- .../egui-charts/src/drawings/manager/edit.rs | 43 +- .../src/drawings/manager/interaction.rs | 6 + .../egui-charts/src/drawings/manager/mod.rs | 24 +- .../egui-charts/src/drawings/manager/paint.rs | 40 +- vendor/egui-charts/src/drawings/mod.rs | 2 +- .../egui-charts/src/drawings/persistence.rs | 76 +- vendor/egui-charts/src/drawings/registry.rs | 12 +- .../drawings/rendering/annotations/labels.rs | 28 +- .../drawings/rendering/annotations/text.rs | 34 + .../src/drawings/rendering/gann.rs | 16 +- .../src/drawings/rendering/lines.rs | 3 +- .../src/drawings/rendering/measurements.rs | 142 +- .../egui-charts/src/drawings/rendering/mod.rs | 10 + .../drawings/rendering/trading/forecast.rs | 19 +- .../drawings/rendering/trading/projection.rs | 12 +- .../rendering/trading/volume_profile.rs | 474 +- .../egui-charts/src/drawings/repositories.rs | 1 + .../src/drawings/services/handle.rs | 2 + .../src/drawings/services/history.rs | 9 +- .../src/drawings/services/interaction.rs | 1 + .../egui-charts/src/drawings/services/snap.rs | 2 + .../src/drawings/services/z_order.rs | 1 + vendor/egui-charts/src/lib.rs | 15 + vendor/egui-charts/src/localization.rs | 14 + vendor/egui-charts/src/model/alert.rs | 133 +- vendor/egui-charts/src/model/bar/bar.rs | 1 + vendor/egui-charts/src/model/bar/bar_data.rs | 1 + vendor/egui-charts/src/model/chart_type.rs | 112 +- vendor/egui-charts/src/model/instrument.rs | 21 +- vendor/egui-charts/src/model/kagi.rs | 101 +- vendor/egui-charts/src/model/line_break.rs | 1 + vendor/egui-charts/src/model/markers.rs | 3 + vendor/egui-charts/src/model/mod.rs | 6 +- vendor/egui-charts/src/model/range_bar.rs | 359 +- vendor/egui-charts/src/model/renko.rs | 43 +- vendor/egui-charts/src/model/session/mod.rs | 9 + vendor/egui-charts/src/model/signal.rs | 15 + vendor/egui-charts/src/model/study.rs | 1 + vendor/egui-charts/src/model/timescale.rs | 45 +- vendor/egui-charts/src/model/tpo.rs | 2 + vendor/egui-charts/src/scales/horizontal.rs | 70 +- vendor/egui-charts/src/scales/mod.rs | 4 +- .../egui-charts/src/scales/price_formatter.rs | 9 + vendor/egui-charts/src/scales/pricescale.rs | 30 +- .../src/scales/pricescale_marks.rs | 189 +- .../egui-charts/src/scales/time_formatter.rs | 27 +- .../egui-charts/src/scales/timescale_marks.rs | 32 + .../egui-charts/src/services/alert_engine.rs | 6 + .../src/services/alert_evaluator.rs | 9 + vendor/egui-charts/src/services/alert_feed.rs | 21 + .../egui-charts/src/services/detectors/mod.rs | 6 + vendor/egui-charts/src/services/events.rs | 9 + vendor/egui-charts/src/services/paper.rs | 11 + .../src/services/profile_directory.rs | 8 + vendor/egui-charts/src/services/settings.rs | 158 +- vendor/egui-charts/src/services/signals.rs | 15 +- vendor/egui-charts/src/strategies/backtest.rs | 28 +- .../egui-charts/src/strategies/library/mod.rs | 8 + .../src/strategies/library/studies.rs | 4 + .../src/strategies/library/tests.rs | 2 + .../src/studies/builtin/auto_drawing.rs | 1 + .../src/studies/builtin/chart_patterns.rs | 3 + .../src/studies/builtin/close_to_close_vol.rs | 58 +- vendor/egui-charts/src/studies/builtin/cvd.rs | 1 + .../src/studies/builtin/elliott_wave.rs | 2 +- .../src/studies/builtin/footprint_studies.rs | 4 + .../src/studies/builtin/guppy_ma.rs | 121 +- .../studies/builtin/historical_volatility.rs | 2 +- .../src/studies/builtin/key_levels.rs | 2 +- .../src/studies/builtin/lunar_phases.rs | 2 + .../src/studies/builtin/ma_combination.rs | 2 + .../src/studies/builtin/majority_rule.rs | 242 +- vendor/egui-charts/src/studies/builtin/mod.rs | 4 +- .../src/studies/builtin/ohlc_volatility.rs | 52 +- .../src/studies/builtin/performance.rs | 2 +- .../src/studies/builtin/price_oscillator.rs | 1 + .../builtin/relative_volume_at_time.rs | 1 + vendor/egui-charts/src/studies/builtin/rsi.rs | 365 +- .../src/studies/builtin/rsi_divergence.rs | 366 +- .../src/studies/builtin/seasonality.rs | 2 +- .../studies/builtin/standard_error_bands.rs | 245 +- .../src/studies/builtin/symbol_pair.rs | 86 +- .../src/studies/builtin/technical_ratings.rs | 489 +- .../src/studies/builtin/trade_delta.rs | 1 + .../src/studies/builtin/trade_profile.rs | 1 + .../studies/builtin/visible_average_price.rs | 87 + .../egui-charts/src/studies/builtin/volume.rs | 1 + .../src/studies/builtin/volume_24h.rs | 18 +- .../src/studies/builtin/volume_price_trend.rs | 136 +- .../src/studies/builtin/volume_profile.rs | 1 + .../egui-charts/src/studies/builtin/vwap.rs | 54 +- .../src/studies/builtin/vwap_auto_anchored.rs | 156 +- .../egui-charts/src/studies/builtin/wedge.rs | 2 +- .../src/studies/builtin/williams_r.rs | 7 +- .../src/studies/builtin/zero_trend_vol.rs | 60 +- .../egui-charts/src/studies/builtin/zigzag.rs | 2 + vendor/egui-charts/src/studies/chart_state.rs | 54 +- vendor/egui-charts/src/studies/custom.rs | 8 + .../src/studies/factory/builtin_properties.rs | 23 +- vendor/egui-charts/src/studies/factory/mod.rs | 18 +- .../src/studies/indicator_trait.rs | 4 +- vendor/egui-charts/src/studies/inputs.rs | 1 + vendor/egui-charts/src/studies/metric.rs | 2 +- vendor/egui-charts/src/studies/mod.rs | 14 +- vendor/egui-charts/src/studies/plots.rs | 1 + vendor/egui-charts/src/studies/reference.rs | 13 +- .../src/studies/reference/expected.txt | 18 + vendor/egui-charts/src/studies/settings.rs | 124 +- vendor/egui-charts/src/studies/stepper.rs | 2 +- vendor/egui-charts/src/studies/table.rs | 365 +- vendor/egui-charts/src/studies/template.rs | 228 +- vendor/egui-charts/src/tokens/resolved.rs | 1 + vendor/egui-charts/src/tokens/semantic.rs | 5 + vendor/egui-charts/src/tokens/sizing.rs | 1 + .../egui-charts/src/ui/context_menu/axis.rs | 23 +- .../src/ui/context_menu/chart_menus/tests.rs | 202 +- .../src/ui/dialogs/alert_dialog/dialog.rs | 118 +- .../src/ui/dialogs/alert_dialog/preset.rs | 61 +- .../src/ui/dialogs/chart_settings/mod.rs | 533 ++- .../ui/dialogs/chart_settings/tabs/canvas.rs | 157 +- .../src/ui/dialogs/chart_settings/tabs/mod.rs | 6 +- .../ui/dialogs/chart_settings/tabs/scales.rs | 67 + .../ui/dialogs/chart_settings/tabs/symbol.rs | 14 +- .../ui/dialogs/chart_settings/tabs/trading.rs | 5 + .../egui-charts/src/ui/dialogs/data_table.rs | 60 +- .../ui/dialogs/drawing_properties/actions.rs | 6 +- .../dialogs/drawing_properties/tabs/inputs.rs | 120 +- .../dialogs/drawing_properties/tabs/style.rs | 2 +- .../ui/dialogs/indicator_dialog/settings.rs | 16 +- .../src/ui/dialogs/keyboard_shortcuts/mod.rs | 149 +- .../src/ui/dialogs/series_settings/dialog.rs | 13 +- .../ui/dialogs/series_settings/tabs/symbol.rs | 61 +- .../ui/drawing_toolbar/utilities/templates.rs | 17 +- vendor/egui-charts/src/ui/financials.rs | 62 +- .../src/ui/floating_toolbar/toolbar.rs | 2 + vendor/egui-charts/src/ui/replay/floating.rs | 9 +- vendor/egui-charts/src/ui/replay/session.rs | 3 +- .../src/ui/strategy_report/tester.rs | 15 +- .../ui/top_toolbar/components/layout_menu.rs | 20 +- .../components/timeframe_selector/mod.rs | 11 +- .../egui-charts/src/ui/top_toolbar/toolbar.rs | 9 + vendor/egui-charts/src/ui/trading/dom.rs | 8 +- .../egui-charts/src/ui/trading/executions.rs | 2 +- .../egui-charts/src/ui/trading/ticket/form.rs | 31 +- .../egui-charts/src/ui/trading/ticket/mod.rs | 213 +- .../egui-charts/src/ui/trading/ticket/view.rs | 16 +- vendor/egui-charts/src/ui/trading/view.rs | 3 +- .../src/ui/widget_bar/panels/alerts_panel.rs | 10 +- .../ui/widget_bar/panels/object_tree/panel.rs | 11 +- .../panels/object_tree/source_tree.rs | 35 +- .../ui/widget_bar/panels/symbol_details.rs | 60 +- .../src/ui/widget_bar/panels/watchlist.rs | 12 + .../src/ui_kit/command_palette/fuzzy.rs | 257 +- .../src/ui_kit/command_palette/palette.rs | 146 +- .../src/ui_kit/notifications/panel.rs | 41 +- vendor/egui-charts/src/widget/alerts.rs | 62 +- vendor/egui-charts/src/widget/anchors.rs | 3 +- vendor/egui-charts/src/widget/builder.rs | 86 +- vendor/egui-charts/src/widget/change_marks.rs | 147 +- vendor/egui-charts/src/widget/clipboard.rs | 43 +- vendor/egui-charts/src/widget/drawing_api.rs | 97 + vendor/egui-charts/src/widget/export.rs | 129 +- vendor/egui-charts/src/widget/feed/mod.rs | 30 +- vendor/egui-charts/src/widget/feed/pump.rs | 7 +- vendor/egui-charts/src/widget/feed/tests.rs | 506 ++- vendor/egui-charts/src/widget/format.rs | 231 +- .../src/widget/frame/background.rs | 188 +- vendor/egui-charts/src/widget/frame/mod.rs | 189 +- .../src/widget/frame/tests/axes.rs | 192 +- .../src/widget/frame/tests/crosshair.rs | 40 +- vendor/egui-charts/src/widget/history.rs | 211 +- vendor/egui-charts/src/widget/interaction.rs | 82 +- vendor/egui-charts/src/widget/keyboard.rs | 418 +- vendor/egui-charts/src/widget/layout.rs | 122 +- vendor/egui-charts/src/widget/layout/copy.rs | 3 +- .../egui-charts/src/widget/layout/drawings.rs | 1287 +++++- vendor/egui-charts/src/widget/marks.rs | 98 +- vendor/egui-charts/src/widget/mod.rs | 29 +- vendor/egui-charts/src/widget/navigation.rs | 35 + vendor/egui-charts/src/widget/palette.rs | 69 +- vendor/egui-charts/src/widget/pan_zoom/mod.rs | 988 +++-- .../egui-charts/src/widget/pan_zoom/state.rs | 8 +- .../egui-charts/src/widget/pane/controls.rs | 256 +- .../src/widget/pane/indicator/config.rs | 2 + .../src/widget/pane/indicator/mod.rs | 68 +- .../src/widget/pane/indicator/paint.rs | 37 +- vendor/egui-charts/src/widget/pane/mod.rs | 14 +- .../egui-charts/src/widget/pane/render/mod.rs | 77 +- .../src/widget/pane/render/tests.rs | 303 +- vendor/egui-charts/src/widget/readout.rs | 24 + vendor/egui-charts/src/widget/replay.rs | 64 +- vendor/egui-charts/src/widget/series/mod.rs | 76 +- .../egui-charts/src/widget/series/options.rs | 12 +- vendor/egui-charts/src/widget/series/paint.rs | 28 +- .../src/widget/series/scales/mod.rs | 147 +- .../src/widget/series/scales/tests.rs | 386 +- vendor/egui-charts/src/widget/series/tests.rs | 50 +- .../egui-charts/src/widget/settings/apply.rs | 335 +- .../egui-charts/src/widget/settings/data.rs | 55 +- vendor/egui-charts/src/widget/settings/mod.rs | 4 +- .../egui-charts/src/widget/stored_drawings.rs | 10 +- vendor/egui-charts/src/widget/time_scale.rs | 31 +- .../src/widget/tool_interaction/mod.rs | 2 +- .../src/widget/tool_interaction/text.rs | 184 +- vendor/egui-charts/src/widget/volume.rs | 77 +- vendor/egui-charts/terminal/Cargo.lock | 1 + vendor/egui-charts/terminal/Cargo.toml | 1 + vendor/egui-charts/terminal/src/action.rs | 7 +- vendor/egui-charts/terminal/src/commands.rs | 979 +++- vendor/egui-charts/terminal/src/drawings.rs | 71 +- vendor/egui-charts/terminal/src/layout.rs | 16 +- vendor/egui-charts/terminal/src/layouts.rs | 40 +- vendor/egui-charts/terminal/src/lib.rs | 17 +- vendor/egui-charts/terminal/src/panels.rs | 170 +- vendor/egui-charts/terminal/src/studies.rs | 6 +- vendor/egui-charts/terminal/src/time.rs | 87 +- vendor/egui-charts/terminal/src/trading.rs | 14 +- 345 files changed, 31606 insertions(+), 3951 deletions(-) create mode 100644 .github/workflows/dimmoff-pine-upstream.yml create mode 100644 RELEASE-NOTES-0.4.0.md create mode 100644 crates/providers/src/options.rs create mode 100644 crates/ui-egui/src/options_view.rs create mode 100644 docs/DIMMOFF-PINE-UPSTREAM.md create mode 100644 vendor/DIMMOFF-PINE-UPSTREAM create mode 100644 vendor/egui-charts/docs/site/src/content/docs/own-data.mdx create mode 100644 vendor/egui-charts/examples/demo/owndata/app.rs create mode 100644 vendor/egui-charts/examples/demo/owndata/bars.rs create mode 100644 vendor/egui-charts/examples/demo/owndata/dialog.rs create mode 100644 vendor/egui-charts/examples/demo/owndata/feed.rs create mode 100644 vendor/egui-charts/examples/demo/owndata/http.rs create mode 100644 vendor/egui-charts/examples/demo/owndata/mod.rs create mode 100644 vendor/egui-charts/examples/demo/owndata/profile.rs create mode 100644 vendor/egui-charts/examples/demo/owndata/ready/binance-spot.json create mode 100644 vendor/egui-charts/examples/demo/owndata/shape.rs create mode 100644 vendor/egui-charts/examples/demo/owndata/socket.rs create mode 100644 vendor/egui-charts/examples/demo/owndata/store.rs create mode 100644 vendor/egui-charts/examples/demo/owndata/stream.rs create mode 100644 vendor/egui-charts/examples/demo/owndata/time.rs create mode 100644 vendor/egui-charts/examples/demo/owndata/tree.rs create mode 100644 vendor/egui-charts/src/data/financials.rs diff --git a/.github/workflows/dimmoff-pine-upstream.yml b/.github/workflows/dimmoff-pine-upstream.yml new file mode 100644 index 0000000..4319173 --- /dev/null +++ b/.github/workflows/dimmoff-pine-upstream.yml @@ -0,0 +1,45 @@ +name: Check DimmOFF Pine upstream + +on: + schedule: + - cron: '17 15 * * *' + workflow_dispatch: + +permissions: + contents: read + issues: write + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - name: Check for upstream commits + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + base=$(tr -d '[:space:]' < vendor/DIMMOFF-PINE-UPSTREAM) + [[ "$base" =~ ^[0-9a-f]{40}$ ]] || { echo 'Invalid DimmOFF Pine revision'; exit 1; } + latest=$(gh api 'repos/DimmOFF/egui-charts/commits/TradingVision-pinescript-impl' --jq .sha) + issue=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open --limit 100 --json number,title,body --jq '.[] | select(.title == "DimmOFF Pine upstream update available" and ((.body // "") | contains(""))) | .number' | head -n 1) + if [[ "$base" == "$latest" ]]; then + echo "DimmOFF Pine upstream is current: $base" + if [[ -n "$issue" ]]; then + gh issue close "$issue" --repo "$GITHUB_REPOSITORY" --comment 'The tracked DimmOFF Pine revision is now current.' + fi + exit 0 + fi + comparison=$(gh api "repos/DimmOFF/egui-charts/compare/$base...$latest") + status=$(jq -r .status <<< "$comparison") + ahead=$(jq -r .ahead_by <<< "$comparison") + behind=$(jq -r .behind_by <<< "$comparison") + compare_url="https://github.com/DimmOFF/egui-charts/compare/$base...$latest" + title='DimmOFF Pine upstream update available' + body=$(printf '\nTradeCraft tracks `%s`; DimmOFF Pine branch is at `%s`.\n\nComparison: %s\n\nStatus: %s; upstream commits ahead: %s; commits behind: %s.\n\nReview Pine and chart changes for useful features, fixes, compatibility and licensing. Preserve TradeCraft modifications and validate the personal Windows, community Windows and macOS builds before updating `vendor/DIMMOFF-PINE-UPSTREAM`. This check does not update code automatically.' "$base" "$latest" "$compare_url" "$status" "$ahead" "$behind") + if [[ -n "$issue" ]]; then + gh issue edit "$issue" --repo "$GITHUB_REPOSITORY" --body "$body" + else + gh issue create --repo "$GITHUB_REPOSITORY" --title "$title" --body "$body" + fi diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 179fef5..a79ea42 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -47,6 +47,7 @@ The current Windows dependency baseline also includes `regex` 1.13.1, `regex-aut - TradeCraft began as a single binary crate, with market data coupled to `egui-charts` and live candle logic in the UI. The workspace now has separate crates and a UI-independent engine. Existing Git history is preserved; the initial commit was made after the initial code already existed and cannot be changed without rewriting history. - The upstream egui-charts terminal owns the live GUI's chart, indicator and layout state. The existing engine remains UI-independent and supports the isolated `--commands` and `--script ` interface; those commands do not control the terminal window. The terminal feed adapter is in the UI crate and calls the provider and engine layers. A comprehensive command registry covering every UI action and an MCP server are not implemented. - The egui-charts source is vendored at `vendor/egui-charts`. Its upstream revision is recorded in `vendor/EGUI-CHARTS-UPSTREAM`; local modifications include host integration, data services and session controls. The scheduled GitHub workflow compares that revision with upstream `main` and opens or updates an issue when they differ. It also opens one tracking issue per newly observed stable upstream release. It does not merge changes automatically. Review the full vendored diff and validate personal Windows, community Windows and macOS builds when updating the dependency; retain its upstream license files, font and icon notices. +- The November 14 upstream integration advances egui-charts from `c9a7f0bbe6410eb6bc69fd2f2e8a6394919ac4f2` to `7a852a5152f9a5c3f3cc556f70170094e976d823`, preserving TradeCraft's Pine table colours, chart panning, provider integration and terminal customizations. Three upstream tests are adapted to TradeCraft's deliberate behavior: keep the user's near-live offset and hide custom intervals when the feed only supports presets. The terminal adds a direct dependency on `png` 0.17.16, already present in the locked application graph. This update was prepared on the macOS branch as shared source, but a macOS build and interactive validation of this revision remain outstanding. The previous macOS build results above do not validate this update. - The terminal's file storage saves named documents using encoded names and a temporary-file rename. Saved layout and drawing restoration, crash recovery, and multi-process conflicts need further verification. Alert definitions and statuses are saved locally; evaluation operates only while the app runs. Tradier charts and watchlists share one dynamically updated market stream; initial quotes use REST snapshots. Yahoo watchlist quotes use delayed REST data. Symbol search combines the selected provider with Kraken crypto pairs. The experimental Pine editor uses an adapted interpreter from DimmOFF's egui-charts fork; its subset and output require further compatibility, resource and live-data verification. - The chart-tab strip saves open chart workspaces in terminal settings and restores them on startup or after changing providers. Switching tabs pauses inactive chart feeds while the watchlist uses the shared Tradier stream. Experimental Pine studies embed their applied source in the snapshot; the last complete snapshot is retained when an unregistered study cannot be serialized. Named layouts remain separate. File storage uses OS file locks and revision checks for settings and drawing conflicts. Workspace restart coverage uses an in-memory store; full process-crash recovery and cross-process behavior still need end-to-end verification. - On a Tradier stream reconnect, chart recovery requests the missing historical range, restores completed bars, then reconciles the forming candle using complete one-minute bars and buffered later ticks. The chart reports recovery or errors; Tradier's intraday retention limits apply. Initial-load history overlap, provider corrections and late trade reconciliation remain open, and recovery under real market-hour interruptions needs further verification. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 17af0cb..5390d50 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -2,7 +2,11 @@ TradeCraft includes a modified copy of [egui-charts](https://github.com/userFRM/egui-charts), including its terminal. Its upstream license texts and third-party notices are in [vendor/egui-charts](vendor/egui-charts/). The upstream terminal manifest has no license field; TradeCraft adds one based on the upstream repository's license statement at the recorded revision, which does not specifically single out the terminal. -The experimental Pine interpreter is adapted from [DimmOFF's egui-charts fork](https://github.com/DimmOFF/egui-charts/tree/229207f089a8dd7ee89373dce1c9bc96309da7d4/examples/demo/pine_engine). The fork's [MIT license at that revision](https://github.com/DimmOFF/egui-charts/blob/229207f089a8dd7ee89373dce1c9bc96309da7d4/LICENSE-MIT) has the same copyright and terms as the vendored egui-charts MIT license. TradeCraft modifies its study adapter, diagnostics and execution safeguards. +The experimental Pine interpreter is adapted from [DimmOFF's egui-charts fork](https://github.com/DimmOFF/egui-charts/tree/229207f089a8dd7ee89373dce1c9bc96309da7d4/examples/demo/pine_engine). The initial import used revision [13bf91a2](https://github.com/DimmOFF/egui-charts/commit/13bf91a2ea55d4b46c8de1dc1291a35d4fc6dd78); a later three-way merge incorporated changes from [229207f0](https://github.com/DimmOFF/egui-charts/commit/229207f089a8dd7ee89373dce1c9bc96309da7d4). TradeCraft retained its own `mod.rs` and resolved conflicts and made further modifications, including to the study adapter, diagnostics and execution safeguards. The chart's `vendor/egui-charts/src/studies/table.rs` also incorporates code copied and adapted from the fork. The fork's [MIT license at the later revision](https://github.com/DimmOFF/egui-charts/blob/229207f089a8dd7ee89373dce1c9bc96309da7d4/LICENSE-MIT) has the same copyright and terms as the vendored egui-charts MIT license. + +The [BB-levels sample](scripts/pine/bb-levels.pine) adapts a script provided by its original author, who confirmed authorship and authorized MIT licensing on November 14, 2026. The sample and TradeCraft's modifications are available under the project's [MIT license](LICENSE). + +After the initial import and merge, TradeCraft selectively incorporated further Pine changes through DimmOFF revision [`e7e1e98b`](https://github.com/DimmOFF/egui-charts/commit/e7e1e98b722e59fc40e30b62bca83f5dbe47989c). The reviewed boundary and adopted changes are recorded in [the Pine upstream review](docs/DIMMOFF-PINE-UPSTREAM.md); the boundary does not mean every upstream change was adopted. TradeCraft uses the default fonts embedded by [epaint_default_fonts 0.37.0](https://crates.io/crates/epaint_default_fonts/0.37.0) through egui's `default_fonts` feature. No font binaries are maintained in this repository. diff --git a/CHANGELOG.md b/CHANGELOG.md index 016613c..498ad09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- Add a read-only Tradier options chain with expiration selection, calls and puts, configurable columns, quotes and available Greeks; open a contract in a chart tab. +- Improve Pine indicator support, including lower-timeframe requests, session flags and historical prior-day values. Compatibility and live behavior still need verification. +- Update the vendored egui-charts main branch to `7a852a5`, including upstream chart and study improvements, while retaining TradeCraft's provider, Pine and chart interaction changes. macOS validation of this update is pending. + ## 0.3.0 — alpha - Add multiple chart tabs and restore saved workspaces, including applied Pine studies, when restarting or changing providers. diff --git a/Cargo.lock b/Cargo.lock index 1242578..128b1ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -990,6 +990,7 @@ dependencies = [ "egui-charts", "egui_extras", "iana-time-zone", + "png 0.17.16", "serde_json", ] @@ -4068,7 +4069,7 @@ dependencies = [ [[package]] name = "tradecraft" -version = "0.3.0" +version = "0.4.0" dependencies = [ "tradecraft-ui-egui", "winresource", @@ -4076,7 +4077,7 @@ dependencies = [ [[package]] name = "tradecraft-core" -version = "0.3.0" +version = "0.4.0" dependencies = [ "chrono", "chrono-tz", @@ -4085,7 +4086,7 @@ dependencies = [ [[package]] name = "tradecraft-engine" -version = "0.3.0" +version = "0.4.0" dependencies = [ "chrono", "chrono-tz", @@ -4098,7 +4099,7 @@ dependencies = [ [[package]] name = "tradecraft-providers" -version = "0.3.0" +version = "0.4.0" dependencies = [ "chrono", "chrono-tz", @@ -4115,7 +4116,7 @@ dependencies = [ [[package]] name = "tradecraft-ui-egui" -version = "0.3.0" +version = "0.4.0" dependencies = [ "chrono", "chrono-tz", @@ -5135,7 +5136,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.3.0" +version = "0.4.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 3a9ea11..9a7a678 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ resolver = "3" exclude = ["vendor/egui-charts", "vendor/egui-charts/terminal"] [workspace.package] -version = "0.3.0" +version = "0.4.0" edition = "2024" license = "MIT" diff --git a/README.md b/README.md index a20bc79..e66e18d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # TradeCraft alpha -TradeCraft remains in alpha until announced otherwise. Versions use `0.minor.patch`: the minor number advances for feature milestones and the patch number for fixes and small improvements. This release is `0.3.0`. The workspace version in `Cargo.toml` is the source of truth; release tags and packages use the same version, such as `v0.3.0`. A version number is not reused for a different release. +TradeCraft remains in alpha until announced otherwise. Versions use `0.minor.patch`: the minor number advances for feature milestones and the patch number for fixes and small improvements. The workspace version is `0.4.0`, in preparation for the next release. The workspace version in `Cargo.toml` is the source of truth; release tags and packages use the same version. A version number is not reused for a different release. A native Rust charting experiment using the egui/eframe stack and the development version of egui-charts. It loads one-, five-, fifteen-minute or daily chart history from Yahoo, Tradier, or Kraken for supported crypto pairs; Tradier streams market price updates for charts and the watchlist over one shared connection. It does not request account information, positions, or order history. Chart and price timestamps use the computer's local time in 12-hour format. @@ -16,9 +16,13 @@ On quit, TradeCraft waits for pending saves. If saving fails or takes longer tha The watchlist shows provider quotes and changes, and symbol search supports company names and tickers. Tradier watchlist prices update from the shared stream; an initial batched quote request supplies the previous close. Yahoo quotes are based on completed candles delayed by at least 15 minutes and refresh approximately once a minute. Kraken's supported crypto spot pairs are available in symbol search and use its public live ticker and candle streams. Crypto watchlist changes are rolling 24-hour changes. BTCUSD remains an alias for Kraken's BTC/USD. Kraken's spot history returns at most 720 recent candles, including the current candle. Provider availability and entitlements apply. +With Tradier selected, use Options in the chart toolbar or right-click a watchlist symbol and choose View options to inspect its chain. Select an expiration and a contract to open a chart tab. The chain is a manually refreshed snapshot; its receipt time is not the timestamp of every quote, and Tradier's Greeks may update less frequently. Coverage, delays, and option-chart history depend on Tradier and the account's entitlements. Expired options history is not available from Tradier. + ## Run -Install Rust, then run `cargo run --release`. The default Yahoo Finance chart uses an unofficial endpoint and is delayed by at least 15 minutes. Open the TradeCraft icon menu and choose Market data settings to select Tradier and enter your own production token. TradeCraft stores its own Tradier token in Windows Credential Locker or macOS Keychain, never in settings.json. The Yahoo endpoint is unofficial; check Yahoo's terms and data rights before distributing an app that uses it. +Install Rust, then run `cargo run --release`. The default Yahoo Finance chart uses an unofficial endpoint and is delayed by at least 15 minutes. Open the TradeCraft icon menu and choose Market data settings to select Tradier and enter your own production token. TradeCraft stores its own Tradier token in Windows Credential Locker or macOS Keychain, never in settings.json. Provider access and data use are subject to applicable third-party terms: [Yahoo Terms of Service](https://legal.yahoo.com/us/en/yahoo/terms/otos/index.html), [Tradier API FAQ](https://docs.tradier.com/brokerage-api/overview/faq), and [Kraken API terms](https://docs-legacy.kraken.com/api/docs/guides/global-intro/). The Yahoo endpoint is unofficial; permission for its automated use and distribution of the integration remains unverified. Linking provider terms does not grant access or resolve those questions. + +TradeCraft connects from the user's device directly to the selected data provider; it does not relay or redistribute provider data through a TradeCraft-operated server. Tradier access uses the user's own account and token. The Yahoo and Kraken integrations use public endpoints without a user account in the app. Users are responsible for reviewing the applicable provider and exchange terms for their access, use, and any sharing or export of market data. Community builds use `cargo build --release` and exclude the VibesTrader credential shortcut. Community provider preferences are stored separately in `settings-community.json`, so they start with Yahoo even if the personal build already uses Tradier. The personal build keeps its existing `settings.json`. Both files are under the local TradeCraft application-data folder. If both builds use a manually entered Tradier token, they share its Windows Credential Locker entry. For a personal build that includes the shortcut and updates the taskbar-pinned executable, run `powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-personal.ps1`. The script builds in a separate directory, verifies the result and replaces `target/personal/tradecraft.exe`, which the pin launches. A running TradeCraft window keeps the old build until fully quit and reopened; the previous executable is retained as a backup. diff --git a/RELEASE-CHECKLIST.md b/RELEASE-CHECKLIST.md index 4686933..8564951 100644 --- a/RELEASE-CHECKLIST.md +++ b/RELEASE-CHECKLIST.md @@ -1,27 +1,17 @@ # Release coordination -## Next release: 0.3.0 (planned) +## 0.4.0 alpha — in preparation -Status as of November 14, 2026: the 0.3.0 alpha is published for Windows, Apple Silicon and Intel macOS. Both Windows editions were rebuilt. The Mac packages were built and tested on GitHub runners; interactive validation on a Mac remains outstanding. +Release scope: read-only Tradier options chains and contract charts, Pine indicator improvements, and the egui-charts update to `7a852a5`. The source is on `codex/macos-build`; much of the release work is uncommitted. The current 0.4.0 version is a release candidate, not a published release. -- [ ] Reconcile the completed work across the TradeCraft chats and the final source. Update `CHANGELOG.md`, draft 0.3.0 release notes and verify known limitations. In particular, reconcile the chart timezone description with the latest Pine behavior and the user's local/New York preference. -- [ ] Review the final diff, untracked files and branch history; preserve all local egui-charts changes. Review the tracked upstream revision and scheduled monitor, including relevant compatibility and licensing changes. -- [ ] Run the dependency license audit for Windows community and personal and both macOS targets on the final locked dependency graph. Review changed dependencies and actual notices; do not update the baseline without review. Resolve or explicitly document remaining distribution and provenance issues in `ARCHITECTURE.md`, `ATTRIBUTION.md` and `licenses/upstream/README.md`. -- [ ] Run appropriate tests and build the community Windows package using `scripts/build-community.ps1`. -- [ ] Build the personal Windows executable using `scripts/build-personal.ps1` and verify the stable `target/personal/tradecraft.exe` was updated. A running app must be fully quit and reopened to load it. -- [ ] Test the published macOS apps interactively, including Keychain, persistence and restart behavior. Apple Silicon and Intel runner builds and automated tests passed; builds are unsigned and not notarized. -- [ ] Verify packages, included notices, versions and release notes against the same final source before publishing. Follow the project's review and release process. +- [ ] Review the complete source diff, including untracked application files, and reconcile the changes from all project chats. Preserve the TradeCraft-specific egui-charts changes and reconcile Pine imports with attribution and review records. +- [ ] Complete `RELEASE-NOTES-0.4.0.md` and update `CHANGELOG.md` for the final release. Verify the notes against the final source and packages. +- [ ] Run the dependency license audit for Windows personal and community and both macOS targets on the final lockfile. Review any changes and include the generated notices. The strict macOS checks previously reported missing notices; the packaging script records these as warnings at the owner's direction. The open upstream and provider-rights issues are not resolved by a successful build. +- [ ] Run the appropriate workspace, options, Pine and vendored chart tests on the final source. Verify the community and personal Windows release builds; the personal build must update and verify `target/personal/tradecraft.exe`. +- [ ] Validate options chains and contract charts with real Tradier data and appropriate account entitlements, including timestamps and missing values. Synthetic tests do not establish live behavior. +- [ ] Build and test both macOS architectures for this revision using GitHub Actions. Inspect the app bundles and notice inventories; the prior 0.3.0 builds do not validate 0.4.0. Interactive Mac validation, including Keychain and workspace restart, remains outstanding. +- [ ] Check the final Windows and macOS archives, version, executable identities and notices against the same release source. Follow the review and release process before publishing. -### Latest audit +The November 14 legal and provenance review records unresolved provider authorization, upstream source and asset provenance, and other distribution questions. These require separate review; no blanket compliance clearance has been established. Preserve that detailed review privately unless its owner authorizes publication. -On November 14, 2026, both Windows 0.3.0 release builds succeeded. The pinned personal executable was updated and the community package was generated. A running personal app must be fully quit and reopened to load its build. The GitHub macOS workflow built and checked both architectures from `2376167`; both packages passed ZIP and executable-architecture checks and were uploaded to the 0.3.0 release. - -On November 13, 2026, `scripts/license-audit.py` passed its graph and notice-availability checks for both Windows configurations (278 packages each). This is not a legal compliance determination; the documented provenance and distribution questions remain open. - -Both strict macOS target checks reported missing license texts for `block2 0.6.2`, `dispatch 0.2.0`, `objc2 0.6.5`, `objc2-encode 4.1.0`, and `objc2-app-kit`, `objc2-core-foundation`, `objc2-core-graphics`, `objc2-foundation`, `objc2-metal` and `objc2-quartz-core` 0.3.2. See `licenses/upstream/README.md` for the evidence and unresolved provenance. At the user's request, the macOS build records missing notices as warnings and includes the inventory; the separate audit remains strict. - -The exact objc2 source revisions are now accessible and confirm their stated license choices, but full copyright notices for the newer packages are still unverified. Upstream also flags an Apple SDK-derived code distribution question. Do not treat the macOS notice or distribution review as complete until these and the `dispatch` notice are resolved. - -An initial GitHub Mac run failed the market-data settings UI test in the full suite. Both architectures passed it when run separately and passed the remaining provider and UI tests; the earlier failure's cause and real Mac interaction still need verification. The separate test reports failures without blocking packaging, while the remaining tests gate the macOS build. - -The 0.3.0 release notes are in `RELEASE-NOTES-0.3.0.md`; verify them against the final artifact before publishing. +The 0.3.0 alpha was published for Windows, Apple Silicon and Intel macOS. Its tag and assets are historical and should not be replaced by this release. diff --git a/RELEASE-NOTES-0.4.0.md b/RELEASE-NOTES-0.4.0.md new file mode 100644 index 0000000..8501e46 --- /dev/null +++ b/RELEASE-NOTES-0.4.0.md @@ -0,0 +1,25 @@ +# TradeCraft 0.4.0 alpha — release candidate + +TradeCraft 0.4.0 adds a read-only options workflow, expands custom Pine indicator support and updates the charting library with new indicator and chart controls. + +## Options chains and contract charts + +With Tradier selected, open **Options** from a chart or a watchlist symbol. Choose an expiration, switch between calls and puts, and inspect available prices, volume, open interest, implied volatility and Greeks. Select a contract's last price to open its chart in a new tab. + +Choose which optional columns to display and keep those preferences between sessions. The chain shows the underlying price among the strikes and presents per-share prices alongside their ×100 amounts for convenient comparison. + +The chain is a manually refreshed snapshot. Availability depends on the Tradier account and provider; the ×100 display is before fees and adjusted contracts may differ. Live Tradier options data and contract charts still require verification. + +## Pine indicators + +Pine indicators gain support for selected additional language features, including finer-timeframe requests, session flags, persistent function-local values and improved handling of historical prior-day values. The update also includes selected improvements from DimmOFF's fork while retaining TradeCraft's editor, safeguards and provider-backed daily history. + +Pine remains a subset of the language. Session flags follow the chart timezone and use regular-session hours without an exchange holiday or early-close calendar; finer history is bounded. See the README and project documentation for compatibility and data limitations. + +## Charts and indicators + +The charting library has been updated with improvements to built-in studies, drawings, appearance and navigation. Highlights include RSI divergence options, additional auto-anchored VWAP bands, expanded Technical Ratings settings, scale appearance controls and drawing settings. TradeCraft's provider integration, Pine work and chart-position behavior are retained. + +## Release status + +TradeCraft remains a read-only alpha. The Windows personal and community editions maintain separate provider preferences. Mac builds and interactive platform behavior require validation for this revision. Provider distribution rights, upstream provenance and third-party notice questions remain documented in the project records; no blanket compliance clearance is implied. diff --git a/crates/providers/src/lib.rs b/crates/providers/src/lib.rs index cc51e08..ede57bb 100644 --- a/crates/providers/src/lib.rs +++ b/crates/providers/src/lib.rs @@ -18,3 +18,4 @@ pub mod market; pub mod reference; pub mod settings; pub mod shared_stream; +pub mod options; diff --git a/crates/providers/src/options.rs b/crates/providers/src/options.rs new file mode 100644 index 0000000..c10e5a3 --- /dev/null +++ b/crates/providers/src/options.rs @@ -0,0 +1,168 @@ +use serde_json::Value; + +#[derive(Clone, Debug)] +pub struct Contract { + /// Original provider fields for optional chain columns. + pub fields: Value, + pub symbol: String, + pub kind: String, + pub strike: f64, + pub bid: Option, + pub ask: Option, + pub last: Option, + pub change: Option, + pub change_percentage: Option, + pub volume: Option, + pub open_interest: Option, + pub iv: Option, + pub delta: Option, + pub gamma: Option, + pub theta: Option, + pub vega: Option, +} + +fn items(value: &Value) -> Vec<&Value> { + match value { + Value::Array(a) => a.iter().collect(), + Value::Object(_) | Value::String(_) => vec![value], + _ => Vec::new(), + } +} + +fn number(value: &Value) -> Option { + value.as_f64().filter(|v| v.is_finite()) +} + +fn parse_expirations(data: &Value) -> Vec { + items(&data["expirations"]["date"]) + .iter() + .filter_map(|v| v.as_str()) + .filter(|s| chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").is_ok()) + .map(str::to_owned) + .collect() +} + +fn parse_chain(data: &Value) -> Vec { + items(&data["options"]["option"]) + .into_iter() + .filter_map(|v| { + let symbol = v["symbol"].as_str()?.to_owned(); + let kind = v["option_type"].as_str()?.to_owned(); + let strike = number(&v["strike"])?; + if symbol.is_empty() || !matches!(kind.as_str(), "call" | "put") || strike <= 0.0 { + return None; + } + let g = &v["greeks"]; + Some(Contract { + fields: v.clone(), + symbol, + kind, + strike, + bid: number(&v["bid"]), + ask: number(&v["ask"]), + last: number(&v["last"]), + change: number(&v["change"]), + change_percentage: number(&v["change_percentage"]), + volume: number(&v["volume"]), + open_interest: number(&v["open_interest"]), + iv: number(&g["mid_iv"]), + delta: number(&g["delta"]), + gamma: number(&g["gamma"]), + theta: number(&g["theta"]), + vega: number(&g["vega"]), + }) + }) + .collect() +} + +async fn get( + client: &reqwest::Client, + token: &str, + path: &str, + params: &[(&str, &str)], +) -> Result { + let response = client + .get(format!("https://api.tradier.com/v1/markets/options/{path}")) + .bearer_auth(token) + .header("Accept", "application/json") + .query(params) + .send() + .await + .map_err(|_| "Tradier options request failed".to_owned())?; + if !response.status().is_success() { + return Err(format!( + "Tradier options unavailable (HTTP {}); check credentials, entitlements and rate limits", + response.status() + )); + } + super::market::read_json(response).await +} + +pub async fn expirations( + client: &reqwest::Client, + token: &str, + symbol: &str, +) -> Result, String> { + Ok(parse_expirations( + &get(client, token, "expirations", &[("symbol", symbol)]).await?, + )) +} + +pub async fn chain( + client: &reqwest::Client, + token: &str, + symbol: &str, + expiration: &str, +) -> Result, String> { + Ok(parse_chain( + &get( + client, + token, + "chains", + &[ + ("symbol", symbol), + ("expiration", expiration), + ("greeks", "true"), + ], + ) + .await?, + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + #[test] + fn parses_single_and_multiple_results_without_inventing_values() { + assert_eq!( + parse_expirations(&json!({"expirations":{"date":"2027-01-15"}})), + vec!["2027-01-15"] + ); + let data = json!({"options":{"option":[{"symbol":"SPY270115C00500000","option_type":"call","strike":500.0,"bid":2.1,"greeks":{"delta":0.4}},{"symbol":"SPY270115P00500000","option_type":"put","strike":500.0}]}}); + let contracts = parse_chain(&data); + assert_eq!(contracts.len(), 2); + assert_eq!(contracts[0].delta, Some(0.4)); + assert_eq!(contracts[1].bid, None); + assert!(parse_chain(&json!({"options":null})).is_empty()); + } + + #[cfg(feature = "vibestrader-credential")] + #[test] + #[ignore = "requires saved Tradier credential and network access"] + fn live_spy_chain() { + let token = crate::credentials::vibestrader_token() + .or_else(|_| crate::credentials::tradecraft_token()) + .expect("saved credential"); + let client = crate::reference::client().unwrap(); + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let dates = rt.block_on(expirations(&client, &token, "SPY")).unwrap(); + let date = dates.first().expect("SPY expiration"); + let contracts = rt.block_on(chain(&client, &token, "SPY", date)).unwrap(); + assert!(contracts.iter().any(|c| c.kind == "call")); + assert!(contracts.iter().any(|c| c.kind == "put")); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 80080a2..672f74a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -12,6 +12,7 @@ )] mod terminal_app; +mod options_view; mod pine_engine; mod pine_editor; mod terminal_feed; @@ -57,11 +58,11 @@ impl TimeFormatter for ChartTimeFormatter { impl ChartTimeFormatter { fn default_formatter(&self) -> DefaultTimeFormatter { - DefaultTimeFormatter { - use_24_hour: false, - show_seconds: false, - date_format: None, - } + let mut formatter = DefaultTimeFormatter::default(); + formatter.use_24_hour = false; + formatter.show_seconds = false; + formatter.date_format = None; + formatter } } diff --git a/crates/ui-egui/src/options_view.rs b/crates/ui-egui/src/options_view.rs new file mode 100644 index 0000000..2f3c769 --- /dev/null +++ b/crates/ui-egui/src/options_view.rs @@ -0,0 +1,1002 @@ +use egui_charts::scales::{CurrencyFormatter, PriceFormatter}; +use std::sync::mpsc::{self, Receiver}; +use tradecraft_providers::{ + options::Contract, + reference::MarketQuote, + settings::{Provider, Settings}, +}; + +const ORANGE: egui::Color32 = egui::Color32::from_rgb(255, 100, 0); +const ROW_HEIGHT: f32 = 44.0; + +enum ResultMessage { + Expirations(Result, String>), + Chain(Result<(Vec, Option), String>), +} + +pub struct OptionsView { + pub open: bool, + symbol: String, + expirations: Vec, + expiration: String, + contracts: Vec, + underlying: Option, + show_puts: bool, + scroll_to_price: bool, + receiver: Option>, + loading: bool, + error: String, + fetched: Option>, + columns: Vec, + columns_error: String, +} + +#[derive(Clone, Copy)] +enum ColumnFormat { + Text, + Price, + Integer, + Greek, + Percent, + Volatility, + Timestamp, +} + +struct Column { + key: &'static str, + title: &'static str, + format: ColumnFormat, + required: bool, + default: bool, +} + +const COLUMNS: &[Column] = &[ + Column { + key: "strike", + title: "Strike", + format: ColumnFormat::Price, + required: true, + default: true, + }, + Column { + key: "volume", + title: "Volume", + format: ColumnFormat::Integer, + required: false, + default: true, + }, + Column { + key: "greeks.delta", + title: "Delta", + format: ColumnFormat::Greek, + required: false, + default: true, + }, + Column { + key: "change_percentage", + title: "% change", + format: ColumnFormat::Percent, + required: true, + default: true, + }, + Column { + key: "change", + title: "Change", + format: ColumnFormat::Price, + required: true, + default: true, + }, + Column { + key: "bid", + title: "Bid", + format: ColumnFormat::Price, + required: true, + default: true, + }, + Column { + key: "ask", + title: "Ask", + format: ColumnFormat::Price, + required: true, + default: true, + }, + Column { + key: "greeks.mid_iv", + title: "IV %", + format: ColumnFormat::Volatility, + required: false, + default: true, + }, + Column { + key: "last", + title: "Last · chart", + format: ColumnFormat::Price, + required: false, + default: true, + }, + Column { + key: "open_interest", + title: "Open interest", + format: ColumnFormat::Integer, + required: false, + default: false, + }, + Column { + key: "greeks.gamma", + title: "Gamma", + format: ColumnFormat::Greek, + required: false, + default: false, + }, + Column { + key: "greeks.theta", + title: "Theta", + format: ColumnFormat::Greek, + required: false, + default: false, + }, + Column { + key: "greeks.vega", + title: "Vega", + format: ColumnFormat::Greek, + required: false, + default: false, + }, + Column { + key: "greeks.rho", + title: "Rho", + format: ColumnFormat::Greek, + required: false, + default: false, + }, + Column { + key: "greeks.phi", + title: "Phi", + format: ColumnFormat::Greek, + required: false, + default: false, + }, + Column { + key: "greeks.bid_iv", + title: "Bid IV %", + format: ColumnFormat::Volatility, + required: false, + default: false, + }, + Column { + key: "greeks.ask_iv", + title: "Ask IV %", + format: ColumnFormat::Volatility, + required: false, + default: false, + }, + Column { + key: "greeks.smv_vol", + title: "SMV volatility %", + format: ColumnFormat::Volatility, + required: false, + default: false, + }, + Column { + key: "bidsize", + title: "Bid size", + format: ColumnFormat::Integer, + required: false, + default: false, + }, + Column { + key: "asksize", + title: "Ask size", + format: ColumnFormat::Integer, + required: false, + default: false, + }, + Column { + key: "open", + title: "Open", + format: ColumnFormat::Price, + required: false, + default: false, + }, + Column { + key: "high", + title: "High", + format: ColumnFormat::Price, + required: false, + default: false, + }, + Column { + key: "low", + title: "Low", + format: ColumnFormat::Price, + required: false, + default: false, + }, + Column { + key: "close", + title: "Close", + format: ColumnFormat::Price, + required: false, + default: false, + }, + Column { + key: "prevclose", + title: "Previous close", + format: ColumnFormat::Price, + required: false, + default: false, + }, + Column { + key: "average_volume", + title: "Average volume", + format: ColumnFormat::Integer, + required: false, + default: false, + }, + Column { + key: "last_volume", + title: "Last trade size", + format: ColumnFormat::Integer, + required: false, + default: false, + }, + Column { + key: "week_52_high", + title: "52-week high", + format: ColumnFormat::Price, + required: false, + default: false, + }, + Column { + key: "week_52_low", + title: "52-week low", + format: ColumnFormat::Price, + required: false, + default: false, + }, + Column { + key: "contract_size", + title: "Contract size", + format: ColumnFormat::Integer, + required: false, + default: false, + }, + Column { + key: "lot_size", + title: "Lot size", + format: ColumnFormat::Integer, + required: false, + default: false, + }, + Column { + key: "symbol", + title: "Contract symbol", + format: ColumnFormat::Text, + required: false, + default: false, + }, + Column { + key: "description", + title: "Description", + format: ColumnFormat::Text, + required: false, + default: false, + }, + Column { + key: "root_symbol", + title: "Option root", + format: ColumnFormat::Text, + required: false, + default: false, + }, + Column { + key: "underlying", + title: "Underlying", + format: ColumnFormat::Text, + required: false, + default: false, + }, + Column { + key: "option_type", + title: "Type", + format: ColumnFormat::Text, + required: false, + default: false, + }, + Column { + key: "expiration_date", + title: "Expiration", + format: ColumnFormat::Text, + required: false, + default: false, + }, + Column { + key: "expiration_type", + title: "Expiration type", + format: ColumnFormat::Text, + required: false, + default: false, + }, + Column { + key: "exch", + title: "Exchange", + format: ColumnFormat::Text, + required: false, + default: false, + }, + Column { + key: "bidexch", + title: "Bid exchange", + format: ColumnFormat::Text, + required: false, + default: false, + }, + Column { + key: "askexch", + title: "Ask exchange", + format: ColumnFormat::Text, + required: false, + default: false, + }, + Column { + key: "trade_date", + title: "Last trade time", + format: ColumnFormat::Timestamp, + required: false, + default: false, + }, + Column { + key: "bid_date", + title: "Bid time", + format: ColumnFormat::Timestamp, + required: false, + default: false, + }, + Column { + key: "ask_date", + title: "Ask time", + format: ColumnFormat::Timestamp, + required: false, + default: false, + }, + Column { + key: "greeks.updated_at", + title: "Greeks updated", + format: ColumnFormat::Text, + required: false, + default: false, + }, +]; + +fn default_columns() -> Vec { + COLUMNS + .iter() + .filter(|c| !c.required && c.default) + .map(|c| c.key.to_owned()) + .collect() +} + +fn columns_path() -> Option { + let name = if cfg!(feature = "vibestrader-credential") { + "options-columns-personal.json" + } else { + "options-columns-community.json" + }; + Some(tradecraft_providers::settings::data_dir()?.join(name)) +} + +fn load_columns() -> Vec { + columns_path() + .and_then(|p| std::fs::read(p).ok()) + .and_then(|data| serde_json::from_slice::>(&data).ok()) + .unwrap_or_else(default_columns) +} + +fn save_columns(columns: &[String]) -> Result<(), String> { + let path = columns_path().ok_or("Options settings directory unavailable")?; + std::fs::create_dir_all(path.parent().ok_or("Invalid options settings path")?) + .map_err(|e| e.to_string())?; + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(path.with_extension("lock")) + .map_err(|e| e.to_string())?; + lock.try_lock() + .map_err(|e| format!("Options settings are busy: {e}"))?; + let json = serde_json::to_string(columns).map_err(|e| e.to_string())?; + crate::terminal_storage::write_atomic(&path, &json).map_err(|e| e.to_string()) +} + +impl Default for OptionsView { + fn default() -> Self { + Self { + open: false, + symbol: String::new(), + expirations: Vec::new(), + expiration: String::new(), + contracts: Vec::new(), + underlying: None, + show_puts: false, + scroll_to_price: false, + receiver: None, + loading: false, + error: String::new(), + fetched: None, + columns: load_columns(), + columns_error: String::new(), + } + } +} + +fn value(value: Option, decimals: usize) -> String { + value + .map(|v| format!("{v:.decimals$}")) + .unwrap_or_else(|| "—".into()) +} + +fn percent(value: Option) -> String { + value + .map(|v| format!("{v:.2}%")) + .unwrap_or_else(|| "—".into()) +} + +fn dollars(number: f64) -> String { + CurrencyFormatter::usd().format(number) +} + +fn contract_price(number: Option) -> String { + number + .filter(|n| n.is_finite()) + .map(|n| format!("{} ({})", dollars(n), dollars(n * 100.0))) + .unwrap_or_else(|| "—".into()) +} + +fn column_value(contract: &Contract, column: &Column) -> String { + let raw = column + .key + .split('.') + .fold(&contract.fields, |v, key| &v[key]); + let number = match column.key { + "strike" => Some(contract.strike), + "volume" => contract.volume, + "greeks.delta" => contract.delta, + "change_percentage" => contract.change_percentage, + "change" => contract.change, + "bid" => contract.bid, + "ask" => contract.ask, + "greeks.mid_iv" => contract.iv, + "last" => contract.last, + "open_interest" => contract.open_interest, + "greeks.gamma" => contract.gamma, + "greeks.theta" => contract.theta, + "greeks.vega" => contract.vega, + _ => raw.as_f64().filter(|v| v.is_finite()), + }; + match column.format { + ColumnFormat::Text => raw + .as_str() + .filter(|s| !s.is_empty()) + .unwrap_or("—") + .to_owned(), + ColumnFormat::Price if matches!(column.key, "bid" | "ask" | "last") => { + contract_price(number) + } + ColumnFormat::Price if column.key == "change" => { + number.map(dollars).unwrap_or_else(|| "—".into()) + } + ColumnFormat::Price => value(number, 2), + ColumnFormat::Integer => number + .map(|n| CurrencyFormatter::new("", 0).format(n)) + .unwrap_or_else(|| "—".into()), + ColumnFormat::Greek => value(number, 4), + ColumnFormat::Percent => percent(number), + ColumnFormat::Volatility => percent(number.map(|n| n * 100.0)), + ColumnFormat::Timestamp => raw + .as_i64() + .and_then(|n| { + if n > 10_000_000_000 { + chrono::DateTime::from_timestamp_millis(n) + } else { + chrono::DateTime::from_timestamp(n, 0) + } + }) + .map(|time| { + time.with_timezone(&chrono::Local) + .format("%b %-d %I:%M %p") + .to_string() + }) + .unwrap_or_else(|| "—".into()), + } +} + +fn column_min_width(column: &Column) -> f32 { + match column.key { + "symbol" | "description" => 210.0, + "bid" | "ask" | "last" => 160.0, + "trade_date" | "bid_date" | "ask_date" | "greeks.updated_at" => 170.0, + _ => 110.0, + } +} + +fn marker_index(rows: &[&Contract], price: f64) -> usize { + rows.iter() + .position(|contract| contract.strike <= price) + .unwrap_or(rows.len()) +} + +fn underlying_marker(ui: &mut egui::Ui, price: f64, width: f32) { + let text = format!("Underlying: ${price:.2}"); + let (rect, response) = ui.allocate_exact_size(egui::vec2(width, 32.0), egui::Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), &text)); + let painter = ui.painter(); + painter.hline( + rect.x_range(), + rect.center().y, + egui::Stroke::new(1.0, ORANGE), + ); + let font = egui::FontId::proportional(14.0); + let text_size = painter + .layout_no_wrap(text.clone(), font.clone(), egui::Color32::BLACK) + .size(); + let badge = egui::Rect::from_center_size(rect.center(), egui::vec2(text_size.x + 24.0, 26.0)); + painter.rect_filled(badge, egui::CornerRadius::same(13), ORANGE); + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + text, + font, + egui::Color32::BLACK, + ); +} + +fn row_separator(ui: &mut egui::Ui, width: f32) { + let (rect, _) = ui.allocate_exact_size(egui::vec2(width, 1.0), egui::Sense::hover()); + let color = ui + .visuals() + .panel_fill + .lerp_to_gamma(ui.visuals().text_color(), 0.35); + ui.painter().hline( + rect.x_range(), + rect.center().y, + egui::Stroke::new(1.0, color), + ); +} + +impl OptionsView { + pub fn open_for(&mut self, symbol: &str, settings: Settings) { + self.open = true; + self.symbol = symbol.to_owned(); + self.expirations.clear(); + self.expiration.clear(); + self.contracts.clear(); + self.underlying = None; + self.show_puts = false; + self.scroll_to_price = false; + self.fetched = None; + self.error.clear(); + self.receiver = None; + if settings.provider != Provider::Tradier { + self.loading = false; + self.error = "Select Tradier in Market data settings to view options.".into(); + } else { + self.request(settings, false); + } + } + + fn request(&mut self, settings: Settings, chain: bool) { + let symbol = self.symbol.clone(); + let expiration = self.expiration.clone(); + self.loading = true; + self.error.clear(); + self.contracts.clear(); + self.underlying = None; + self.fetched = None; + let (tx, rx) = mpsc::channel(); + self.receiver = Some(rx); + std::thread::spawn(move || { + let result = (|| { + let token = tradecraft_engine::tradier_token(settings.use_vibestrader) + .map_err(str::to_owned)?; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|_| "Could not start options request".to_owned())?; + let client = tradecraft_providers::reference::client()?; + Ok(if chain { + ResultMessage::Chain(runtime.block_on(async { + let contracts = tradecraft_providers::options::chain( + &client, + &token, + &symbol, + &expiration, + ) + .await?; + let quote = tradecraft_providers::reference::tradier_quotes( + &client, + &token, + std::slice::from_ref(&symbol), + ) + .await + .ok() + .and_then(|quotes| { + quotes + .into_iter() + .find(|q| q.symbol.eq_ignore_ascii_case(&symbol)) + }); + Ok((contracts, quote)) + })) + } else { + ResultMessage::Expirations(runtime.block_on( + tradecraft_providers::options::expirations(&client, &token, &symbol), + )) + }) + })(); + let _ = tx.send(result.unwrap_or_else(|e| { + if chain { + ResultMessage::Chain(Err(e)) + } else { + ResultMessage::Expirations(Err(e)) + } + })); + }); + } + + pub fn show(&mut self, ctx: &egui::Context, settings: Settings) -> Option { + if let Some(rx) = &self.receiver { + match rx.try_recv() { + Ok(message) => { + self.receiver = None; + self.loading = false; + match message { + ResultMessage::Expirations(Ok(dates)) => { + self.expirations = dates; + if let Some(date) = self.expirations.first() { + self.expiration = date.clone(); + self.request(settings, true); + } else { + self.error = + "No listed expirations found for this instrument.".into(); + } + } + ResultMessage::Chain(Ok((contracts, quote))) => { + self.contracts = contracts; + self.underlying = quote; + self.scroll_to_price = true; + self.fetched = Some(chrono::Local::now()); + } + ResultMessage::Expirations(Err(e)) | ResultMessage::Chain(Err(e)) => { + self.error = e + } + } + } + Err(mpsc::TryRecvError::Disconnected) => { + self.receiver = None; + self.loading = false; + self.error = "Options request stopped unexpectedly.".into(); + } + Err(mpsc::TryRecvError::Empty) => {} + } + } + if !self.open { + return None; + } + let mut open = self.open; + let mut picked = None; + let screen = ctx.content_rect().size(); + let width = (screen.x * 0.92).min(1500.0); + let height = (screen.y * 0.88).min(1000.0); + egui::Window::new(format!("Options · {}", self.symbol)) + .open(&mut open).default_size(egui::vec2(width, height)).resizable(true) + .show(ctx, |ui| { + if let Some(quote) = &self.underlying { + let change = quote.last - quote.previous_close; + let percent = if quote.previous_close != 0.0 { change / quote.previous_close * 100.0 } else { 0.0 }; + ui.label(egui::RichText::new(format!("{} ${:.2} ({:+.2}%)", self.symbol, quote.last, percent)).strong().size(18.0)); + ui.small(format!("Underlying quote as of {}", quote.time.with_timezone(&chrono::Local).format("%b %-d, %I:%M:%S %p"))); + } else { + ui.label(egui::RichText::new(&self.symbol).strong().size(18.0)); + } + ui.add_space(8.0); + ui.heading(format!("{} {}", self.symbol, if self.show_puts { "puts" } else { "calls" })); + ui.add_space(8.0); + ui.horizontal(|ui| { + for (label, puts) in [("Calls", false), ("Puts", true)] { + let selected = self.show_puts == puts; + let mut button = egui::Button::new(egui::RichText::new(label).size(16.0).color(if selected { egui::Color32::BLACK } else { ORANGE }).strong()).min_size(egui::vec2(95.0, 36.0)); + if selected { button = button.fill(ORANGE); } + if ui.add(button).clicked() && !selected { self.show_puts = puts; self.scroll_to_price = true; } + } + ui.add_space(8.0); + let previous = self.expiration.clone(); + let expiration_label = ui.label("Expiration"); + egui::ComboBox::from_id_salt("options_expiration").width(190.0).selected_text(if self.expiration.is_empty() { "Unavailable".into() } else { self.expiration.clone() }).show_ui(ui, |ui| { + for date in &self.expirations { ui.selectable_value(&mut self.expiration, date.clone(), date); } + }).response.labelled_by(expiration_label.id); + if previous != self.expiration { self.request(settings, true); } + if ui.add_enabled(!self.loading && settings.provider == Provider::Tradier, egui::Button::new("Refresh")).clicked() { self.request(settings, !self.expiration.is_empty()); } + let mut columns_changed = false; + ui.menu_button("Columns", |ui| { + ui.strong("Options columns"); + ui.label("Required columns are always shown."); + egui::ScrollArea::vertical().id_salt("column_picker").max_height(420.0).show(ui, |ui| { + for column in COLUMNS { + let mut visible = column.required || self.columns.iter().any(|key| key == column.key); + if ui.add_enabled(!column.required, egui::Checkbox::new(&mut visible, column.title)).changed() { + if visible { self.columns.push(column.key.to_owned()); } else { self.columns.retain(|key| key != column.key); } + columns_changed = true; + } + } + }); + }); + if columns_changed { + self.columns_error = save_columns(&self.columns).err().map(|e| format!("Could not save columns: {e}")).unwrap_or_default(); + } + }); + ui.add_space(8.0); + if !self.columns_error.is_empty() { ui.label(&self.columns_error); } + if self.loading { ui.label("Loading options…"); } + if !self.error.is_empty() { ui.label(&self.error); } + if let Some(time) = self.fetched { + ui.small(format!("Snapshot received {} · Tradier data may be delayed; Greeks update approximately hourly. Bracketed prices are × 100 before fees; adjusted contracts may differ. Select a strike or last price to open its chart.", time.format("%b %-d, %I:%M:%S %p"))); + if self.contracts.is_empty() { ui.label("No contracts returned for this expiration."); } + } + ui.add_space(8.0); + let kind = if self.show_puts { "put" } else { "call" }; + let mut rows: Vec<_> = self.contracts.iter().filter(|c| c.kind == kind).collect(); + rows.sort_by(|a, b| b.strike.total_cmp(&a.strike).then_with(|| a.symbol.cmp(&b.symbol))); + let nearest = self.underlying.as_ref().and_then(|quote| rows.iter().enumerate().min_by(|(_, a), (_, b)| (a.strike - quote.last).abs().total_cmp(&(b.strike - quote.last).abs())).map(|(i, _)| i)); + let marker = self.underlying.as_ref().filter(|_| !rows.is_empty()).map(|quote| marker_index(&rows, quote.last)); + let scroll = self.scroll_to_price; + self.scroll_to_price = false; + let visible: Vec<_> = COLUMNS.iter().filter(|column| column.required || self.columns.iter().any(|key| key == column.key)).collect(); + egui::ScrollArea::horizontal().id_salt("options_horizontal").show(ui, |ui| { + let spacing = ui.spacing().item_spacing.x; + let count = visible.len(); + let minimums: Vec = visible.iter().map(|column| { + let minimum = column_min_width(column); + if matches!(column.key, "bid" | "ask" | "last") { + let widest = rows.iter().filter_map(|c| match column.key { "bid" => c.bid, "ask" => c.ask, _ => c.last }).filter(|v| v.is_finite()).max_by(|a, b| a.abs().total_cmp(&b.abs())); + let text = contract_price(widest); + let size = if column.key == "last" { egui::FontId::proportional(14.0) } else { egui::FontId::proportional(15.0) }; + minimum.max(ui.painter().layout_no_wrap(text, size, ui.visuals().text_color()).size().x + 24.0) + } else { minimum } + }).collect(); + let extra = ((ui.available_width() - spacing * (count.saturating_sub(1) as f32) - 24.0 - minimums.iter().sum::()) / count as f32).max(0.0); + let widths: Vec = minimums.iter().map(|minimum| minimum + extra).collect(); + let table_width = widths.iter().sum::() + spacing * count.saturating_sub(1) as f32; + let header_color = ui.visuals().panel_fill.lerp_to_gamma(ui.visuals().text_color(), 0.12); + egui::Frame::new().fill(header_color).show(ui, |ui| { + ui.horizontal(|ui| { + for (column, width) in visible.iter().zip(&widths) { + ui.add_sized([*width, 36.0], egui::Label::new(egui::RichText::new(column.title).size(16.0).strong())); + } + }); + }); + row_separator(ui, table_width); + egui::ScrollArea::vertical().id_salt("options_rows").auto_shrink([false, false]).show(ui, |ui| { + for (index, c) in rows.iter().enumerate() { + if marker == Some(index) { + if let Some(quote) = &self.underlying { underlying_marker(ui, quote.last, table_width); } + } + let row = ui.horizontal(|ui| { + for (column, width) in visible.iter().zip(&widths) { + if column.key == "strike" || column.key == "last" { + let text = if column.key == "strike" { dollars(c.strike) } else if c.last.is_some() { contract_price(c.last) } else { "View chart".into() }; + let color = if column.key == "last" { ORANGE } else { ui.visuals().text_color() }; + let mut button = egui::Button::new(egui::RichText::new(text).size(if column.key == "last" { 14.0 } else { 15.0 }).color(color).strong()); + if column.key == "strike" { button = button.frame(false); } + if ui.add_sized([*width, ROW_HEIGHT], button).on_hover_text(&c.symbol).clicked() { picked = Some(c.symbol.clone()); } + } else { + let text = column_value(c, column); + ui.add_sized([*width, ROW_HEIGHT], egui::Label::new(egui::RichText::new(text).size(15.0))); + } + } + }); + if scroll && nearest == Some(index) { row.response.scroll_to_me(Some(egui::Align::Center)); } + row_separator(ui, table_width); + } + if marker == Some(rows.len()) { + if let Some(quote) = &self.underlying { underlying_marker(ui, quote.last, table_width); } + } + }); + }); + }); + self.open = open; + picked + } +} + +#[cfg(test)] +mod tests { + use super::*; + use egui_kittest::kittest::Queryable; + + fn contract(symbol: &str, kind: &str, strike: f64, last: f64) -> Contract { + Contract { + fields: serde_json::Value::Null, + symbol: symbol.into(), + kind: kind.into(), + strike, + last: Some(last), + bid: None, + ask: None, + change: None, + change_percentage: None, + volume: None, + open_interest: None, + iv: None, + delta: None, + gamma: None, + theta: None, + vega: None, + } + } + + fn view() -> OptionsView { + OptionsView { + open: true, + symbol: "SPY".into(), + expiration: "2027-01-15".into(), + expirations: vec!["2027-01-15".into()], + contracts: vec![ + contract("SPY_CALL", "call", 500.0, 3.06), + contract("SPY_PUT", "put", 500.0, 4.28), + ], + fetched: Some(chrono::Local::now()), + columns: default_columns(), + ..Default::default() + } + } + + #[test] + fn chain_switches_contract_type_and_opens_selected_contract() { + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(1400.0, 900.0)) + .build_ui_state( + |ui, state: &mut (OptionsView, Option)| { + state.1 = state + .0 + .show(ui.ctx(), Settings::default()) + .or_else(|| state.1.take()); + }, + (view(), None), + ); + h.run_steps(3); + assert!(h.query_by_label("$3.06 ($306.00)").is_some()); + assert!(h.query_by_label("$4.28 ($428.00)").is_none()); + h.get_by_label("Puts").click(); + h.run_steps(3); + h.get_by_label("$4.28 ($428.00)").click(); + h.run_steps(2); + assert_eq!(h.state().1.as_deref(), Some("SPY_PUT")); + } + + #[test] + fn percentages_and_underlying_marker_use_displayed_units_and_strike_order() { + assert_eq!(percent(Some(-58.65)), "-58.65%"); + assert_eq!(percent(None), "—"); + let high = contract("HIGH", "call", 750.0, 1.0); + let low = contract("LOW", "call", 749.0, 1.0); + let rows = vec![&high, &low]; + assert_eq!(marker_index(&rows, 749.60), 1); + assert_eq!(marker_index(&rows, 760.0), 0); + assert_eq!(marker_index(&rows, 740.0), 2); + } + + #[test] + fn required_columns_remain_visible_and_optional_fields_are_formatted() { + let selected: Vec = vec!["open_interest".into(), "greeks.bid_iv".into()]; + let shown: Vec<_> = COLUMNS + .iter() + .filter(|c| c.required || selected.iter().any(|key| key == c.key)) + .map(|c| c.key) + .collect(); + for key in ["strike", "change_percentage", "change", "bid", "ask"] { + assert!(shown.contains(&key)); + } + assert!(!shown.contains(&"volume")); + let mut c = contract("SPY_CALL", "call", 500.0, 3.06); + c.open_interest = Some(8249.0); + c.fields = serde_json::json!({"greeks": {"bid_iv": 0.125}}); + assert_eq!( + column_value( + &c, + COLUMNS.iter().find(|c| c.key == "open_interest").unwrap() + ), + "8,249" + ); + assert_eq!( + column_value( + &c, + COLUMNS.iter().find(|c| c.key == "greeks.bid_iv").unwrap() + ), + "12.50%" + ); + } + + #[test] + fn formats_volume_change_and_contract_prices() { + let mut c = contract("SPY_CALL", "call", 500.0, 3.06); + c.volume = Some(42112.0); + c.bid = Some(1.23); + c.ask = Some(1.25); + c.change = Some(-2.75); + let field = + |key| column_value(&c, COLUMNS.iter().find(|column| column.key == key).unwrap()); + assert_eq!(field("volume"), "42,112"); + assert_eq!(field("bid"), "$1.23 ($123.00)"); + assert_eq!(field("ask"), "$1.25 ($125.00)"); + assert_eq!(field("last"), "$3.06 ($306.00)"); + assert_eq!(field("change"), "-$2.75"); + assert_eq!(contract_price(None), "—"); + } + + #[test] + fn column_picker_exposes_optional_parameters() { + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(1400.0, 900.0)) + .build_ui_state( + |ui, view: &mut OptionsView| { + view.show(ui.ctx(), Settings::default()); + }, + view(), + ); + h.run_steps(3); + h.get_by_label("Columns").click(); + h.run_steps(3); + assert!( + h.query_by_label("Required columns are always shown.") + .is_some() + ); + assert!(h.query_by_label("Open interest").is_some()); + assert!(h.query_by_label("Gamma").is_some()); + } + + #[test] + #[ignore = "headless visual inspection"] + fn render_options_view() { + let mut view = view(); + view.underlying = Some(MarketQuote { + symbol: "SPY".into(), + last: 499.60, + previous_close: 500.0, + time: chrono::Utc::now(), + }); + view.scroll_to_price = false; + view.contracts[0].change_percentage = Some(-58.65); + view.contracts[0].iv = Some(0.24); + view.contracts[0].bid = Some(3.04); + view.contracts[0].ask = Some(3.08); + view.contracts[0].change = Some(-2.75); + view.contracts[0].volume = Some(42112.0); + for strike in 496..=504 { + view.contracts.push(contract( + &format!("SPY{strike}C"), + "call", + strike as f64, + 3.06, + )); + } + let mut h = egui_kittest::Harness::builder() + .allow_missing_glyphs() + .with_size(egui::vec2(1440.0, 900.0)) + .wgpu() + .build_ui_state( + |ui, view: &mut OptionsView| { + egui_charts::theme::apply_to_egui(ui.ctx(), &egui_charts::theme::Theme::dark()); + view.show(ui.ctx(), Settings::default()); + }, + view, + ); + h.run_steps(3); + h.render() + .unwrap() + .save( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../target/options-preview.png"), + ) + .unwrap(); + } +} diff --git a/crates/ui-egui/src/pine_engine/ast.rs b/crates/ui-egui/src/pine_engine/ast.rs index 76d1561..e90dbcf 100644 --- a/crates/ui-egui/src/pine_engine/ast.rs +++ b/crates/ui-egui/src/pine_engine/ast.rs @@ -1,6 +1,8 @@ //! The parsed shape of a script: statements, expressions, inputs and the diagnostics the editor //! shows for what this subset does not run. +use std::collections::HashSet; + use crate::pine_engine::value::Value; /// Identifies a call site, so a builtin keeps its state (`ta.ema`'s previous value) between bars @@ -104,6 +106,135 @@ pub enum Expr { }, } +impl Expr { + /// Visits this expression and every subexpression, for the analyses a run does once. + pub fn visit(&self, f: &mut impl FnMut(&Expr)) { + f(self); + match self { + Expr::Member { target, .. } => target.visit(f), + Expr::Call { + receiver, args, .. + } => { + if let Some(receiver) = receiver { + receiver.visit(f); + } + for arg in args { + arg.value.visit(f); + } + } + Expr::Index { target, index } => { + target.visit(f); + index.visit(f); + } + Expr::Unary { value, .. } => value.visit(f), + Expr::Binary { left, right, .. } => { + left.visit(f); + right.visit(f); + } + Expr::Ternary { + cond, + then, + otherwise, + } => { + cond.visit(f); + then.visit(f); + otherwise.visit(f); + } + Expr::If { + cond, + then, + otherwise, + } => { + cond.visit(f); + visit_stmts(then, f); + if let Some(otherwise) = otherwise { + visit_stmts(otherwise, f); + } + } + Expr::Array(items) => { + for item in items { + item.visit(f); + } + } + Expr::Lambda { body, .. } => body.visit(f), + Expr::Switch { subject, arms } => { + if let Some(subject) = subject { + subject.visit(f); + } + for arm in arms { + for cond in &arm.conds { + cond.visit(f); + } + visit_stmts(&arm.body, f); + } + } + _ => {} + } + } +} + +/// Visits every expression a block holds, including those inside functions and types. +pub fn visit_stmts(body: &[Stmt], f: &mut impl FnMut(&Expr)) { + for statement in body { + match statement { + Stmt::Assign { value, .. } | Stmt::Expr(value) | Stmt::Tuple { value, .. } => { + value.visit(f) + } + Stmt::If { + cond, + then, + otherwise, + } => { + cond.visit(f); + visit_stmts(then, f); + if let Some(otherwise) = otherwise { + visit_stmts(otherwise, f); + } + } + Stmt::For { + from, + to, + step, + body, + .. + } => { + from.visit(f); + to.visit(f); + if let Some(step) = step { + step.visit(f); + } + visit_stmts(body, f); + } + Stmt::ForIn { iterable, body, .. } => { + iterable.visit(f); + visit_stmts(body, f); + } + Stmt::While { cond, body, .. } => { + cond.visit(f); + visit_stmts(body, f); + } + Stmt::FieldAssign { target, value, .. } => { + target.visit(f); + value.visit(f); + } + Stmt::Function(function) => { + for default in function.defaults.iter().flatten() { + default.visit(f); + } + visit_stmts(&function.body, f); + } + Stmt::Type(declaration) => { + for field in &declaration.fields { + if let Some(default) = &field.default { + default.visit(f); + } + } + } + _ => {} + } + } +} + /// One branch of a `switch`. #[derive(Clone, Debug)] pub struct SwitchArm { @@ -208,4 +339,6 @@ pub struct Program { pub body: Block, pub inputs: Vec, pub diagnostics: Vec, + /// The call sites the script reads with `[n]`: found once, since every run needs them. + pub indexed: HashSet, } diff --git a/crates/ui-egui/src/pine_engine/builtins.rs b/crates/ui-egui/src/pine_engine/builtins.rs index 465570f..054db69 100644 --- a/crates/ui-egui/src/pine_engine/builtins.rs +++ b/crates/ui-egui/src/pine_engine/builtins.rs @@ -185,7 +185,6 @@ pub const TA_NAMES: &[&str] = &[ "valuewhen", "pivothigh", "pivotlow", - "na", "rising", "falling", "mom", @@ -843,7 +842,6 @@ fn ta_known(name: &str, state: &mut TaState, args: &[Value], bar: &Bar) -> Optio } num(state.window.iter().sum::() / volume) } - "na" => Some(Value::Bool(true)), "range" => { let src = args.first().and_then(number)?; let len = length(args.get(1), 1); diff --git a/crates/ui-egui/src/pine_engine/lexer.rs b/crates/ui-egui/src/pine_engine/lexer.rs index 1163d4b..2b91518 100644 --- a/crates/ui-egui/src/pine_engine/lexer.rs +++ b/crates/ui-egui/src/pine_engine/lexer.rs @@ -177,7 +177,14 @@ fn lex_line( at += 1; while at < bytes.len() && bytes[at] != quote { if bytes[at] == '\\' && at + 1 < bytes.len() { - text.push(bytes[at + 1]); + // Pine writes a line break in a label as `\n`; other escaped characters + // stand for themselves, as `\"` does. + text.push(match bytes[at + 1] { + 'n' => '\n', + 't' => '\t', + 'r' => '\r', + escaped => escaped, + }); at += 2; continue; } diff --git a/crates/ui-egui/src/pine_engine/parser.rs b/crates/ui-egui/src/pine_engine/parser.rs index 5091a51..30095ab 100644 --- a/crates/ui-egui/src/pine_engine/parser.rs +++ b/crates/ui-egui/src/pine_engine/parser.rs @@ -46,12 +46,14 @@ impl Parser { let mut overlay = true; let body = parser.parse_body(&mut title, &mut overlay)?; inputs_of(&body, &mut parser.inputs); + let indexed = crate::pine_engine::runtime::indexed_calls(&body); Ok(Program { title, overlay, body, inputs: parser.inputs, diagnostics: parser.diagnostics, + indexed, }) } diff --git a/crates/ui-egui/src/pine_engine/runtime.rs b/crates/ui-egui/src/pine_engine/runtime.rs index 2d246c1..c6dda9e 100644 --- a/crates/ui-egui/src/pine_engine/runtime.rs +++ b/crates/ui-egui/src/pine_engine/runtime.rs @@ -11,6 +11,7 @@ use egui_charts::studies::{ FillBoundary, PlotType, StudyCell, StudyFill, StudyTable, StudyTablePosition, }; +use crate::pine_engine::ast; use crate::pine_engine::ast::{ Arg, Diagnostic, Expr, Function, NodeId, Program, Stmt, TypeDecl, }; @@ -66,7 +67,7 @@ impl Default for Context { } } -/// A history the host fetched for a `request.security` on another symbol. +/// A history the host fetched for a `request.security` on another symbol or a lower timeframe. #[derive(Clone, Debug)] pub struct SecurityData { pub symbol: String, @@ -129,7 +130,8 @@ pub struct RunOutput { pub fills: Vec, pub drawings: Vec, pub tables: Vec, - /// Other-symbol histories the script read, as `(symbol, interval)`. + /// Histories the script read besides the chart's own series: another symbol or a lower + /// timeframe, as `(symbol, interval)`. pub security_requests: Vec<(String, egui_charts::model::Timeframe)>, pub diagnostics: Vec, } @@ -159,6 +161,7 @@ pub struct DrawingOutput { pub fill_color: Option, pub width: f32, pub style: egui_charts::model::LineStyle, + pub label_style: Option, pub font_size: f32, } @@ -167,6 +170,9 @@ pub struct DrawingOutput { struct Var { value: Value, history: Vec, + /// Whether a `var` already ran its initializer, including one in a function that a script + /// first reached on a later bar. + initialized: bool, } #[derive(Clone, Debug)] @@ -203,6 +209,25 @@ struct SecuritySlot { /// series comes from another symbol, so a reload starts it over. key: Option, ta: HashMap, + function_vars: HashMap<(Vec, String), Value>, + /// The script variables the request's expression can read, found on its first evaluation. + /// Only they are copied from the chart's own state, since a request over bars reads none. + referenced: Option, +} + +/// The chart variables a `request.security` expression can read. +#[derive(Debug)] +enum SecurityVars { + /// All of them: the expression names its source at run time, as `input.source` does. + All, + /// Only these, found by reading the expression and the functions it calls. + Named(HashSet), +} + +struct LowerSeries { + opens: Vec, + closes: Vec, + values: Vec, } /// Runs one script over a bar series. @@ -213,6 +238,9 @@ pub struct Evaluator<'a> { inputs: &'a HashMap, vars: HashMap, locals: Vec>, + function_path: Vec, + function_frames: Vec<(usize, HashSet)>, + function_vars: HashMap<(Vec, String), Value>, functions: HashMap<&'a str, &'a Function>, types: HashMap<&'a str, &'a TypeDecl>, ta: HashMap, @@ -224,6 +252,14 @@ pub struct Evaluator<'a> { shapes: Vec, shape_at: HashMap, security: HashMap, + /// The value a call site answered on each bar, kept only for call sites a script indexes + /// with `[n]`, so `time(tf)[1]` and `ta.sma(...)[1]` read what the earlier bars saw. + call_history: HashMap>, + /// The call sites whose value `call_history` keeps. + indexed: &'a HashSet, + lower: HashMap<(NodeId, String, egui_charts::model::Timeframe), LowerSeries>, + sampling: Option<(NodeId, Vec<(usize, Value)>)>, + nested_lower: bool, /// Histories for `request.security` calls on other symbols, supplied by the host. sources: &'a [SecurityData], /// Every other-symbol `request.security` this run asked for, with its interval. @@ -269,6 +305,9 @@ impl<'a> Evaluator<'a> { inputs, vars: HashMap::new(), locals: Vec::new(), + function_path: Vec::new(), + function_frames: Vec::new(), + function_vars: HashMap::new(), functions, types, ta: HashMap::new(), @@ -280,6 +319,11 @@ impl<'a> Evaluator<'a> { shapes: Vec::new(), shape_at: HashMap::new(), security: HashMap::new(), + call_history: HashMap::new(), + indexed: &program.indexed, + lower: HashMap::new(), + sampling: None, + nested_lower: false, sources, security_requests: Vec::new(), diagnostics: Vec::new(), @@ -424,6 +468,7 @@ impl<'a> Evaluator<'a> { .map(|cell| match cell { StudyCell::Text(text) => text, StudyCell::Percent(_) => String::new(), + _ => String::new(), }) .collect() } else { @@ -466,14 +511,12 @@ impl<'a> Evaluator<'a> { } } } - let table = StudyTable { - title: String::new(), - columns: headings, - rows: cells, - cell_bg, - cell_text, - position: table_position(fields.get("__position").and_then(Value::text)), - }; + let mut table = StudyTable::default(); + table.columns = headings; + table.rows = cells; + table.cell_bg = cell_bg; + table.cell_text = cell_text; + table.position = table_position(fields.get("__position").and_then(Value::text)); built.push((filled, table)); } built.sort_by_key(|(filled, _)| std::cmp::Reverse(*filled)); @@ -517,8 +560,10 @@ impl<'a> Evaluator<'a> { let var = self.vars.entry(name.to_owned()).or_insert_with(|| Var { value: Value::Na, history: Vec::new(), + initialized: true, }); var.value = value; + var.initialized = true; } else if let Some(scope) = self.locals.last_mut() { scope.insert(name.to_owned(), value); } @@ -538,8 +583,32 @@ impl<'a> Evaluator<'a> { reassign, } => { // `var x = …` runs on the first bar only; a missing one is `na` until assigned. - if *sticky && self.bar > 0 { - return self.ident(name); + if *sticky && let Some((scope_index, _)) = self.function_frames.last() { + let scope_index = *scope_index; + let key = (self.function_path.clone(), name.clone()); + let value = match self.function_vars.get(&key) { + Some(value) => value.clone(), + None => { let value = self.eval(value); self.function_vars.insert(key, value.clone()); value } + }; + self.locals[scope_index].insert(name.clone(), value.clone()); + self.function_frames.last_mut().unwrap().1.insert(name.clone()); + return value; + } + if *sticky && self.locals.is_empty() { + if let Some(var) = self.vars.get(name) + && var.initialized + { + return var.value.clone(); + } + let value = self.eval(value); + let var = self.vars.entry(name.to_owned()).or_insert_with(|| Var { + value: Value::Na, + history: Vec::new(), + initialized: false, + }); + var.value = value.clone(); + var.initialized = true; + return value; } let value = self.eval(value); self.store(name, value.clone(), *reassign); @@ -797,7 +866,17 @@ impl<'a> Evaluator<'a> { receiver, args, line, - } => self.call(*id, callee, receiver.as_deref(), args, *line), + } => { + let value = self.call(*id, callee, receiver.as_deref(), args, *line); + if self.indexed.contains(id) { + let history = self.call_history.entry(*id).or_default(); + if history.len() <= self.bar { + history.resize(self.bar + 1, Value::Na); + } + history[self.bar] = value.clone(); + } + value + } Expr::Index { target, index } => self.index(target, index), Expr::Unary { op, value } => { let value = self.eval(value); @@ -911,6 +990,16 @@ impl<'a> Evaluator<'a> { .get(self.bar) .map(|bar| Value::Num(bar.time.timestamp_millis() as f64)) .unwrap_or(Value::Na), + // A bar closes one timeframe after it opens; a trade-based chart has no duration. + "time_close" => self + .bars + .get(self.bar) + .map(|bar| { + Value::Num( + (bar.time.timestamp_millis() + self.context.timeframe.duration_ms()) as f64, + ) + }) + .unwrap_or(Value::Na), "hour" => self.clock(|time| time.hour() as f64), "minute" => self.clock(|time| time.minute() as f64), "second" => self.clock(|time| time.second() as f64), @@ -954,6 +1043,27 @@ impl<'a> Evaluator<'a> { .unwrap_or(Value::Na) } + /// Session boundaries use the chart's selected timezone. Regular hours are the + /// configured fallback of 09:30–16:00 because exchange calendars are unavailable. + fn session_boundary(&self, regular: bool, first: bool) -> bool { + let Some(bar) = self.bars.get(self.bar) else { return false; }; + let now = bar.time.with_timezone(&self.context.timezone); + let in_regular = |time: &chrono::DateTime| { + let minute = time.hour() * 60 + time.minute(); + (570..960).contains(&minute) + }; + if regular && !in_regular(&now) { return false; } + let other = if first { self.bar.checked_sub(1).and_then(|i| self.bars.get(i)) } else { self.bars.get(self.bar + 1) }; + if let Some(other) = other { + let other = other.time.with_timezone(&self.context.timezone); + return other.date_naive() != now.date_naive() || (regular && !in_regular(&other)); + } + if first { return true; } + let end = bar.time + chrono::Duration::milliseconds(self.context.timeframe.duration_ms().max(0)); + let end = end.with_timezone(&self.context.timezone); + end.date_naive() != now.date_naive() || (regular && !in_regular(&end)) + } + fn member(&self, path: &str) -> Value { // An `enum` entry or a type's default: `Color.red` is a constant, not an object field. if let Some((namespace, name)) = path.split_once('.') @@ -967,6 +1077,10 @@ impl<'a> Evaluator<'a> { .unwrap_or(Value::Na); } match path { + "session.isfirstbar" => return Value::Bool(self.session_boundary(false, true)), + "session.islastbar" => return Value::Bool(self.session_boundary(false, false)), + "session.isfirstbar_regular" => return Value::Bool(self.session_boundary(true, true)), + "session.islastbar_regular" => return Value::Bool(self.session_boundary(true, false)), "math.pi" => return Value::Num(std::f64::consts::PI), "math.e" => return Value::Num(std::f64::consts::E), "barstate.isfirst" => return Value::Bool(self.bar == 0), @@ -1478,6 +1592,21 @@ impl<'a> Evaluator<'a> { return Value::Na; } let offset = offset as usize; + if let Expr::Call { id, .. } = target { + // Evaluating the call keeps a stateful builtin in step with Pine; `[0]` then reads + // back the value this bar just recorded. + self.eval(target); + return self + .bar + .checked_sub(offset) + .and_then(|bar| { + self.call_history + .get(id) + .and_then(|history| history.get(bar)) + .cloned() + }) + .unwrap_or(Value::Na); + } let Expr::Ident(name) = target else { return Value::Na; }; @@ -1793,12 +1922,26 @@ impl<'a> Evaluator<'a> { if matches!(value, Value::Object(_)) && let Some(function) = self.functions.get(method.as_str()).copied() { - return self.call_function(function, args, Some(value), line); + return self.call_function(id, function, args, Some(value), line); } } if let Some(rest) = name.strip_prefix("timeframe.") { return match rest { - "in_seconds" => Value::Num((self.context.timeframe.duration_ms() / 1000) as f64), + "in_seconds" => { + let text = args + .first() + .map(|arg| self.eval(&arg.value)) + .and_then(|value| value.text().map(str::to_owned)) + .filter(|text| !text.is_empty()); + match text.as_deref().and_then(Bucket::parse) { + Some(bucket) => Value::Num((bucket.duration_ms() / 1000) as f64), + // Without a period the chart's own interval is what Pine answers. + None if text.is_none() => { + Value::Num((self.context.timeframe.duration_ms() / 1000) as f64) + } + None => Value::Na, + } + } // True on the first bar of a new `period`, as `timeframe.change` documents. "change" => { let period = args @@ -1845,16 +1988,20 @@ impl<'a> Evaluator<'a> { if callee.len() == 1 && let Some(function) = self.functions.get(name.as_str()).copied() { - return self.call_function(function, args, None, line); + return self.call_function(id, function, args, None, line); } self.unsupported(line, &name) } - /// `request.security(symbol, timeframe, expression)`: the expression's value on the last - /// closed bar of `timeframe`, sampled from the bars on the chart. Another symbol reads the - /// history the host supplied for it. With `lookahead=barmerge.lookahead_on` the higher bar is - /// taken whole as soon as it opens, as Pine does when it repaints historical security values. fn security(&mut self, id: NodeId, args: &[Arg]) -> Value { + let value = self.security_value(id, args); + if let Some((sampled, readings)) = &mut self.sampling && *sampled == id { + readings.push((self.bar, value.clone())); + } + value + } + + fn security_value(&mut self, id: NodeId, args: &[Arg]) -> Value { let symbol = args .first() .map(|arg| self.eval(&arg.value)) @@ -1882,16 +2029,14 @@ impl<'a> Evaluator<'a> { None => return Value::Na, }, }; - if !symbol.is_empty() && symbol != self.context.symbol { - return self.security_other(id, &symbol, bucket, expr, lookahead); - } - if bucket == chart { + if bucket == chart && (symbol.is_empty() || symbol == self.context.symbol) { return self.eval(expr); } if bucket.duration_ms() < self.context.timeframe.duration_ms() { - // A lower timeframe is `request.security_lower_tf`'s series, which this engine does - // not hold. - return Value::Na; + return self.lower_security(id, &symbol, bucket, lookahead); + } + if !symbol.is_empty() && symbol != self.context.symbol { + return self.security_other(id, &symbol, bucket, expr, lookahead); } if bucket == Bucket::Day && !lookahead { let zone = named(args, "timezone") @@ -1910,6 +2055,8 @@ impl<'a> Evaluator<'a> { bucket, key: None, ta: HashMap::new(), + function_vars: HashMap::new(), + referenced: None, }); if lookahead { if slot.key != Some(key) { @@ -1960,6 +2107,64 @@ impl<'a> Evaluator<'a> { value } + /// Evaluate a same-symbol finer series once, then select only bars within this chart bar. + fn lower_security(&mut self, id: NodeId, symbol: &str, bucket: Bucket, lookahead: bool) -> Value { + let Some(timeframe) = bucket.timeframe() else { return Value::Na; }; + let symbol = if symbol.is_empty() { self.context.symbol.clone() } else { symbol.to_owned() }; + let request = (symbol.clone(), timeframe); + if !self.security_requests.contains(&request) { self.security_requests.push(request); } + if self.nested_lower { + let message = "Nested lower-timeframe requests are not supported".to_owned(); + if self.reported.insert((0, message.clone())) { self.diagnostics.push(Diagnostic { line: 0, message }); } + return Value::Na; + } + let Some(source) = self.sources.iter().find(|s| s.symbol == symbol && s.timeframe == timeframe) else { return Value::Na; }; + if source.bars.len() > 10_000 { + let message = "Lower-timeframe history exceeds 10,000 bars".to_owned(); + if self.reported.insert((0, message.clone())) { self.diagnostics.push(Diagnostic { line: 0, message }); } + return Value::Na; + } + let Some(bar) = self.bars.get(self.bar) else { return Value::Na; }; + let start = bar.time.timestamp_millis(); + let Some(end) = start.checked_add(self.context.timeframe.duration_ms()) else { return Value::Na; }; + let key = (id, symbol.clone(), timeframe); + if !self.lower.contains_key(&key) { + let mut context = self.context.clone(); + context.symbol = symbol; + context.timeframe = timeframe; + let mut sub = Evaluator::new(self.program, &source.bars, &context, self.inputs, self.sources); + sub.nested_lower = true; + sub.sampling = Some((id, Vec::new())); + sub.steps = self.steps; + let body = sub.program.body.as_slice(); + for at in 0..source.bars.len() { + sub.bar = at; + if sub.charge(0) { break; } + sub.run_block(body); + sub.finish_bar(); + if sub.out_of_budget { break; } + } + self.steps = sub.steps; + self.out_of_budget |= sub.out_of_budget; + for diagnostic in sub.diagnostics.drain(..) { + if self.reported.insert((diagnostic.line, diagnostic.message.clone())) { self.diagnostics.push(diagnostic); } + } + let opens: Vec<_> = source.bars.iter().map(|b| b.time.timestamp_millis()).collect(); + let closes: Vec<_> = opens.iter().map(|open| open.saturating_add(timeframe.duration_ms())).collect(); + let mut values = vec![Value::Na; source.bars.len()]; + for (at, value) in sub.sampling.take().map(|(_, v)| v).unwrap_or_default() { + if let Some(slot) = values.get_mut(at) { *slot = value; } + } + self.lower.insert(key.clone(), LowerSeries { opens, closes, values }); + } + let series = &self.lower[&key]; + let first = series.opens.partition_point(|open| *open < start); + let last = series.closes.partition_point(|close| *close <= end); + if first >= last { return Value::Na; } + let at = if lookahead { first } else { last - 1 }; + series.values.get(at).cloned().unwrap_or(Value::Na) + } + /// Read the provider's daily series instead of folding extended intraday bars into it. fn security_same_daily(&mut self, id: NodeId, symbol: &str, expr: &Expr, timezone: &egui_charts::model::TimezoneId) -> Value { use egui_charts::model::Timeframe; @@ -1973,8 +2178,24 @@ impl<'a> Evaluator<'a> { let Some(current_time) = self.bars.get(self.bar).map(|bar| bar.time) else { return Value::Na; }; let date = current_time.with_timezone(timezone).date_naive(); let completed = source.bars.partition_point(|bar| bar.time.with_timezone(timezone).date_naive() < date); + // A literal historical OHLCV reference names a completed daily bar. Read it + // directly for every intraday bar, including historical premarket bars; today's + // provider bar may contain data that was not yet known at that time. + if let Expr::Index { target, index } = expr + && let (Expr::Ident(field), Expr::Number(offset)) = (target.as_ref(), index.as_ref()) + && offset.is_finite() && *offset >= 1.0 && offset.fract() == 0.0 && *offset <= usize::MAX as f64 + && matches!(field.as_str(), "open" | "high" | "low" | "close" | "volume") + { + return completed.checked_sub(*offset as usize) + .and_then(|at| source.bars.get(at)) + .map(|bar| Value::Num(match field.as_str() { + "open" => bar.open, "high" => bar.high, "low" => bar.low, + "close" => bar.close, _ => bar.volume, + })) + .unwrap_or(Value::Na); + } let mut slot = self.security.remove(&id).unwrap_or_else(|| SecuritySlot { - bars: Vec::new(), values: Vec::new(), bucket: Bucket::Day, key: None, ta: HashMap::new(), + bars: Vec::new(), values: Vec::new(), bucket: Bucket::Day, key: None, ta: HashMap::new(), function_vars: HashMap::new(), referenced: None, }); // Closed daily bars are evaluated only once as chart time advances. let new_bars = source.bars[slot.bars.len().min(completed)..completed].to_vec(); @@ -2016,7 +2237,8 @@ impl<'a> Evaluator<'a> { self.security_requests.push(request); } if bucket.duration_ms() < self.context.timeframe.duration_ms() { - // A lower timeframe is `request.security_lower_tf`'s series. + // Only the chart's own symbol is run again on a finer series; another symbol's lower + // timeframe would need a second history this engine does not fetch. return Value::Na; } let Some(bar) = self.bars.get(self.bar) else { @@ -2048,6 +2270,8 @@ impl<'a> Evaluator<'a> { bucket, key: Some(first), ta: HashMap::new(), + function_vars: HashMap::new(), + referenced: None, }); // A changed interval or a deeper history re-reads the series from its start. if slot.bucket != bucket || slot.key != Some(first) { @@ -2057,6 +2281,8 @@ impl<'a> Evaluator<'a> { bucket, key: Some(first), ta: HashMap::new(), + function_vars: HashMap::new(), + referenced: slot.referenced, }; } let new_bars: Vec = source.bars[slot.bars.len().min(seen)..seen].to_vec(); @@ -2075,25 +2301,38 @@ impl<'a> Evaluator<'a> { /// keeping its `ta` state between those bars. fn eval_security(&mut self, slot: &mut SecuritySlot, expr: &Expr, bar: usize) -> Value { let mut sub = Evaluator::new(self.program, &[], self.context, self.inputs, self.sources); + sub.steps = self.steps; + sub.nested_lower = self.nested_lower; sub.bars = Cow::Owned(std::mem::take(&mut slot.bars)); sub.ta = std::mem::take(&mut slot.ta); + sub.function_vars = std::mem::take(&mut slot.function_vars); + // A request inside a lower-timeframe run must not start another such run. // A chart series passed to `request.security` keeps the value it had when the // higher-timeframe bar closed. - sub.vars = self - .vars - .iter() - .map(|(name, var)| { - ( - name.clone(), - Var { - value: var.value.clone(), - history: Vec::new(), - }, - ) - }) - .collect(); + if slot.referenced.is_none() { + slot.referenced = Some(referenced_vars(self.program, expr)); + } + let copy = |name: &String, var: &Var| { + ( + name.clone(), + Var { + value: var.value.clone(), + history: Vec::new(), + initialized: var.initialized, + }, + ) + }; + sub.vars = match slot.referenced.as_ref().unwrap() { + SecurityVars::All => self.vars.iter().map(|(name, var)| copy(name, var)).collect(), + SecurityVars::Named(names) => names + .iter() + .filter_map(|name| self.vars.get(name).map(|var| copy(name, var))) + .collect(), + }; sub.bar = bar; let value = sub.eval(expr); + self.steps = sub.steps; + self.out_of_budget |= sub.out_of_budget; for diagnostic in sub.diagnostics.drain(..) { if self .reported @@ -2104,6 +2343,7 @@ impl<'a> Evaluator<'a> { } slot.bars = std::mem::take(&mut sub.bars).into_owned(); slot.ta = std::mem::take(&mut sub.ta); + slot.function_vars = std::mem::take(&mut sub.function_vars); for request in sub.security_requests.drain(..) { if !self.security_requests.contains(&request) { self.security_requests.push(request); @@ -2293,6 +2533,7 @@ impl<'a> Evaluator<'a> { fn call_function( &mut self, + id: NodeId, function: &'a Function, args: &[Arg], receiver: Option, @@ -2333,6 +2574,8 @@ impl<'a> Evaluator<'a> { ); } self.locals.push(scope); + self.function_path.push(id); + self.function_frames.push((self.locals.len() - 1, HashSet::new())); // A parameter the caller left out takes the default the script declared for it. for (at, default) in function.defaults.iter().enumerate() { let Some(default) = default else { continue }; @@ -2349,6 +2592,13 @@ impl<'a> Evaluator<'a> { let value = self.run_block(&function.body); self.control = control; self.depth -= 1; + let (scope_index, names) = self.function_frames.pop().unwrap(); + for name in names { + if let Some(value) = self.locals[scope_index].get(&name) { + self.function_vars.insert((self.function_path.clone(), name), value.clone()); + } + } + self.function_path.pop(); self.locals.pop(); value } @@ -2650,10 +2900,13 @@ impl<'a> Evaluator<'a> { fields.insert("__columns".into(), Value::Num(columns as f64)); fields.insert("__rows".into(), Value::Num(rows as f64)); // `table.new(position.top_right, columns, rows, ...)`: the first argument is a member - // path, which is read as text so it is not evaluated as an unknown name. + // path, which is read as text so it is not evaluated as an unknown name. A script may + // also pass a variable holding that constant, which evaluates to the member's name. let position = args .first() - .and_then(|arg| dotted(&arg.value)) + .map(|arg| self.eval(&arg.value)) + .and_then(|value| value.text().map(str::to_owned)) + .or_else(|| args.first().and_then(|arg| dotted(&arg.value))) .unwrap_or_else(|| "position.top_right".into()); fields.insert("__position".into(), Value::Str(position)); drop(fields); @@ -2709,6 +2962,50 @@ impl<'a> Evaluator<'a> { } } } + // `table.cell_set_text_color(table_id, column, row, color)` and its two siblings + // write the cell `table.cell` writes, without its width, height or alignment. + "cell_set_text" | "cell_set_text_color" | "cell_set_bgcolor" => { + let column = index(args.get(1).map(|arg| self.eval(&arg.value))); + let row = index(args.get(2).map(|arg| self.eval(&arg.value))); + let value = args + .get(3) + .map(|arg| self.eval(&arg.value)) + .unwrap_or(Value::Na); + let mut fields = value::lock_object(&shared); + if method == "cell_set_text" { + let text = builtins::display(&value); + match text.is_empty() { + true => { + fields.remove(&format!("c:{column}:{row}")); + } + false => { + fields.insert(format!("c:{column}:{row}"), Value::Str(text)); + } + } + return Value::Na; + } + let key = format!( + "{}:{column}:{row}", + if method == "cell_set_bgcolor" { "b" } else { "t" } + ); + match value.color() { + Some(color) => { + fields.insert(key, Value::Color(color)); + } + None => { + fields.remove(&key); + } + } + } + "set_position" => { + let position = args + .get(1) + .map(|arg| self.eval(&arg.value)) + .and_then(|value| value.text().map(str::to_owned)) + .or_else(|| args.get(1).and_then(|arg| dotted(&arg.value))) + .unwrap_or_else(|| "position.bottom_right".into()); + value::lock_object(&shared).insert("__position".into(), Value::Str(position)); + } "clear" => { let mut bound = |at: usize, fallback: usize| { args.get(at) @@ -3056,13 +3353,13 @@ fn drawing_output(object: &value::ObjectRef) -> Option { .unwrap_or_default() .to_owned() }; - let style = fields + let style_text = fields .get("style") .and_then(Value::text) .unwrap_or("style_solid"); - let style = if style.contains("dashed") { + let style = if style_text.contains("dashed") { egui_charts::model::LineStyle::Dashed - } else if style.contains("dotted") { + } else if style_text.contains("dotted") { egui_charts::model::LineStyle::Dotted } else { egui_charts::model::LineStyle::Solid @@ -3082,6 +3379,8 @@ fn drawing_output(object: &value::ObjectRef) -> Option { fill_color: None, width: number("width") as f32, style, + label_style: None, + font_size, }, DrawingKind::Label => DrawingOutput { @@ -3095,6 +3394,8 @@ fn drawing_output(object: &value::ObjectRef) -> Option { fill_color: colour("color"), width: 1.0, style, + label_style: Some(style_text.to_owned()), + font_size, }, DrawingKind::Box => DrawingOutput { @@ -3108,6 +3409,8 @@ fn drawing_output(object: &value::ObjectRef) -> Option { fill_color: colour("fill_color"), width: number("border_width") as f32, style, + label_style: None, + font_size, }, DrawingKind::Fill => { @@ -3136,6 +3439,8 @@ fn drawing_output(object: &value::ObjectRef) -> Option { fill_color: colour("color"), width: 0.0, style, + label_style: None, + font_size, } } @@ -3227,6 +3532,84 @@ fn mintick_text(value: f64, mintick: f64) -> String { format!("{value:.decimals$}") } +/// The call sites a script reads with `[n]`, whose value on every bar +/// [`Evaluator::call_history`] keeps for it. +pub(crate) fn indexed_calls(body: &[Stmt]) -> HashSet { + let mut ids = HashSet::new(); + ast::visit_stmts(body, &mut |expr| { + if let Expr::Index { target, .. } = expr + && let Expr::Call { id, .. } = &**target + { + ids.insert(*id); + } + }); + ids +} + +/// The script variables an expression can read, including through the functions it calls. A +/// `request.security` request hands the chart's values only for these, so a request that reads +/// bars alone copies nothing and stays cheap on a long history. +fn referenced_vars(program: &Program, expr: &Expr) -> SecurityVars { + let mut functions: HashMap<&str, &Function> = HashMap::new(); + for statement in &program.body { + if let Stmt::Function(function) = statement { + functions.insert(function.name.as_str(), function); + } + } + let mut names = HashSet::new(); + let mut called = HashSet::new(); + let mut all = false; + collect_names(expr, &functions, &mut names, &mut called, &mut all); + if all { + SecurityVars::All + } else { + SecurityVars::Named(names) + } +} + +fn collect_names( + expr: &Expr, + functions: &HashMap<&str, &Function>, + names: &mut HashSet, + called: &mut HashSet, + all: &mut bool, +) { + let mut queue: Vec = Vec::new(); + fn reading( + expr: &Expr, + names: &mut HashSet, + queue: &mut Vec, + all: &mut bool, + ) { + match expr { + Expr::Ident(name) => { + names.insert(name.clone()); + } + // The setting holds the name of a series, so what it reads is only known at run time. + Expr::Call { callee, .. } if callee.join(".") == "input.source" => *all = true, + Expr::Call { callee, .. } if callee.len() == 1 => queue.push(callee[0].clone()), + _ => {} + } + } + expr.visit(&mut |expr| reading(expr, names, &mut queue, all)); + while let Some(callee) = queue.pop() { + let Some(function) = functions.get(callee.as_str()).copied() else { + continue; + }; + if !called.insert(callee) { + continue; + } + // A default argument fills a parameter even when the caller leaves it out, so it can + // read a chart value as well. + for default in function.defaults.iter().flatten() { + default.visit(&mut |expr| reading(expr, names, &mut queue, all)); + } + ast::visit_stmts(&function.body, &mut |expr| { + reading(expr, names, &mut queue, all) + }); + } +} + /// The namespaced name a v3/v4 script's bare builtin call means: `sma` is `ta.sma`, `abs` is /// `math.abs`, `color(...)` is `color.new` and `security(...)` is `request.security`. fn legacy_name(name: &str) -> Option { @@ -3346,17 +3729,18 @@ fn line_pattern(value: &Value) -> egui_charts::model::LineStyle { } } -/// A stable colour for a plot that names none. +/// The Pine `position.*` corner a table sits in, as the path or the member's bare name. fn table_position(name: Option<&str>) -> StudyTablePosition { + let name = name.map(|name| name.strip_prefix("position.").unwrap_or(name)); match name { - Some("position.top_left") => StudyTablePosition::TopLeft, - Some("position.top_center") => StudyTablePosition::TopCenter, - Some("position.top_right") => StudyTablePosition::TopRight, - Some("position.middle_left") => StudyTablePosition::MiddleLeft, - Some("position.middle_center") => StudyTablePosition::MiddleCenter, - Some("position.middle_right") => StudyTablePosition::MiddleRight, - Some("position.bottom_left") => StudyTablePosition::BottomLeft, - Some("position.bottom_center") => StudyTablePosition::BottomCenter, + Some("top_left") => StudyTablePosition::TopLeft, + Some("top_center") => StudyTablePosition::TopCenter, + Some("top_right") => StudyTablePosition::TopRight, + Some("middle_left") => StudyTablePosition::MiddleLeft, + Some("middle_center") => StudyTablePosition::MiddleCenter, + Some("middle_right") => StudyTablePosition::MiddleRight, + Some("bottom_left") => StudyTablePosition::BottomLeft, + Some("bottom_center") => StudyTablePosition::BottomCenter, _ => StudyTablePosition::BottomRight, } } @@ -3519,6 +3903,63 @@ fn closed_bars(bars: &[Bar], timeframe: egui_charts::model::Timeframe, now: i64) #[cfg(test)] mod tests { use super::*; + + #[test] + fn persistent_locals_are_separate_for_each_function_call_site() { + let source = "indicator(\"Scopes\")\na(step) =>\n var total = 0.0\n total := total + step\n total\nb(step) =>\n var total = 100.0\n total := total + step\n total\nplot(a(1))\nplot(a(2))\nplot(b(3))\n"; + let output = run(source, &[5.0, 6.0, 7.0]); + assert!(output.diagnostics.is_empty(), "{:?}", output.diagnostics); + assert_eq!(output.plots[0].values, [1.0, 2.0, 3.0]); + assert_eq!(output.plots[1].values, [2.0, 4.0, 6.0]); + assert_eq!(output.plots[2].values, [103.0, 106.0, 109.0]); + } + + #[test] + fn finer_security_uses_only_closed_bars_inside_each_chart_bar() { + let program = Parser::parse("indicator(\"Finer\")\nplot(request.security(syminfo.tickerid, \"1\", close))\n").unwrap(); + let context = Context { symbol: "TEST".into(), timeframe: egui_charts::model::Timeframe::Min5, ..Context::default() }; + let chart: Vec<_> = minute_bars(15).into_iter().step_by(5).collect(); + let mut finer = minute_bars(10); + finer.retain(|b| b.time != Utc.with_ymd_and_hms(2024, 1, 1, 0, 7, 0).unwrap()); + let sources = [SecurityData { symbol: "TEST".into(), timeframe: egui_charts::model::Timeframe::Min1, bars: finer }]; + let output = Evaluator::new(&program, &chart, &context, &HashMap::new(), &sources).run(); + assert!(output.diagnostics.is_empty(), "{:?}", output.diagnostics); + assert_eq!(&output.plots[0].values[..2], &[5.0, 10.0]); + assert!(output.plots[0].values[2].is_nan()); + assert_eq!(output.security_requests, [("TEST".into(), egui_charts::model::Timeframe::Min1)]); + } + + #[test] + fn excessive_finer_history_reports_a_limit() { + let program = Parser::parse("indicator(\"Limit\")\nplot(request.security(syminfo.tickerid, \"1\", close))\n").unwrap(); + let context = Context { symbol: "TEST".into(), timeframe: egui_charts::model::Timeframe::Min5, ..Context::default() }; + let chart = minute_bars(1); + let sources = [SecurityData { symbol: "TEST".into(), timeframe: egui_charts::model::Timeframe::Min1, bars: minute_bars(10_001) }]; + let output = Evaluator::new(&program, &chart, &context, &HashMap::new(), &sources).run(); + assert!(output.diagnostics.iter().any(|d| d.message.contains("10,000 bars"))); + } + + #[test] + fn session_dates_follow_pacific_midnight() { + let program = Parser::parse("indicator(\"Day\")\nplot(session.isfirstbar ? 1 : 0)\nplot(session.islastbar ? 1 : 0)\n").unwrap(); + let make = |hour, minute| Bar::new(Utc.with_ymd_and_hms(2024, 1, 3, hour, minute, 0).unwrap(), 1.0, 2.0, 0.0, 1.0, 1.0); + let bars = [make(7, 50), make(7, 55), make(8, 0)]; + let context = Context { timeframe: egui_charts::model::Timeframe::Min5, timezone: "America/Los_Angeles".parse().unwrap(), ..Context::default() }; + let output = Evaluator::new(&program, &bars, &context, &HashMap::new(), &[]).run(); + assert_eq!(output.plots[0].values, [1.0, 0.0, 1.0]); + assert_eq!(output.plots[1].values, [0.0, 1.0, 0.0]); + } + + #[test] + fn session_boundaries_use_chart_timezone_and_regular_hours() { + let program = Parser::parse("indicator(\"Session\")\nplot(session.isfirstbar ? 1 : 0)\nplot(session.isfirstbar_regular ? 1 : 0)\nplot(session.islastbar_regular ? 1 : 0)\n").unwrap(); + let make = |h, m| Bar::new(Utc.with_ymd_and_hms(2024, 1, 2, h, m, 0).unwrap(), 1.0, 2.0, 0.0, 1.0, 1.0); + let bars = [make(17, 25), make(17, 30), make(23, 55), make(0, 0)]; + let context = Context { timeframe: egui_charts::model::Timeframe::Min5, timezone: "America/Los_Angeles".parse().unwrap(), ..Context::default() }; + let output = Evaluator::new(&program, &bars[..3], &context, &HashMap::new(), &[]).run(); + assert_eq!(output.plots[1].values, [0.0, 1.0, 0.0]); + assert_eq!(output.plots[2].values, [0.0, 0.0, 1.0]); + } use crate::pine_engine::parser::Parser; use chrono::{TimeZone, Utc}; @@ -3683,6 +4124,30 @@ mod tests { assert_eq!(output.plots[1].values.last().copied(), Some(12.0)); } + #[test] + fn historical_intraday_bars_read_completed_daily_ohlcv_without_future_data() { + use chrono::TimeZone; + let make = |day, hour, high, low, close| Bar::new( + chrono::Utc.with_ymd_and_hms(2024, 1, day, hour, 0, 0).unwrap(), + low, high, low, close, 10.0, + ); + let chart = [make(2, 14, 20.0, 10.0, 15.0), make(3, 5, 30.0, 20.0, 25.0), + make(3, 15, 40.0, 20.0, 30.0), make(4, 5, 50.0, 30.0, 40.0)]; + // The day-four daily bar is deliberately extreme: earlier chart bars must never read it. + let source = SecurityData { symbol: "TEST".into(), timeframe: egui_charts::model::Timeframe::Day1, + bars: vec![make(2, 14, 140.0, 90.0, 115.0), make(3, 14, 150.0, 100.0, 145.0), make(4, 14, 999.0, 1.0, 999.0)] }; + let script = crate::pine_engine::Script::parse("//@version=4\nstudy(\"Previous day\")\nplot(security(syminfo.tickerid, 'D', high[1], timezone=\"America/New_York\"))\nplot(security(syminfo.tickerid, 'D', low[1], timezone=\"America/New_York\"))\nplot(security(syminfo.tickerid, 'D', close[1], timezone=\"America/New_York\"))\nplot(security(syminfo.tickerid, 'D', high[2], timezone=\"America/New_York\"))\n").unwrap(); + let context = Context { symbol: "TEST".into(), timezone: "America/Los_Angeles".parse().unwrap(), ..Context::default() }; + let output = script.run(&chart, &context, &[source]); + assert!(output.diagnostics.is_empty(), "{:?}", output.diagnostics); + assert!(output.plots[0].values[0].is_nan()); + assert_eq!(&output.plots[0].values[1..], &[140.0, 140.0, 150.0]); + assert_eq!(&output.plots[1].values[1..], &[90.0, 90.0, 100.0]); + assert_eq!(&output.plots[2].values[1..], &[115.0, 115.0, 145.0]); + assert!(output.plots[3].values[2].is_nan()); + assert_eq!(output.plots[3].values[3], 140.0); + } + #[test] fn lookahead_on_reads_the_higher_bar_from_its_first_chart_bar() { let output = run_bars( @@ -3710,6 +4175,19 @@ mod tests { assert_eq!(values[120], 90.0); } + /// A chart value a request reads, even through a function, comes from the chart's own state; + /// a request that reads bars alone copies none of it. + #[test] + fn request_security_reads_the_chart_value_a_function_returns() { + let output = run_bars( + "indicator(\"T\")\ndouble = close * 2\nshown() => double\nplot(request.security(syminfo.tickerid, \"60\", shown()))\n", + minute_bars(62), + ); + let values = &output.plots[0].values; + assert!(values[59].is_nan(), "the first hour has not closed yet"); + assert_eq!(values[60], 122.0); + } + #[test] fn another_symbol_is_na() { let output = run( @@ -3824,6 +4302,37 @@ mod tests { assert_eq!(table.position, StudyTablePosition::TopRight); } + /// A script may keep its corner in a variable, as CISD does with its position input. + #[test] + fn a_table_takes_its_position_from_a_variable() { + let output = run( + "indicator(\"T\")\ntp = position.middle_right\nvar table t = table.new(tp, 1, 1)\ntable.cell(t, 0, 0, \"x\")\nplot(close)\n", + &[1.0], + ); + assert_eq!(output.tables[0].position, StudyTablePosition::MiddleRight); + } + + #[test] + fn table_setters_update_existing_cells_and_position() { + let source = r#"indicator("Dashboard") +var table board = table.new(position.top_left, 1, 2) +table.cell(board, 0, 0, "Heading") +table.cell(board, 0, 1, "old") +table.cell_set_text(board, 0, 1, "updated") +table.cell_set_bgcolor(board, 0, 1, color.red) +table.cell_set_text_color(board, 0, 1, color.white) +table.set_position(board, position.bottom_right) +plot(close) +"#; + let output = run(source, &[3.0, 4.0]); + assert!(output.diagnostics.is_empty(), "{:?}", output.diagnostics); + let table = &output.tables[0]; + assert_eq!(table.position, StudyTablePosition::BottomRight); + assert_eq!(table.rows[1][0], StudyCell::Text("updated".into())); + assert_eq!(table.cell_bg[1][0], Some(egui::Color32::RED)); + assert_eq!(table.cell_text[1][0], Some(egui::Color32::WHITE)); + } + #[test] fn every_table_is_kept_richest_first() { let output = run( @@ -4410,6 +4919,62 @@ plot(dayofweek.monday == 2 ? 1 : 0) assert_eq!(output.plots[6].values[1], 1.0); } + #[test] + fn na_only_reads_a_missing_value_as_missing() { + let output = run( + "indicator(\"T\")\ntype S\n float v\n label l\ns = S.new(1.0, label.new(bar_index, close, \"x\"))\nplot(na(s) ? 1 : 0)\nplot(na(s.l) ? 1 : 0)\nplot(na(close) ? 1 : 0)\nplot(na(close[999]) ? 1 : 0)\n", + &[1.0, 2.0], + ); + assert!(output.diagnostics.is_empty(), "{:?}", output.diagnostics); + let at = |index: usize| output.plots[index].values[1]; + // An object that exists is a value, even when one of its fields is `na`. + assert_eq!(at(0), 0.0); + assert_eq!(at(1), 0.0); + assert_eq!(at(2), 0.0); + assert_eq!(at(3), 1.0); + } + + #[test] + fn a_call_reads_its_own_history_with_an_index() { + let output = run_bars( + "indicator(\"T\")\nplot(time(\"60\")[1])\nplot(ta.sma(close, 2)[1])\nplot(timeframe.in_seconds(\"1D\"))\n", + minute_bars(63), + ); + assert!(output.diagnostics.is_empty(), "{:?}", output.diagnostics); + // The bar before 01:01 opened at 00:00, and the first bar has nothing behind it. + assert!(output.plots[0].values[0].is_nan()); + assert_eq!(output.plots[0].values[61], 1_704_070_800_000.0); + // The two-bar average of the bar before the third one. + assert_eq!(output.plots[1].values[2], 1.5); + assert_eq!(output.plots[2].values[0], 86_400.0); + } + + #[test] + fn time_close_is_the_bar_open_plus_its_timeframe() { + let output = run_bars( + "indicator(\"T\")\nplot(time_close - time)\nplot(time_close(\"60\") - time)\n", + minute_bars(2), + ); + assert!(output.diagnostics.is_empty(), "{:?}", output.diagnostics); + assert_eq!(output.plots[0].values, [60_000.0, 60_000.0]); + // The first bar opens at midnight and its hour closes at 01:00; the second opens at 01:00. + assert_eq!(output.plots[1].values, [3_600_000.0, 3_540_000.0]); + } + + #[test] + fn a_label_keeps_its_line_breaks() { + let output = run( + "indicator(\"T\")\nlabel.new(bar_index, high, \"4H\\n(1:02)\", style = label.style_label_down)\nlabel.new(bar_index, low, \"●\", style = label.style_label_up)\n", + &[1.0, 2.0], + ); + assert!(output.diagnostics.is_empty(), "{:?}", output.diagnostics); + let [.., above, below] = &output.drawings[..] else { + panic!("two labels, got {:?}", output.drawings); + }; + assert_eq!(above.text, "4H\n(1:02)"); + assert_eq!(below.text, "●"); + } + #[test] fn a_feature_heavy_script_runs_without_diagnostics() { let script = r#"indicator("Sink", overlay=true) @@ -5088,13 +5653,14 @@ t = table.new(position.top_right, 3, 2, bgcolor=color.new(color.black, 50), bord if barstate.islast table.cell(t, 0, 0, "A", bgcolor=color.blue, text_color=color.white, text_size=size.small) table.cell(t, 1, 0, str.format("{0} {1,number,#.##}", "x", 1.234)) + table.cell(t, 0, 1, "B", bgcolor=color.blue, text_color=color.white) table.merge_cells(t, 0, 1, 2, 1) table.set_position(t, position.bottom_left) table.set_bgcolor(t, color.new(color.navy, 80)) table.set_border_color(t, color.gray) table.set_border_width(t, 2) - table.cell_set_text_color(t, 0, 0, color.yellow) - table.cell_set_bgcolor(t, 0, 0, color.olive) + table.cell_set_text_color(t, 0, 1, color.yellow) + table.cell_set_bgcolor(t, 0, 1, color.olive) table.cell_set_text(t, 1, 1, "upd") table.cell_set_text_size(t, 1, 1, size.large) l = label.new(bar_index, high, "x") @@ -5121,6 +5687,19 @@ plot(close) "#; let output = run(script, &[10.0, 11.0]); assert!(output.diagnostics.is_empty(), "{:?}", output.diagnostics); + let table = output.tables.first().expect("the table has cells"); + assert_eq!(table.position, StudyTablePosition::BottomLeft); + assert_eq!( + table.rows, + [vec![ + StudyCell::Text("B".into()), + StudyCell::Text("upd".into()), + StudyCell::Text(String::new()) + ]] + ); + let olive = Some(Color32::from_rgb(128, 128, 0)); + assert_eq!(table.cell_bg, [vec![olive; 3]]); + assert_eq!(table.cell_text, [vec![Some(Color32::YELLOW); 3]]); let line = output .drawings .iter() diff --git a/crates/ui-egui/src/pine_engine/study.rs b/crates/ui-egui/src/pine_engine/study.rs index 4b10396..d6a1142 100644 --- a/crates/ui-egui/src/pine_engine/study.rs +++ b/crates/ui-egui/src/pine_engine/study.rs @@ -40,9 +40,9 @@ pub struct PineStudy { markers: Vec, drawings: Vec, tables: Vec, - /// Histories the last run read for `request.security` on other symbols. + /// Histories the last run read for `request.security` on other series. sources: Vec, - /// Other-symbol histories the script asks the chart for, as `(symbol, interval)`. + /// Histories the script asked the chart for besides its own series, as `(symbol, interval)`. requests: Vec<(String, Timeframe)>, inputs: Vec, visible: bool, @@ -438,6 +438,9 @@ fn study_drawing(output: &DrawingOutput) -> Drawing { drawing.font_size = output.font_size; drawing.fill_color = output.fill_color.map(|color| color.to_srgba_unmultiplied()); drawing.text_color = output.text_color.map(|color| color.to_srgba_unmultiplied()); + if let Some(style) = &output.label_style { + drawing.custom_settings = serde_json::json!({"pine_label_style": style}); + } if !output.text.is_empty() { drawing.text = Some(output.text.clone()); } @@ -542,6 +545,31 @@ mod tests { use super::*; use chrono::DateTime; + #[test] + fn pine_label_styles_reach_the_chart_drawing() { + let mut study = PineStudy::new("indicator(\"Labels\")\nlabel.new(bar_index, close, \"A\", style=label.style_label_down)\nlabel.new(bar_index, close, \"B\", style=label.style_label_up)\n").unwrap(); + study.calculate(&bars(&[10.0])); + let drawings = study.drawings(); + assert_eq!(drawings.len(), 2); + assert_eq!(drawings[0].custom_settings["pine_label_style"], "style_label_down"); + assert_eq!(drawings[1].custom_settings["pine_label_style"], "style_label_up"); + } + + #[test] + fn finer_history_is_requested_and_used_after_arrival() { + let mut study = PineStudy::new("indicator(\"Finer\")\nplot(request.security(syminfo.tickerid, \"1\", close))\n").unwrap(); + study.set_instrument(Some(&Instrument::new("TEST"))); + study.set_timeframe(Timeframe::Min5); + let chart = vec![Bar::new(DateTime::UNIX_EPOCH, 1.0, 2.0, 0.0, 1.0, 1.0)]; + study.calculate(&chart); + let request = study.data_requests().pop().expect("finer history requested"); + assert_eq!(request.timeframe, Some(Timeframe::Min1)); + let finer: Vec<_> = (0..5).map(|i| Bar::new(DateTime::UNIX_EPOCH + chrono::Duration::minutes(i), 1.0, 10.0, 0.0, (i + 1) as f64, 1.0)).collect(); + let source = StudyData { request, bars: &finer, clock: egui_charts::model::BarClock::new(Timeframe::Min1), instrument: None, timeframe: Timeframe::Min1 }; + study.update_data(&chart, 0, &[source]); + assert_eq!(study.values().value(0, 0), Some(5.0)); + } + #[test] fn session_levels_ignore_after_hours_and_show_prior_close() { use chrono::TimeZone; @@ -558,6 +586,11 @@ mod tests { assert!(output.diagnostics.is_empty(), "{:?}", output.diagnostics); let latest: Vec<_> = output.plots.iter().map(|plot| *plot.values.last().unwrap()).collect(); assert_eq!(latest, [150.0, 100.0, 140.0, 90.0, 115.0, 120.0, 110.0]); + for bar in 3..bars.len() { + assert_eq!(output.plots[2].values[bar], 140.0); + assert_eq!(output.plots[3].values[bar], 90.0); + assert_eq!(output.plots[4].values[bar], 115.0); + } assert_eq!(output.security_requests, [("TEST".into(), Timeframe::Day1)]); assert!(output.plots[4].track_price && output.plots[4].track_price_solid); assert_eq!(output.plots[4].color, Color32::YELLOW); diff --git a/crates/ui-egui/src/terminal_app.rs b/crates/ui-egui/src/terminal_app.rs index 598c139..a0c3529 100644 --- a/crates/ui-egui/src/terminal_app.rs +++ b/crates/ui-egui/src/terminal_app.rs @@ -170,6 +170,7 @@ pub struct TerminalApp { menu_icon: Option, pine: crate::pine_editor::PineEditor, pine_catalog_revision: u64, + options: crate::options_view::OptionsView, } impl TerminalApp { #[cfg(test)] @@ -219,6 +220,7 @@ impl TerminalApp { menu_icon: None, pine, pine_catalog_revision: 0, + options: crate::options_view::OptionsView::default(), } } pub(crate) fn init_tray(&mut self, ctx: &egui::Context) { @@ -248,7 +250,9 @@ impl TerminalApp { terminal.set_force_session_control(true); terminal.set_script_manager_available(true); terminal.set_time_controls_in_tabs(true); + terminal.panels_mut().watchlist.set_options_action(true); let toolbar = terminal.top_toolbar_mut(); + toolbar.host_inline_action = Some(("options".into(), "Options".into(), egui::Color32::from_rgb(255, 100, 0), 18.0)); toolbar .host_menu_entries .push(("market-data-settings".into(), "Market data settings".into())); @@ -547,10 +551,13 @@ impl TerminalApp { }); let toolbar = self.terminal.top_toolbar_mut(); toolbar.host_menu_image = Some((icon.id(), egui::vec2(24.0, 24.0)).into()); - toolbar.host_status = Some(if self.alert_error.is_empty() { + let status = if self.alert_error.is_empty() { label } else { format!("{label} · {}", self.alert_error) + }; + egui::Panel::bottom("tradecraft_connection_status").show(ui, |ui| { + ui.label(status); }); let overrides = if self.settings.provider == Provider::Tradier { self.feed.calendar_overrides() @@ -566,6 +573,12 @@ impl TerminalApp { } chart.show(ui) }) { + if matches!(action, egui_charts_terminal::Action::TopToolbar(TopToolbarAction::Host(ref id)) if id == "options") { + self.options.open_for(self.terminal.chart().symbol(), self.settings); + } + if let egui_charts_terminal::Action::Watchlist(egui_charts::ui::widget_bar::panels::WatchlistAction::Options(ref symbol)) = action { + self.options.open_for(symbol, self.settings); + } if matches!(action, egui_charts_terminal::Action::TopToolbar(TopToolbarAction::Host(ref id)) if id == "market-data-settings") { self.draft = self.settings; @@ -588,6 +601,9 @@ impl TerminalApp { } } self.pine.show(ui.ctx(), self.terminal.chart_mut()); + if let Some(symbol) = self.options.show(ui.ctx(), self.settings) { + self.terminal.open_symbol_tab(&symbol); + } if self.pine.revision != self.pine_catalog_revision { self.terminal .set_indicator_factory(indicator_factory(&self.pine.library)); @@ -1719,6 +1735,33 @@ mod tests { } panic!("Missing candle was not restored: {}", feed.status()); } + #[test] + fn option_chart_tab_displays_readable_contract_name() { + let mut app = TerminalApp::new(); + app.terminal.chart_mut().set_symbol("SPY261116C00755000"); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(1400.0, 800.0)) + .build_ui_state(|ui, app: &mut TerminalApp| app.show_ui(ui), app); + h.run_steps(3); + assert!(h.query_by_label("SPY 755C").is_some()); + assert_eq!(h.state().terminal.chart().symbol(), "SPY261116C00755000"); + } + + #[test] + fn options_toolbar_opens_for_active_instrument() { + let mut app = TerminalApp::new(); + app.settings.provider = Provider::Yahoo; + app.terminal.chart_mut().set_symbol("SPY"); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(1400.0, 800.0)) + .build_ui_state(|ui, app: &mut TerminalApp| app.show_ui(ui), app); + h.run_steps(3); + h.get_by_label("Options").click(); + h.run_steps(3); + assert!(h.query_by_label("Options · SPY").is_some()); + assert!(h.query_by_label("Select Tradier in Market data settings to view options.").is_some()); + } + #[test] fn market_data_settings_are_accessible() { let mut h = egui_kittest::Harness::builder() diff --git a/docs/DIMMOFF-PINE-UPSTREAM.md b/docs/DIMMOFF-PINE-UPSTREAM.md new file mode 100644 index 0000000..b2aa27a --- /dev/null +++ b/docs/DIMMOFF-PINE-UPSTREAM.md @@ -0,0 +1,25 @@ +# DimmOFF Pine review + +TradeCraft reviewed DimmOFF's `TradingVision-pinescript-impl` branch from +`229207f089a8dd7ee89373dce1c9bc96309da7d4` through +`e7e1e98b722e59fc40e30b62bca83f5dbe47989c`. The tracked revision records +the review boundary; it does not imply that every upstream change was adopted. + +The interpreter incorporates selected changes for call-expression history, +timeframe values, missing objects, string escapes, table cell updates and +position, and reducing work in higher-timeframe requests. TradeCraft retains +its own safeguards, diagnostics, daily provider history and timezone behavior. +The chart library was not updated as part of this review. + +TradeCraft also implements lower-timeframe `request.security` with fetched bars, +session boundary flags, Pine label placement and persistent function-local +`var` values. Finer history is limited to 10,000 bars and nested finer requests +report an unsupported diagnostic. `request.security_lower_tf` remains unsupported. +Session flags use the selected chart timezone. As exchange calendars are not +tracked, regular-session flags use 09:30–16:00 in that timezone and do not model +holidays or early closes. Function-local persistence is isolated by call path. + +The Pine source remains adapted from DimmOFF's MIT-licensed fork; see +`ATTRIBUTION.md` and the vendored MIT license. No new dependency or upstream +font or asset was adopted in this review. macOS validation requires a macOS +environment. diff --git a/licenses/dependency-baseline.json b/licenses/dependency-baseline.json index 0e39cc4..682d1c2 100644 --- a/licenses/dependency-baseline.json +++ b/licenses/dependency-baseline.json @@ -908,23 +908,23 @@ "license": "MIT", "source": "registry+https://github.com/rust-lang/crates.io-index" }, - "tradecraft-core@0.3.0": { + "tradecraft-core@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft-engine@0.3.0": { + "tradecraft-engine@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft-providers@0.3.0": { + "tradecraft-providers@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft-ui-egui@0.3.0": { + "tradecraft-ui-egui@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft@0.3.0": { + "tradecraft@0.4.0": { "license": "MIT", "source": "workspace/path" }, @@ -2010,23 +2010,23 @@ "license": "MIT", "source": "registry+https://github.com/rust-lang/crates.io-index" }, - "tradecraft-core@0.3.0": { + "tradecraft-core@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft-engine@0.3.0": { + "tradecraft-engine@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft-providers@0.3.0": { + "tradecraft-providers@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft-ui-egui@0.3.0": { + "tradecraft-ui-egui@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft@0.3.0": { + "tradecraft@0.4.0": { "license": "MIT", "source": "workspace/path" }, @@ -3072,23 +3072,23 @@ "license": "MIT", "source": "registry+https://github.com/rust-lang/crates.io-index" }, - "tradecraft-core@0.3.0": { + "tradecraft-core@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft-engine@0.3.0": { + "tradecraft-engine@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft-providers@0.3.0": { + "tradecraft-providers@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft-ui-egui@0.3.0": { + "tradecraft-ui-egui@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft@0.3.0": { + "tradecraft@0.4.0": { "license": "MIT", "source": "workspace/path" }, @@ -4186,23 +4186,23 @@ "license": "MIT", "source": "registry+https://github.com/rust-lang/crates.io-index" }, - "tradecraft-core@0.3.0": { + "tradecraft-core@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft-engine@0.3.0": { + "tradecraft-engine@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft-providers@0.3.0": { + "tradecraft-providers@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft-ui-egui@0.3.0": { + "tradecraft-ui-egui@0.4.0": { "license": "MIT", "source": "workspace/path" }, - "tradecraft@0.3.0": { + "tradecraft@0.4.0": { "license": "MIT", "source": "workspace/path" }, diff --git a/scripts/license-audit.py b/scripts/license-audit.py index 444be59..4df9554 100644 --- a/scripts/license-audit.py +++ b/scripts/license-audit.py @@ -75,7 +75,7 @@ def main(): destination.mkdir(parents=True, exist_ok=True) # Older package scripts wrote an inventory here; do not ship a stale one. (destination / "dependencies" / "INDEX.md").unlink(missing_ok=True) - for name in ("LICENSE", "ATTRIBUTION.md", "ARCHITECTURE.md"): + for name in ("LICENSE", "ATTRIBUTION.md", "ARCHITECTURE.md", "README.md"): shutil.copy2(ROOT / name, destination / name) for relative in ("LICENSE-MIT", "LICENSE-APACHE", "THIRD-PARTY-NOTICES.md", "assets/icons/LICENSE-lucide.txt", "assets/fonts/LICENSE-roboto.txt"): output = destination / "vendor" / "egui-charts" / relative diff --git a/scripts/pine/bb-levels.pine b/scripts/pine/bb-levels.pine index 96ac706..456ecad 100644 --- a/scripts/pine/bb-levels.pine +++ b/scripts/pine/bb-levels.pine @@ -1,4 +1,6 @@ //@version=4 +// SPDX-FileCopyrightText: BB-levels original author and TradeCraft contributors +// SPDX-License-Identifier: MIT study(title="BB levels - regular and premarket", shorttitle="BB levels", overlay=true) // Session times are New York time, regardless of the chart's display timezone. diff --git a/vendor/DIMMOFF-PINE-UPSTREAM b/vendor/DIMMOFF-PINE-UPSTREAM new file mode 100644 index 0000000..59cdf7d --- /dev/null +++ b/vendor/DIMMOFF-PINE-UPSTREAM @@ -0,0 +1 @@ +e7e1e98b722e59fc40e30b62bca83f5dbe47989c diff --git a/vendor/EGUI-CHARTS-UPSTREAM b/vendor/EGUI-CHARTS-UPSTREAM index 9ee8a4c..26bc984 100644 --- a/vendor/EGUI-CHARTS-UPSTREAM +++ b/vendor/EGUI-CHARTS-UPSTREAM @@ -1 +1 @@ -c9a7f0bbe6410eb6bc69fd2f2e8a6394919ac4f2 +7a852a5152f9a5c3f3cc556f70170094e976d823 diff --git a/vendor/egui-charts/ROADMAP.md b/vendor/egui-charts/ROADMAP.md index e3b532b..9b51041 100644 --- a/vendor/egui-charts/ROADMAP.md +++ b/vendor/egui-charts/ROADMAP.md @@ -13,24 +13,24 @@ The crate provides an engine without egui, an egui 0.37 chart widget, and termin - [x] Candles, OHLC bars, hollow candles and volume candles, with configurable rising and falling colours. Hollow and volume candles keep independent body, border and wick visibility and rising/falling colours, which persist in layouts and undo; series settings show and change the hollow and volume candle colours, and layouts saved before hollow or volume candles had these switches restore as they were drawn; volume candles and OHLC bars can also compare each close with the previous close. Added candle series accept a border width and per-bar body, wick and border colours; borders stay inside the body and default to disabled, on added volume candles too, while added hollow candles keep a 1.5 point border and take a positive width. The main series' last price line, its label and `series_last_value` of columns, hollow candles, and candles, volume candles and OHLC bars coloured by the previous close, take the direction of the last candle; added series compare the last bar's close with its open. Hollow and volume candles also take a bar's own body, border and wick colours. Candles, OHLC bars and volume candles that close at their open use rising colours, matching their last price line and label; volume bars, their tags and hover readout borders use the same direction rule. - [x] Line, line with markers, step line, area, HLC area, baseline, columns and high-low charts; line and area charts accept a `PriceSource`, and the Columns chart keeps its own for the price each column reaches. High-low charts draw every bar in one colour and print each bar's high and low once zoomed in far enough to fit them, with independent label visibility, colour and size that persist in layouts and undo, and labels in the price scale's text colour until a colour is chosen and at 1 to 256 points; layouts and chart settings templates saved before these controls restore without labels. Added high-low series tag their last value and draw their price line in their bar colour. Added column series apply their configured hit tolerance around their painted bounds, including flat bodies, dense bars and single-point histories; zero uses the body bounds and all hits stay inside the plot. Baseline fills accept independent colours at the pane edge and the base on each price side, including point overrides, while older settings keep flat fills. Area and baseline plots support point markers with independent radii for main and added series. Added series retain their own curved and patterned lines, OHLC open-tick visibility and thin bars, area gradient endpoints, relative gradients and fill inversion. Line-based added series pulse continuously or on last-bar updates on their own pane and scale; expired update pulses stop requesting repaints. - [x] Main-series conflation has a configurable physical-pixel threshold or can be disabled. `Chart::prepare_conflation` prepares the shared render cache before a dense view; groups retain price extremes, gaps and per-bar colours and refresh after data, price-source or grouping changes. -- [x] Heikin-Ashi, Renko, Kagi, line break, point and figure, and range-bar transformations and rendering. Heikin-Ashi retains independent body, border and wick visibility and rising/falling colours; Symbol settings also select original-only scale prices or the default pair of original and transformed closes, and series settings show and change the same colours. These choices persist in layouts and undo; layouts saved before them restore with the original close alone. -- [x] Renko box sizing and wicks, line-break lookback, and price-based chart parameters are configurable. +- [x] Heikin-Ashi, Renko, Kagi, line break, point and figure, and range-bar transformations and rendering. Heikin-Ashi retains independent body, border and wick visibility and rising/falling colours; Symbol settings also select original-only scale prices or the default pair of original and transformed closes, and series settings show and change the same colours. These choices persist in layouts and undo; layouts saved before them restore with the original close alone. The time-independent types hide volume, with the volume study's price-axis tag and tooltip rows, and their automatic scale keeps the last price line and label in view while the newest element is shown. +- [x] Renko box sizing and wicks, line-break lookback, and price-based chart parameters are configurable. Renko bricks and range bars complete on the close or trade that reaches their size for decimal sizes such as 0.1, 0.05 and 0.01, and their prices are counted in sizes instead of added up. ATR and percentage sizes resolve once from the loaded history and keep their value while bars stream in, when chart settings are applied without editing their method and while the replay cursor moves; until enough history is loaded the chart names the bars it waits for, and other settings still apply. - [x] Market Profile (TPO) uses exchange sessions or calendar days, with letters in their blocks by default or plain blocks, initial balance, point of control, value area and composite profiles; autoscale fits the full displayed distributions and cropped profiles retain their session and central-level readouts. POC, value-area and optional midpoint captions keep a gutter at the first or offscreen session opening, separate nearby levels and reveal their prices on hover. - [x] Volume Footprint and Session Volume Profile aggregate supplied executions on time, tick, volume, range and delta intervals with an instrument tick size; bars without complete retained executions use candles. Session profiles require `studies`, divide the chart by the chart's hours, the instrument's regular or extended hours, or a daily window of their own in any zone, and group executions into a row count or whole ticks per row; autoscale includes their full price rows after range edits, and manual crops retain session and POC/value-area readouts. Hosts can restrict the chart type menu and favourite strip to declared historical or live executions for the resolved instrument; unavailable favourites stay saved. - [ ] Leave bars outside the chosen session hours out of session volume profiles instead of joining them to the session before. -- [x] Kagi lines change thickness at the shoulder or waist they cross within a continuing leg. +- [x] Kagi lines change thickness at the shoulder or waist they cross within a continuing leg. The first line starts at the first close and takes the direction of the first move beyond the reversal amount, up or down. - [x] Point and figure charts take a high/low or close-only source from chart parameters and settings. -- [x] Range charts build their bars from the supplied executions, falling back to the OHLC approximation while the chart holds none; `Chart::range_bar_source` reports which one is shown. +- [x] Range charts build their bars from the supplied executions, after the OHLC approximation of the bars before the one holding the first held trade, and fall back to the approximation alone while the chart holds none; replay follows the same rule at its cursor, and `Chart::range_bar_source` reports which one is shown. The approximation takes each bar from its open to the extreme nearer the open, then to the other extreme and to the close, and a range bar closes at its high when a rise completes it and at its low when a fall does. Each range bar is drawn over its whole range, from its low to its high. - [x] Volume candle bodies scale with their share of the largest visible volume, narrowing to the wick width at zero volume. -- [x] HLC area charts draw high, low and close lines with their own colour, width and style, and two fills with their own colour and opacity, which a palette colour keeps; high line, low line and each fill can be hidden. The settings persist in layouts and undo, and layouts and chart templates saved with the former fill opacity and close line width restore as they were drawn. Kagi stroke widths are exposed in the settings. +- [x] HLC area charts draw high, low and close lines with their own colour, width and style, and two fills with their own colour and opacity, which a palette colour keeps; high line, low line and each fill can be hidden. The close line follows the bar closes whatever price source the line and area types plot. The settings persist in layouts and undo, and layouts and chart templates saved with the former fill opacity and close line width restore as they were drawn. Kagi stroke widths are exposed in the settings. - [x] TPO profiles can show a statistics table below them with the point of control, value area, initial balance range, TPO counts below and above the point of control, rotation factor and range extension, switched by one setting on the chart type and the study. - [x] TPO single-print highlights and the midpoint caption and marker are off by default and switch on from the chart's settings or the study's inputs. Charts and studies saved before the midpoint had a setting restore with it shown. ### Pan, Zoom and Cursor -- [x] Cursor-centred wheel zoom, horizontal pan, drag pan, touch pan and pinch zoom. Plain dragging remains available after a drawing selection is released or its pane is removed. Rolling the wheel away zooms in on time and price axes; rolling it toward zooms out, including Ctrl/Command wheel and trackpad scrolling, while axis drags, Shift+wheel pan and pinches retain their directions. Scroll and scale gesture groups can be disabled independently without changing their individual permissions; disabling scrolling stops its momentum, and the scale switch also covers axis drags and resets in every pane. -- [x] Touch drags can start kinetic scrolling with configurable damping. -- [x] Axis drag scaling, double-click reset, box zoom and optional chart-owned navigation buttons. Fit content includes every loaded bar series across panes, including hidden series and whitespace, reserves the configured bar or pixel right margin, and respects spacing limits. An empty main series uses the union of added-series timestamps for its horizontal mapping. Live updates preserve the view on valued bars; filling a whitespace tail in its own slot follows only when both shift options are enabled and the view is near the live edge. Removing a whitespace tail through a pop, data replacement or replay seek keeps the right offset and any pending start index. Appended bars retain their new-bar follow policy. Bars arriving between frames, older or newer and in any number, on a chart type that rebuilds its bars or on a chart without main bars, keep a following view at its live edge, including with a fixed right edge, and a scrolled-back view on its bars. +- [x] Cursor-centred wheel zoom, horizontal pan, drag pan, touch pan and pinch zoom. A pinch zooms around the midpoint between the fingers and follows its movement, so the bars under both fingers stay under them. Plain dragging remains available after a drawing selection is released or its pane is removed. Rolling the wheel away zooms in on time and price axes; rolling it toward zooms out, including Ctrl/Command wheel and trackpad scrolling, while axis drags, Shift+wheel pan and pinches retain their directions. Over the price axis of the main series, of a study pane or of an added series the wheel zooms that scale alone, around the pointer. Scroll and scale gesture groups can be disabled independently without changing their individual permissions; disabling scrolling stops its momentum, and the scale switch also covers axis drags and resets in every pane. +- [x] Touch drags can start kinetic scrolling with configurable damping. A drag that came to rest before its release stays where it was dropped. A press, a touch, the wheel and the pan and zoom keys stop the scrolling. With the default options a flick continues at the speed of the drag, up to 3000 points per second, and settles in under two seconds. +- [x] Axis drag scaling, double-click reset, box zoom and optional chart-owned navigation buttons, which the demo shows while the pointer is over a chart. Every price axis zooms around the price where its drag began and returns to automatic scaling on a double-click. A time-axis drag zooms around the bar that was pressed by its whole movement, whatever frames it spans, and coming back restores the view. Fit content includes every loaded bar series across panes, including hidden series and whitespace, reserves the configured bar or pixel right margin, and respects spacing limits. An empty main series uses the union of added-series timestamps for its horizontal mapping. Live updates preserve the view on valued bars; filling a whitespace tail in its own slot follows only when both shift options are enabled and the view is near the live edge. Removing a whitespace tail through a pop, data replacement or replay seek keeps the right offset and any pending start index. Appended bars retain their new-bar follow policy. Bars arriving between frames, older or newer and in any number, on a chart type that rebuilds its bars or on a chart without main bars, keep a following view at its live edge, including with a fixed right edge, and a scrolled-back view on its bars. Consecutive view movements by key or navigation button are one undo step, which restores the view from before them, and leave redo available. - [x] Programmatic crosshair positions target a bar series in its own price units, scale and pane, with labels in their target axis columns on either side, pointer precedence and matching image exports. A hidden target keeps the time guide in every pane and restores its saved price readout when shown. Invalid positions and removed targets clear the crosshair. Positions set from code persist inside layouts with crosshair synchronization on or off, and return after a linked pointer leaves. - [x] Cross, dot and arrow cursor modes, styled crosshair lines, price/time labels and OHLC snapping. One-point dots in axis-aligned lines and dotted construction guides cover at least one device pixel in each direction at every scale, faded by their device width when thinner than one device pixel. Both lines and both axis labels have independent visibility switches; saved options without label switches inherit each label's line switch; hidden mode suppresses every crosshair element. Independent time-scale filters exclude whitespace and hidden-only values from crosshair indices without removing stored data; visible series and study values keep their slots eligible. Line-based main and added series accept independent crosshair marker radii, fills, border colours and border widths, including on independent scales and in separate panes. Markers start hidden; enabling them without colour overrides keeps the point's line colour and a ring in the background at the marker or the secondary pane's fill. Added-series crosshair markers avoid allocating chart parameters on hovered frames. - [x] Main-pane crosshair snapping includes visible studies and added series on their own scales for time-based charts. Close-only snapping compares visible main and added-series closes on every chart type, preferring the main series and then added-series draw order on equal screen distances. @@ -47,11 +47,11 @@ The crate provides an engine without egui, an egui 0.37 chart widget, and termin - [x] Linear numeric horizontal scales for strikes and maturities use actual sample keys without placeholder bars; series, panes, ticks and cursor conversions share their positions. Time charts retain ordinal spacing. Custom horizontal domains accept categorical and structured host keys ordered by their type, with shared formatting, typed lookup and annotation placement; unknown keys are rejected and repeated keys update one slot. Drawing anchors and their saved coordinates follow keys on custom and numeric axes, including whitespace, regardless of the chart timeframe. Numeric and custom-key domains retain their initial spacing unit across updates, preserving pixel distances per key and the keys in a scrolled-back view, including historical insertions and added-series domains. Numeric bar bodies are capped by the closest neighbouring keys in view at the configured candle-width ratio, for main and added series. Volume and automatic study bars also fit these gaps, keeping their own width ratios. - [x] Chart-wide time, price, percentage and volume formatters, plus per-series price formatters. Saved series styles declare price, abbreviated volume or raw percentage display with precision and minimum movement, independently of scale transforms. Their prices retain the chart's thousands grouping and their changes retain built-in signs; host formatter text stays as supplied. Logarithmic volume ticks retain their lower decades without changing linear abbreviated-unit spacing. Explicit series and chart price formatters take precedence; a shared axis takes tick settings from its first visible series, and each series retains its own tags and readouts. Price and percentage tick hooks receive the complete ordered list for each axis in its displayed units, including edge ticks; main and independent series axes measure their width from that same list, while crosshair and price tags keep individual-value formatting. Time tick hooks receive the current locale and display-time context and can defer individual ticks to the normal locale-aware text without changing crosshair formatting. Drawing prices and price changes use their pane's raw-price formatter, including measurements, forecasts, projections, position levels and rectangle heights. Position axis tags in separate series panes follow the owning series' formatter and display grid. - [x] Locale-aware date names and configurable date patterns. Forecast dates use the chart's display time zone and crosshair time formatter, including host formatting and clock visibility. -- [x] Chart-owned panes share the time axis and support resizing, reordering, stretch sizing, collapse and maximise controls. Ctrl/Command plus double-click collapses or restores the pointed pane, including its header, and preserves sizing, focus, undo and saved layouts; outside every pane it stays an ordinary double-click. With the price pane collapsed, the other panes fill the chart and keep dragging, scrolling and pinching the time scale. Removing any pane, including the original price pane, deletes its members and annotations while preserving surviving panes and their horizontal mapping; the final pane is kept. Pane menus disable removal and merging when a contained study disallows user editing, and their member controls keep read-only studies in place, including on the price pane. Host pane operations remain available. Snapshots preserve layouts without the original pane; the main series stays out of such a layout while its bars keep arriving from the host or the feed for the studies and the time axis. +- [x] Chart-owned panes share the time axis and support resizing, reordering, stretch sizing, collapse and maximise controls. Ctrl/Command plus double-click collapses or restores the pointed pane, including its header, and preserves sizing, focus, undo and saved layouts; outside every pane it stays an ordinary double-click. Dragging, scrolling and pinching over the plot of any pane move the shared time scale as over the price pane. With the price pane collapsed, the other panes fill the chart and keep that navigation. Removing any pane, including the original price pane, deletes its members and annotations while preserving surviving panes and their horizontal mapping; the final pane is kept. Pane menus disable removal and merging when a contained study disallows user editing, and their member controls keep read-only studies in place, including on the price pane. Host pane operations remain available. Snapshots preserve layouts without the original pane; the main series stays out of such a layout while its bars keep arriving from the host or the feed for the studies and the time axis. - [x] Main and added series and studies can move between panes. The main series retains its data, horizontal mapping, price scale, annotations and pointer readouts in its destination; snapshots and undo preserve placement. Studies and added series can use separate panes and independent scales. Named left, right, additional and hidden overlay assignments share options and ranges only within their pane; painting, axis controls, hit tests and coordinate queries follow those assignments after pane moves, and snapshots retain each pane's named scales. The demo menu's Samples entries open synthetic strike and maturity charts with numeric crosshair readouts and preserve the price workspace on return. -- [x] Pane-local axis enumeration and commands place every labelled scale at either edge or join their sources onto one scale while retaining raw values and series formatting. Unused axes hide by default and return when a source becomes visible; the policy and layout survive saving and undo. Axis and plot menus expose these controls in the library and demo, and chart settings edit the main series' pane. +- [x] Pane-local axis enumeration and commands place every labelled scale at either edge or join their sources onto one scale while retaining raw values and series formatting. Unused axes hide by default and return when a source becomes visible; the policy and layout survive saving and undo. Axis and plot menus expose these controls in the library and demo, and chart settings edit the main series' pane. One price-scale menu serves every price axis: a study pane's axis opens it with the rows of its own scale, and a touch held on the main price axis, a study pane's axis, an added series' axis or the time axis opens that axis' menu as a secondary click does. - [x] Scale settings control currency and unit labels, scale-mode and price-action buttons, price-to-bar ratio, label overlap and symbol, study and extended-session value colours. The demo menu converts synthetic USD prices to US cents through the host feed contract, including history, executions and book prices, and keeps the unit through replay and saved layouts. -- [ ] Maximise the pane holding the main series by double-click, as study panes do. +- [x] A double-click on the plot of the pane holding the main series maximises or restores it, as on study panes, while a double-click that finishes or selects a drawing or lands on a series, an axis or the status line keeps its own effect. - [ ] Study moves into new panes still append at the bottom; directional creation immediately above or below the current pane remains incomplete. - [x] The Scale Price Chart Only setting keeps overlay studies and their primitives out of the main price scale's autoscale range, and the left-axis scale mode applies when the main scale is drawn on the left axis alone. - [x] Added-series value tags and last-value queries use configured scale precision when no formatter is supplied, otherwise the nearest tick label's decimals with at least two; saved numeric display declarations also control their tags and readouts. @@ -72,10 +72,10 @@ The crate provides an engine without egui, an egui 0.37 chart widget, and termin - [x] Elliott impulse, correction, triangle and combination drawings render labelled waves. - [x] Cyclic lines, repeating time cycles and sine lines. - [x] Long/short position drawings expose entry, stop, target, instrument-aware risk sizing and bar-based profit/loss, with selection-only or persistent statistics, condensed tags, account-currency conversion supplied by the host, quantity precision and undoable direction reversal from the drawing menu and selection toolbar, and their own line colour and width, label text, plates, zone fill, per-zone opacity and border; forecasts, copied bars and three-anchor measured projections. -- [x] Anchored VWAP with green, olive and teal deviation bands whose colours can be changed, the first on and lightly filled, and a handle on the first plotted value even across zero-volume bars or an anchor before loaded history; fixed and anchored volume-profile drawings read complete executions or finer bars where the chart holds them and otherwise estimate distributions from chart bars, and start with cyan and pink up/down rows over a faint tint, more opaque inside the value area, under one point of control line across the range or, when anchored, the pane. Their handles sit at the top of the range or on the point of control, and a fixed range can extend right from the earlier anchor in either placement order, including its finer-history request. +- [x] Anchored VWAP of a chosen bar price (typical price by default) with green, olive and teal bands whose colours can be changed, measured in standard deviations or percent of the VWAP, the first on and lightly filled in a colour and opacity of its own, an optional background from the anchor, a line that can be hidden or drawn as another plot type, an optional dotted latest-value line with a price tag at a chosen precision, and a handle on the first plotted value even across zero-volume bars or an anchor before loaded history; fixed and anchored volume-profile drawings read complete executions or finer bars where the chart holds them and otherwise estimate distributions from chart bars, and start with cyan and pink up/down rows over a faint tint, more opaque inside the value area, under one point of control line across the range or, when anchored, the pane. Their handles sit at the top of the range or on the point of control, and a fixed range can extend right from the earlier anchor in either placement order, including its finer-history request. - [x] Price, date and combined range measurements use actual bar timestamps; quick measure also reports volume and instrument ticks/pips when supplied. - [x] Brush, highlighter, arrows, rectangles, rotated rectangles, circles, ellipses, triangles, arcs, sectors, polylines, paths and quadratic/cubic curves. Curved outlines and analysis arcs adapt to physical pixels and refine only near the view; freehand strokes interpolate their samples with centripetal Catmull-Rom curves, with matching selection outlines, and a brush can fill the area its stroke encloses. Rectangles, circles and ellipses write a note at their centre in its own colour, size, weight and slant; a selected one shows its text field on the chart, and a click there edits the note in place. -- [x] Editable text, notes, callouts, price labels, comments, signposts and tables with persistent cell contents. Callout borders use their configured width and pattern. Text, anchored text and callout text can wrap at a set width, and text and anchored text can grow and shrink with the zoom instead of keeping their size. A price label sets the text, background and border colours of its badge with their opacity, and a price note styles its price label and its typed text apart: each has a colour, a size, bold and italic. Text, notes, price labels, comments, signposts, flags and tables offer no line width or pattern and keep drawing any pattern saved on them. +- [x] Editable text, notes, callouts, price labels, comments, signposts and tables with persistent cell contents. Callout borders use their configured width and pattern. Text, anchored text and callout text can wrap at a set width, and text and anchored text can grow and shrink with the zoom instead of keeping their size. A price label sets the text, background and border colours of its badge with their opacity, and a price note styles its price label and its typed text apart: each has a colour, a size, bold and italic. Text, notes, pins, price labels, comments, signposts, flags and tables offer no line width or pattern; a pattern saved on one still draws on its border or leader line, which a pin shows only while selected. - [x] Image annotations load an address through application-installed egui image loaders; local post and idea cards store editable supplied content. - [x] Searchable bundled icons, emoji and stickers with size controls and recent selections. - [x] Fibonacci retracement and extension fills share their level lines' horizontal span; their labels default to the height of the lines and show only for levels inside the price pane, including its boundaries. Channel levels can extend to the pane edges. Each Fibonacci tool with levels starts from a table for its geometry; the retracement, extension, channel, wedge and trend-based time tables list further ratios hidden, and circle, arc and wedge backgrounds fill to the centre. Retracements and extensions configure each level's width and custom text, label and text alignment, font size and construction-line visibility; their text edits directly on the chart and survives templates, cancellation, history and restoration. Channels expose label size, horizontal and vertical placement and shared level width. Wedges keep each arc's width and pattern and can hide their radial construction edges; both families preserve levels through preview, cancellation, templates, history and saved files. Time zones and trend-based time projections configure each level's width and pattern, label size, horizontal and vertical alignment and construction-line visibility; projection lines remain selectable in either anchor direction. Circles and resistance arcs configure each level's width and pattern, label size and construction-line visibility. Resistance arcs can close into full circles with matching fills and labels; spirals configure direction, line width and pattern. Circles, arcs and spirals share the same preview, cancellation, templates, history and restoration. Speed resistance fans keep separate price and time levels, draw their grid in its own colour, width and pattern or hide it, label each side of their box independently and can be mirrored vertically; hosts change these settings in one undoable edit. @@ -91,8 +91,8 @@ The crate provides an engine without egui, an egui 0.37 chart widget, and termin - [x] Fixed-point placement keeps clicked anchors; free paths finish with Enter or double-click. - [x] Selection uses rendered strokes, fills and text, with geometry and anchor fallbacks before painting. A click on a drawing selects it alone, clearing a selected series or study in every pane. Ctrl/Command-drag on empty pane space adds drawings intersecting the selection area, including locked drawings for inspection; editing still honours locks. The area follows its pane across layout changes and ends on release even if the pane disappears. The preview and released selection use current drawing geometry while live updates move the view. Escape cancels the area gesture. -- [x] Anchor handles, dragging, OHLC/study/drawing magnet snapping, repeated placement, locking and visibility controls. Both magnet strengths include visible study plots on their rendered scales, in whichever pane holds the main series, and leave out the bars and volume of a hidden main series; disabling study snapping leaves bar and drawing targets available. The aggregate hide control follows the active chart and toggles supported groups together. -- [x] Undoable drawing creation, edits, deletion, ordering, flat groups and moves between panes. Bulk removal asks before including locked drawings, can remember either choice, and restores drawings and editable studies together in one undo step. +- [x] Anchor handles, dragging, OHLC/study/drawing magnet snapping, repeated placement, locking and visibility controls. Both magnet strengths include visible study plots on their rendered scales, in whichever pane holds the main series, and leave out the bars and volume of a hidden main series; disabling study snapping leaves bar and drawing targets available. The aggregate hide control follows the active chart and toggles supported groups together. The hide shortcut, like the toolbar entry, hides every drawing unless all are already hidden; hiding a drawing in any way deselects it. +- [x] Undoable drawing creation, edits, deletion, ordering, flat groups and moves between panes. Bulk removal asks before including locked drawings, can remember either choice, and restores drawings and editable studies together in one undo step. Undo and redo do nothing while a drawing is dragged, and the drag records one step when it ends. - [x] Properties edit style, tool inputs, text, timeframe visibility and validated price/time coordinates. Each measurement switch, placement and text alignment changes independently across a selection, preserving the other settings on each drawing. A hue-only recolour preserves each selected drawing's opacity and the palette's exact RGB values; an edited opacity applies to all selected drawings, each keeping its hue when the custom editor changes only the opacity of an opaque colour. Other selected drawings accept fill edits only when they support a fill. Drawing menus and the selected toolbar offer current, higher, lower and all-interval visibility filters, with undo and saved templates. Time intervals compare by duration; trade intervals compare within their own unit. - [x] Public timestamp-based creation and anchor editing, drawing enumeration, per-tool defaults and custom drawing registration. Creation uses each tool's style before saved overrides: arcs and polylines start with a 20% tint, price ranges and quick measure with a 15% tint, anchored VWAP at 1 px, and pitchfans with individual level colours. The terminal toolbar retints a new shape's matching fill with its chosen line colour at the fill's own opacity, preserving independent fills and other saved style settings. A pin's popup is a card in the theme's colours, tied to the pin by a thin line; a table draws its grid and border in the drawing colour; and the default colours of box borders and table grids take a shade that keeps 4:1 on the theme. - [x] Per-drawing selection, saving and object-list flags; drawing change notifications and registry availability controls. @@ -108,20 +108,21 @@ The crate provides an engine without egui, an egui 0.37 chart widget, and termin ### Calculations and Rendering -- [x] `IndicatorFactory` registers 204 indicators with default features and accepts downstream registrations; the study picker groups its built-in results on Indicators, Profiles, Patterns and Order flow pages, each offered only while it has an accepted study. Hosts can restrict Order flow entries, including search and favourites, to the feed services each study's inputs read; requirements are cached when feed metadata or the factory changes. Other categories keep their existing availability. The chooser has a 200-point sidebar, a fixed name header and favourite stars on hovered, focused or starred rows whose focus follows the study through reordering and whose labels and tooltips name the translated study; its light preset uses separate muted inks for section labels, the header and search hints. +- [x] `IndicatorFactory` registers 205 indicators with default features and accepts downstream registrations; the study picker groups its built-in results on Indicators, Profiles, Patterns and Order flow pages, each offered only while it has an accepted study. Hosts can restrict Order flow entries, including search and favourites, to the feed services each study's inputs read; requirements are cached when feed metadata or the factory changes. Other categories keep their existing availability. The chooser has a 200-point sidebar, a fixed name header and favourite stars on hovered, focused or starred rows whose focus follows the study through reordering and whose labels and tooltips name the translated study; its light preset uses separate muted inks for section labels, the header and search hints. - [x] Host-backed options profiles offer their help article in the legend and study menu and appear on Profiles for declared option-chain feeds, with nearest or listed expiries and inclusive date cutoffs, separate volume and open-interest measures, split or net sides, put/call readouts and an optional multiplier-weighted max-pain level. Missing contract fields hide the inputs that need them; saved measures and levels wait until those fields arrive. Saved profiles restore expiry and measure by label while keeping explicit editor changes and resets, with Nearest for an expiry no longer listed. Gamma exposure uses the selected chain rows or the feed's supplied snapshot, with signed net bars from zero by default, separate call and put bars, optional call and put walls that omit sides with no exposure, and zero gamma only from the provider. Legends and strike hover show units, the sign convention and snapshot time; every snapshot replaces the bars and levels. Expected move is off by default and draws a labelled expiry band from the nearest-strike straddle mids or ATM implied volatility with calendar-day scaling; missing inputs and expired dates remove the band. Historical chains use their requested observation instant and the latest fallback close known then, using the next bar opening as its close boundary and the final bar from its own opening. Hidden profiles retain their computed values for cursor payloads and alerts while omitting their chart geometry. - [x] Moving-average families include SMA, EMA, WMA, HMA, ALMA, KAMA and configurable combinations, ribbons and crossing markers. - [x] Momentum and trend studies include RSI, MACD, Stochastic, ADX, SuperTrend, Ichimoku and Parabolic SAR. RSI opens with a middle level and an RSI-based moving average. RSI, Williams %R and Rank Correlation offer the same smoothing inputs: a type of none, SMA, SMA with Bollinger bands, EMA, SMMA (RMA), WMA or VWMA, a length, and a band deviation that shows only for the band type. Rank Correlation opens with a lookback of 10, a 14-bar SMA of the index, and levels at +80, 0 and -80 with the band between the outer two filled. DPO and Know Sure Thing draw a dashed zero guide with editable colour, style, width, visibility and latest value line; a KST saved before its guide restores with it hidden. -- [x] Volatility and channel studies include Bollinger Bands, ATR, Keltner, Donchian and historical volatility. Bollinger Bands, Envelopes and Keltner expose source and band inputs, independent plot value lines and a band visibility switch that retains its colour and opacity even when boundary plots are hidden. Preview, cancellation, history and saved templates retain these settings; Keltner source edits change its basis while its range calculations keep the original bars. Envelopes and Keltner select an exponential basis with a checkbox, off and on respectively by default; older saved average choices still load. Donchian fills the area between its outer bands with a faint blue by default; applied settings retain the band colour, opacity and visibility separately from its plot styles and latest-value lines. Median takes a source for its rolling median, the bar midpoint by default, while its ATR bands keep the original bars. -- [x] Volume studies include OBV, MFI, accumulation/distribution and VWAP; VWAP supports calendar/session and supplied event anchors with deviation or percentage bands, and opens with one filled band at one standard deviation. +- [x] Volatility and channel studies include Bollinger Bands, ATR, Keltner, Donchian and historical volatility. Bollinger Bands, Envelopes and Keltner expose source and band inputs, independent plot value lines and a band visibility switch that retains its colour and opacity even when boundary plots are hidden. Preview, cancellation, history and saved templates retain these settings; Keltner source edits change its basis while its range calculations keep the original bars. Envelopes and Keltner select an exponential basis with a checkbox, off and on respectively by default; older saved average choices still load. Donchian fills the area between its outer bands with a faint blue by default; applied settings retain the band colour, opacity and visibility separately from its plot styles and latest-value lines. Median takes a source for its rolling median, the bar midpoint by default, while its ATR bands keep the original bars. Close-to-close, Garman-Klass and zero-trend volatility are listed with historical volatility and take the trading days per year they are annualized over, 252 by default, so older saved studies keep their values. +- [x] Volume studies include OBV, MFI, accumulation/distribution and VWAP; VWAP supports calendar/session and supplied event anchors with deviation or percentage bands, opens with one filled band at one standard deviation and can be hidden on daily and longer intervals. VWAP Auto Anchored draws three band pairs at one, two and three times a multiple of the deviation or of one percent of the VWAP, the first shown and filled. - [x] Visible, fixed, session, periodic, anchored and auto-anchored volume profiles sum supplied executions in whole-tick rows, mark incomplete spans and fall back to finer-bar or chart-bar estimates, with translucent cyan and pink rows that keep candles readable and stay stronger in the value area, session and periodic rows sized by a Width input of 30% of their span by default, and a 2 px point of control in the foreground colour across each profile's span, or across the whole plot for the visible range. Selection follows painted rows and guides. Session and periodic studies optionally carry each finished profile's POC, VAH and VAL to the first later bar trading in its row of the profile, or on the line for the VAH, including profiles left of the view; forming and partial execution profiles carry no levels. - [x] Regression, rank correlation, pivot levels, ZigZag, candlestick patterns, seasonality and market-structure studies. Daily-based pivots load the complete period preceding their oldest retained levels, including yearly and multi-year groups, from paged host history. -- [x] Majority Rule reports +1, -1 or zero from the majority of rising versus falling closes over its lookback. +- [x] Negative and Positive Volume Index studies start at 1000, move by the close's percentage change on bars whose volume fell or rose, and draw a signal EMA whose length is an editable input, 255 by default. +- [x] Majority Rule reports the percentage of rising closes over its lookback by default, or +1, -1 or zero from the majority of rising versus falling closes when the output is set to direction. - [x] Higher Interval Candles aggregate chart bars into the interval that follows the chart's by default: two hours below one minute when the chart interval divides two hours, one day below one day, one week below one week, one month below one month, three months below three months and twelve months from there on. Turning the automatic interval off uses a chosen longer interval, and bars longer than a day join the period they open in. - [x] Automatic trend-line, channel, Fibonacci and pitchfork studies use ZigZag pivots with the `drawings` feature. Automatic Fibonacci drawings use the same initial level palette, visible ratios, spare levels and band opacity as manually placed drawings. Automatic pitchfork backgrounds have a saved transparency percentage, from opaque to clear, starting at 85%. - [x] Shared renderers support lines, steps, histograms, columns, dots, crosses, areas, shapes, bar/background colours and filled regions. - [x] MACD histogram columns, displaced Ichimoku cloud fills into visible future space, and separate Parabolic SAR crosses. -- [x] RSI reads 100 with no losses, 0 with no gains and 50 on flat prices at any price size, and its divergence and stochastic studies use the same values. +- [x] RSI reads 100 with no losses, 0 with no gains and 50 on flat prices at any price size, and its divergence and stochastic studies use the same values. Its Calculate divergence input marks the regular bullish and bearish divergences between its swings and the highs and lows of price. - [x] Connors RSI's price and streak components use Wilder smoothing and read 100 on gains alone. Its pane opens with dashed guides at 70, 30 and a faint 50, and a light blue fill tied to the outer guides even when the middle guide moves past them. Applied settings independently edit guide values, colours, patterns, widths and visibility, fill colour and opacity, and the latest-value line; snapshots and saved templates retain them. - [x] Both Tasuki Gap detectors need the third candle to open inside the second body and close inside the gap. - [x] Woodies CCI reads the close, with separate neutral, transition and established histogram colours. @@ -130,11 +131,11 @@ The crate provides an engine without egui, an egui 0.37 chart widget, and termin - [x] Bollinger Bands select their basis average, and BandWidth has expansion and contraction lookbacks. - [x] VWAP band multipliers and event dates are editable in applied-study settings. - [x] Request finer profile data, from a feed's suggestion or a chosen interval, and adapt session profile rows to the zoom. -- [x] Spread, Ratio and Correlation Coefficient read their second symbol from the host; correlation also offers log returns. +- [x] Spread, Ratio and Correlation Coefficient read their second symbol from the host; correlation also offers log returns. Correlation Coefficient opens as an area with dashed guides at 1, -1 and zero, each with editable visibility, value, colour, style, width and latest value line; one saved as a line with the zero guide alone restores that way, with the guides at its bounds hidden. - [ ] Add a dedicated log-return correlation study. - [x] Trend Strength Index plots the rolling correlation of price with bar position. - [x] Automatic chart-pattern, wedge and key-level detection studies. -- [x] Composite technical ratings and lunar phases. +- [x] Composite technical ratings, rated on both groups or one, with higher-interval rows and a placed, sized and coloured table, and lunar phases. - [ ] Add a dedicated volatility-index study. - [x] ADX-breakout, divergence, key-reversal, intraday and missed-pivot studies. - [ ] Add the remaining specialised reversal and ghost-pivot studies. @@ -166,14 +167,14 @@ Execution-based calculations use supplied trades and their aggressor side. Unkno - [x] `Footprint` aggregates bid, ask and unknown volume and execution counts by time or trade-based bar and integer tick row, with execution-size filtering against original fills. Grouped rows add their counts and average size divides total volume by executions, including unknown sides; empty rows and bars have no average. Volume and delta thresholds split fills exactly, counting a contributing execution once per bar, equal exchange timestamps retain separate bars, and interval changes rebuild from retained executions. - [x] Footprint cells support a default ladder with the sell column left and the buy column right of a narrow candle body, plus bid/ask, total volume, delta, delta-plus-volume, sell/buy execution counts, total executions and average execution size modes, up to four columns per bar, profile or boxed rendering, automatic or fixed-tick row grouping and opening/closing price ticks in a separate gutter; their values have clearance from underlying price guides, and grouped rows fit within autoscale for feed-backed and host-supplied footprints while they are drawn as cells (fixed rows, or automatic rows with a tick minimum, whichever group zoom selects in a plot with room for more than two such rows), with room for the summary below the lowest row; bars drawn as candles keep the candle fit. The statistics table offers Trades and Average size rows. - [x] Per-bar point of control, value area and horizontal/diagonal imbalance highlighting, with one inclusive minimum dominant-side volume for cells and stacked zones after row grouping; compact values fit detail columns and POC outlines recede in the overview. By default sell and buy cells shade separately in four volume steps mixed with the background the chart paints, the POC row is filled, the value area is two dotted lines, imbalanced sides get an edge strip, and each ladder bar writes its sell and buy totals with a delta and total volume box, as values alone where its labels do not fit, with room left below the lowest bar when the price scale fits. -- [x] Public calculations and renderers expose stacked diagonal imbalance zones, unrevisited POC levels, volume clusters and per-bar statistics; annotation captions avoid footprint values, with compact overview marks and hover details. Statistics use selectable rows with shared labels, aligned compact values, explicit percentages and ratios, and a zoom-in or resize notice when detail cannot fit. Both Symbol dialogs expose footprint display, rows, levels, imbalances, annotations, numbers and statistics, plus execution-profile display, value area, developing POC and volume nodes. These settings save, restore and undo with the chart; footprint colours follow the theme until selected. +- [x] Public calculations and renderers expose stacked diagonal imbalance zones, unrevisited POC levels, volume clusters and per-bar statistics; annotation captions avoid footprint values, with compact overview marks and hover details. Statistics use selectable rows with shared labels, aligned compact values, explicit percentages and ratios, and a zoom-in or resize notice when detail cannot fit; the rows include buy and sell volume as shares of the bar's volume, the bar's range, its point of control and the change of volume from the previous bar, and the cumulative delta can restart with each session. Both Symbol dialogs expose footprint display, rows, levels, imbalances, annotations, numbers and statistics, plus execution-profile display, value area, developing POC and volume nodes. These settings save, restore and undo with the chart; footprint colours follow the theme until selected. - [x] Execution-based delta histograms and cumulative-delta candles, including intrabar extremes and configurable reset boundaries, render in a supplied pane mapping. The cumulative execution study offers optional confirmed divergence and exhaustion price markers, with study outputs for bar-close alerts. - [x] Trade profiles aggregate supplied ranges with bid/ask, volume or delta display, developing POC, value area and local volume nodes; public range editing supports merging and splitting. Symbol settings optionally trace the developing value area and extend each prior-session POC, VAH and VAL to the first later bar trading in its row, including levels from offscreen sessions. Value-area levels use the selected share, and all lines remain consistent after history rebuilds. - [x] Feed-backed footprints keep at most 5,000 bars and 50,000 price rows, dropping the oldest bars first and marking them incomplete, and take out the executions the trade store evicts. - [x] Size-filtered cumulative delta has a study pane with its own scale and lot-precision readouts. - [x] Combined size-range delta labels its inclusive buckets; rolling volume/delta supports histograms. - [x] Delta-percentage and bid/ask-ratio thresholds mark qualifying footprint bars and are available in both Symbol dialogs; `FootprintStudyConfig::min_delta` sets a minimum for the delta POC. -- [x] Footprint cells offer fixed, delta-opacity and imbalance colouring and a dominant-side column, with abbreviated values, zero display and a font size range that scales with row volume, all in both Symbol dialogs. +- [x] Footprint cells offer fixed, delta-opacity and imbalance colouring and a dominant-side column, with abbreviated values, zero display and a font size range that scales with row volume, all in both Symbol dialogs. Imbalance strips, imbalance colouring and stacked imbalance zones take the buy and sell colours, or buy and sell imbalance colours of their own. - [x] Footprint extreme bid/ask-ratio annotations and pullback highlights are available in both Symbol dialogs, off by default. - [x] Imbalance zones can compare at the same price or diagonally, expire after a configurable number of bars through `FootprintStudyConfig::extend_bars`, and report unvisited, revisited or expired state, which the renderer fades and names on hover. - [x] Unfinished highs need sell volume at the bar's highest row and unfinished lows need buy volume at its lowest row; their levels extend until a later bar revisits them or the configured number of bars ends. @@ -242,16 +243,17 @@ Execution-based calculations use supplied trades and their aggressor side. Unkno - [x] Top toolbar with symbol search, comparison, interval/type selection, study, alert, replay, history, settings, save and layout actions. Interval and snapshot section headings use quiet grey ink in light themes and retain the dark palette. - [x] Symbol search supports venue-qualified text and independent type, exchange, country, sector and data-provider filters, pagination, keyboard navigation and host results. Related listings and futures contracts expand and collapse beneath their root, retaining the selected venue and provider in results and saved recents; the terminal loads comparisons from the chart feed on shared percentage scales, separate scales or panes, and displays arithmetic spreads as candles in their own panes. Demo spreads show cached history before execution bootstrap finishes and refresh when their components or display inputs change. -- [x] Timeframe toolbar provides range presets, go-to-date, time zone, regular/extended session and adjustment requests. `Terminal` fits ranges to loaded history, navigates dates in the chart time zone, switches intervals and sessions, restores interval favourites, and requests host-supplied dividend adjustment. +- [x] Timeframe toolbar provides range presets, go-to-date, time zone, regular/extended session and adjustment requests. `Terminal` fits ranges to loaded history, navigates dates in the chart time zone, switches intervals and sessions, restores starred, custom and hidden intervals and starred chart types, and requests host-supplied dividend adjustment. - [x] Drawing toolbar rules follow the shared toolbar palette; selected tools and latched utilities use theme colours in every preset and custom palette. Drawing toolbar categories, cursor modes, snapping, repeated placement, locking and template actions; drawing and cursor favourites appear on the floating strip through `show_floating_with_action`, while `show_floating` offers only drawing tools and hides when none are available. Cursor stars show on hover or keyboard focus. `UserSettings` keeps them in order, omits unknown modes when reading, and starts older documents with no cursor stars; the demo migrates its earlier storage key into that document. A control in the top-left menu hides or restores the left tools; toolbar visibility and locked-removal preferences survive reopening. -- [x] Chart settings apply backgrounds, grids, candle parts and colours, previous-close colouring, crosshair styling, session shading and watermarks. Reset to defaults restores axis text, both grid directions, candle colours and the symbol watermark to the colours of a new chart under the theme the dialog is shown with, and leaves the crosshair following the theme as a new chart does. Demo visibility and order-flow menus follow the active chart through settings, undo and saved layouts; symbol changes select aggregate or individual-order depth sampling from the feed. Feed display options participate in chart undo without changing the book profile's inherited visibility. Axis labels and tags select a chart-local font family; each host watermark line selects its own family while retaining size, weight and alignment. Host text and image watermarks can be assigned and cleared independently per pane, follow pane resizing and ordering, clip to their plot and are dropped with their pane. Named families use fonts installed by the host. Axes use proportional fonts until their family is installed, then use it on the next frame while retaining the saved name. +- [x] Chart settings apply backgrounds, grids, candle parts and colours, previous-close colouring, crosshair styling, session shading and watermarks. A solid or gradient background covers every pane and the time axis as one surface, whether the chart or the layout showing it paints it; the fills behind legend rows and behind the labels of a study's own axis take the colour behind them, and gradient colours that were not picked follow a theme change as the solid colour does. The scale text colour applies to the price and time axes, to the axes and legends of study panes and to the axis of a study on a scale of its own. Reset to defaults restores axis text, both grid directions, candle colours and the symbol watermark to the colours of a new chart under the theme the dialog is shown with, leaves the crosshair following the theme as a new chart does, and restores a new chart's top, bottom and right margins. A palette colour chosen on the Canvas tab keeps the opacity of the colour it replaces. Demo visibility and order-flow menus follow the active chart through settings, undo and saved layouts; symbol changes select aggregate or individual-order depth sampling from the feed. Feed display options participate in chart undo without changing the book profile's inherited visibility. Axis labels and tags select a chart-local font family; each host watermark line selects its own family while retaining size, weight and alignment. Host text and image watermarks can be assigned and cleared independently per pane, follow pane resizing and ordering, clip to their plot and are dropped with their pane. Named families use fonts installed by the host. Axes use proportional fonts until their family is installed, then use it on the next frame while retaining the saved name. - [x] Status settings control supplied logos, last day change and study backdrops; legend text and controls have opaque backing over profiles, and every legend backdrop takes the extended hours shading beneath it; Symbol settings request dividend-adjusted history from the host. Each added-series legend row reveals its remove button on mouse hover or keyboard focus; taps on its hidden control reach the chart without removing the series. Removal affects that series alone, undo restores its data and row position, and reopened layouts use the restored series handles. -- [x] The chart data table follows history corrections, study edits, live study data and studies of the bars in view, with newest rows first. Its symbol control opens host search, the watchlist remains usable, and column choices stay with each chart and its study plots when other studies are added or removed, through symbol changes and restored state. Loading and feed errors appear in the table. +- [x] Chart settings carry five more values of the chart, which are saved with them and copied by Apply to all: the axis font family, chosen next to the font size among the families installed in the context; the thousands separator of price labels (none, comma, space or apostrophe); whether the last price line and label follow the newest bar or the newest bar in view; session breaks, on the Events tab beside the time axis menu entry; and a right margin that shows and takes part of a bar and shows a margin set in pixels as its width in bars. Settings and templates saved before these choices keep the chart's own, and Reset to defaults gives those of a new chart. +- [x] The chart data table follows history corrections, study edits, live study data, added series and studies of the bars in view, with newest rows first. Each visible added series has a column of its closes, titled as its legend shows it and empty where it has no bar at the row's time. Its symbol control opens host search, the watchlist remains usable, and column choices stay with each chart and its study plots when other studies are added or removed, through symbol changes and restored state. Loading and feed errors appear in the table. - [x] Object tree supports selection, filtering, visibility, locks, ordering, rename, duplication, pane moves and bulk actions; a data window shows OHLCV and study values. A list of the layout's drawings by symbol counts each drawing and its linked copies once, including symbols only stored, sorts each symbol by name or last edit in a saved order, and deletes one symbol in one undo, including after the host replaces its layout with a clone. The demo includes every live comparison, spread and separate-pane symbol with visibility, focus, removal and pane-local draw ordering. Its added-series settings edit the selected series appearance, last value, price line and scale as one undoable edit, with cancellation and named-layout persistence. Taking over an added baseline series style retains its rising and falling colours, line width and flat fills until edited. Attaching to an existing axis retains its settings; `Chart::shared_price_scale` reads a main-pane axis even when only studies use it. -- [x] Editable shortcut bindings are shared by chart input, help and menu hints; quick search uses a command palette. Alt plus Ctrl/Command exposes a pointer-price button, even with the axis button hidden; its menu draws a line in the pointed pane and, in the pane of the main series, returns alert and order actions at that price to the host. Other panes read their own scale, so they offer the line alone. The menu retains its original price and pane through layout resizing. Text editors and drawing drags retain their gestures. Hosts can append icon actions and submenus to the fixed top-left toolbar menu, even with its built-in entries hidden. The demo offers its readout, appearance, formatting and populated showcase samples there without adding a row above the chart. Every top-level entry has an icon and aligned label, with toggle checks and submenu arrows at the right, including phone panel actions. Order flow opens from this menu at every width with a footprint icon; the default demo right rail contains the built-in panels and Help. Below 600 points, a Panels entry near the start of the menu keeps the available rail panels reachable in short windows. Its submenu scrolls, choosing the active panel closes it, and resizing preserves one active panel. +- [x] Editable shortcut bindings are shared by chart input, help and menu hints; quick search uses a command palette. The demo's quick search reaches every chart action of its toolbars, menus and shortcuts through the same handlers and shows each row's current binding. Alt plus Ctrl/Command exposes a pointer-price button, even with the axis button hidden; its menu draws a line in the pointed pane and, in the pane of the main series, returns alert and order actions at that price to the host. Other panes read their own scale, so they offer the line alone. The menu retains its original price and pane through layout resizing. Text editors and drawing drags retain their gestures. Hosts can append icon actions and submenus to the fixed top-left toolbar menu, even with its built-in entries hidden. The demo offers its readout, appearance, formatting and populated showcase samples there without adding a row above the chart. Every top-level entry has an icon and aligned label, with toggle checks and submenu arrows at the right, including phone panel actions. Order flow opens from this menu at every width with a footprint icon; the default demo right rail contains the built-in panels and Help. Below 600 points, a Panels entry near the start of the menu keeps the available rail panels reachable in short windows. Its submenu scrolls, choosing the active panel closes it, and resizing preserves one active panel. - [x] Watchlists support named lists, sections, sorting, row reordering, flags, symbol navigation and text import/export. -- [x] Feed-backed panels render symbol details, news, calendars, hotlists, screener tables and grouped market heatmaps; `FinancialsPanel` charts and tabulates supplied financial figures. Demo quotes and symbol details share daily volume totals maintained as data changes. The demo offers Financials only for populated fixtures and opens a company sample from its Samples menu and quick search. -- [ ] Assemble a terminal that owns component state, handles all actions and lets the application intercept them. `Terminal` also runs the widget bar and side panels, persists watchlists, routes panel symbol selections, derives performance and seasonality from chart bars, opens host-fed profile cards, trades through the supplied brokers and docks the account and strategy report. It also handles time controls, comparisons, spread selection and host-supplied dividend adjustment, and runs multi-chart grids, layout tabs, saved layouts, favourites, autosave and Ctrl+S. `Terminal` still returns the replay controls and start picker, quick search, image capture, copy, link and publish, export dialog responses including the layout menu's downloads, non-drawing paste, drawing template actions, the data table, CSV and apply-to-layout chart menu entries, and the quick search, snapshot, help, indicator search, symbol search and open-layout shortcuts. The demo does not use `Terminal` yet. +- [x] Feed-backed panels render symbol details, news, calendars, hotlists, screener tables and grouped market heatmaps; `FinancialsPanel` charts and tabulates the financial figures `Datafeed::financials` supplies, which the terminal opens from symbol details in place of the charts. Demo quotes and symbol details share daily volume totals maintained as data changes. The demo offers Financials only for populated fixtures and opens a company sample from its Samples menu and quick search. +- [ ] Assemble a terminal that owns component state, handles all actions and lets the application intercept them. `Terminal` also runs the widget bar and side panels, persists watchlists, routes panel symbol selections, derives performance and seasonality from chart bars, opens host-fed profile cards, trades through the supplied brokers and docks the account and strategy report. It also handles quick search, keyboard shortcuts, snapshots, chart exports, the loaded-data table, time controls, comparisons, spread selection and host-supplied dividend adjustment, and runs multi-chart grids, layout tabs, saved layouts, favourites, autosave and Ctrl+S. `Terminal` still returns the replay controls and start picker, image link and publish, drawing template actions and the apply-to-layout chart menu entry; hosts add their own quick search entries with `Terminal::add_command`. The demo does not use `Terminal` yet. - [x] Dock the supplied broker account and host strategy report in shared bottom tabs, with collapse, restore and maximise controls. - [ ] Open the study editor and replay-trading surfaces as tabs of the same bottom dock. - [ ] Open the drawing toolbar's colour popup from a visible control, and keep the favourite tools strip in `Terminal` settings. @@ -277,9 +279,9 @@ Execution-based calculations use supplied trades and their aggressor side. Unkno ### Export -- [x] `Chart::export_csv` (the default-enabled `csv` feature) exports OHLCV and study values with timestamps and missing-value handling. +- [x] `Chart::export_csv` (the default-enabled `csv` feature) exports OHLCV, the closes of visible added series and study values with timestamps and missing-value handling. - [x] `Chart::export_png` (the default-enabled `png-export` feature) renders an isolated chart frame on the CPU after font initialisation; export controls include size, title, timestamp, all pane watermarks, crosshair and transparency. Image frames, PNG and SVG independently include or exclude foreground primitives and the crosshair; foreground defaults to included, while frozen exports omit pointer hover and selection decorations and retain persistent drawings and the main series' style. SVG exports quote named font families as CSS strings and escape their XML attributes, including names restored from saved layouts. -- [x] Export dialog and demo actions save images/data or copy images through application facilities. The demo exports either the active chart or the visible arrangement as PNG or SVG, with shared image options and opted-in trading overlays. The terminal's file callback receives its alert, watchlist, screener, account and strategy report text exports and shows returned save errors as toasts. +- [x] Export dialog and demo actions save images/data or copy images through application facilities. The demo exports either the active chart or the visible arrangement as PNG or SVG, with shared image options and opted-in trading overlays. The terminal's file callback receives its chart PNG, SVG and CSV exports and its alert, watchlist, screener, account and strategy report text exports, and shows returned save errors as toasts and in the open export dialog. - [ ] Capture the toolbars and side panels around the charts in a complete terminal image, and run image capture in `Terminal`. Chart images already include trading overlays, host textures and feed-backed order-flow visuals. - [ ] Add print/PDF output. - [ ] Integrate a native save-file chooser and provide an `Exportable` adapter for direct chart export. @@ -310,7 +312,7 @@ Execution-based calculations use supplied trades and their aggressor side. Unkno - [x] Runtime symbol/interval changes reload the feed; explicit reload and reset paths invalidate old work. - [x] Public events report pointer, range, symbol, interval and data changes; pointer moves and clicks retain screen and pane positions on empty plots and outside loaded history, with an optional stored timestamp instead of an extrapolated data time. Cursor payloads select main and added-series points at their rendered horizontal positions, including interleaved timestamps, and return only data at the selected time; stationary pointers refresh when that data changes. Removing the main series also removes its bar and previous close from cursor payloads. The vertical guide, time label, linked position and image export use that same selected timestamp, including points between main-series slots. Pointer notifications retain the originating button or touch details, position and modifiers, with no input origin for state-driven updates. Modifier keys reflect the originating event even if the chart was hidden while keys changed or window focus is lost later in the frame. A touch release retains its contact identity even when its lift position differs from the emulated pointer release. Opt-in operation notifications preserve each accepted direct data load or update, including unchanged updates, and distinguish appends, existing-bar updates and historical insertions. Compact state-change events and queue overflow reporting remain available. Custom menu entries and toolbar controls return application identifiers. Cursor and click payloads can include hidden study plots with stable study ids through `Chart::set_cursor_data_policy`; visible readouts, rendering and autoscale keep their visibility rules, and missing values stay absent. Marker hover targets include the owning series, time and optional host identity; custom price-line targets include their live handle and series. Annotation targets follow their paint layers in every pane and refresh when annotations are hidden, clipped or removed. A marker click notification uses that same resolved target, so a covered marker cannot also report a click. Visible annotations retain their identities when time-scale filters leave no eligible cursor data, without returning filtered values. - [x] Added price series, custom study-backed series and attached `Primitive` renderers support visibility, hit testing, scale participation and removal. Primitive price and time tags support explicit text colour, independent ticks and fixed axis offsets with clipping and priority over automatic tags; in every pane fixed tags paint above series value and drawing position tags, leave out the scale labels under them and stay below the crosshair labels, and time tags stay on the time axis below footprint statistics rows; automatic data positioning and contrasting text remain the defaults. Custom data series own host-fed typed `CustomPoint` values with their own keys, whitespace and prices: setting and updating sort, resolve duplicate keys and count invalid points, renderers read the points through their view, all prices of the points in view fit the scale, and key, logical-position, range and cursor queries return them without touching the main bars. Pane-owned `PanePrimitive` decorations draw and hit test without a series or price scale, survive member removal in retained panes, detach once when their pane is removed and join image exports once their `attached` hook has run. Primitive passes support optional backgrounds before their foregrounds in attachment order across the pane, including custom renderers and conflated data, while empty background phases keep custom renderers in their series slots. Member primitives paint their Below pass before every plot of a shared pane and their Series pass after every plot, in attachment order. Structured primitive and custom-renderer hits identify individual objects and carry their cursor and host data through hover and click payloads, ranked by draw pass and distance with deterministic ties; cursor-only implementations keep their existing behavior. Bar-series logical-range queries return stored slices and shared-scale distances, including gaps and fractional bounds outside the data. Last-value queries select the latest loaded or visible valued bar of main and added series, returning its raw close, shared logical position, pane coordinate, tag colour and scale-formatted text while skipping whitespace. A selected close without a valid scale coordinate, including zero and negative logarithmic prices, returns no last value. Discrete time and series lookups support exact matches and directional neighbours on the shared horizontal scale; time-coordinate queries report absent scale points while continuous mappings remain available. Main and added bar series have a persistent draw order within each pane, shared by painting and hit selection and retained in chart snapshots. Custom renderers above a built-in hit compete by pass and distance; lower renderers cannot discard those candidates. Custom volume renderers paint all passes and receive pointer hits without requiring another primitive background. The demo menu's Samples entries demonstrate toggleable session backgrounds, axis labels and a custom range pane with pointer feedback. -- [x] Live change markers on main and added bar series retain their configured rise and fall colours while fading linearly over their lifetime on egui's frame clock from the first frame after a change, whether or not the series is drawn, so a series shown again draws only marks still within their duration. Another changed close in the same bar slot replaces its mark at the bar's current timestamp and restarts the fade; a restamp with an unchanged close moves its existing mark with the bar without restarting the fade. Replacing a marked bar with whitespace removes its mark; a whitespace bar's first prices mark no change, and expired markers are removed and stop requesting repaints. Marks leave with popped bars and bars hidden by replay; popping and removing the oldest bars keep marks of the surviving bars, as does replay for added series. Marks follow their stored bars when pausing a feed changes the merge clock. Undoing removal of an added series during replay also drops marks of bars outside its restored window. Replay retains marks at the exact timestamps of surviving host bars, including separate bars within one displayed interval. +- [x] Live change markers on main and added bar series retain their configured rise and fall colours while fading linearly over their lifetime on egui's frame clock from the first frame that can show a change, or from the frame of an update made while egui's frames do not show the chart, whether or not the series is drawn, so a series or chart shown again draws only marks still within their duration. Another changed close in the same bar slot replaces its mark at the bar's current timestamp and restarts the fade; a restamp with an unchanged close moves its existing mark with the bar without restarting the fade. Replacing a marked bar with whitespace removes its mark; a whitespace bar's first prices mark no change, and expired markers are removed and stop requesting repaints. Marks leave with popped bars and bars hidden by replay; popping and removing the oldest bars keep marks of the surviving bars, as does replay for added series. Marks follow their stored bars when pausing a feed changes the merge clock. Undoing removal of an added series during replay also drops marks of bars outside its restored window. Replay retains marks at the exact timestamps of surviving host bars, including separate bars within one displayed interval. - [x] Changing symbols resets a stale manual price range. - [x] `ChartBuilder` accepts locale, formatters, storage and a study factory, and `build_restored` builds a chart from saved state. - [x] Trade and depth requests take bounded time ranges, and older trades and depth columns page during scroll-back. @@ -318,7 +320,7 @@ Execution-based calculations use supplied trades and their aggressor side. Unkno ## Infrastructure - [x] Feature layers separate the engine, built-in studies, widget, drawings, icons and terminal UI; engine and study calculations need no egui. CSV I/O and PNG export are optional, enabled by default and by `ui`; icons alone install only their embedded image loader. -- [x] `Theme` provides editable palettes with dark, light and high-contrast presets; shared tokens cover sizing, spacing, corners and colours. +- [x] `Theme` provides editable palettes with dark, light and high-contrast presets; shared tokens cover sizing, spacing, corners and colours. Undo and redo restore what the user edited and leave the colours that follow the theme on the active theme, and a theme change is not an undo step. - [x] Host translation lookup with English fallback, locale/date formatters and optional named time zones. The demo persists independent language and number-format samples and applies host formatting to its data window and exported chart. The demo selects light, dark, high contrast or system appearance, preserves explicit choices and follows later system changes. - [x] The demo exposes floating, tracking and magnifier readouts, hover or hold activation, lens size and zoom; magnified candles stay inside the circular lens. Its annotation editor creates, edits and removes series markers and price lines, controls marker fitting and layering, and configures live change-marker duration. - [x] Accessibility roles/states, keyboard focus and a textual bar/study readout. @@ -347,7 +349,7 @@ The crate renders supplied data and exposes interfaces for application services. The order below prioritises correctness and complete library workflows. It carries no delivery dates. -1. **Chart rendering and order flow:** leave bars outside session hours out of session profiles, finish pane maximising and scale name tags, and the ladder's size mode and highlight tiers. +1. **Chart rendering and order flow:** leave bars outside session hours out of session profiles, finish scale name tags, and the ladder's size mode and highlight tiers. 2. **Indicators and drawings:** finish the remaining style and calculation controls of built-in studies, volume profile study settings and the remaining dedicated studies; give drawing tools their own default styles and complete the labels of line drawings. 3. **Terminal UI:** handle the remaining actions with application interception and move the demo onto `Terminal`; gate order-flow entries on the feed's declarations, add the depth panel and open the study editor and replay trading in the bottom dock; finish the colour popup, quick settings menu and standalone replay toolbar. 4. **Layouts and snapshots:** restore custom series from snapshots and include symbol navigation in terminal undo. diff --git a/vendor/egui-charts/THIRD-PARTY-NOTICES.md b/vendor/egui-charts/THIRD-PARTY-NOTICES.md index 29346dc..c0a72c2 100644 --- a/vendor/egui-charts/THIRD-PARTY-NOTICES.md +++ b/vendor/egui-charts/THIRD-PARTY-NOTICES.md @@ -106,4 +106,4 @@ The guide examples under `examples/docs` embed Roboto and the same default fonts ## Root certificates in the native demo -The native demo's HTTP image loader includes Mozilla's root certificates through `webpki-roots` 1.0.11. This certificate data is licensed under the Community Data License Agreement - Permissive 2.0; the full text is in [`examples/demo/LICENSE-webpki-roots.txt`](examples/demo/LICENSE-webpki-roots.txt). +The native demo's own-data connections (the REST history and the WebSocket stream of a data source the user configures) include Mozilla's root certificates through `webpki-roots` 1.0.12. This certificate data is licensed under the Community Data License Agreement - Permissive 2.0; the full text is in [`examples/demo/LICENSE-webpki-roots.txt`](examples/demo/LICENSE-webpki-roots.txt). diff --git a/vendor/egui-charts/benches/check-regressions-test.py b/vendor/egui-charts/benches/check-regressions-test.py index 7369eef..9f60c9f 100644 --- a/vendor/egui-charts/benches/check-regressions-test.py +++ b/vendor/egui-charts/benches/check-regressions-test.py @@ -20,6 +20,8 @@ assert os.environ['MALLOC_MMAP_THRESHOLD_'] == '131072' binary, flag, scenario = sys.argv[5:] assert flag == '--regression' +if scenario == os.environ.get('TEST_FAIL'): + sys.exit(1) assert binary.endswith(('/base/frame_time', '/head/frame_time')) samples = int(os.environ['FRAME_TIME_FRAMES']) assert samples in (0, 1 if scenario == 'trade-replay' else 20) @@ -72,6 +74,12 @@ def run(*args): assert compared.returncode == 1 assert "::error::Invalid instruction delta for frame-1000" in compared.stderr + # A scenario that fails must fail the whole measurement, not drop out of the counts. + env.update(TEST_FAIL="depth") + measured = run("--measure", work / "head") + assert measured.returncode == 1, measured + assert "::error::No instruction count for depth" in measured.stderr + print("instruction comparison: PASS") # Cache identity must distinguish processor models and flags, but not the core count. diff --git a/vendor/egui-charts/benches/check-regressions.sh b/vendor/egui-charts/benches/check-regressions.sh index 3e6fdc2..b8f9c46 100644 --- a/vendor/egui-charts/benches/check-regressions.sh +++ b/vendor/egui-charts/benches/check-regressions.sh @@ -21,13 +21,12 @@ elif [[ $mode != --compare ]]; then fi base_bin=$work/base/frame_time head_bin=$work/head/frame_time -log=$work/log # glibc raises its mmap threshold as large blocks are freed, which changes whether growing a # vector copies it. That moved the tessellator's mesh growth by about 5% for unrelated changes, # so the threshold is fixed and counts follow the code. export MALLOC_MMAP_THRESHOLD_=131072 instructions() { - local count + local count log=$work/$2.log if ! FRAME_TIME_FRAMES=$3 valgrind --tool=cachegrind --cache-sim=no --branch-sim=no \ --cachegrind-out-file=/dev/null "$1" --regression "$2" > /dev/null 2> "$log"; then cat "$log" >&2 @@ -37,21 +36,36 @@ instructions() { [[ $count =~ ^[0-9]+$ ]] || { cat "$log" >&2; exit 1; } echo "$count" } -if [[ $mode != --measure ]]; then - printf '| Scenario | Base instructions | Head instructions | Change | Tolerance |\n' - printf '|---|---:|---:|---:|---:|\n' +scenarios=(frame-1000 frame-100000 frame-1000000 heikin tick tick-studies append append-studies bar-limit studies drawings depth bubbles tpo-400 tpo-1600 trade-replay session-resample markers events comparisons-1 comparisons-2 comparisons-5) +# A replay already looks up 100,000 ids; one measured frame is enough. +samples_of() { if [[ $1 == trade-replay ]]; then echo 1; else echo 20; fi; } +if [[ $mode == --measure ]]; then + measure() { + local zero measured + zero=$(instructions "$base_bin" "$1" 0) + measured=$(instructions "$base_bin" "$1" "$(samples_of "$1")") + printf '%s %s %s\n' "$1" "$zero" "$measured" > "$work/$1.counts" + } + # Cachegrind counts instructions, not time, so the scenarios run side by side, one per processor. + # A failed scenario leaves no counts file and fails below. + slots=$(nproc) + for scenario in "${scenarios[@]}"; do + while (( $(jobs -pr | wc -l) >= slots )); do wait -n || true; done + measure "$scenario" & + done + wait + for scenario in "${scenarios[@]}"; do + [[ -s $work/$scenario.counts ]] || { echo "::error::No instruction count for $scenario" >&2; exit 1; } + cat "$work/$scenario.counts" + done + exit 0 fi +printf '| Scenario | Base instructions | Head instructions | Change | Tolerance |\n' +printf '|---|---:|---:|---:|---:|\n' fail=0 -for scenario in frame-1000 frame-100000 frame-1000000 heikin tick tick-studies append append-studies bar-limit studies drawings depth bubbles tpo-400 tpo-1600 trade-replay session-resample markers events comparisons-1 comparisons-2 comparisons-5; do - # A replay already looks up 100,000 ids; one measured batch is enough. - samples=20 - [[ $scenario != trade-replay ]] || samples=1 - if [[ $mode == --measure ]]; then - base0=$(instructions "$base_bin" "$scenario" 0) - base_measured=$(instructions "$base_bin" "$scenario" "$samples") - printf '%s %s %s\n' "$scenario" "$base0" "$base_measured" - continue - elif [[ $mode == --compare ]]; then +for scenario in "${scenarios[@]}"; do + samples=$(samples_of "$scenario") + if [[ $mode == --compare ]]; then read -r base0 base_measured <<< "$(awk -v s="$scenario" '$1 == s { print $2, $3 }' "$1")" read -r head0 head_measured <<< "$(awk -v s="$scenario" '$1 == s { print $2, $3 }' "$2")" [[ $base0 =~ ^[0-9]+$ && $base_measured =~ ^[0-9]+$ && $head0 =~ ^[0-9]+$ && $head_measured =~ ^[0-9]+$ ]] || { diff --git a/vendor/egui-charts/benches/frame_time.rs b/vendor/egui-charts/benches/frame_time.rs index 2ff1822..11db475 100644 --- a/vendor/egui-charts/benches/frame_time.rs +++ b/vendor/egui-charts/benches/frame_time.rs @@ -326,10 +326,8 @@ fn footprint(filters: &[String], frames: usize) { options.time_scale.min_bar_spacing = 0.0; let mut chart = Chart::new(BarData::from_bars(bars)).with_chart_options(options); chart.set_visible_bars(100_000); - let config = FootprintConfig { - studies: Some(Default::default()), - ..Default::default() - }; + let mut config = FootprintConfig::default(); + config.studies = Some(Default::default()); let samples = frame::run(vec2(1440.0, 900.0), pos2(700.0, 400.0), frames, |ui| { egui::CentralPanel::default().show(ui, |ui| { chart.show_footprint(ui, &flow, &config); @@ -600,16 +598,14 @@ fn price_based(filters: &[String], frames: usize) { .map(|i| { let open = close; close += step(); - Bar { - time: start + Duration::minutes(i), + Bar::new( + start + Duration::minutes(i), open, + open.max(close) + 0.05, + open.min(close) - 0.05, close, - high: open.max(close) + 0.05, - low: open.min(close) - 0.05, - volume: 100.0, - colors: None, - payload: None, - } + 100.0, + ) }) .collect(); let size = RenkoConfig::from_atr(&bars, 14, 0.5).brick_size; diff --git a/vendor/egui-charts/benches/stream.rs b/vendor/egui-charts/benches/stream.rs index 78f148e..9af3d3d 100644 --- a/vendor/egui-charts/benches/stream.rs +++ b/vendor/egui-charts/benches/stream.rs @@ -160,7 +160,6 @@ fn tail_updates() { println!("| study | bars | tick median us | append median us | incremental |"); println!("|---|---:|---:|---:|---|"); let mut factory = IndicatorFactory::new(); - factory.register("C2C Vol", || Box::new(CloseToCloseVol::default())); factory.register("Price Channel", || Box::new(PriceChannel::default())); factory.register("HLC3", || Box::new(HLC3::default())); factory.register("HL2", || Box::new(HL2::default())); diff --git a/vendor/egui-charts/docs/capture/Cargo.lock b/vendor/egui-charts/docs/capture/Cargo.lock index aad7613..c2d9dc8 100644 --- a/vendor/egui-charts/docs/capture/Cargo.lock +++ b/vendor/egui-charts/docs/capture/Cargo.lock @@ -385,6 +385,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bit-set" version = "0.10.0" @@ -415,6 +421,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -638,6 +653,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -659,6 +683,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "csv" version = "1.4.0" @@ -686,12 +720,28 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "data-url" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -837,12 +887,16 @@ dependencies = [ "egui-charts", "egui_extras", "egui_kittest", + "ehttp", "image", "log", "maudio", "rfd", + "rustls", "serde", "serde_json", + "tungstenite", + "webpki-roots", ] [[package]] @@ -921,6 +975,20 @@ dependencies = [ "wgpu", ] +[[package]] +name = "ehttp" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d1c51126a4e8242c5b3bcd4c5b350ed3540f0c13c10e0c3c840a3833fa3474c" +dependencies = [ + "document-features", + "js-sys", + "ureq", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "either" version = "1.19.0" @@ -1215,6 +1283,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -1225,6 +1303,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1375,6 +1464,22 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -2408,6 +2513,15 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "presser" version = "0.3.1" @@ -2480,6 +2594,35 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "range-alloc" version = "0.1.5" @@ -2598,6 +2741,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "ron" version = "0.12.2" @@ -2665,6 +2822,41 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -2779,6 +2971,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -2924,6 +3127,12 @@ dependencies = [ "float-cmp", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "svgtypes" version = "0.15.3" @@ -3127,6 +3336,22 @@ dependencies = [ "once_cell", ] +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand", + "sha1", + "thiserror 2.0.21", +] + [[package]] name = "type-map" version = "0.5.1" @@ -3142,6 +3367,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "uds_windows" version = "1.2.1" @@ -3183,13 +3414,48 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + [[package]] name = "usvg" version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" dependencies = [ - "base64", + "base64 0.22.1", "data-url", "flate2", "imagesize", @@ -3205,6 +3471,12 @@ dependencies = [ "xmlwriter", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "uuid" version = "1.26.1" @@ -3259,6 +3531,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -3453,6 +3731,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "wgpu" version = "30.0.1" @@ -4107,6 +4394,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zlib-rs" version = "0.6.8" diff --git a/vendor/egui-charts/docs/capture/Cargo.toml b/vendor/egui-charts/docs/capture/Cargo.toml index c6af042..cb1b928 100644 --- a/vendor/egui-charts/docs/capture/Cargo.toml +++ b/vendor/egui-charts/docs/capture/Cargo.toml @@ -21,6 +21,11 @@ egui_kittest = { version = "0.37.0", features = ["wgpu", "eframe"] } chrono = "0.4.43" log = "0.4.29" maudio = "0.1.15" +# The demo's own-data connections: REST history and the WebSocket stream of a visitor's source. +ehttp = "0.7.2" +tungstenite = { version = "0.29.0", default-features = false, features = ["handshake"] } +rustls = { version = "0.23.40", default-features = false, features = ["ring", "std", "tls12"] } +webpki-roots = "1.0.7" serde = { version = "1", features = ["derive"] } serde_json = "1" image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } diff --git a/vendor/egui-charts/docs/host-data-services.md b/vendor/egui-charts/docs/host-data-services.md index 64b21f8..82618c1 100644 --- a/vendor/egui-charts/docs/host-data-services.md +++ b/vendor/egui-charts/docs/host-data-services.md @@ -45,11 +45,17 @@ The chart's Signals menu controls category visibility without deleting data. Hos Implement optional [`Datafeed::price_targets`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/data/trait.Datafeed.html#method.price_targets) to answer [`data::PriceTargets`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/data/struct.PriceTargets.html). Its default returns [`FeedError::NotSupported`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/data/enum.FeedError.html#variant.NotSupported), which shows neither targets nor an error. Prices must be finite, ordered `low <= average <= high`, and accompanied by an analyst count and publication and horizon dates. The horizon must follow publication. -The Symbol tab's **Analyst price targets** setting, or [`Chart::set_price_targets_visible`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.Chart.html#method.set_price_targets_visible), enables projections. They start at the last close with a value and end at midnight UTC on the horizon date. Leave enough future whitespace with [`set_visible_logical_range`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.Chart.html#method.set_visible_logical_range) to see that date and its labels. Automatic price fitting includes the target extremes while the projections reach the visible time range. The host price formatter receives instrument prices, including on percentage and indexed scales. Percentage change is `(target - close) / close * 100`; a zero close omits the percentage. Labels stay below the legend and quote controls in narrow charts. Hovering an endpoint or visible label shows the count and dates, including when the horizon is offscreen. +The Symbol tab's **Analyst price targets** setting, or [`Chart::set_price_targets_visible`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.Chart.html#method.set_price_targets_visible), enables projections. A host that passes its feed's capabilities to [`SettingsDialog::set_feed_capabilities`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/ui/dialogs/chart_settings/struct.SettingsDialog.html#method.set_feed_capabilities) offers the setting only when they declare [`FeedService::PriceTargets`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/model/enum.FeedService.html#variant.PriceTargets) for the symbol. Projections start at the last close with a value and end at midnight UTC on the horizon date. Leave enough future whitespace with [`set_visible_logical_range`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.Chart.html#method.set_visible_logical_range) to see that date and its labels. Automatic price fitting includes the target extremes while the projections reach the visible time range. The host price formatter receives instrument prices, including on percentage and indexed scales. Percentage change is `(target - close) / close * 100`; a zero close omits the percentage. Labels stay below the legend and quote controls in narrow charts. Hovering an endpoint or visible label shows the count and dates, including when the horizon is offscreen. A symbol change clears the targets and ignores its old replies. [`reload_price_targets`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.Chart.html#method.reload_price_targets) requests updated estimates; [`take_price_targets_error`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.Chart.html#method.take_price_targets_error) reports errors other than unsupported data. Hiding targets retains their answer. Price-based charts do not draw projections. -The demo's quick search has **Toggle API samples** for host signals and **Show analyst price targets** for SAMPLE's daily projection. Its synthetic feed implements these contracts on native and browser builds. +The demo's quick search has **Toggle all sample overlays** for host signals and **Analyst price targets** for SAMPLE's daily projection. On another symbol, on a price-based chart type or while the price series is hidden, it says why and leaves the chart unchanged. Its synthetic feed implements these contracts on native and browser builds. + +## Company financials + +Implement optional [`Datafeed::financials`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/data/trait.Datafeed.html#method.financials) to answer [`data::CompanyFinancials`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/data/struct.CompanyFinancials.html) with the host's reported statements. Each [`FinancialPage`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/data/struct.FinancialPage.html) names a page and its periods, oldest first; each [`FinancialRow`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/data/struct.FinancialRow.html) supplies one optional figure per period. Keep missing figures as `None`; non-finite values render as unavailable. The currency labels amounts without converting them. The types need no UI feature and are still re-exported from `ui::financials`. + +[`SymbolDetailsPanel`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/ui/widget_bar/panels/symbol_details/struct.SymbolDetailsPanel.html) asks its feed for each new symbol's figures along with its details and holds a nonempty answer in [`financials`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/ui/widget_bar/panels/symbol_details/struct.SymbolDetailsPanel.html#method.financials). It ignores answers for an earlier symbol; the default [`FeedError::NotSupported`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/data/enum.FeedError.html#variant.NotSupported) shows nothing, and other errors show in the panel. The terminal offers **Financials** in the panel's More menu only once figures are held. Choosing it closes the side panel and shows [`FinancialsPanel`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/ui/financials/struct.FinancialsPanel.html) in place of the charts, with statement tabs, a chart of the selected row and the table of all reported rows. It follows symbol changes, and **Back to chart** restores the charts. A host composing its own UI opens `FinancialsPanel::new` with the held figures when [`take_financials_request`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/ui/widget_bar/panels/symbol_details/struct.SymbolDetailsPanel.html#method.take_financials_request) reports the choice. The host owns financial data acquisition and refreshes; the library supplies no accounts or data provider. ## Market heatmap diff --git a/vendor/egui-charts/docs/progress/features.csv b/vendor/egui-charts/docs/progress/features.csv index b88736c..4e89622 100644 --- a/vendor/egui-charts/docs/progress/features.csv +++ b/vendor/egui-charts/docs/progress/features.csv @@ -19,16 +19,17 @@ Builder API,Builder integration,Custom drawing tools from a downstream crate,inc Builder API,Builder integration,Custom indicator metadata,unverified,library,src/studies/indicator_trait.rs;src/studies/inputs.rs;src/studies/settings.rs;src/chart/rendering/indicator.rs;src/chart/rendering/axes/study_scale.rs, Builder API,Builder integration,Custom indicators from a downstream crate,unverified,library,src/studies/factory/mod.rs;src/ui/dialogs/indicator_dialog/dialog.rs;src/widget/studies.rs;src/studies/custom.rs;terminal/src/studies.rs, Builder API,Builder integration,Custom series types from a downstream crate,unverified,library,src/widget/primitives.rs;src/widget/pane/render/mod.rs;src/chart/primitives.rs;src/widget/frame/mod.rs;src/widget/pane/indicator/mod.rs;examples/demo/primitive_scene.rs;examples/demo/commands.rs;examples/primitives.rs;src/widget/events.rs;src/widget/crosshair.rs;src/widget/series/mod.rs;src/chart/rendering/axes/mod.rs;src/widget/marks.rs;src/chart/rendering/axes/study_scale.rs;src/widget/series/scales/mod.rs,1936;1901;1900;2189;2308;2309;2310;2311;2492 +Builder API,Builder integration,Demo on a visitor's own REST and WebSocket data,unverified,library,examples/demo/owndata/profile.rs;examples/demo/owndata/feed.rs;examples/demo/owndata/bars.rs;examples/demo/owndata/time.rs;examples/demo/owndata/stream.rs;examples/demo/owndata/socket.rs;examples/demo/owndata/dialog.rs;examples/demo/owndata/app.rs;examples/demo/controller.rs;examples/demo/owndata/store.rs;examples/demo/owndata/ready/binance-spot.json;docs/site/src/content/docs/own-data.mdx,2677;2965;2966;2982 Builder API,Builder integration,Demo startup status and recovery,unverified,library,examples/demo/main.rs;examples/demo/index.html,1932 Builder API,Builder integration,Desktop webview integration,missing,library,, Builder API,Builder integration,Embedding with a data feed,unverified,host,src/widget/builder.rs;src/widget/feed/mod.rs;src/widget/frame/mod.rs, -Builder API,Builder integration,Full trading-terminal UI around the chart,incomplete,library,src/ui/app_state.rs;src/ui/trading/mod.rs;terminal/src/lib.rs;terminal/src/core.rs;terminal/src/services.rs;terminal/src/layout.rs;terminal/src/trading.rs;terminal/src/panels.rs;terminal/src/time.rs;terminal/src/alerts.rs;terminal/src/layouts.rs,205;383 +Builder API,Builder integration,Full trading-terminal UI around the chart,incomplete,library,src/ui/app_state.rs;src/ui/trading/mod.rs;terminal/src/lib.rs;terminal/src/core.rs;terminal/src/services.rs;terminal/src/layout.rs;terminal/src/trading.rs;terminal/src/panels.rs;terminal/src/time.rs;terminal/src/alerts.rs;terminal/src/layouts.rs;terminal/src/commands.rs,205;383 Builder API,Builder integration,Minimal embedding,unverified,library,src/widget/builder.rs;src/widget/frame/mod.rs, Builder API,Builder integration,Pane-owned primitives,unverified,library,src/chart/primitives.rs;src/widget/primitives.rs;src/widget/export.rs;src/widget/pane/mod.rs;src/widget/pane/render/mod.rs;src/widget/frame/mod.rs;src/widget/events.rs;src/widget/marks.rs,1902;2190;2209 Builder API,Builder integration,Pluggable formatters and session rules,unverified,library,src/widget/builder.rs;src/model/session/mod.rs;src/widget/format.rs;src/widget/frame/sessions.rs;src/scales/price_formatter.rs,2483 Builder API,Builder integration,Primitive axis labels,unverified,library,src/chart/primitives.rs;src/chart/rendering/axes/mod.rs;src/widget/frame/mod.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/render/mod.rs;src/widget/pane/indicator/paint.rs;src/widget/primitives.rs,1900;2206;2207;2208;2502 Builder API,Builder integration,Primitive backgrounds within draw passes,unverified,library,src/chart/primitives.rs;src/widget/primitives.rs;src/widget/frame/mod.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/render/mod.rs,1899;1902;2493 -Builder API,Builder integration,Public API surface and structure,unverified,library,src/prelude.rs;src/lib.rs;src/widget/mod.rs;src/model/mod.rs;src/widget/pan_zoom/mod.rs;src/widget/interaction.rs;src/widget/builder.rs;src/styles/mod.rs, +Builder API,Builder integration,Public API surface and structure,unverified,library,src/prelude.rs;src/lib.rs;src/widget/mod.rs;src/model/mod.rs;src/widget/pan_zoom/mod.rs;src/widget/interaction.rs;src/widget/builder.rs;src/styles/mod.rs;src/data/inbox/mod.rs;src/data/inbox/sink.rs;src/model/signal.rs;src/scales/timescale_marks.rs;src/studies/mod.rs;src/studies/settings.rs;src/drawings/persistence.rs;src/drawings/registry.rs, Builder API,Builder integration,Runnable guide examples,unverified,library,examples/docs/Cargo.toml;examples/docs/main.rs;examples/docs/first_chart.rs;examples/docs/index.html;docs/site/src/components/Example.astro;docs/site/src/content/docs/first-chart.mdx;docs/site/src/styles/custom.css;.github/workflows/deploy-demo.yml;examples/docs/scenes/series.rs;examples/docs/scenes/chart_types.rs;docs/site/src/content/docs/series.mdx;docs/site/src/content/docs/series/candles-and-bars.mdx;docs/site/src/content/docs/series/line.mdx;docs/site/src/content/docs/series/area.mdx;docs/site/src/content/docs/series/baseline.mdx;docs/site/src/content/docs/series/histogram.mdx;docs/site/src/content/docs/chart-types.mdx;docs/site/src/content/docs/chart-types/transforms.mdx;examples/docs/scenes/mod.rs;examples/docs/scenes/price_scale.rs;examples/docs/scenes/time_scale.rs;examples/docs/scenes/panes.rs;examples/docs/site.test.mjs;docs/site/src/content/docs/price-scale.mdx;docs/site/src/content/docs/time-scale.mdx;docs/site/src/content/docs/panes.mdx;docs/site/src/content/docs/horizontal-scales.mdx;docs/site/src/content/docs/extensions.mdx;docs/site/src/content/docs/extensions/custom-series.mdx;examples/docs/scenes/extensions.rs;examples/docs/scenes/theme.rs;docs/site/src/content/docs/theming.mdx;docs/site/src/content/docs/time-zones.mdx;docs/site/src/content/docs/accessibility.mdx;examples/docs/scenes/studies.rs;docs/site/src/content/docs/studies/custom.mdx;docs/site/src/content/docs/studies/live-data.mdx;docs/site/src/content/docs/studies.mdx;examples/docs/scenes/recipes.rs;docs/site/src/content/docs/tutorial/second-series.mdx;docs/site/src/content/docs/interaction.mdx;docs/site/src/content/docs/recipes/index.mdx;docs/site/src/content/docs/recipes/annotations.mdx;docs/site/src/content/docs/recipes/price-volume.mdx;docs/site/src/content/docs/recipes/host-readout.mdx;docs/site/src/content/docs/recipes/synchronized.mdx;docs/site/src/content/docs/recipes/export.mdx;examples/docs/scenes/order_flow.rs;examples/docs/scenes/recording_replay.rs;examples/docs/scenes/host_report.rs;docs/order-flow.md;docs/order-flow-replay.md;docs/study-data.md;docs/strategy-report.md;docs/host-data-services.md;docs/site/guides.mjs;docs/site/prepare-guides.mjs;docs/site/prepare-guides.test.mjs,1845;1846;1847;1849;1850;1852;1848;1851 Builder API,Builder integration,Scripted demo tour and themed README captures,unverified,library,docs/capture/main.rs;docs/capture/animation.rs;docs/capture/pointer.rs;docs/capture/clock.c;docs/capture/regenerate.sh;docs/capture/verify.py;docs/site/tour.test.mjs;README.md;docs/site/src/content/docs/index.mdx,1996;2075;2169 Builder API,Builder integration,Threading model for feeding data,unverified,library,src/data/mod.rs;src/data/inbox/mod.rs;src/widget/feed/mod.rs;src/data/inbox/sink.rs, @@ -78,7 +79,7 @@ Builder API,Save/load adapter,Drawings persistence,incomplete,library,src/widget Builder API,Save/load adapter,Save and load layout UI,incomplete,library,src/ui/top_toolbar/components/layout_menu.rs;terminal/src/layouts.rs;examples/demo/layouts.rs;examples/demo/replay.rs;examples/demo/storage.rs,1941;2363;2182;2472;2476 Builder API,Save/load adapter,Save and restore the complete chart state,incomplete,library,src/widget/snapshot.rs;src/studies/template.rs;src/studies/factory/mod.rs;src/studies/builtin/ma_combination.rs;src/widget/builder.rs;src/studies/builtin/trading_sessions.rs;src/studies/builtin/vwap.rs;src/studies/builtin/auto_drawing.rs;src/config/crosshair.rs;src/studies/settings.rs;src/studies/indicator_trait.rs,1058;2419;2472;2476;2486;2333;2335;2337;2523 Builder API,Save/load adapter,Storage adapter contract,unverified,host,src/services/storage.rs;src/services/document.rs;src/ui/dialogs/templates/store.rs;src/ui/top_toolbar/components/layout_menu.rs, -Builder API,Save/load adapter,Study templates,incomplete,library,src/studies/template.rs;src/widget/study_templates.rs;src/studies/factory/mod.rs;src/studies/builtin/ma_combination.rs;src/ui/dialogs/templates/store.rs;src/studies/builtin/trading_sessions.rs;src/studies/builtin/vwap.rs;src/studies/builtin/auto_drawing.rs;src/studies/settings.rs;src/studies/indicator_trait.rs,2333;2335;2337;2419;2523;1485 +Builder API,Save/load adapter,Study templates,incomplete,library,src/studies/template.rs;src/widget/study_templates.rs;src/studies/factory/mod.rs;src/studies/builtin/ma_combination.rs;src/ui/dialogs/templates/store.rs;src/studies/builtin/trading_sessions.rs;src/studies/builtin/vwap.rs;src/studies/builtin/auto_drawing.rs;src/studies/settings.rs;src/studies/indicator_trait.rs;src/widget/clipboard.rs,2333;2335;2337;2419;2523;1485;2985 Builder API,Save/load adapter,User settings persistence,unverified,host,src/services/settings.rs;src/config/cursor.rs;examples/demo/layouts.rs;examples/demo/controller.rs, Builder API,Widget API and customization,Change interval at runtime,verified,library,src/widget/feed/mod.rs;src/widget/events.rs, Builder API,Widget API and customization,Change symbol at runtime,unverified,library,src/widget/feed/mod.rs;src/scales/pricescale.rs;src/widget/events.rs, @@ -94,14 +95,14 @@ Builder API,Widget API and customization,Custom price formatter,unverified,libra Builder API,Widget API and customization,Data conflation controls and preparation,incomplete,library,src/config/chart.rs;src/widget/merge.rs;src/widget/frame/mod.rs;src/widget/primitives.rs;src/widget/pane/render/mod.rs;src/widget/pane/indicator/mod.rs, Builder API,Widget API and customization,Export chart data,unverified,library,src/widget/export.rs;src/model/bar/io.rs;Cargo.toml,1963 Builder API,Widget API and customization,Hide or show the main series,unverified,library,src/widget/series/mod.rs;src/widget/marks.rs;src/widget/frame/mod.rs, -Builder API,Widget API and customization,Live change markers,unverified,library,src/model/markers.rs;src/widget/change_marks.rs;src/widget/marks.rs;src/widget/series/mod.rs;src/widget/replay.rs;src/widget/series/paint.rs;src/chart/rendering/markers.rs,1892;2478;2479;2480;2481;2482;2700;2702 +Builder API,Widget API and customization,Live change markers,unverified,library,src/model/markers.rs;src/widget/change_marks.rs;src/widget/marks.rs;src/widget/series/mod.rs;src/widget/frame/mod.rs;src/widget/replay.rs;src/widget/series/paint.rs;src/chart/rendering/markers.rs,1892;2478;2479;2480;2481;2482;2700;2702;2922 Builder API,Widget API and customization,Locale-aware date formatting,unverified,library,src/scales/time_formatter.rs;Cargo.toml;src/widget/format.rs;examples/demo/formatting.rs;src/ui/widget_bar/panels/object_tree/data_window.rs,1939 -Builder API,Widget API and customization,Localisation of UI text,incomplete,library,src/localization.rs;src/ui/top_toolbar/components/layout_menu.rs;src/chart/rendering/trading_lines/mod.rs;src/chart/rendering/legend/mod.rs;src/ui/context_menu/mod.rs;src/ui/context_menu/series.rs;src/ui/context_menu/study.rs;src/ui/context_menu/drawing.rs;src/ui/trading/view.rs;src/ui/trading/events.rs;src/ui/trading/account_panel/mod.rs;src/ui_kit/notifications/panel.rs;src/chart/rendering/overlays/tooltip.rs;src/chart/rendering/alert_levels.rs;src/chart/rendering/axes/mod.rs;src/drawings/rendering/trading/position.rs;src/ui/timeframe_toolbar/date_picker.rs;src/ui/timeframe_toolbar/toolbar.rs;src/ui/dialogs/indicator_dialog/dialog.rs;src/ui/export.rs;src/ui/widget_bar/panels/alerts_panel.rs;src/ui/widget_bar/panels/calendar.rs;src/ui/widget_bar/panels/chats.rs;src/ui/widget_bar/panels/hotlists.rs;src/ui/widget_bar/panels/news.rs;src/ui/widget_bar/panels/screener.rs;src/ui/widget_bar/panels/symbol_details.rs;src/ui/dialogs/indicator_dialog/templates.rs;src/ui/trading/ticket/form.rs;src/widget/stored_drawings.rs;src/ui_kit/status_message/mod.rs,204 +Builder API,Widget API and customization,Localisation of UI text,incomplete,library,src/localization.rs;src/ui/top_toolbar/components/layout_menu.rs;src/chart/rendering/trading_lines/mod.rs;src/chart/rendering/legend/mod.rs;src/ui/context_menu/mod.rs;src/ui/context_menu/series.rs;src/ui/context_menu/study.rs;src/ui/context_menu/drawing.rs;src/ui/trading/view.rs;src/ui/trading/events.rs;src/ui/trading/account_panel/mod.rs;src/ui_kit/notifications/panel.rs;src/chart/rendering/overlays/tooltip.rs;src/chart/rendering/alert_levels.rs;src/chart/rendering/axes/mod.rs;src/drawings/rendering/trading/position.rs;src/ui/timeframe_toolbar/date_picker.rs;src/ui/timeframe_toolbar/toolbar.rs;src/ui/dialogs/indicator_dialog/dialog.rs;src/ui/export.rs;src/ui/widget_bar/panels/alerts_panel.rs;src/ui/widget_bar/panels/calendar.rs;src/ui/widget_bar/panels/chats.rs;src/ui/widget_bar/panels/hotlists.rs;src/ui/widget_bar/panels/news.rs;src/ui/widget_bar/panels/screener.rs;src/ui/widget_bar/panels/symbol_details.rs;src/ui/dialogs/indicator_dialog/templates.rs;src/ui/trading/ticket/form.rs;src/widget/stored_drawings.rs;src/ui_kit/status_message/mod.rs;src/ui/trading/ticket/mod.rs;src/drawings/rendering/measurements.rs;src/chart/overlays/footprint.rs,204;2979;2989 Builder API,Widget API and customization,Multiple charts per widget,unverified,library,src/widget/layout.rs;src/ui/multi_chart.rs, Builder API,Widget API and customization,Per-chart rendering callbacks,unverified,library,src/widget/layout.rs;terminal/src/layout.rs,2596 Builder API,Widget API and customization,Price scale API,unverified,library,src/scales/pricescale.rs;src/widget/mod.rs;src/widget/series/options.rs;src/widget/series/scales/mod.rs;src/widget/frame/mod.rs;src/model/series_scale.rs,2044 Builder API,Widget API and customization,Screenshots,incomplete,library,src/widget/export.rs;src/widget/raster.rs;src/widget/svg.rs;src/widget/feed/mod.rs;examples/demo/commands.rs;Cargo.toml;src/widget/frame/mod.rs;src/widget/pane/render/mod.rs;src/chart/rendering/watermark.rs;src/widget/pane/mod.rs,1884;1890;1934;1963;2172;2461 -Builder API,Widget API and customization,Series and scale API facade,unverified,library,src/widget/series/options.rs;src/widget/series/scales/mod.rs;src/widget/time_scale.rs;src/widget/series/mod.rs;src/widget/mod.rs;src/model/timescale.rs;src/studies/chart_state.rs;src/widget/frame/mod.rs,1862;1863;1865;1882;1893;1915;2463;2465 +Builder API,Widget API and customization,Series and scale API facade,unverified,library,src/widget/series/options.rs;src/widget/series/scales/mod.rs;src/widget/time_scale.rs;src/widget/series/mod.rs;src/widget/mod.rs;src/model/timescale.rs;src/studies/chart_state.rs;src/widget/frame/mod.rs;src/widget/change_marks.rs,1862;1863;1865;1882;1893;1915;2463;2465 Builder API,Widget API and customization,Series draw order including the main series,unverified,library,src/widget/series/options.rs;src/widget/pane/mod.rs;src/widget/frame/mod.rs;src/widget/snapshot.rs;src/widget/pane/render/mod.rs,1866;1904 Builder API,Widget API and customization,Study defaults,unverified,library,src/studies/factory/mod.rs;src/studies/template.rs;src/widget/clipboard.rs;src/services/alert_evaluator.rs;src/ui/dialogs/indicator_dialog/dialog.rs,2063;2443 Builder API,Widget API and customization,Style overrides,incomplete,library,src/widget/mod.rs;src/widget/builder.rs;src/config/chart.rs;src/widget/frame/mod.rs,832 @@ -112,96 +113,96 @@ Builder API,Widget API and customization,Visible range get and set,unverified,li Builder API,Widget API and customization,Widget constructor options,incomplete,library,src/widget/builder.rs;src/widget/stored_drawings.rs;src/widget/frame/mod.rs,1102 Chart,Chart settings and themes,Added-series settings in the demo,incomplete,library,examples/demo/comparison.rs;examples/demo/controller.rs;examples/demo/layouts.rs;src/widget/series/options.rs,1915;1869;2518 Chart,Chart settings and themes,Alerts tab,incomplete,host,src/ui/dialogs/chart_settings/tabs/trading.rs;src/widget/settings/data.rs;src/ui/dialogs/chart_settings/tabs/mod.rs;terminal/src/alerts.rs;terminal/src/studies.rs, -Chart,Chart settings and themes,Background,incomplete,library,src/widget/settings/apply.rs;src/widget/frame/background.rs,2762;2763;2764 +Chart,Chart settings and themes,Background,incomplete,library,src/widget/settings/apply.rs;src/widget/frame/background.rs;src/widget/layout.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/indicator/paint.rs;src/widget/pane/render/mod.rs;src/chart/rendering/legend/mod.rs;src/chart/rendering/legend/study_controls.rs;src/chart/rendering/axes/study_scale.rs;src/widget/export.rs;src/widget/palette.rs,2762;2763;2764 Chart,Chart settings and themes,Candle colour customisation,incomplete,library,src/widget/settings/apply.rs;src/chart/rendering/candles/candlestick.rs;src/chart/rendering/candles/candle.rs;src/widget/frame/mod.rs;src/widget/series/options.rs;src/widget/series/paint.rs;examples/demo/comparison.rs;src/model/chart_style.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/chart/rendering/candles/heikin_ashi.rs;src/widget/palette.rs;src/widget/mod.rs;src/ui/dialogs/chart_settings/mod.rs,1859;2103;2104;2105;2475;2517;2141 -Chart,Chart settings and themes,Canvas tab,incomplete,library,src/ui/dialogs/chart_settings/tabs/canvas.rs;src/widget/settings/apply.rs;src/widget/settings/data.rs;src/ui/dialogs/chart_settings/tabs/mod.rs;src/ui/dialogs/chart_settings/mod.rs,832;1871;2504 -Chart,Chart settings and themes,Chart settings dialog,incomplete,library,src/ui/dialogs/chart_settings/mod.rs;src/widget/settings/apply.rs;src/ui_kit/modal/modal.rs;src/ui/dialogs/chart_settings/tabs/mod.rs;src/ui_kit/dialog/mod.rs;src/ui_kit/sidebar_layout/mod.rs;src/tokens/mod.rs,2504;2713;2714;2715;2765;2766;2767 +Chart,Chart settings and themes,Canvas tab,incomplete,library,src/ui/dialogs/chart_settings/tabs/canvas.rs;src/widget/settings/apply.rs;src/widget/settings/data.rs;src/ui/dialogs/chart_settings/tabs/mod.rs;src/ui/dialogs/chart_settings/mod.rs,832;1871;2504;2770;2881 +Chart,Chart settings and themes,Chart settings dialog,incomplete,library,src/ui/dialogs/chart_settings/mod.rs;src/widget/settings/apply.rs;src/ui_kit/modal/modal.rs;src/ui/dialogs/chart_settings/tabs/mod.rs;src/ui_kit/dialog/mod.rs;src/ui_kit/sidebar_layout/mod.rs;src/tokens/mod.rs;src/widget/settings/data.rs,2504;2713;2714;2715;2765;2766;2767;2880 Chart,Chart settings and themes,Crosshair appearance,incomplete,library,src/widget/settings/apply.rs;src/chart/rendering/overlays/crosshair.rs;src/painting/dashed_line.rs;src/config/crosshair.rs;src/theme/presets.rs;src/widget/frame/mod.rs;src/model/chart_style.rs;src/chart/rendering/candles/line.rs;src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/pane/render/mod.rs;src/ui/dialogs/chart_settings/mod.rs;src/widget/pane/indicator/mod.rs;src/widget/frame/background.rs,1871;2536;2504;2499;2500 -Chart,Chart settings and themes,Events tab,incomplete,host,src/model/time_scale_event.rs;src/widget/settings/apply.rs;src/ui/dialogs/chart_settings/tabs/trading.rs;src/ui/dialogs/chart_settings/tabs/mod.rs;src/widget/frame/mod.rs,2830 +Chart,Chart settings and themes,Events tab,unverified,host,src/model/time_scale_event.rs;src/widget/settings/apply.rs;src/ui/dialogs/chart_settings/tabs/trading.rs;src/ui/dialogs/chart_settings/tabs/mod.rs;src/widget/frame/mod.rs,2830 Chart,Chart settings and themes,Grid lines,incomplete,library,src/chart/rendering/axes/labels.rs;src/chart/rendering/grid.rs;src/widget/settings/apply.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/indicator/paint.rs;src/painting/dashed_line.rs;src/theme/presets.rs;src/scales/timescale_marks.rs;src/scales/horizontal.rs;src/model/timezone.rs;src/widget/merge.rs;src/widget/frame/mod.rs;src/ui/dialogs/chart_settings/mod.rs,832;2536;2504 -Chart,Chart settings and themes,Light and dark themes,incomplete,library,src/widget/mod.rs;src/widget/palette.rs;src/config/chart.rs;src/model/markers.rs;src/chart/rendering/markers.rs;src/theme/presets.rs;src/theme/style.rs;src/chart/rendering/axes/mod.rs;examples/demo/controller.rs;src/widget/frame/mod.rs;examples/demo/formatting.rs;examples/demo/layouts.rs;src/ui/dialogs/chart_settings/mod.rs,1940;1521;2504;2713;2714;2715;2764;2766 -Chart,Chart settings and themes,Navigation and pane buttons,incomplete,library,src/widget/navigation.rs;src/widget/pane/mod.rs;src/widget/pane/controls.rs;src/widget/settings/data.rs;src/widget/frame/mod.rs,2831 -Chart,Chart settings and themes,Scales and lines tab,incomplete,library,src/ui/dialogs/chart_settings/tabs/scales.rs;src/widget/settings/apply.rs;src/widget/settings/data.rs;src/ui/dialogs/chart_settings/tabs/mod.rs;src/chart/rendering/axes/mod.rs;src/widget/frame/mod.rs,2455 -Chart,Chart settings and themes,Scales text colour size and family,incomplete,library,src/config/chart.rs;src/widget/settings/data.rs;src/widget/settings/apply.rs;src/chart/rendering/axes/mod.rs;src/chart/rendering/axes/labels.rs;src/widget/frame/mod.rs;src/widget/export.rs;src/widget/svg.rs;src/ui/dialogs/chart_settings/mod.rs,1885;2461;2462;2504;2768;2769 +Chart,Chart settings and themes,Light and dark themes,unverified,library,src/widget/mod.rs;src/widget/palette.rs;src/config/chart.rs;src/model/markers.rs;src/chart/rendering/markers.rs;src/theme/presets.rs;src/theme/style.rs;src/chart/rendering/axes/mod.rs;examples/demo/controller.rs;src/widget/frame/mod.rs;examples/demo/formatting.rs;examples/demo/layouts.rs;src/ui/dialogs/chart_settings/mod.rs;src/widget/history.rs;examples/demo/commands.rs,1940;1521;2504;2713;2714;2715;2764;2766;2813 +Chart,Chart settings and themes,Navigation and pane buttons,incomplete,library,src/widget/navigation.rs;src/widget/pane/mod.rs;src/widget/pane/controls.rs;src/widget/settings/data.rs;src/widget/frame/mod.rs;examples/demo/controller.rs, +Chart,Chart settings and themes,Scales and lines tab,incomplete,library,src/ui/dialogs/chart_settings/tabs/scales.rs;src/widget/settings/apply.rs;src/widget/settings/data.rs;src/ui/dialogs/chart_settings/tabs/mod.rs;src/chart/rendering/axes/mod.rs;src/widget/frame/mod.rs,2455;2836;2888 +Chart,Chart settings and themes,Scales text colour size and family,unverified,library,src/config/chart.rs;src/widget/settings/data.rs;src/widget/settings/apply.rs;src/chart/rendering/axes/mod.rs;src/chart/rendering/axes/labels.rs;src/widget/frame/mod.rs;src/widget/export.rs;src/widget/svg.rs;src/ui/dialogs/chart_settings/mod.rs;src/ui/dialogs/chart_settings/tabs/canvas.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/indicator/paint.rs;src/widget/pane/render/mod.rs;src/chart/rendering/axes/study_scale.rs,1885;2461;2462;2504;2768;2769 Chart,Chart settings and themes,Session background shading,incomplete,library,src/chart/rendering/session_breaks.rs;src/chart/rendering/legend/mod.rs;src/widget/frame/mod.rs;src/widget/frame/sessions.rs, Chart,Chart settings and themes,Status line tab,incomplete,library,src/widget/settings/apply.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/ui/dialogs/chart_settings/tabs/mod.rs;src/widget/frame/mod.rs, Chart,Chart settings and themes,Symbol tab,incomplete,library,src/widget/settings/apply.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/ui/dialogs/chart_settings/tabs/mod.rs;src/model/chart_style.rs;src/chart/rendering/candles/heikin_ashi.rs;src/widget/frame/mod.rs,2103;2104;2105;2107;2108;2141;2517 Chart,Chart settings and themes,Trading tab,incomplete,host,src/widget/settings/data.rs;src/ui/trading/mod.rs;src/ui/dialogs/chart_settings/tabs/trading.rs;src/ui/dialogs/chart_settings/tabs/mod.rs;terminal/src/trading.rs, -Chart,Chart settings and themes,Watermark,incomplete,library,src/widget/settings/apply.rs;src/widget/mod.rs;src/chart/rendering/watermark.rs;src/config/chart.rs;src/widget/palette.rs;src/theme/presets.rs;src/widget/frame/mod.rs;src/widget/frame/background.rs;src/widget/pane/mod.rs;src/widget/pane/render/mod.rs;src/widget/export.rs;src/widget/history.rs;src/ui/dialogs/chart_settings/mod.rs,1885;1890;2504;2770 +Chart,Chart settings and themes,Watermark,unverified,library,src/widget/settings/apply.rs;src/widget/mod.rs;src/chart/rendering/watermark.rs;src/config/chart.rs;src/widget/palette.rs;src/theme/presets.rs;src/widget/frame/mod.rs;src/widget/frame/background.rs;src/widget/pane/mod.rs;src/widget/pane/render/mod.rs;src/widget/export.rs;src/widget/history.rs;src/ui/dialogs/chart_settings/mod.rs;src/ui/dialogs/chart_settings/tabs/canvas.rs,1885;1890;2504;2770 Chart,Chart types,Area,incomplete,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/area.rs;src/widget/frame/mod.rs;src/model/chart_style.rs;src/chart/rendering/candles/line.rs;src/widget/series/options.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/widget/series/paint.rs;examples/demo/comparison.rs,1869;1870 Chart,Chart types,Bars,incomplete,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/candlestick.rs;src/chart/rendering/candles/bar.rs;src/widget/series/options.rs;src/widget/series/paint.rs;examples/demo/comparison.rs;src/model/chart_style.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/widget/settings/apply.rs;src/widget/series/scales/mod.rs;src/model/bar/time.rs;src/model/timescale.rs;src/widget/series/mod.rs;src/widget/time_scale.rs;src/widget/frame/mod.rs,1869;2141;2475;2498;2517 Chart,Chart types,Baseline,incomplete,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/area.rs;src/model/chart_style.rs;src/model/bar/bar.rs;src/widget/series/options.rs;src/chart/rendering/candles/line.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/widget/series/paint.rs;src/widget/frame/mod.rs;examples/demo/comparison.rs,1860;1869;1870;2518 Chart,Chart types,Candlestick chart,incomplete,library,src/widget/builder.rs;src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/candlestick.rs;src/chart/rendering/candles/candle.rs;src/widget/frame/mod.rs;src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/settings/apply.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/model/bar/time.rs;src/model/timescale.rs;src/widget/series/mod.rs;src/widget/time_scale.rs,1859;1869;2141;2475;2498;2517 Chart,Chart types,Chart type selector,incomplete,library,src/ui/top_toolbar/components/chart_type_selector.rs;src/ui/top_toolbar/toolbar.rs;src/widget/builder.rs, Chart,Chart types,Columns,incomplete,library,src/model/chart_type.rs;src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/candlestick.rs;src/widget/series/paint.rs;src/model/chart_style.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/model/bar/time.rs;src/model/timescale.rs;src/widget/series/mod.rs;src/widget/time_scale.rs;src/widget/frame/mod.rs,1876;2141;2498;1869 -Chart,Chart types,HLC area,incomplete,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/area.rs;src/model/chart_style.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/widget/series/options.rs;src/widget/palette.rs;src/ui/dialogs/series_settings/dialog.rs;src/widget/settings/data.rs,2107;2771 +Chart,Chart types,HLC area,unverified,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/area.rs;src/model/chart_style.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/widget/series/options.rs;src/widget/palette.rs;src/ui/dialogs/series_settings/dialog.rs;src/widget/settings/data.rs,2107 Chart,Chart types,Heikin Ashi,incomplete,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/heikin_ashi.rs;src/model/bar/bar_data.rs;src/chart/rendering/candles/candle.rs;src/widget/frame/mod.rs;src/model/chart_style.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/widget/settings/apply.rs;src/widget/series/options.rs;src/widget/series/scales/mod.rs;src/widget/mod.rs;src/model/bar/time.rs;src/model/timescale.rs;src/widget/series/mod.rs;src/widget/time_scale.rs;src/widget/series/paint.rs,1869;2103;2498;2517 Chart,Chart types,High-low,incomplete,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/range.rs;src/model/chart_style.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/widget/series/options.rs;src/widget/series/scales/mod.rs;src/widget/frame/mod.rs;src/widget/snapshot.rs;src/model/bar/time.rs;src/model/timescale.rs;src/widget/series/mod.rs;src/widget/time_scale.rs;src/widget/series/paint.rs,2108;2498;1869 Chart,Chart types,Hollow candles,incomplete,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/candlestick.rs;src/chart/rendering/candles/helpers.rs;src/model/chart_style.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/widget/settings/apply.rs;src/widget/series/options.rs;src/widget/series/scales/mod.rs;src/widget/frame/mod.rs;src/widget/mod.rs;src/widget/snapshot.rs;src/model/bar/time.rs;src/model/timescale.rs;src/widget/series/mod.rs;src/widget/time_scale.rs;src/widget/series/paint.rs,2104;2498;1869 -Chart,Chart types,Kagi,incomplete,library,src/chart/rendering/candles/price_based.rs;src/model/kagi.rs;src/chart/rendering/candles/japanese.rs;src/model/chart_style.rs;src/ui/dialogs/series_settings/tabs/symbol.rs,2767;2772;2773;2832;2834 +Chart,Chart types,Kagi,incomplete,library,src/chart/rendering/candles/price_based.rs;src/model/kagi.rs;src/chart/rendering/candles/japanese.rs;src/model/chart_style.rs;src/ui/dialogs/series_settings/tabs/symbol.rs,2832;2834 Chart,Chart types,Line,incomplete,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/line.rs;src/painting/dashed_line.rs;src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/frame/mod.rs;examples/demo/comparison.rs,1869 Chart,Chart types,Line break,incomplete,library,src/chart/rendering/candles/price_based.rs;src/model/line_break.rs;src/chart/rendering/candles/japanese.rs, Chart,Chart types,Line with markers,incomplete,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/line.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/painting/dashed_line.rs;src/model/chart_style.rs;src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/frame/mod.rs;examples/demo/comparison.rs,1869;1870 Chart,Chart types,Per-type style options,incomplete,library,src/model/chart_style.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/chart/rendering/candles/area.rs;src/chart/rendering/candles/japanese.rs;src/widget/series/options.rs;src/chart/rendering/candles/line.rs;src/widget/series/paint.rs;src/widget/frame/mod.rs;examples/demo/comparison.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/chart/rendering/candles/heikin_ashi.rs;src/widget/settings/apply.rs;src/chart/rendering/candles/bar.rs;src/chart/rendering/candles/candlestick.rs,1860;1869;1870;2103;2104;2105;2108;2141;2517;2518 -Chart,Chart types,Point and figure,incomplete,library,src/chart/rendering/candles/price_based.rs;src/model/point_figure.rs;src/model/range_bar.rs;src/chart/rendering/candles/japanese.rs,2767;2773;2832;2833;2834 -Chart,Chart types,Price-based type parameters,incomplete,library,src/model/chart_type.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/chart/rendering/candles/price_based.rs;src/model/chart_style.rs,2767;2780;2781 -Chart,Chart types,"Price-based types: axis, crosshair and legend",incomplete,library,src/widget/series/mod.rs;src/studies/chart_state.rs;src/chart/rendering/candles/price_based.rs;src/chart/rendering/overlays/crosshair.rs;src/widget/frame/mod.rs,2778;2779;2832 -Chart,Chart types,Range,incomplete,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/price_based.rs;src/model/range_bar.rs;src/data/trades.rs;src/widget/series/mod.rs;src/widget/feed/mod.rs,2774;2775;2776;2777;2835;2836;2837 -Chart,Chart types,Renko,incomplete,library,src/chart/rendering/candles/price_based.rs;src/model/renko.rs;src/chart/rendering/candles/japanese.rs;src/ui/dialogs/series_settings/tabs/symbol.rs,2775;2778;2832;2838 +Chart,Chart types,Point and figure,incomplete,library,src/chart/rendering/candles/price_based.rs;src/model/point_figure.rs;src/model/range_bar.rs;src/chart/rendering/candles/japanese.rs,2832;2833;2834 +Chart,Chart types,Price-based type parameters,incomplete,library,src/model/chart_type.rs;src/chart/rendering/candles/mod.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/chart/rendering/candles/price_based.rs;src/model/chart_style.rs;src/widget/builder.rs;src/widget/settings/apply.rs;src/widget/replay.rs, +Chart,Chart types,"Price-based types: axis, crosshair and legend",incomplete,library,src/widget/series/mod.rs;src/studies/chart_state.rs;src/chart/rendering/candles/price_based.rs;src/chart/rendering/overlays/crosshair.rs;src/widget/frame/mod.rs,2832 +Chart,Chart types,Range,incomplete,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/price_based.rs;src/chart/rendering/candles/range.rs;src/chart/rendering/candles/japanese.rs;src/model/range_bar.rs;src/model/renko.rs;src/data/trades.rs;src/widget/series/mod.rs;src/widget/feed/mod.rs;src/widget/builder.rs,2835;2837 +Chart,Chart types,Renko,incomplete,library,src/chart/rendering/candles/price_based.rs;src/model/renko.rs;src/chart/rendering/candles/japanese.rs;src/ui/dialogs/series_settings/tabs/symbol.rs,2832;2838 Chart,Chart types,Session volume profile,incomplete,host,src/widget/feed/mod.rs;src/studies/builtin/trade_profile.rs;src/chart/overlays/trade_profile.rs;src/widget/merge.rs;src/data/footprint.rs;src/widget/trade_profile.rs;src/studies/chart_state.rs;src/widget/frame/mod.rs;src/model/chart_type.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/data/order_flow.rs;src/data/inbox/sink.rs, Chart,Chart types,Step line,incomplete,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/line.rs;src/painting/dashed_line.rs;src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/frame/mod.rs;examples/demo/comparison.rs,1869 Chart,Chart types,Time Price Opportunity,incomplete,library,src/chart/rendering/candles/mod.rs;src/chart/rendering/candles/tpo.rs;src/model/tpo.rs;src/model/session/exchange.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/chart/rendering/candles/line.rs;src/tokens/mod.rs;src/tokens/semantic.rs;src/model/chart_type.rs;src/studies/chart_state.rs;src/widget/frame/mod.rs,2432 Chart,Chart types,Volume candles,incomplete,library,src/chart/rendering/candles/candlestick.rs;src/widget/frame/mod.rs;src/model/chart_style.rs;src/ui/dialogs/chart_settings/mod.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/widget/settings/apply.rs;src/widget/series/options.rs;src/widget/series/scales/mod.rs;src/widget/palette.rs;src/ui/dialogs/series_settings/dialog.rs;src/widget/mod.rs;src/widget/snapshot.rs;src/widget/builder.rs;src/model/bar/time.rs;src/model/timescale.rs;src/widget/series/mod.rs;src/widget/time_scale.rs;src/widget/series/paint.rs,1869;2105;2475;2498;2517 -Chart,Chart types,Volume footprint,incomplete,host,src/widget/feed/mod.rs;src/data/footprint.rs;src/chart/overlays/footprint.rs;src/widget/merge.rs;benches/frame_time.rs;src/widget/feed/pump.rs;src/widget/frame/mod.rs;src/model/chart_type.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/data/order_flow.rs;src/data/inbox/sink.rs;src/data/inbox/mod.rs;src/data/trades.rs,2458;2696;2697;2754;2839;2723;2840;2841;2842 +Chart,Chart types,Volume footprint,incomplete,host,src/widget/feed/mod.rs;src/data/footprint.rs;src/chart/overlays/footprint.rs;src/widget/merge.rs;benches/frame_time.rs;src/widget/feed/pump.rs;src/widget/frame/mod.rs;src/model/chart_type.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/data/order_flow.rs;src/data/inbox/sink.rs;src/data/inbox/mod.rs;src/data/trades.rs,2458;2696;2697;2754;2839;2723;2841 Chart,Compare and overlay,Compare on a new price scale,verified,host,src/model/series_scale.rs;src/widget/series/options.rs;src/widget/series/scales/mod.rs, -Chart,Compare and overlay,Compare symbol,incomplete,host,src/widget/series/options.rs;src/widget/feed/mod.rs;src/widget/studies_data.rs;terminal/src/compare.rs;src/widget/series/paint.rs;examples/demo/comparison.rs;examples/demo/live.rs;examples/demo/controller.rs;src/ui/dialogs/symbol_search/compare.rs,1920;1915;2194;2783 +Chart,Compare and overlay,Compare symbol,unverified,host,src/widget/series/options.rs;src/widget/feed/mod.rs;src/widget/studies_data.rs;terminal/src/compare.rs;src/widget/series/paint.rs;examples/demo/comparison.rs;examples/demo/live.rs;examples/demo/controller.rs;src/ui/dialogs/symbol_search/compare.rs,1920;1915;2194 Chart,Compare and overlay,Overlay a symbol on the same price scale,verified,host,src/widget/series/options.rs;src/widget/series/mod.rs;src/widget/format.rs;src/widget/series/paint.rs,2483 Chart,Compare and overlay,Percent scale when comparing,verified,library,src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/series/scales/mod.rs;src/model/series_style.rs;src/scales/pricescale.rs,1874 -Chart,Crosshair and interaction,Auto-scroll to realtime and jump-to-latest button,incomplete,library,src/widget/series/mod.rs;src/widget/time_scale.rs;src/widget/frame/mod.rs;src/widget/navigation.rs;src/config/timescale.rs;src/model/timescale.rs;src/studies/chart_state.rs;src/widget/interaction.rs;src/widget/pane/render/mod.rs,1879;2346;2488;2501;2784 -Chart,Crosshair and interaction,"Chart, series and drawing context menus",incomplete,library,src/ui/context_menu/mod.rs;src/ui/context_menu/chart_menus/mod.rs;src/ui/context_menu/series.rs;src/ui/context_menu/drawing.rs;src/widget/drawing_api.rs;terminal/src/drawings.rs;terminal/src/studies.rs;src/ui/floating_toolbar/toolbar.rs;examples/demo/controller.rs;terminal/src/panels.rs;terminal/src/trading.rs,566 +Chart,Crosshair and interaction,Auto-scroll to realtime and jump-to-latest button,unverified,library,src/widget/series/mod.rs;src/widget/time_scale.rs;src/widget/frame/mod.rs;src/widget/navigation.rs;src/config/timescale.rs;src/model/timescale.rs;src/studies/chart_state.rs;src/widget/interaction.rs;src/widget/pane/render/mod.rs,1879;2346;2488;2501;2784 +Chart,Crosshair and interaction,"Chart, series and drawing context menus",incomplete,library,src/ui/context_menu/mod.rs;src/ui/context_menu/chart_menus/mod.rs;src/ui/context_menu/series.rs;src/ui/context_menu/drawing.rs;src/widget/drawing_api.rs;terminal/src/drawings.rs;terminal/src/studies.rs;src/ui/floating_toolbar/toolbar.rs;examples/demo/controller.rs;terminal/src/panels.rs;terminal/src/trading.rs;terminal/src/commands.rs,566 Chart,Crosshair and interaction,Crosshair across all panes,incomplete,library,src/widget/pane/render/mod.rs;src/widget/pane/indicator/mod.rs;src/widget/frame/mod.rs;src/widget/sync.rs,1883;2512;2471 Chart,Crosshair and interaction,Crosshair index eligibility,verified,library,src/config/timescale.rs;src/widget/crosshair.rs;src/widget/events.rs;src/widget/frame/mod.rs;src/widget/pane/render/mod.rs;src/widget/sync.rs,1880;2512 Chart,Crosshair and interaction,Crosshair lines and independent axis labels,incomplete,library,src/chart/rendering/overlays/crosshair.rs;src/scales/time_formatter.rs;src/painting/dashed_line.rs;src/config/crosshair.rs;src/chart/rendering/axes/mod.rs;src/theme/presets.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/render/mod.rs;src/scales/horizontal.rs;src/widget/frame/mod.rs;src/widget/export.rs;src/widget/sync.rs;src/widget/snapshot.rs,1883;2536;2512;2466;2469;2472;107 Chart,Crosshair and interaction,Cursor types,incomplete,library,src/widget/tool_interaction/cursor_modes/mod.rs;src/widget/tool_interaction/cursor_modes/eraser.rs;src/widget/tool_interaction/selection.rs;src/widget/pane/render/mod.rs;src/drawings/manager/interaction.rs;src/widget/frame/mod.rs,107 -Chart,Crosshair and interaction,Double-click on axes to reset,incomplete,library,src/widget/pan_zoom/mod.rs;src/widget/pane/mod.rs;src/widget/pane/controls.rs;src/widget/frame/mod.rs;src/config/interaction.rs,1888;2228;2785 -Chart,Crosshair and interaction,Drag on the time axis to zoom,incomplete,library,src/widget/pan_zoom/mod.rs;src/widget/frame/mod.rs;src/config/interaction.rs,1888;2786 -Chart,Crosshair and interaction,Drag or wheel on the price axis to zoom,incomplete,library,src/widget/pan_zoom/mod.rs;src/widget/frame/mod.rs;src/config/interaction.rs;src/widget/pane/controls.rs;src/widget/series/paint.rs;src/scales/pricescale.rs,1888;2570;2787;2788 +Chart,Crosshair and interaction,Double-click on axes to reset,unverified,library,src/widget/pan_zoom/mod.rs;src/widget/pane/mod.rs;src/widget/pane/controls.rs;src/widget/series/paint.rs;src/widget/frame/mod.rs;src/config/interaction.rs,1888;2228;2785 +Chart,Crosshair and interaction,Drag on the time axis to zoom,unverified,library,src/widget/pan_zoom/mod.rs;src/widget/frame/mod.rs;src/config/interaction.rs,1888;2786 +Chart,Crosshair and interaction,Drag or wheel on the price axis to zoom,unverified,library,src/widget/pan_zoom/mod.rs;src/widget/frame/mod.rs;src/config/interaction.rs;src/widget/pane/controls.rs;src/widget/series/paint.rs;src/scales/pricescale.rs,1888;2570;2787;2788 Chart,Crosshair and interaction,Drag to pan,incomplete,library,src/widget/pan_zoom/mod.rs;src/widget/frame/mod.rs;src/config/interaction.rs;src/widget/pane/render/mod.rs;src/drawings/manager/interaction.rs,1888;2226;2488;2542 -Chart,Crosshair and interaction,Go to date,incomplete,library,src/widget/builder.rs;src/widget/pan_zoom/mod.rs;terminal/src/time.rs,2789 +Chart,Crosshair and interaction,Go to date,incomplete,library,src/widget/builder.rs;src/widget/pan_zoom/mod.rs;terminal/src/time.rs, Chart,Crosshair and interaction,Horizontal scroll,incomplete,library,src/widget/pan_zoom/mod.rs;src/widget/frame/mod.rs;src/config/interaction.rs,1888;2488 Chart,Crosshair and interaction,Hover tooltip and floating data window,incomplete,library,src/chart/rendering/overlays/tooltip.rs;src/widget/readout.rs;src/scales/horizontal.rs;src/scales/time_formatter.rs;src/widget/frame/mod.rs;examples/demo/annotations.rs;src/widget/format.rs;src/config/tooltip.rs;terminal/src/drawings.rs,1938;2293;2475;2512;2483 -Chart,Crosshair and interaction,Kinetic scroll,incomplete,library,src/widget/pan_zoom/mod.rs;src/config/kinetic.rs;src/widget/mod.rs;src/widget/builder.rs;src/config/interaction.rs,1888;2790;2791;2792 +Chart,Crosshair and interaction,Kinetic scroll,unverified,library,src/widget/pan_zoom/mod.rs;src/widget/pan_zoom/state.rs;src/widget/keyboard.rs;src/config/kinetic.rs;src/widget/mod.rs;src/widget/builder.rs;src/config/interaction.rs,1888;2790;2791;2792 Chart,Crosshair and interaction,Magnet crosshair,incomplete,library,src/config/crosshair.rs;src/widget/crosshair.rs;src/widget/series/scales/mod.rs;src/widget/frame/mod.rs;src/widget/pane/render/mod.rs;src/widget/events.rs;src/widget/series/options.rs;src/widget/series/paint.rs, Chart,Crosshair and interaction,Mouse wheel zoom anchored at the cursor,incomplete,library,src/widget/pan_zoom/mod.rs;src/model/timescale.rs;src/widget/frame/mod.rs;src/config/interaction.rs;src/widget/pane/render/mod.rs;src/config/timescale.rs;src/widget/time_scale.rs,1888;2226;2567;2570 -Chart,Crosshair and interaction,Pinch zoom and two-finger pan,incomplete,library,src/widget/pan_zoom/mod.rs;src/widget/frame/mod.rs;src/config/interaction.rs;src/widget/pane/render/mod.rs,1888;2226;2567;2793 -Chart,Crosshair and interaction,Price scale and time scale context menus,incomplete,library,src/ui/context_menu/mod.rs;src/ui/context_menu/chart_menus/mod.rs;src/ui/context_menu/axis.rs;src/widget/series/scales/mod.rs;src/widget/pane/controls.rs,2044;2794;2795;2796 +Chart,Crosshair and interaction,Pinch zoom and two-finger pan,unverified,library,src/widget/pan_zoom/mod.rs;src/widget/frame/mod.rs;src/config/interaction.rs;src/widget/pane/render/mod.rs,1888;2226;2567;2793 +Chart,Crosshair and interaction,Price scale and time scale context menus,incomplete,library,src/ui/context_menu/mod.rs;src/ui/context_menu/chart_menus/mod.rs;src/ui/context_menu/axis.rs;src/widget/series/scales/mod.rs;src/widget/pane/controls.rs;src/widget/series/paint.rs;src/widget/history.rs,2044;2794;2795;2796 Chart,Crosshair and interaction,Programmatic crosshair positioning,incomplete,library,src/widget/layout.rs;src/widget/sync.rs;src/widget/frame/mod.rs;src/widget/pane/render/mod.rs;src/widget/export.rs;src/chart/rendering/overlays/crosshair.rs;src/widget/pane/indicator/mod.rs,1883;2474;2512;2466;2469;2471 Chart,Crosshair and interaction,Scroll and scale handler group switches,incomplete,library,src/config/interaction.rs;src/widget/pan_zoom/mod.rs;src/widget/pane/controls.rs;src/widget/series/paint.rs,1888 -Chart,Crosshair and interaction,Table view of chart data,incomplete,library,src/widget/export.rs;src/widget/snapshot.rs;src/ui/dialogs/data_table.rs;src/ui/context_menu/mod.rs;src/widget/readout.rs;src/widget/studies.rs;src/widget/mod.rs;src/widget/builder.rs;src/widget/series/mod.rs;src/widget/studies_data.rs;src/widget/feed/pump.rs;src/widget/frame/mod.rs;src/widget/feed/mod.rs;examples/demo/controller.rs,2100;2219;2220;2221;2222;2223;2452;2701;2753;2843 +Chart,Crosshair and interaction,Table view of chart data,incomplete,library,src/widget/export.rs;src/widget/snapshot.rs;src/ui/dialogs/data_table.rs;src/ui/context_menu/mod.rs;src/widget/readout.rs;src/widget/studies.rs;src/widget/mod.rs;src/widget/builder.rs;src/widget/series/mod.rs;src/widget/studies_data.rs;src/widget/feed/pump.rs;src/widget/frame/mod.rs;src/widget/feed/mod.rs;examples/demo/controller.rs;terminal/src/commands.rs,2100;2219;2220;2221;2222;2223;2452;2701;2753;2843 Chart,Crosshair and interaction,Touch crosshair tracking,incomplete,library,src/config/interaction.rs;src/config/tooltip.rs;src/widget/interaction.rs;src/widget/frame/mod.rs;src/widget/pane/render/mod.rs;src/widget/events.rs,1889;2488;2489;2487;2512 -Chart,Crosshair and interaction,Undo and redo,verified,library,src/widget/history.rs;src/widget/feed/mod.rs;examples/demo/controller.rs;src/widget/series/mod.rs;src/widget/replay.rs;src/widget/pane/render/mod.rs;src/widget/events.rs;src/widget/series/options.rs;examples/demo/comparison.rs;terminal/src/compare.rs;src/scales/pricescale.rs;src/widget/layout.rs;src/widget/studies_data.rs;src/widget/studies.rs;src/studies/settings.rs,1922;2316;2321;2505;2520;2527;2522;2688;2689 +Chart,Crosshair and interaction,Undo and redo,incomplete,library,src/widget/history.rs;src/widget/feed/mod.rs;examples/demo/controller.rs;src/widget/series/mod.rs;src/widget/replay.rs;src/widget/pane/render/mod.rs;src/widget/events.rs;src/widget/series/options.rs;examples/demo/comparison.rs;terminal/src/compare.rs;src/scales/pricescale.rs;src/widget/layout.rs;src/widget/studies_data.rs;src/widget/studies.rs;src/studies/settings.rs;src/drawings/manager/interaction.rs;src/widget/palette.rs,1922;2316;2321;2505;2520;2527;2522;2688;2689;2812;2813;2844;2949 Chart,Crosshair and interaction,Zoom-to-rectangle tool,incomplete,library,src/widget/pan_zoom/mod.rs;src/widget/pan_zoom/box_zoom.rs, -Chart,Keyboard shortcuts,Copy and paste drawings across symbols,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/widget/clipboard.rs;src/widget/pane/mod.rs;src/studies/template.rs;src/model/bar/time.rs;src/ui/context_menu/drawing.rs;terminal/src/drawings.rs;examples/demo/controller.rs,2418;2445;2804;2805 -Chart,Keyboard shortcuts,Ctrl+Left/Right move further,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs,2797 +Chart,Keyboard shortcuts,Copy and paste drawings across symbols,unverified,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/widget/clipboard.rs;src/widget/pane/mod.rs;src/studies/template.rs;src/model/bar/time.rs;src/ui/context_menu/drawing.rs;terminal/src/drawings.rs;examples/demo/controller.rs;terminal/src/commands.rs,2418;2445;2805;2804 +Chart,Keyboard shortcuts,Ctrl+Left/Right move further,unverified,library,src/config/keyboard.rs;src/widget/keyboard.rs,2797 Chart,Keyboard shortcuts,Delete and Escape on a selected drawing,verified,library,src/config/keyboard.rs;src/widget/keyboard.rs, -Chart,Keyboard shortcuts,Digits or comma to change interval,incomplete,library,src/widget/keyboard.rs;src/config/keyboard.rs;terminal/src/time.rs,2801 -Chart,Keyboard shortcuts,Drawing tool hotkeys,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/ui/drawing_toolbar/shortcuts.rs;src/widget/tool_interaction/mod.rs,2798;2799 -Chart,Keyboard shortcuts,Go to date,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs;terminal/src/time.rs,2798;2799 -Chart,Keyboard shortcuts,Hide all drawings,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs,2802;2803 +Chart,Keyboard shortcuts,Digits or comma to change interval,incomplete,library,src/widget/keyboard.rs;src/config/keyboard.rs;terminal/src/time.rs;examples/demo/interval.rs,3023 +Chart,Keyboard shortcuts,Drawing tool hotkeys,unverified,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/ui/drawing_toolbar/shortcuts.rs;src/widget/tool_interaction/mod.rs, +Chart,Keyboard shortcuts,Go to date,unverified,library,src/config/keyboard.rs;src/widget/keyboard.rs;terminal/src/time.rs, +Chart,Keyboard shortcuts,Hide all drawings,unverified,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/drawings/manager/edit.rs,2802;2803 Chart,Keyboard shortcuts,Jump to latest bar,verified,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/widget/time_scale.rs, -Chart,Keyboard shortcuts,Keyboard zoom,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/model/timescale.rs,2798 -Chart,Keyboard shortcuts,Left/Right arrows move the chart or selected drawings,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/widget/interaction.rs,2797 +Chart,Keyboard shortcuts,Keyboard zoom,unverified,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/model/timescale.rs, +Chart,Keyboard shortcuts,Left/Right arrows move the chart or selected drawings,unverified,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/widget/interaction.rs, Chart,Keyboard shortcuts,Maximize chart,incomplete,library,src/config/keyboard.rs;src/widget/layout.rs, Chart,Keyboard shortcuts,Next and previous chart,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/widget/layout.rs;terminal/src/layouts.rs, -Chart,Keyboard shortcuts,Open indicators,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs,2798;2800 -Chart,Keyboard shortcuts,Quick search,incomplete,library,src/config/keyboard.rs;src/ui_kit/command_palette/palette.rs,2806;2807;2808;2809 +Chart,Keyboard shortcuts,Open indicators,unverified,library,src/config/keyboard.rs;src/widget/keyboard.rs;terminal/src/commands.rs,2798;2800 +Chart,Keyboard shortcuts,Quick search,incomplete,library,src/config/keyboard.rs;src/ui_kit/command_palette/palette.rs;src/ui_kit/command_palette/fuzzy.rs;terminal/src/commands.rs;examples/demo/commands.rs, Chart,Keyboard shortcuts,Reset chart,verified,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/widget/time_scale.rs, Chart,Keyboard shortcuts,Save layout,verified,library,src/config/keyboard.rs;terminal/src/layouts.rs, -Chart,Keyboard shortcuts,Scale toggles,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs,2798;2799;2810 -Chart,Keyboard shortcuts,Shortcut list dialog,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/ui/dialogs/keyboard_shortcuts/mod.rs,2798;2811 -Chart,Keyboard shortcuts,Snapshot,incomplete,library,src/config/keyboard.rs;src/widget/export.rs;src/ui/top_toolbar/toolbar.rs, -Chart,Keyboard shortcuts,Type to change symbol,incomplete,host,src/widget/keyboard.rs,2798;2799;2800;2810 -Chart,Keyboard shortcuts,Undo and redo,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/widget/history.rs;src/widget/layout.rs;src/widget/studies.rs;src/studies/settings.rs,2505;2522;2688;2689;2810;2812;2813;2844 +Chart,Keyboard shortcuts,Scale toggles,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs,2810;2798;2799 +Chart,Keyboard shortcuts,Shortcut list dialog,unverified,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/ui/dialogs/keyboard_shortcuts/mod.rs;terminal/src/commands.rs,2798 +Chart,Keyboard shortcuts,Snapshot,incomplete,library,src/config/keyboard.rs;src/widget/export.rs;src/ui/top_toolbar/toolbar.rs;terminal/src/commands.rs, +Chart,Keyboard shortcuts,Type to change symbol,incomplete,host,src/widget/keyboard.rs;terminal/src/commands.rs,2798;2799;2800;2810 +Chart,Keyboard shortcuts,Undo and redo,incomplete,library,src/config/keyboard.rs;src/widget/keyboard.rs;src/widget/history.rs;src/widget/layout.rs;src/widget/studies.rs;src/studies/settings.rs;src/drawings/manager/interaction.rs;src/widget/palette.rs,2505;2522;2688;2689;2810;2812;2813;2844;2949 Chart,Legend and data window,Data window panel,incomplete,library,src/ui/widget_bar/panels/object_tree/data_window.rs;src/widget/readout.rs;src/scales/horizontal.rs;src/scales/time_formatter.rs;src/widget/frame/mod.rs;examples/demo/formatting.rs;terminal/src/drawings.rs;src/widget/format.rs,1939;2483;2814;2815;2817;2818;2819 Chart,Legend and data window,Indicator entries in the legend,incomplete,library,src/chart/rendering/legend/mod.rs;src/widget/pane/render/mod.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/indicator/paint.rs;src/config/chart.rs;src/theme/presets.rs;src/studies/builtin/order_flow.rs;src/studies/indicator_trait.rs;src/studies/settings.rs;src/widget/frame/mod.rs;examples/demo/controller.rs, Chart,Legend and data window,Legend buttons,incomplete,library,src/chart/rendering/legend/mod.rs;src/chart/rendering/legend/study_controls.rs;src/widget/crosshair.rs;src/widget/pane/render/mod.rs;src/studies/settings.rs;src/widget/series/paint.rs;src/widget/frame/mod.rs;src/widget/history.rs;src/widget/snapshot.rs;src/widget/layout.rs,2040;2029;2437;2519;2524 @@ -214,22 +215,22 @@ Chart,Multi-chart and sync,Multi-chart layout container,incomplete,library,src/w Chart,Multi-chart and sync,Symbol and interval sync groups,incomplete,library,src/widget/layout.rs;src/widget/history.rs;src/widget/frame/mod.rs;src/widget/snapshot.rs;examples/demo/replay.rs;examples/demo/storage.rs;examples/demo/layouts.rs,1941;2102;2437;2688;2826;2827;2828;2829 Chart,Multi-chart and sync,Sync crosshair,incomplete,library,src/widget/layout.rs;src/widget/sync.rs;src/widget/frame/mod.rs,2474;2512;2814;2852;2853 Chart,Multi-chart and sync,Sync date range,incomplete,library,src/widget/layout.rs;src/widget/sync.rs;src/model/timescale.rs,2854 -Chart,Multi-chart and sync,Sync drawings,incomplete,library,src/widget/layout.rs;src/widget/layout/drawings.rs;src/widget/stored_drawings.rs;src/widget/history.rs;src/drawings/services/history.rs,2855;2856;2857;2858 +Chart,Multi-chart and sync,Sync drawings,unverified,library,src/widget/layout.rs;src/widget/layout/drawings.rs;src/widget/stored_drawings.rs;src/widget/history.rs;src/drawings/services/history.rs, Chart,Multi-chart and sync,Sync interval,verified,host,src/widget/layout.rs;src/widget/feed/mod.rs;src/widget/sync.rs;src/model/timescale.rs, -Chart,Multi-chart and sync,Sync symbol,incomplete,host,src/widget/layout.rs;src/widget/feed/mod.rs,2826;2829;2864 +Chart,Multi-chart and sync,Sync symbol,incomplete,host,src/widget/layout.rs;src/widget/feed/mod.rs,2826;2829 Chart,Multi-chart and sync,Sync time,incomplete,library,src/widget/layout.rs;src/widget/sync.rs;src/model/timescale.rs, Chart,Multi-chart and sync,Up to 16 charts per tab,verified,library,src/widget/layout.rs, -Chart,Panes,Collapse pane,incomplete,library,src/widget/pane/mod.rs;src/widget/pane/controls.rs;src/widget/pane/render/mod.rs;src/widget/frame/mod.rs;src/widget/keyboard.rs,2028;2226;2227;2228;2860 -Chart,Panes,Maximize pane,incomplete,library,src/widget/pane/mod.rs;src/widget/pane/controls.rs;src/widget/pane/render/mod.rs;src/widget/pane/indicator/mod.rs,2859;2860;2861 +Chart,Panes,Collapse pane,unverified,library,src/widget/pane/mod.rs;src/widget/pane/controls.rs;src/widget/pane/render/mod.rs;src/widget/frame/mod.rs;src/widget/keyboard.rs, +Chart,Panes,Maximize pane,unverified,library,src/widget/pane/mod.rs;src/widget/pane/controls.rs;src/widget/pane/render/mod.rs;src/widget/pane/indicator/mod.rs;src/widget/frame/mod.rs, Chart,Panes,"Move indicator to another pane, merge, or new pane",incomplete,library,src/widget/pane/mod.rs;src/widget/pane/controls.rs;src/widget/studies.rs,89;827;2521 -Chart,Panes,Move pane up or down,incomplete,library,src/widget/pane/mod.rs;src/widget/pane/controls.rs,2862 +Chart,Panes,Move pane up or down,unverified,library,src/widget/pane/mod.rs;src/widget/pane/controls.rs, Chart,Panes,Per-pane price scales,incomplete,library,src/widget/pane/render/mod.rs;src/widget/pane/mod.rs;src/widget/pane/controls.rs;src/widget/series/options.rs;src/widget/series/scales/mod.rs;src/chart/rendering/markers.rs;src/widget/frame/mod.rs;src/scales/pricescale.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/indicator/paint.rs;src/widget/snapshot.rs;src/widget/format.rs;src/widget/events.rs;src/widget/time_scale.rs;src/model/series_scale.rs;src/widget/history.rs,1878;2044;2526;2469 -Chart,Panes,Programmatic pane and series API,verified,library,src/widget/pane/mod.rs;src/widget/series/options.rs;src/widget/series/mod.rs;src/widget/frame/mod.rs;src/widget/pane/render/mod.rs;src/widget/events.rs;src/widget/snapshot.rs;src/widget/series/scales/mod.rs;src/widget/volume.rs;src/model/series_scale.rs;src/widget/primitives.rs;src/chart/primitives.rs;src/chart/rendering/watermark.rs,1867;1890;1902;2044 +Chart,Panes,Programmatic pane and series API,unverified,library,src/widget/pane/mod.rs;src/widget/series/options.rs;src/widget/series/mod.rs;src/widget/frame/mod.rs;src/widget/pane/render/mod.rs;src/widget/events.rs;src/widget/snapshot.rs;src/widget/series/scales/mod.rs;src/widget/volume.rs;src/model/series_scale.rs;src/widget/primitives.rs;src/chart/primitives.rs;src/chart/rendering/watermark.rs,1867;1890;1902;2044 Chart,Panes,Remove pane,verified,library,src/widget/pane/mod.rs;src/widget/pane/controls.rs;src/widget/pane/render/mod.rs;src/widget/frame/mod.rs;src/widget/primitives.rs;src/widget/snapshot.rs;src/widget/studies.rs;src/widget/series/options.rs;src/widget/series/mod.rs;src/widget/feed/mod.rs;src/widget/history.rs,1877;1902;2521 -Chart,Panes,Resize panes by dragging the separator,incomplete,library,src/widget/pane/mod.rs;src/widget/pane/controls.rs;src/widget/pane/render/mod.rs,2865 +Chart,Panes,Resize panes by dragging the separator,unverified,library,src/widget/pane/mod.rs;src/widget/pane/controls.rs;src/widget/pane/render/mod.rs, Chart,Panes,Separate indicator panes,verified,library,src/widget/pane/mod.rs;src/widget/pane/render/mod.rs, -Chart,Panes,Shared time axis across panes,incomplete,library,src/widget/pane/render/mod.rs;src/widget/time_scale.rs;src/studies/chart_state.rs;src/widget/series/mod.rs;src/widget/frame/mod.rs,1882;2226;2866 -Chart,Panes,Volume area in the main pane,verified,library,src/widget/volume.rs;src/chart/rendering/candles/volume.rs;src/theme/mod.rs;src/theme/presets.rs;src/widget/frame/mod.rs;src/chart/coords/mod.rs;src/model/timescale.rs;src/chart/rendering/indicator.rs;src/widget/time_scale.rs;src/chart/rendering/candles/candlestick.rs,2475;2497;2498 +Chart,Panes,Shared time axis across panes,unverified,library,src/widget/pane/render/mod.rs;src/widget/time_scale.rs;src/studies/chart_state.rs;src/widget/series/mod.rs;src/widget/frame/mod.rs;src/widget/pan_zoom/mod.rs,1882;2226;2866 +Chart,Panes,Volume area in the main pane,unverified,library,src/widget/volume.rs;src/chart/rendering/candles/volume.rs;src/theme/mod.rs;src/theme/presets.rs;src/widget/frame/mod.rs;src/chart/coords/mod.rs;src/model/timescale.rs;src/chart/rendering/indicator.rs;src/widget/time_scale.rs;src/chart/rendering/candles/candlestick.rs,2475;2497;2498 Chart,Scales and axes,Auto-scale,incomplete,library,src/studies/chart_state.rs;src/scales/pricescale.rs;src/ui/top_toolbar/components/settings_menu/menu.rs;src/widget/frame/mod.rs;src/widget/series/scales/mod.rs;src/chart/rendering/markers.rs;src/widget/pane/render/mod.rs;src/model/series_style.rs;src/chart/primitives.rs;src/widget/primitives.rs;src/widget/pane/indicator/mod.rs;src/studies/plots.rs,1875;2458;2526;2642;2867 Chart,Scales and axes,Bar spacing and time zoom,incomplete,library,src/model/timescale.rs;src/widget/pan_zoom/mod.rs;src/config/timescale.rs;src/widget/sync.rs;src/widget/mod.rs;src/widget/builder.rs;src/widget/keyboard.rs;src/widget/time_scale.rs;src/studies/chart_state.rs;src/widget/frame/mod.rs;src/model/bar/time.rs;src/widget/series/mod.rs;src/scales/horizontal.rs;src/widget/series/scales/mod.rs;src/widget/snapshot.rs;docs/site/src/content/docs/horizontal-scales.mdx,1882;2497;2570 Chart,Scales and axes,Bid and ask lines,incomplete,host,src/widget/mod.rs;src/widget/settings/apply.rs;src/chart/rendering/axes/mod.rs;src/painting/dashed_line.rs;src/widget/frame/mod.rs,2536 @@ -241,11 +242,11 @@ Chart,Scales and axes,Index-based time axis,verified,library,src/model/timescale Chart,Scales and axes,Indexed to 100 scale,incomplete,library,src/scales/pricescale.rs;src/scales/pricescale_marks.rs;src/studies/chart_state.rs;src/ui/dialogs/series_settings/tabs/scales.rs;src/widget/mod.rs;src/model/series_style.rs;src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/frame/mod.rs;src/painting/dashed_line.rs;src/widget/pane/indicator/mod.rs;src/widget/series/scales/mod.rs;src/widget/pane/render/mod.rs,1874;2536;2526;2469 Chart,Scales and axes,Indicator labels and last values on the scale,incomplete,library,src/chart/rendering/axes/mod.rs;src/widget/settings/apply.rs;src/chart/rendering/axes/study_scale.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/indicator/paint.rs;src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/series/scales/mod.rs;src/widget/volume.rs;src/studies/settings.rs;src/widget/frame/mod.rs,2868 Chart,Scales and axes,Invert scale,verified,library,src/widget/settings/apply.rs;src/widget/mod.rs;src/scales/pricescale.rs;src/widget/frame/mod.rs, -Chart,Scales and axes,Last price line and label,incomplete,library,src/chart/rendering/axes/mod.rs;src/widget/settings/apply.rs;src/painting/dashed_line.rs;src/model/series_style.rs;src/widget/frame/mod.rs;src/model/chart_style.rs;src/chart/rendering/candles/heikin_ashi.rs;src/chart/rendering/candles/helpers.rs;src/widget/series/scales/mod.rs,2103;2536 +Chart,Scales and axes,Last price line and label,incomplete,library,src/chart/rendering/axes/mod.rs;src/widget/settings/apply.rs;src/painting/dashed_line.rs;src/model/series_style.rs;src/widget/frame/mod.rs;src/model/chart_style.rs;src/chart/rendering/candles/heikin_ashi.rs;src/chart/rendering/candles/helpers.rs;src/widget/series/scales/mod.rs;src/ui/dialogs/chart_settings/tabs/scales.rs;src/widget/settings/data.rs,2103;2536;2836 Chart,Scales and axes,Left price scale and moving the scale,incomplete,library,src/widget/settings/apply.rs;src/widget/mod.rs;src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/series/scales/mod.rs;src/ui/context_menu/axis.rs;src/widget/frame/mod.rs;src/widget/snapshot.rs,2869;2870 Chart,Scales and axes,Lock price to bar ratio,incomplete,library,src/ui/context_menu/axis.rs;src/scales/pricescale.rs;src/widget/frame/mod.rs;src/widget/series/scales/mod.rs, Chart,Scales and axes,Logarithmic scale,incomplete,library,src/scales/pricescale.rs;src/studies/chart_state.rs;src/ui/context_menu/axis.rs;src/scales/pricescale_marks.rs;src/widget/mod.rs;src/widget/feed/pump.rs;src/widget/feed/mod.rs;src/widget/frame/mod.rs;src/widget/series/scales/mod.rs;src/widget/pane/indicator/mod.rs;src/studies/plots.rs,2465;2526;2484;2642;2690;2867;2869;2871;2872;2873 -Chart,Scales and axes,Maturity horizontal scale,incomplete,library,src/scales/horizontal.rs;src/model/timescale.rs;src/model/bar/time.rs;src/chart/coords/mod.rs;src/chart/rendering/axes/labels.rs;src/widget/time_scale.rs;src/widget/series/paint.rs;src/widget/pane/indicator/config.rs;src/widget/frame/mod.rs;examples/demo/numeric_scenes.rs;examples/demo/commands.rs;src/widget/anchors.rs;src/widget/replay.rs;src/widget/series/mod.rs;src/studies/chart_state.rs;src/widget/series/scales/mod.rs;src/chart/rendering/indicator.rs;src/chart/rendering/candles/volume.rs;src/widget/volume.rs;src/chart/indicators/plots.rs;src/chart/indicators/hit_test.rs;src/chart/rendering/candles/candlestick.rs;src/widget/snapshot.rs;docs/site/src/content/docs/horizontal-scales.mdx,1857;1935;2497;2498;2874;2875 +Chart,Scales and axes,Maturity horizontal scale,unverified,library,src/scales/horizontal.rs;src/model/timescale.rs;src/model/bar/time.rs;src/chart/coords/mod.rs;src/chart/rendering/axes/labels.rs;src/widget/time_scale.rs;src/widget/series/paint.rs;src/widget/pane/indicator/config.rs;src/widget/frame/mod.rs;examples/demo/numeric_scenes.rs;examples/demo/commands.rs;src/widget/anchors.rs;src/widget/replay.rs;src/widget/series/mod.rs;src/studies/chart_state.rs;src/widget/series/scales/mod.rs;src/chart/rendering/indicator.rs;src/chart/rendering/candles/volume.rs;src/widget/volume.rs;src/chart/indicators/plots.rs;src/chart/indicators/hit_test.rs;src/chart/rendering/candles/candlestick.rs;src/widget/snapshot.rs;docs/site/src/content/docs/horizontal-scales.mdx,1857;1935;2497;2498;2874;2875 Chart,Scales and axes,Multiple price scales and pin to scale,incomplete,library,src/model/series_scale.rs;src/widget/series/options.rs;src/widget/series/scales/mod.rs;src/widget/pane/mod.rs;src/widget/pane/render/mod.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/indicator/paint.rs;src/widget/pane/controls.rs;src/widget/snapshot.rs;src/widget/format.rs;src/widget/events.rs;src/widget/time_scale.rs;src/ui/context_menu/axis.rs;src/widget/settings/data.rs;src/widget/settings/apply.rs;src/ui/dialogs/chart_settings/tabs/scales.rs;src/widget/history.rs,1878;2044 Chart,Scales and axes,Numeric horizontal scales,incomplete,library,src/scales/horizontal.rs;src/model/timescale.rs;src/model/bar/time.rs;src/chart/coords/mod.rs;src/chart/rendering/axes/labels.rs;src/widget/time_scale.rs;src/widget/series/paint.rs;src/widget/pane/indicator/config.rs;src/widget/frame/mod.rs;src/widget/anchors.rs;src/widget/replay.rs;src/widget/series/mod.rs;src/studies/chart_state.rs;src/widget/series/scales/mod.rs;src/chart/rendering/indicator.rs;src/chart/rendering/candles/volume.rs;src/widget/volume.rs;src/chart/indicators/plots.rs;src/chart/indicators/hit_test.rs;src/chart/rendering/candles/candlestick.rs;src/widget/snapshot.rs;docs/site/src/content/docs/horizontal-scales.mdx,1857;2497;2498 Chart,Scales and axes,Pane axis placement and unused-axis hiding,verified,library,src/model/series_scale.rs;src/widget/series/options.rs;src/widget/series/scales/mod.rs;src/widget/series/paint.rs;src/widget/pane/mod.rs;src/widget/pane/render/mod.rs;src/widget/pane/controls.rs;src/widget/frame/mod.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/indicator/paint.rs;src/widget/history.rs;src/widget/snapshot.rs;src/scales/pricescale.rs;src/chart/rendering/axes/study_scale.rs;src/ui/context_menu/axis.rs;src/ui/context_menu/chart_menus/mod.rs;src/widget/settings/data.rs;src/widget/settings/apply.rs;src/ui/dialogs/chart_settings/tabs/scales.rs;src/widget/builder.rs;src/ui/context_menu/study.rs,2044 @@ -253,15 +254,15 @@ Chart,Scales and axes,Percent scale,incomplete,library,src/scales/pricescale.rs; Chart,Scales and axes,Previous close line,incomplete,library,src/widget/settings/apply.rs;src/chart/rendering/axes/mod.rs;src/painting/dashed_line.rs;src/widget/frame/mod.rs,2536 Chart,Scales and axes,Price label precision,incomplete,library,src/model/series_style.rs;src/widget/format.rs;src/scales/price_formatter.rs;src/widget/snapshot.rs;src/widget/settings/apply.rs;src/widget/mod.rs;src/chart/rendering/overlays/crosshair.rs;src/scales/pricescale.rs;src/scales/pricescale_marks.rs;src/chart/rendering/axes/mod.rs;src/chart/rendering/axes/labels.rs;src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/series/scales/mod.rs;src/widget/frame/mod.rs;src/widget/pane/render/mod.rs,2463;2483;2485;2486;2494;2815;2876;2877;2878;2879 Chart,Scales and axes,Regular price scale,verified,library,src/scales/pricescale.rs;src/studies/chart_state.rs;src/scales/pricescale_marks.rs;src/widget/mod.rs;src/widget/feed/pump.rs;src/widget/feed/mod.rs;src/widget/frame/mod.rs;src/widget/pane/indicator/mod.rs;src/widget/series/scales/mod.rs;src/studies/plots.rs,2526;2642 -Chart,Scales and axes,Right offset,incomplete,library,src/model/timescale.rs;src/widget/mod.rs;src/widget/builder.rs;src/widget/time_scale.rs;src/widget/pan_zoom/mod.rs;src/widget/sync.rs;src/studies/chart_state.rs;src/widget/frame/mod.rs,1882;2765;2881 -Chart,Scales and axes,Right price scale,verified,library,src/widget/mod.rs;src/chart/rendering/axes/labels.rs;src/chart/rendering/axes/mod.rs;src/widget/frame/mod.rs;src/widget/series/paint.rs,2494 +Chart,Scales and axes,Right offset,unverified,library,src/model/timescale.rs;src/widget/mod.rs;src/widget/builder.rs;src/widget/time_scale.rs;src/widget/pan_zoom/mod.rs;src/widget/sync.rs;src/studies/chart_state.rs;src/widget/frame/mod.rs;src/widget/settings/apply.rs;src/widget/settings/data.rs;src/ui/dialogs/chart_settings/tabs/canvas.rs,1882;2765;2881 +Chart,Scales and axes,Right price scale,unverified,library,src/widget/mod.rs;src/chart/rendering/axes/labels.rs;src/chart/rendering/axes/mod.rs;src/widget/frame/mod.rs;src/widget/series/paint.rs,2494 Chart,Scales and axes,Scale margins,incomplete,library,src/widget/settings/apply.rs;src/scales/pricescale.rs;src/widget/frame/mod.rs;src/model/series_style.rs;src/chart/primitives.rs;src/widget/primitives.rs;src/widget/series/scales/mod.rs;src/studies/chart_state.rs;src/widget/pane/indicator/mod.rs,1875;2171;2173;2526;2873;2880;2882 Chart,Scales and axes,Series display formats,incomplete,library,src/model/series_style.rs;src/widget/format.rs;src/scales/price_formatter.rs;src/scales/pricescale.rs;src/widget/series/options.rs;src/widget/series/scales/mod.rs;src/widget/frame/mod.rs;src/widget/pane/render/mod.rs;src/widget/snapshot.rs;examples/demo/comparison.rs;src/scales/pricescale_marks.rs;src/chart/rendering/legend/mod.rs;src/chart/rendering/overlays/tooltip.rs;src/ui/widget_bar/panels/object_tree/data_window.rs,2483;2484;2485;2486 -Chart,Scales and axes,Session breaks,incomplete,library,src/chart/rendering/session_breaks.rs;src/ui/context_menu/axis.rs;src/config/chart.rs;src/widget/palette.rs;src/model/session/exchange.rs;src/model/session/mod.rs;src/model/clock.rs;src/widget/frame/mod.rs;src/widget/format.rs;src/widget/frame/sessions.rs, -Chart,Scales and axes,Symbol name label on the scale,incomplete,library,;src/config/chart.rs;src/chart/rendering/axes/mod.rs;src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/series/scales/mod.rs;src/widget/settings/apply.rs;src/widget/settings/data.rs;src/widget/frame/mod.rs,2883 -Chart,Scales and axes,Thousands grouping in price labels,incomplete,library,src/config/chart.rs;src/scales/price_formatter.rs;src/scales/pricescale.rs;src/scales/pricescale_marks.rs;src/chart/rendering/axes/mod.rs;src/chart/rendering/overlays/crosshair.rs;src/chart/rendering/axes/labels.rs;src/chart/rendering/legend/mod.rs;src/widget/pane/render/mod.rs;src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/series/scales/mod.rs;src/widget/frame/mod.rs;src/widget/format.rs,2483;2888;2889 +Chart,Scales and axes,Session breaks,incomplete,library,src/chart/rendering/session_breaks.rs;src/ui/context_menu/axis.rs;src/config/chart.rs;src/widget/palette.rs;src/model/session/exchange.rs;src/model/session/mod.rs;src/model/clock.rs;src/widget/frame/mod.rs;src/widget/format.rs;src/widget/frame/sessions.rs;src/ui/dialogs/chart_settings/tabs/trading.rs;src/widget/settings/apply.rs;src/widget/settings/data.rs,2830 +Chart,Scales and axes,Symbol name label on the scale,incomplete,library,src/config/chart.rs;src/chart/rendering/axes/mod.rs;src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/series/scales/mod.rs;src/widget/settings/apply.rs;src/widget/settings/data.rs;src/widget/frame/mod.rs,2883 +Chart,Scales and axes,Thousands grouping in price labels,incomplete,library,src/config/chart.rs;src/scales/price_formatter.rs;src/scales/pricescale.rs;src/scales/pricescale_marks.rs;src/chart/rendering/axes/mod.rs;src/chart/rendering/overlays/crosshair.rs;src/chart/rendering/axes/labels.rs;src/chart/rendering/legend/mod.rs;src/widget/pane/render/mod.rs;src/widget/series/options.rs;src/widget/series/paint.rs;src/widget/series/scales/mod.rs;src/widget/frame/mod.rs;src/widget/format.rs;src/widget/settings/apply.rs;src/widget/settings/data.rs;src/ui/dialogs/chart_settings/tabs/scales.rs,2483;2888;2889 Chart,Scales and axes,Time axis labels,incomplete,library,src/scales/timescale_marks.rs;src/scales/horizontal.rs;src/scales/time_formatter.rs;src/widget/format.rs;src/chart/rendering/axes/labels.rs;src/model/bar/time.rs;src/widget/time_scale.rs;src/styles/sizing.rs;src/model/timezone.rs;src/widget/merge.rs;src/widget/frame/mod.rs,828 -Chart,Scales and axes,Time zone selection,incomplete,library,src/widget/settings/apply.rs;src/scales/time_formatter.rs;src/widget/time_scale.rs;src/model/bar/time.rs;src/chart/rendering/axes/labels.rs;src/model/timezone.rs;src/widget/frame/mod.rs;src/widget/format.rs;terminal/src/time.rs,2884;2885;2886;2887 +Chart,Scales and axes,Time zone selection,incomplete,library,src/widget/settings/apply.rs;src/scales/time_formatter.rs;src/widget/time_scale.rs;src/model/bar/time.rs;src/chart/rendering/axes/labels.rs;src/model/timezone.rs;src/widget/frame/mod.rs;src/widget/format.rs;terminal/src/time.rs,2885;2886;2887 Drawings,Drawing management,Alerts on drawings,unverified,library,src/drawings/domain/drawing.rs;src/ui/context_menu/drawing.rs, Drawings,Drawing management,Anchor markers only on selected drawings,unverified,library,src/drawings/manager/paint.rs;src/drawings/services/handle.rs;src/drawings/rendering/lines.rs;src/drawings/rendering/measurements.rs;src/drawings/rendering/shapes.rs;src/drawings/rendering/pitchfork.rs;src/drawings/rendering/gann.rs;src/drawings/rendering/fibonacci.rs;src/drawings/rendering/patterns.rs;src/drawings/rendering/elliott.rs;src/drawings/rendering/cycles.rs;src/drawings/rendering/trading/volume_profile.rs;src/drawings/rendering/trading/bars_pattern.rs;src/drawings/rendering/trading/projection.rs;src/drawings/rendering/annotations/text.rs;src/drawings/rendering/annotations/callout.rs;src/drawings/rendering/annotations/notes.rs;src/drawings/rendering/annotations/signpost.rs;src/drawings/rendering/style.rs, Drawings,Drawing management,Box selection,unverified,library,src/widget/tool_interaction/selection.rs;src/drawings/services/selection.rs;src/drawings/manager/interaction.rs;src/widget/tool_interaction/mod.rs;src/widget/frame/mod.rs;src/drawings/manager/paint.rs,2037;2542;2543 @@ -294,14 +295,14 @@ Drawings,Drawing management,Style settings honoured by renderers,incomplete,libr Drawings,Drawing management,Sync drawings across layouts,unverified,library,src/widget/layout.rs;src/widget/layout/drawings.rs;src/drawings/manager/mod.rs;src/model/bar/time.rs;src/drawings/manager/edit.rs;src/widget/stored_drawings.rs, Drawings,Drawing management,Text entry for annotation tools,unverified,library,src/widget/tool_interaction/mod.rs;src/widget/tool_interaction/text.rs;src/drawings/manager/mod.rs;src/drawings/manager/paint.rs;src/drawings/manager/edit.rs;src/drawings/services/history.rs;src/widget/history.rs, Drawings,Drawing management,"Text on lines, channels and shapes",incomplete,library,src/drawings/rendering/lines.rs;src/drawings/rendering/channels.rs;src/drawings/rendering/measurements.rs;src/drawings/rendering/mod.rs;src/config/drawing_tool/behavior.rs;src/drawings/services/interaction.rs;src/widget/svg.rs;src/drawings/domain/drawing.rs;src/drawings/rendering/shapes.rs;src/ui/dialogs/drawing_properties/tabs/text.rs;src/widget/tool_interaction/text.rs,2630 -Drawings,Drawing management,Undo and redo of drawing edits,unverified,library,src/drawings/manager/mod.rs;src/drawings/manager/edit.rs;src/drawings/manager/interaction.rs;src/widget/history.rs;src/widget/keyboard.rs;src/drawings/services/history.rs;src/ui/dialogs/drawing_properties/dialog.rs;src/widget/layout.rs,2527 +Drawings,Drawing management,Undo and redo of drawing edits,unverified,library,src/drawings/manager/mod.rs;src/drawings/manager/edit.rs;src/drawings/manager/interaction.rs;src/widget/history.rs;src/widget/keyboard.rs;src/drawings/services/history.rs;src/ui/dialogs/drawing_properties/dialog.rs;src/widget/layout.rs,2527;2731;2812 Drawings,Drawing management,Visibility per timeframe,incomplete,library,src/ui/dialogs/drawing_properties/actions.rs;src/ui/dialogs/drawing_properties/tabs/visibility.rs;src/drawings/domain/options.rs;src/drawings/manager/mod.rs;src/drawings/manager/edit.rs;src/widget/feed/mod.rs;src/ui/context_menu/drawing.rs;src/ui/context_menu/chart_menus/mod.rs;src/ui/floating_toolbar/toolbar.rs,2039 Drawings,Drawing management,Z-order,unverified,library,src/drawings/manager/mod.rs;src/ui/widget_bar/panels/object_tree/chart_actions.rs;src/drawings/manager/edit.rs, Drawings,Drawings,ABCD pattern,incomplete,library,src/drawings/rendering/patterns.rs;src/painting/dashed_line.rs;src/config/drawing_tool/behavior.rs;src/drawings/domain/drawing.rs,141;2536 Drawings,Drawings,API: default style overrides for new drawings,unverified,library,src/drawings/manager/mod.rs;src/drawings/domain/template.rs;src/drawings/manager/edit.rs;src/drawings/manager/interaction.rs;src/drawings/domain/drawing.rs;terminal/src/drawings.rs,2506;2507;2508 Drawings,Drawings,API: drawing templates through the save/load adapter,unverified,library,src/services/storage.rs;src/ui/dialogs/templates/store.rs;src/drawings/domain/template.rs, Drawings,Drawings,"API: per-drawing selection, saving, user-edit and object-tree flags",unverified,library,src/drawings/domain/drawing.rs;src/drawings/manager/mod.rs;src/widget/anchors.rs;src/drawings/manager/edit.rs;src/widget/tool_interaction/text.rs,2606 -Drawings,Drawings,Anchored VWAP,incomplete,library,src/drawings/rendering/trading/volume_profile.rs;src/drawings/domain/vwap.rs;src/ui/dialogs/drawing_properties/tabs/inputs.rs;src/drawings/domain/drawing.rs;src/drawings/manager/paint.rs;src/drawings/manager/interaction.rs,1362 +Drawings,Drawings,Anchored VWAP,incomplete,library,src/drawings/rendering/trading/volume_profile.rs;src/drawings/domain/vwap.rs;src/ui/dialogs/drawing_properties/tabs/inputs.rs;src/drawings/domain/drawing.rs;src/drawings/manager/paint.rs;src/drawings/manager/interaction.rs;src/widget/drawing_api.rs,1362 Drawings,Drawings,Anchored text,unverified,library,src/drawings/domain/drawing.rs;src/drawings/rendering/annotations/text.rs;src/drawings/manager/mod.rs;src/drawings/manager/edit.rs;src/drawings/rendering/style.rs;src/ui/dialogs/drawing_properties/tabs/text.rs;src/config/drawing_tool/behavior.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/floating_toolbar/toolbar.rs;src/ui/dialogs/drawing_properties/actions.rs;src/drawings/persistence.rs,2442;2441;141;2516;2624 Drawings,Drawings,Anchored volume profile,incomplete,library,src/drawings/rendering/trading/volume_profile.rs;src/data/volume_profile.rs;src/painting/volume_profile.rs;src/drawings/rendering/mod.rs;src/data/footprint.rs;src/widget/feed/pump.rs;src/widget/tool_interaction/mod.rs;src/widget/studies_data.rs;src/model/instrument.rs;src/widget/feed/mod.rs;src/widget/frame/mod.rs;src/drawings/manager/paint.rs;src/ui/dialogs/drawing_properties/tabs/inputs.rs;src/drawings/domain/drawing.rs;src/drawings/persistence.rs,1362;1497;2516 Drawings,Drawings,Arc,unverified,library,src/drawings/rendering/lines.rs;src/config/drawing_tool/behavior.rs;src/drawings/rendering/shapes.rs;src/drawings/rendering/mod.rs;src/drawings/rendering/style.rs;src/drawings/rendering/outline.rs;src/drawings/domain/drawing.rs;terminal/src/drawings.rs;src/drawings/persistence.rs,1362;2507;2516 @@ -364,11 +365,11 @@ Drawings,Drawings,Highlighter,incomplete,library,src/drawings/rendering/shapes.r Drawings,Drawings,Horizontal line,incomplete,library,src/drawings/rendering/lines.rs;src/drawings/domain/options.rs;src/drawings/domain/drawing.rs;src/config/drawing_tool/behavior.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/dialogs/drawing_properties/tabs/text.rs;src/painting/dashed_line.rs;src/drawings/manager/paint.rs;src/widget/frame/mod.rs;src/widget/drawing_api.rs;src/ui/context_menu/mod.rs;src/ui/context_menu/chart_menus/mod.rs;src/widget/keyboard.rs;src/ui/dialogs/drawing_properties/actions.rs,2028;2536;2379;2435 Drawings,Drawings,Horizontal ray,unverified,library,src/drawings/rendering/lines.rs;src/drawings/rendering/mod.rs;src/drawings/domain/options.rs;src/drawings/domain/drawing.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/dialogs/drawing_properties/tabs/text.rs;src/painting/dashed_line.rs;src/drawings/manager/paint.rs;src/widget/frame/mod.rs;src/widget/drawing_api.rs;src/ui/dialogs/drawing_properties/actions.rs,2282;2536;2379;2435 Drawings,Drawings,Icons and emojis,incomplete,library,src/ui/drawing_toolbar/glyph_picker.rs;src/drawings/manager/mod.rs;src/drawings/rendering/media.rs;src/drawings/glyphs.rs;src/drawings/manager/interaction.rs;src/drawings/services/handle.rs;src/drawings/persistence.rs,2516 -Drawings,Drawings,Ideas,unverified,host,src/drawings/rendering/media.rs;src/widget/tool_interaction/text.rs;src/drawings/categories.rs;src/model/post.rs;src/services/posts.rs;src/widget/posts.rs;src/widget/events.rs;src/drawings/manager/interaction.rs;src/ui/ideas.rs, +Drawings,Drawings,Ideas,unverified,host,src/drawings/rendering/media.rs;src/widget/tool_interaction/text.rs;src/drawings/categories.rs;src/model/post.rs;src/services/posts.rs;src/widget/posts.rs;src/widget/events.rs;src/drawings/manager/interaction.rs;src/ui/ideas.rs;examples/demo/feeds.rs,1477 Drawings,Drawings,Image,incomplete,library,src/drawings/rendering/media.rs;src/widget/tool_interaction/text.rs;src/drawings/categories.rs;src/drawings/domain/image.rs;src/widget/events.rs;src/widget/drawing_api.rs;src/drawings/services/handle.rs;src/ui/dialogs/drawing_properties/tabs/inputs.rs, Drawings,Drawings,Info line,unverified,library,src/drawings/rendering/measurements.rs;src/drawings/rendering/lines.rs;src/drawings/rendering/outline.rs;src/drawings/domain/options.rs;src/drawings/domain/drawing.rs;src/ui/dialogs/drawing_properties/actions.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/dialogs/drawing_properties/tabs/text.rs;src/drawings/rendering/style.rs;src/config/drawing_tool/behavior.rs;src/widget/drawing_api.rs;src/drawings/persistence.rs,2325;2323;2345;2379;2516 Drawings,Drawings,Inside pitchfork,incomplete,library,src/drawings/rendering/pitchfork.rs;src/ui/dialogs/drawing_properties/tabs/inputs.rs;src/drawings/domain/pitchfork.rs;src/config/drawing_tool/behavior.rs;src/drawings/domain/drawing.rs;src/drawings/persistence.rs,1362;2506;141;2516 -Drawings,Drawings,Long position,unverified,library,src/drawings/manager/mod.rs;src/drawings/rendering/trading/position.rs;src/drawings/services/handle.rs;src/ui/dialogs/drawing_properties/tabs/inputs.rs;src/drawings/domain/options.rs;src/drawings/manager/edit.rs;src/drawings/domain/drawing.rs;src/ui/dialogs/drawing_properties/actions.rs;src/ui/dialogs/drawing_properties/dialog.rs;src/widget/pane/render/mod.rs;src/widget/frame/mod.rs;src/widget/format.rs;src/drawings/manager/paint.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/dialogs/drawing_properties/tabs/text.rs;src/widget/drawing_api.rs;src/ui/context_menu/drawing.rs;src/ui/context_menu/chart_menus/mod.rs;src/ui/floating_toolbar/toolbar.rs,2485;2603;141;2620;2685;2686 +Drawings,Drawings,Long position,unverified,library,src/drawings/manager/mod.rs;src/drawings/rendering/trading/position.rs;src/drawings/services/handle.rs;src/ui/dialogs/drawing_properties/tabs/inputs.rs;src/drawings/domain/options.rs;src/drawings/manager/edit.rs;src/drawings/domain/drawing.rs;src/ui/dialogs/drawing_properties/actions.rs;src/ui/dialogs/drawing_properties/dialog.rs;src/widget/pane/render/mod.rs;src/widget/frame/mod.rs;src/widget/format.rs;src/drawings/manager/paint.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/dialogs/drawing_properties/tabs/text.rs;src/widget/drawing_api.rs;src/ui/context_menu/drawing.rs;src/ui/context_menu/chart_menus/mod.rs;src/ui/floating_toolbar/toolbar.rs,2485;2603;141;2620;2685;2686;2920 Drawings,Drawings,Measure,incomplete,library,src/drawings/rendering/measurements.rs;src/ui/drawing_toolbar/utilities/measure.rs;src/drawings/manager/interaction.rs;src/widget/tool_interaction/selection.rs;src/drawings/domain/drawing.rs;src/drawings/persistence.rs,1362;2516 Drawings,Drawings,Modified Schiff pitchfork,incomplete,library,src/drawings/rendering/pitchfork.rs;src/config/drawing_tool/behavior.rs;src/ui/dialogs/drawing_properties/tabs/inputs.rs;src/drawings/domain/pitchfork.rs;src/drawings/domain/drawing.rs;src/drawings/persistence.rs,1362;2506;141;2516 Drawings,Drawings,Multi-point drawing creation,unverified,library,src/widget/drawing_api.rs;src/drawings/manager/mod.rs;src/drawings/validation.rs;src/drawings/manager/interaction.rs, @@ -380,7 +381,7 @@ Drawings,Drawings,Pitchfan,incomplete,library,src/drawings/rendering/pitchfork.r Drawings,Drawings,Pitchfork,incomplete,library,src/drawings/rendering/pitchfork.rs;src/config/drawing_tool/behavior.rs;src/ui/dialogs/drawing_properties/tabs/inputs.rs;src/drawings/domain/pitchfork.rs;src/drawings/domain/drawing.rs;src/drawings/persistence.rs,1362;2506;141;2516 Drawings,Drawings,Polyline,incomplete,library,src/drawings/rendering/lines.rs;src/drawings/manager/mod.rs;src/widget/tool_interaction/interaction.rs;src/drawings/manager/edit.rs;src/ui/dialogs/drawing_properties/actions.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/drawings/rendering/style.rs;src/painting/dashed_line.rs;src/drawings/rendering/mod.rs;src/drawings/domain/drawing.rs;src/drawings/domain/template.rs;src/drawings/manager/interaction.rs;src/widget/keyboard.rs;src/drawings/rendering/shapes.rs;terminal/src/drawings.rs;src/drawings/persistence.rs,141;2507;2516 Drawings,Drawings,Position forecast,incomplete,library,src/drawings/rendering/trading/forecast.rs;src/drawings/rendering/measurements.rs;src/drawings/rendering/trading/projection.rs, -Drawings,Drawings,Price label,unverified,library,src/drawings/rendering/annotations/labels.rs;src/drawings/rendering/mod.rs;src/drawings/domain/drawing.rs;src/config/drawing_tool/behavior.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/floating_toolbar/toolbar.rs;src/drawings/persistence.rs,2442;2516;2631 +Drawings,Drawings,Price label,unverified,library,src/drawings/rendering/annotations/labels.rs;src/drawings/rendering/mod.rs;src/drawings/domain/drawing.rs;src/config/drawing_tool/behavior.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/floating_toolbar/toolbar.rs;src/drawings/persistence.rs,2442;2516;2631;2914 Drawings,Drawings,Price note,incomplete,library,src/drawings/rendering/annotations/labels.rs;src/drawings/domain/options.rs;src/widget/tool_interaction/text.rs;src/config/drawing_tool/behavior.rs;src/drawings/rendering/mod.rs;src/drawings/manager/interaction.rs;src/drawings/rendering/style.rs;src/ui/dialogs/drawing_properties/tabs/text.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/floating_toolbar/toolbar.rs;src/drawings/persistence.rs,2442;2516;2631 Drawings,Drawings,Price range,incomplete,library,src/drawings/rendering/measurements.rs;src/drawings/rendering/mod.rs;src/config/drawing_tool/behavior.rs;src/drawings/domain/drawing.rs;terminal/src/drawings.rs;src/drawings/persistence.rs,1362;2507;2516 Drawings,Drawings,Projection,unverified,library,src/drawings/rendering/trading/projection.rs;src/drawings/rendering/measurements.rs;src/config/drawing_tool/behavior.rs, @@ -391,11 +392,11 @@ Drawings,Drawings,Rotated rectangle,unverified,library,src/drawings/rendering/sh Drawings,Drawings,Schiff pitchfork,incomplete,library,src/drawings/rendering/pitchfork.rs;src/config/drawing_tool/behavior.rs;src/ui/dialogs/drawing_properties/tabs/inputs.rs;src/drawings/domain/pitchfork.rs;src/drawings/domain/drawing.rs;src/drawings/persistence.rs,1362;2506;141;2516 Drawings,Drawings,Screen-anchored drawing creation,unverified,library,src/drawings/domain/drawing.rs;src/widget/drawing_api.rs;src/drawings/manager/mod.rs;src/drawings/manager/interaction.rs, Drawings,Drawings,Sector,unverified,library,src/drawings/rendering/shapes.rs;src/drawings/rendering/mod.rs;src/config/drawing_tool/behavior.rs;src/drawings/rendering/style.rs;src/drawings/rendering/outline.rs, -Drawings,Drawings,Short position,unverified,library,src/drawings/manager/mod.rs;src/drawings/rendering/trading/position.rs;src/drawings/services/handle.rs;src/ui/dialogs/drawing_properties/tabs/inputs.rs;src/drawings/domain/options.rs;src/drawings/manager/edit.rs;src/drawings/domain/drawing.rs;src/ui/dialogs/drawing_properties/actions.rs;src/ui/dialogs/drawing_properties/dialog.rs;src/widget/pane/render/mod.rs;src/widget/frame/mod.rs;src/widget/format.rs;src/drawings/manager/paint.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/dialogs/drawing_properties/tabs/text.rs;src/widget/drawing_api.rs;src/ui/context_menu/drawing.rs;src/ui/context_menu/chart_menus/mod.rs;src/ui/floating_toolbar/toolbar.rs,2485;2605;2632;2620;2685;2686 +Drawings,Drawings,Short position,unverified,library,src/drawings/manager/mod.rs;src/drawings/rendering/trading/position.rs;src/drawings/services/handle.rs;src/ui/dialogs/drawing_properties/tabs/inputs.rs;src/drawings/domain/options.rs;src/drawings/manager/edit.rs;src/drawings/domain/drawing.rs;src/ui/dialogs/drawing_properties/actions.rs;src/ui/dialogs/drawing_properties/dialog.rs;src/widget/pane/render/mod.rs;src/widget/frame/mod.rs;src/widget/format.rs;src/drawings/manager/paint.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/dialogs/drawing_properties/tabs/text.rs;src/widget/drawing_api.rs;src/ui/context_menu/drawing.rs;src/ui/context_menu/chart_menus/mod.rs;src/ui/floating_toolbar/toolbar.rs,2485;2605;2632;2620;2685;2686;2920 Drawings,Drawings,Signpost,incomplete,library,src/drawings/rendering/annotations/signpost.rs;src/widget/tool_interaction/text.rs;src/config/drawing_tool/behavior.rs;src/drawings/domain/drawing.rs;src/drawings/manager/interaction.rs;src/drawings/services/handle.rs;src/drawings/rendering/annotations/labels.rs;src/drawings/rendering/style.rs;src/ui/dialogs/drawing_properties/tabs/text.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/floating_toolbar/toolbar.rs;src/drawings/persistence.rs,2442;141;2516 Drawings,Drawings,Sine line,unverified,library,src/drawings/rendering/cycles.rs;src/drawings/rendering/style.rs;src/config/drawing_tool/behavior.rs, Drawings,Drawings,Single-point drawing creation,verified,library,src/widget/drawing_api.rs;src/drawings/manager/mod.rs;src/drawings/domain/drawing.rs;src/drawings/manager/edit.rs, -Drawings,Drawings,Social posts,incomplete,host,src/drawings/rendering/media.rs;src/widget/tool_interaction/text.rs;src/drawings/categories.rs;src/model/post.rs;src/services/posts.rs;src/widget/posts.rs;src/widget/events.rs, +Drawings,Drawings,Social posts,unverified,host,src/drawings/rendering/media.rs;src/widget/tool_interaction/text.rs;src/drawings/categories.rs;src/model/post.rs;src/services/posts.rs;src/widget/posts.rs;src/widget/events.rs;examples/demo/feeds.rs,1477 Drawings,Drawings,Stickers,unverified,library,src/drawings/glyphs.rs;src/ui/drawing_toolbar/glyph_picker.rs;src/drawings/rendering/media.rs;src/drawings/services/handle.rs, Drawings,Drawings,Table,incomplete,library,src/drawings/rendering/annotations/table.rs;src/widget/tool_interaction/text.rs;src/drawings/rendering/style.rs;src/drawings/domain/drawing.rs;src/config/drawing_tool/behavior.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/floating_toolbar/toolbar.rs,1362;2442 Drawings,Drawings,Text,unverified,library,src/drawings/rendering/annotations/text.rs;src/drawings/rendering/style.rs;src/widget/tool_interaction/text.rs;src/drawings/domain/drawing.rs;src/ui/dialogs/drawing_properties/tabs/text.rs;src/config/drawing_tool/behavior.rs;src/ui/dialogs/drawing_properties/tabs/style.rs;src/ui/floating_toolbar/toolbar.rs;src/ui/dialogs/drawing_properties/actions.rs;src/drawings/persistence.rs,2442;2441;141;2516;2624 @@ -420,9 +421,9 @@ Options,Options profile,Call and put volume by strike,incomplete,host,src/studie Options,Options profile,Max pain from open interest,unverified,host,src/studies/builtin/options_volume_profile.rs;src/data/option_chain.rs;src/ui/dialogs/indicator_dialog/dialog.rs;src/chart/rendering/indicator.rs,1758;2476 Options,Options profile,Put/call ratios of volume and open interest,incomplete,host,src/studies/builtin/options_volume_profile.rs;src/data/option_chain.rs;src/ui/dialogs/indicator_dialog/dialog.rs,1758 Order flow,Order flow,"Depth heatmap, order book and volume bubble settings in the chart settings dialog",unverified,library,src/ui/dialogs/chart_settings/mod.rs;src/ui/dialogs/chart_settings/tabs/order_flow.rs;src/ui/top_toolbar/components/settings_menu/types.rs;src/widget/settings/data.rs;src/widget/settings/apply.rs;src/widget/feed/mod.rs;src/widget/history.rs;examples/demo/controller.rs,1750;1917 -Order flow,Order flow,"Footprints on tick, volume, range and delta intervals",incomplete,library,src/data/footprint.rs;src/data/order_flow.rs;src/data/inbox/sink.rs;src/widget/feed/mod.rs;src/widget/feed/pump.rs;src/widget/frame/mod.rs;src/data/trades.rs;src/chart/overlays/footprint.rs;src/data/inbox/mod.rs,1752;2326;2327;2328;2555;2680;2710 +Order flow,Order flow,"Footprints on tick, volume, range and delta intervals",incomplete,library,src/data/footprint.rs;src/data/order_flow.rs;src/data/inbox/sink.rs;src/widget/feed/mod.rs;src/widget/feed/pump.rs;src/widget/frame/mod.rs;src/data/trades.rs;src/chart/overlays/footprint.rs;src/data/inbox/mod.rs,1752;2326;2327;2328;2555;2680;2710;2723;2936 Order flow,Order flow,"Prior-session POC, VAH and VAL extended until revisited, and developing value area lines",unverified,library,src/studies/builtin/trade_profile.rs;src/chart/overlays/trade_profile.rs;src/model/chart_type.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/widget/frame/mod.rs;src/data/footprint.rs,1753 -Order flow,Order flow,Anchored developing VWAP drawing tool,unverified,library,src/drawings/rendering/trading/volume_profile.rs;src/drawings/rendering/mod.rs, +Order flow,Order flow,Anchored developing VWAP drawing tool,incomplete,library,src/drawings/rendering/trading/volume_profile.rs;src/drawings/rendering/mod.rs;src/drawings/domain/vwap.rs,1362 Order flow,Order flow,Bar POC lines extended until price revisits them,incomplete,library,src/studies/builtin/footprint_studies.rs;src/chart/overlays/footprint.rs;src/widget/frame/mod.rs, Order flow,Order flow,Best bid and best ask lines drawn across the heatmap,unverified,library,src/chart/overlays/liquidity_heatmap.rs;src/widget/feed/mod.rs;src/widget/frame/mod.rs, Order flow,Order flow,Bid/ask split profile and delta profile,unverified,library,src/studies/builtin/trade_profile.rs;src/chart/overlays/trade_profile.rs;src/data/footprint.rs;src/widget/trade_profile.rs;src/studies/chart_state.rs;src/widget/frame/mod.rs, @@ -449,7 +450,7 @@ Order flow,Order flow,Depth ladder session and resettable profiles,unverified,li Order flow,Order flow,Depth ladder with configurable visible levels and negative-price scrolling,incomplete,library,src/ui/trading/dom.rs;src/ui/trading/mod.rs;src/data/depth.rs,236;1756;2533 Order flow,Order flow,Developing POC line through the session,unverified,library,src/studies/builtin/trade_profile.rs;src/chart/overlays/trade_profile.rs;src/data/footprint.rs;src/widget/trade_profile.rs;src/widget/frame/mod.rs, Order flow,Order flow,Diagonal imbalance detection and highlighting,incomplete,library,src/data/footprint.rs;src/chart/overlays/footprint.rs;src/widget/frame/mod.rs, -Order flow,Order flow,Execution volume bubbles at trade prices and times,unverified,library,src/widget/feed/mod.rs;src/chart/overlays/volume_bubbles.rs;src/model/clock.rs;src/widget/frame/mod.rs,2301;2302;2426 +Order flow,Order flow,Execution volume bubbles at trade prices and times,unverified,library,src/widget/feed/mod.rs;src/chart/overlays/volume_bubbles.rs;src/model/clock.rs;src/widget/frame/mod.rs;src/data/trades.rs,2301;2302;2426;2725 Order flow,Order flow,Footprint and session volume profile settings in the chart settings dialog,incomplete,library,src/model/chart_type.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs;src/widget/frame/mod.rs;src/widget/trade_profile.rs;src/chart/overlays/footprint.rs;src/chart/overlays/trade_profile.rs,1751 Order flow,Order flow,Footprint cell colour and intensity modes,incomplete,library,src/chart/overlays/footprint.rs;src/widget/frame/background.rs;src/widget/frame/mod.rs;src/data/footprint.rs;src/model/chart_type.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs, Order flow,Order flow,Footprint chart type: bid x ask traded volume with opening and closing price ticks,unverified,library,src/data/footprint.rs;src/widget/feed/mod.rs;src/chart/overlays/footprint.rs;src/ui/top_toolbar/components/chart_type_selector.rs;benches/frame_time.rs;src/widget/frame/mod.rs, @@ -484,7 +485,7 @@ Order flow,Order flow,Order-level trade classification,incomplete,library,src/da Order flow,Order flow,Passive wall detection,unverified,library,src/services/detectors/liquidity.rs;src/services/detectors/depth.rs;src/services/detectors/mod.rs;src/model/signal.rs;src/widget/signals.rs, Order flow,Order flow,Per-bar delta and volume heatmap strip,unverified,library,src/chart/overlays/heatmap_strip.rs, Order flow,Order flow,Per-bar delta as histogram or candles,incomplete,library,src/data/footprint.rs;src/studies/builtin/trade_delta.rs;src/chart/series/trade_delta.rs;src/chart/series/mod.rs;src/data/order_flow.rs;src/studies/builtin/order_flow.rs;src/studies/factory/mod.rs;src/chart/indicators/plots.rs;src/data/trades.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/indicator/paint.rs, -Order flow,Order flow,Per-bar order-flow statistics table with shared labels and aligned compact values,unverified,library,src/data/footprint.rs;src/chart/overlays/footprint.rs;src/chart/overlays/mod.rs;src/widget/frame/mod.rs;src/model/chart_type.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs, +Order flow,Order flow,Per-bar order-flow statistics table with shared labels and aligned compact values,incomplete,library,src/data/footprint.rs;src/chart/overlays/footprint.rs;src/chart/overlays/mod.rs;src/widget/frame/mod.rs;src/model/chart_type.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs,2841 Order flow,Order flow,"Profile POC, value area and VAH/VAL lines",unverified,library,src/data/footprint.rs;src/data/volume_profile.rs;src/chart/overlays/trade_profile.rs;src/painting/volume_profile.rs;src/chart/rendering/volume_profile.rs;src/widget/trade_profile.rs, Order flow,Order flow,Profile peaks and valleys with sensitivity,incomplete,library,src/studies/builtin/trade_profile.rs;src/chart/overlays/trade_profile.rs;src/widget/trade_profile.rs, Order flow,Order flow,Proprietary order-flow models,incomplete,library,src/model/tpo.rs;src/chart/rendering/candles/tpo.rs, @@ -501,12 +502,12 @@ Order flow,Order flow,TPO initial balance period and extension levels,incomplete Order flow,Order flow,TPO poor high and poor low marks,unverified,library,src/model/tpo.rs;src/model/chart_type.rs;src/chart/rendering/candles/tpo.rs;src/ui/dialogs/series_settings/tabs/symbol.rs,1743 Order flow,Order flow,TPO session statistics table,incomplete,library,src/model/tpo.rs;src/model/chart_type.rs;src/chart/rendering/candles/tpo.rs;src/studies/builtin/time_price_opportunity.rs;src/ui/dialogs/series_settings/tabs/symbol.rs,2432 Order flow,Order flow,Tape reconstruction and passive fill details,unverified,library,src/data/trades.rs;src/data/orders.rs;src/model/quote.rs;src/widget/feed/mod.rs;src/ui/widget_bar/panels/time_and_sales.rs, -Order flow,Order flow,Tick-by-tick trade replay with speed control and multi-symbol sessions,unverified,library,src/data/replay.rs;src/data/inbox/sink.rs;src/data/order_flow.rs;src/data/mod.rs;src/model/clock.rs;src/model/session/exchange.rs;src/widget/replay.rs;src/widget/series/mod.rs;src/widget/feed/pump.rs;examples/demo/replay.rs;examples/demo/comparison.rs,2126;2748 +Order flow,Order flow,Tick-by-tick trade replay with speed control and multi-symbol sessions,unverified,library,src/data/replay.rs;src/data/inbox/sink.rs;src/data/order_flow.rs;src/data/mod.rs;src/model/clock.rs;src/model/session/exchange.rs;src/widget/replay.rs;src/widget/series/mod.rs;src/widget/feed/pump.rs;examples/demo/replay.rs;examples/demo/comparison.rs,2126;2748;2750 Order flow,Order flow,Tick-count bars,incomplete,library,src/model/timeframe.rs;src/ui/top_toolbar/components/timeframe_selector/mod.rs;src/data/inbox/mod.rs;src/widget/feed/mod.rs;src/data/inbox/sink.rs, Order flow,Order flow,"Time and sales with size filters, sound alerts and fractional timestamps",incomplete,library,src/ui/widget_bar/panels/time_and_sales.rs;src/data/trades.rs, Order flow,Order flow,Time price opportunity profiles and single prints,incomplete,library,src/model/tpo.rs;src/model/session/exchange.rs;src/chart/rendering/candles/tpo.rs;src/studies/builtin/time_price_opportunity.rs;src/tokens/mod.rs;src/tokens/semantic.rs;src/model/chart_type.rs;src/ui/dialogs/series_settings/tabs/symbol.rs;src/chart/rendering/legend/mod.rs;src/widget/frame/mod.rs,2432 Order flow,Order flow,"Trade-based session, composite and visible-range volume profiles",unverified,library,src/studies/builtin/trade_profile.rs;src/chart/overlays/trade_profile.rs;src/data/footprint.rs;src/widget/trade_profile.rs;src/widget/frame/mod.rs, -Order flow,Order flow,Trade-size filtered CVD,unverified,library,src/data/order_flow.rs;src/studies/builtin/order_flow.rs;src/data/footprint.rs;src/studies/builtin/trade_delta.rs;src/chart/series/trade_delta.rs;src/data/inbox/sink.rs;src/widget/feed/pump.rs;src/studies/factory/mod.rs;src/chart/indicators/plots.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/indicator/paint.rs;src/data/trades.rs;src/studies/indicator_trait.rs;src/studies/settings.rs;src/chart/rendering/legend/mod.rs,2555;2710 +Order flow,Order flow,Trade-size filtered CVD,unverified,library,src/data/order_flow.rs;src/studies/builtin/order_flow.rs;src/data/footprint.rs;src/studies/builtin/trade_delta.rs;src/chart/series/trade_delta.rs;src/data/inbox/sink.rs;src/widget/feed/pump.rs;src/studies/factory/mod.rs;src/chart/indicators/plots.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/indicator/paint.rs;src/data/trades.rs;src/studies/indicator_trait.rs;src/studies/settings.rs;src/chart/rendering/legend/mod.rs,2555;2710;2936 Order flow,Order flow,Unfinished auction detection with extension lines,unverified,library,src/studies/builtin/footprint_studies.rs;src/chart/overlays/footprint.rs;src/widget/frame/mod.rs, Order flow,Order flow,"VWAP envelopes: standard deviation or percent bands, three pairs",incomplete,library,src/studies/builtin/vwap.rs;src/chart/rendering/indicator.rs;src/studies/indicator_trait.rs;src/studies/settings.rs;src/chart/rendering/legend/mod.rs;src/widget/pane/indicator/paint.rs;src/studies/template.rs,2337 Order flow,Order flow,Value area per bar highlighted on the footprint,unverified,library,src/data/footprint.rs;src/chart/overlays/footprint.rs;src/widget/frame/mod.rs, @@ -519,7 +520,7 @@ Order flow,Order flow data model,Backpressure and per-frame coalescing for high- Order flow,Order flow data model,Building bars from trades,unverified,library,src/data/inbox/mod.rs;src/data/mod.rs;src/data/inbox/sink.rs;src/model/clock.rs;src/data/inbox/tests.rs;src/data/merge.rs;src/widget/studies_data.rs;src/widget/feed/mod.rs;src/widget/feed/pump.rs, Order flow,Order flow data model,Depth history store,unverified,library,src/data/depth_history.rs;src/widget/feed/mod.rs, Order flow,Order flow data model,Grouping fills into parent market orders,unverified,library,src/model/quote.rs;src/data/trades.rs;src/widget/feed/mod.rs;src/data/mod.rs, -Order flow,Order flow data model,Historical trades and depth paging for a time range,unverified,library,src/data/mod.rs;src/widget/feed/mod.rs;src/data/trades.rs;src/data/depth_history.rs, +Order flow,Order flow data model,Historical trades and depth paging for a time range,unverified,library,src/data/mod.rs;src/widget/feed/mod.rs;src/data/trades.rs;src/data/depth_history.rs,2724 Order flow,Order flow data model,Incremental depth updates with sequence numbers and snapshot resync,unverified,library,src/data/depth.rs;src/data/inbox/mod.rs;src/data/inbox/sink.rs;src/widget/feed/mod.rs;benches/regression/mod.rs, Order flow,Order flow data model,Historical trades and depth request for a time range,incomplete,library,src/data/mod.rs;src/widget/feed/mod.rs;src/data/trades.rs, Order flow,Order flow data model,Level 2 order book snapshots,unverified,library,src/model/quote.rs;src/data/inbox/mod.rs;src/data/inbox/sink.rs;src/data/depth.rs;src/widget/feed/mod.rs, @@ -570,7 +571,7 @@ Studies,Indicator infrastructure,Study editing permissions,unverified,library,sr Studies,Indicator infrastructure,Study help articles,unverified,host,src/studies/settings.rs;src/studies/indicator_trait.rs;src/studies/factory/mod.rs;src/chart/rendering/legend/study_controls.rs;src/ui/context_menu/study.rs;examples/demo/controller.rs,2040;2524 Studies,Indicator infrastructure,Study levels and the fill between them,unverified,library,src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/studies/indicator_trait.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/indicator/config.rs;src/widget/pane/indicator/paint.rs;src/chart/indicators/plots.rs;src/chart/rendering/indicator.rs;src/studies/builtin/smi.rs;src/studies/builtin/stochastic.rs;src/studies/builtin/stochastic_rsi.rs,2061;2414;2416;2420;2642 Studies,Indicator infrastructure,Volume profile candle visibility,unverified,library,src/painting/volume_profile.rs;src/studies/builtin/volume_profile.rs;src/chart/rendering/indicator.rs;src/chart/rendering/volume_profile.rs;src/data/volume_profile.rs,2297 -Studies,Indicators,24-hour Volume,unverified,library,src/studies/builtin/volume_24h.rs;src/data/study.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs;src/studies/builtin/lower_interval.rs;src/studies/settings.rs;src/studies/template.rs;src/widget/snapshot.rs;src/widget/export.rs;src/widget/studies.rs,2531;2662;2682;2683;2684 +Studies,Indicators,24-hour Volume,unverified,library,src/studies/builtin/volume_24h.rs;src/model/instrument.rs;src/data/study.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs;src/studies/builtin/lower_interval.rs;src/studies/settings.rs;src/studies/template.rs;src/widget/snapshot.rs;src/widget/export.rs;src/widget/studies.rs,2531;2662;2682;2683;2684;2920 Studies,Indicators,52 Week High/Low,unverified,library,src/studies/builtin/week52_highlow.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs;src/widget/studies.rs, Studies,Indicators,Accelerator Oscillator,unverified,library,src/studies/builtin/accelerator_oscillator.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs;src/widget/studies.rs, Studies,Indicators,Accumulation Distribution,incomplete,library,src/studies/builtin/acc_dist.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs;src/widget/studies.rs, @@ -581,14 +582,14 @@ Studies,Indicators,Advance/Decline Ratio,unverified,host,src/studies/builtin/mar Studies,Indicators,Advance/Decline Ratio bars,unverified,library,src/studies/builtin/advance_decline_ratio_bars.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,All Candlestick Patterns,incomplete,library,src/studies/builtin/candlestick_patterns/mod.rs;src/chart/rendering/indicator.rs,177 Studies,Indicators,All Chart Patterns,incomplete,library,;src/studies/builtin/chart_patterns.rs,1084;1085 -Studies,Indicators,Analyst price forecast,unverified,host,src/data/mod.rs;src/data/targets.rs;src/widget/targets.rs;src/widget/frame/mod.rs, +Studies,Indicators,Analyst price forecast,unverified,host,src/data/mod.rs;src/data/targets.rs;src/widget/targets.rs;src/widget/frame/mod.rs;src/ui/dialogs/chart_settings/mod.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs,2981 Studies,Indicators,Anchored Volume Profile,unverified,library,src/studies/builtin/volume_profile.rs;src/data/volume_profile.rs;src/chart/rendering/indicator.rs;src/painting/volume_profile.rs;src/chart/rendering/volume_profile.rs;src/data/study.rs;src/widget/studies_data.rs;src/studies/indicator_trait.rs;src/studies/settings.rs;src/model/instrument.rs;src/studies/template.rs;src/chart/rendering/legend/mod.rs;src/data/order_flow.rs;src/data/footprint.rs, Studies,Indicators,Arnaud Legoux Moving Average,unverified,library,src/studies/builtin/alma.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Aroon Indicator,incomplete,library,src/studies/builtin/aroon.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Aroon Oscillator,unverified,library,src/studies/builtin/aroon_oscillator.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Auto Anchored Volume Profile,unverified,library,src/studies/builtin/volume_profile.rs;src/data/volume_profile.rs;src/chart/rendering/indicator.rs;src/painting/volume_profile.rs;src/chart/rendering/volume_profile.rs;src/data/study.rs;src/widget/studies_data.rs;src/studies/indicator_trait.rs;src/studies/settings.rs;src/model/instrument.rs;src/data/order_flow.rs;src/data/footprint.rs, Studies,Indicators,Auto Fib Retracement,unverified,library,src/studies/builtin/auto_drawing.rs;src/studies/builtin/zigzag.rs;src/chart/indicators/plots.rs;src/drawings/rendering/mod.rs;src/drawings/rendering/fibonacci.rs;src/studies/factory/mod.rs;src/studies/builtin/atr.rs;src/drawings/domain/options.rs,1362 -Studies,Indicators,Auto Pitchfork,incomplete,library,src/studies/builtin/auto_drawing.rs;src/studies/builtin/zigzag.rs;src/chart/indicators/plots.rs;src/drawings/rendering/mod.rs;src/drawings/rendering/pitchfork.rs;src/studies/factory/mod.rs;src/studies/builtin/atr.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;examples/demo/controller.rs,2645 +Studies,Indicators,Auto Pitchfork,incomplete,library,src/studies/builtin/auto_drawing.rs;src/studies/builtin/zigzag.rs;src/chart/indicators/plots.rs;src/drawings/rendering/mod.rs;src/drawings/rendering/pitchfork.rs;src/studies/factory/mod.rs;src/studies/builtin/atr.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;examples/demo/controller.rs,2978 Studies,Indicators,Auto fib extension,unverified,library,src/studies/builtin/auto_drawing.rs;src/studies/builtin/zigzag.rs;src/chart/indicators/plots.rs;src/drawings/rendering/mod.rs;src/drawings/rendering/fibonacci.rs;src/studies/factory/mod.rs;src/studies/builtin/atr.rs;src/drawings/domain/options.rs,1362 Studies,Indicators,Auto key levels,incomplete,library,;src/studies/builtin/key_levels.rs,1091 Studies,Indicators,Auto trendlines,unverified,library,src/studies/builtin/auto_drawing.rs;src/studies/builtin/zigzag.rs;src/studies/factory/mod.rs;src/chart/indicators/plots.rs;src/drawings/rendering/mod.rs;src/drawings/rendering/lines.rs;src/studies/builtin/atr.rs, @@ -673,12 +674,12 @@ Studies,Indicators,Chart Pattern Triangle,unverified,library,src/studies/builtin Studies,Indicators,Chart Pattern Triple Bottom,unverified,library,src/studies/builtin/chart_patterns.rs;src/studies/factory/mod.rs;src/studies/settings.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Chart Pattern Triple Top,unverified,library,src/studies/builtin/chart_patterns.rs;src/studies/factory/mod.rs;src/studies/settings.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Chop Zone,unverified,library,src/studies/builtin/chop_zone.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, -Studies,Indicators,Choppiness Index,unverified,library,src/studies/builtin/choppiness.rs;src/studies/factory/mod.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/widget/pane/indicator/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, +Studies,Indicators,Choppiness Index,unverified,library,src/studies/builtin/choppiness.rs;src/studies/factory/mod.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/widget/pane/indicator/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs,2411 Studies,Indicators,Commodity Channel Index,unverified,library,src/studies/builtin/cci.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Connors RSI,incomplete,library,src/studies/builtin/connors_rsi.rs;src/studies/factory/mod.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/widget/pane/indicator/paint.rs;src/chart/indicators/plots.rs;src/studies/indicator_trait.rs;src/chart/rendering/indicator.rs,2414 Studies,Indicators,Coppock Curve,unverified,library,src/studies/builtin/coppock.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Correlation - Log,missing,library,,1081 -Studies,Indicators,Correlation Coefficient,incomplete,library,;src/studies/builtin/symbol_pair.rs,1081 +Studies,Indicators,Correlation Coefficient,incomplete,library,src/studies/builtin/symbol_pair.rs;src/studies/template.rs;src/studies/factory/mod.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/chart/indicators/plots.rs;src/chart/rendering/indicator.rs,1081;2655 Studies,Indicators,Crypto derivatives metrics,incomplete,host,src/data/metrics.rs;src/data/mod.rs;src/studies/metric.rs;src/widget/studies_data.rs;src/ui/dialogs/indicator_dialog/dialog.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Crypto on-chain and ETF metrics,unverified,host,src/data/metrics.rs;src/data/mod.rs;src/studies/metric.rs;src/widget/studies_data.rs;src/ui/dialogs/indicator_dialog/dialog.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Cumulative Volume Delta,unverified,library,src/data/footprint.rs;src/studies/builtin/trade_delta.rs;src/chart/series/trade_delta.rs;src/studies/builtin/mod.rs;src/studies/builtin/volume_delta.rs;src/studies/builtin/lower_interval.rs, @@ -697,7 +698,7 @@ Studies,Indicators,Exponential Moving Average,unverified,library,src/studies/bui Studies,Indicators,Fisher Transform,unverified,library,src/studies/builtin/fisher_transform.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Fixed Range Volume Profile,incomplete,library,src/studies/builtin/volume_profile.rs;src/data/volume_profile.rs;src/chart/rendering/indicator.rs;src/painting/volume_profile.rs;src/chart/rendering/volume_profile.rs;src/data/study.rs;src/widget/studies_data.rs;src/studies/indicator_trait.rs;src/studies/settings.rs;src/model/instrument.rs;src/studies/template.rs;src/data/order_flow.rs;src/data/footprint.rs, Studies,Indicators,Gaps,unverified,library,src/studies/builtin/gaps.rs;src/chart/indicators/plots.rs;src/studies/factory/mod.rs, -Studies,Indicators,Guppy Multiple Moving Average,incomplete,library,src/studies/builtin/guppy_ma.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, +Studies,Indicators,Guppy Multiple Moving Average,unverified,library,src/studies/builtin/guppy_ma.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Historical Volatility,unverified,library,src/studies/builtin/historical_volatility.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Hull Moving Average,incomplete,library,src/studies/builtin/hma.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Ichimoku Cloud,unverified,library,src/studies/builtin/ichimoku.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, @@ -711,7 +712,7 @@ Studies,Indicators,Linear Regression Curve,unverified,library,src/studies/builti Studies,Indicators,Linear Regression Slope,incomplete,library,src/studies/builtin/linear_regression.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,MA Cross,incomplete,library,src/studies/builtin/ma_combination.rs;src/studies/builtin/ma_presets.rs;src/studies/builtin/ma_multiple.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,MA with EMA Cross,unverified,library,src/studies/builtin/ma_combination.rs;src/studies/builtin/ma_presets.rs;src/studies/builtin/ma_multiple.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, -Studies,Indicators,Majority Rule,incomplete,library,src/studies/builtin/majority_rule.rs;src/studies/factory/mod.rs, +Studies,Indicators,Majority Rule,unverified,library,src/studies/builtin/majority_rule.rs;src/studies/factory/mod.rs;src/studies/template.rs,2988 Studies,Indicators,Mass Index,unverified,library,src/studies/builtin/mass_index.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,McGinley Dynamic,unverified,library,src/studies/builtin/mcginley_dynamic.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Median,unverified,library,src/studies/builtin/median.rs;src/studies/settings.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs,2666 @@ -728,7 +729,7 @@ Studies,Indicators,Moving Average Multiple,unverified,library,src/studies/builti Studies,Indicators,Moving Average Ribbon,unverified,library,src/studies/builtin/ma_combination.rs;src/studies/builtin/ma_presets.rs;src/studies/builtin/ma_multiple.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Moving Average Triple,unverified,library,src/studies/builtin/ma_combination.rs;src/studies/builtin/ma_presets.rs;src/studies/builtin/ma_multiple.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Multi-Time Period Charts,incomplete,library,src/studies/builtin/higher_interval_candles.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, -Studies,Indicators,Negative Volume Index,incomplete,library,src/studies/builtin/volume_price_trend.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, +Studies,Indicators,Negative Volume Index,unverified,library,src/studies/builtin/volume_price_trend.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Net Volume,incomplete,library,src/studies/builtin/net_volume.rs;src/studies/indicator_trait.rs,173 Studies,Indicators,On Balance Volume,unverified,library,src/studies/builtin/obv.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Open Interest,unverified,host,src/data/metrics.rs;src/data/mod.rs;src/studies/metric.rs;src/widget/studies_data.rs;src/ui/dialogs/indicator_dialog/dialog.rs;src/chart/rendering/indicator.rs, @@ -740,10 +741,10 @@ Studies,Indicators,Performance,incomplete,library,src/studies/builtin/performanc Studies,Indicators,Periodic Volume Profile,incomplete,library,src/studies/builtin/volume_profile.rs;src/data/volume_profile.rs;src/chart/rendering/indicator.rs;src/painting/volume_profile.rs;src/chart/rendering/volume_profile.rs;src/data/study.rs;src/widget/studies_data.rs;src/studies/indicator_trait.rs;src/studies/settings.rs;src/model/instrument.rs;src/data/order_flow.rs;src/data/footprint.rs;src/studies/builtin/trade_profile.rs,2297;2415 Studies,Indicators,Pivot Points High Low,unverified,library,src/studies/builtin/pivot_points_high_low.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Pivot Points Standard,incomplete,library,src/studies/builtin/pivot_points.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs;src/chart/indicators/plots.rs;src/studies/template.rs;src/chart/rendering/legend/mod.rs;src/widget/pane/indicator/paint.rs;src/studies/settings.rs;src/studies/builtin/projected_pivot_points.rs;src/widget/studies_data.rs,2525;2528;2531 -Studies,Indicators,Positive Volume Index,incomplete,library,src/studies/builtin/volume_price_trend.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, +Studies,Indicators,Positive Volume Index,unverified,library,src/studies/builtin/volume_price_trend.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Price Channel,unverified,library,src/studies/builtin/price_channel.rs;src/studies/builtin/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Price Momentum Oscillator,unverified,library,src/studies/builtin/price_momentum_oscillator.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, -Studies,Indicators,Price Target,incomplete,host,src/data/mod.rs;src/data/targets.rs;src/widget/targets.rs;src/widget/frame/mod.rs, +Studies,Indicators,Price Target,incomplete,host,src/data/mod.rs;src/data/targets.rs;src/widget/targets.rs;src/widget/frame/mod.rs;src/ui/dialogs/chart_settings/mod.rs;src/ui/dialogs/chart_settings/tabs/symbol.rs,2981 Studies,Indicators,Price Volume Trend,incomplete,library,src/studies/builtin/volume_price_trend.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Pring's Special K,unverified,library,src/studies/builtin/special_k.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,RCI Ribbon,unverified,library,src/studies/builtin/rci_ribbon.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, @@ -751,7 +752,7 @@ Studies,Indicators,RSI Divergence Indicator,incomplete,library,src/studies/built Studies,Indicators,Rank Correlation Index,incomplete,library,src/studies/builtin/rank_correlation.rs;src/studies/builtin/smoothing.rs;src/studies/factory/mod.rs;src/studies/template.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Rate of Change,unverified,library,src/studies/builtin/roc.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/chart/indicators/plots.rs,2649 Studies,Indicators,Ratio,incomplete,library,src/services/search/expression.rs,1081 -Studies,Indicators,Relative Strength Index,incomplete,library,src/studies/builtin/rsi.rs;src/studies/builtin/smoothing.rs;src/studies/factory/mod.rs;src/studies/template.rs,1089;2335 +Studies,Indicators,Relative Strength Index,unverified,library,src/studies/builtin/rsi.rs;src/studies/builtin/rsi_divergence.rs;src/studies/builtin/smoothing.rs;src/studies/factory/mod.rs;src/studies/template.rs,1089;2335;2673;2913 Studies,Indicators,Relative Vigor Index,unverified,library,src/studies/builtin/relative_vigor.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Relative Volatility Index,unverified,library,src/studies/builtin/relative_volatility_index.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Relative Volume at Time,unverified,library,src/studies/builtin/relative_volume_at_time.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, @@ -772,13 +773,13 @@ Studies,Indicators,Smoothed Moving Average,incomplete,library,src/studies/builti Studies,Indicators,Spread,incomplete,library,src/services/search/expression.rs,1081 Studies,Indicators,Standard Deviation,unverified,library,src/studies/builtin/std_dev.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Standard Error,unverified,library,src/studies/builtin/standard_error.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, -Studies,Indicators,Standard Error Bands,incomplete,library,src/studies/builtin/standard_error_bands.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, +Studies,Indicators,Standard Error Bands,unverified,library,src/studies/builtin/smoothing.rs;src/studies/builtin/standard_error_bands.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Stochastic,incomplete,library,src/studies/builtin/stochastic.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/widget/pane/indicator/paint.rs;examples/demo/controller.rs,2416 Studies,Indicators,Stochastic Momentum Index,incomplete,library,src/studies/builtin/smi.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/chart/rendering/indicator/gradient.rs;src/studies/plots.rs;src/chart/rendering/axes/study_scale.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/studies/indicator_trait.rs;src/chart/indicators/plots.rs;src/widget/pane/indicator/mod.rs;src/widget/series/scales/mod.rs,2420;2642 Studies,Indicators,Stochastic RSI,incomplete,library,src/studies/builtin/stochastic_rsi.rs;src/studies/builtin/rsi.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/widget/pane/indicator/paint.rs;examples/demo/controller.rs,2416 Studies,Indicators,Supertrend,unverified,library,src/studies/builtin/supertrend.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,TRIX,unverified,library,src/studies/builtin/trix.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, -Studies,Indicators,Technical Ratings,incomplete,library,src/studies/builtin/technical_ratings.rs;src/studies/builtin/stochastic.rs;src/studies/builtin/cci.rs;src/studies/factory/mod.rs;src/chart/rendering/indicator.rs;src/studies/table.rs;src/widget/pane/indicator/mod.rs,1119 +Studies,Indicators,Technical Ratings,incomplete,library,src/studies/builtin/technical_ratings.rs;src/studies/builtin/stochastic.rs;src/studies/builtin/cci.rs;src/studies/factory/mod.rs;src/chart/rendering/indicator.rs;src/studies/table.rs;src/widget/pane/indicator/mod.rs;src/widget/pane/render/mod.rs,1119;2674 Studies,Indicators,Time Price Opportunity,incomplete,library,src/studies/builtin/time_price_opportunity.rs;src/model/tpo.rs;src/model/session/exchange.rs;src/chart/rendering/candles/tpo.rs;src/tokens/mod.rs;src/tokens/semantic.rs;src/widget/frame/mod.rs,2432 Studies,Indicators,Time Weighted Average Price,unverified,library,src/studies/builtin/twap.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Trading Sessions,incomplete,library,src/studies/builtin/trading_sessions.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/chart/indicators/plots.rs;src/chart/indicators/hit_test.rs;src/studies/indicator_trait.rs;src/studies/settings.rs;src/studies/template.rs, @@ -789,21 +790,21 @@ Studies,Indicators,Typical Price,incomplete,library,src/studies/builtin/typical_ Studies,Indicators,Ulcer Index,unverified,library,src/studies/builtin/ulcer_index.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Ultimate Oscillator,unverified,library,src/studies/builtin/ultimate_oscillator.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/chart/indicators/plots.rs,2649 Studies,Indicators,Up/Down Volume,incomplete,library,src/studies/builtin/up_down_volume.rs;src/widget/studies_data.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs;src/studies/builtin/lower_interval.rs, -Studies,Indicators,VWAP Auto Anchored,incomplete,library,src/studies/builtin/vwap_auto_anchored.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, +Studies,Indicators,VWAP Auto Anchored,incomplete,library,src/studies/builtin/vwap_auto_anchored.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs;src/studies/template.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/chart/indicators/plots.rs, Studies,Indicators,Visible Average Price,unverified,library,src/studies/builtin/visible_average_price.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/chart/indicators/plots.rs,2654 Studies,Indicators,Visible Range Volume Profile,unverified,library,src/studies/builtin/volume_profile.rs;src/data/volume_profile.rs;src/chart/rendering/indicator.rs;src/painting/volume_profile.rs;src/chart/rendering/volume_profile.rs;src/data/study.rs;src/widget/studies_data.rs;src/studies/indicator_trait.rs;src/studies/settings.rs;src/model/instrument.rs;src/data/order_flow.rs;src/data/footprint.rs, -Studies,Indicators,Volatility Close-to-Close,incomplete,library,src/studies/builtin/historical_volatility.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, +Studies,Indicators,Volatility Close-to-Close,unverified,library,src/studies/builtin/close_to_close_vol.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs;src/studies/factory/mod.rs, Studies,Indicators,Volatility Index,missing,library,,173 -Studies,Indicators,Volatility O-H-L-C,incomplete,library,src/studies/builtin/ohlc_volatility.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, +Studies,Indicators,Volatility O-H-L-C,unverified,library,src/studies/builtin/ohlc_volatility.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Volatility Stop,unverified,library,src/studies/builtin/volatility_stop.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, -Studies,Indicators,Volatility Zero Trend Close-to-Close,incomplete,library,src/studies/builtin/zero_trend_vol.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, +Studies,Indicators,Volatility Zero Trend Close-to-Close,unverified,library,src/studies/builtin/zero_trend_vol.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Volume,unverified,library,src/studies/builtin/volume.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/widget/volume.rs;src/studies/palette.rs;src/chart/coords/mod.rs;src/model/timescale.rs;src/chart/rendering/indicator.rs;src/chart/rendering/candles/volume.rs;src/widget/time_scale.rs;src/chart/rendering/candles/candlestick.rs;src/widget/pane/indicator/mod.rs,2497;2498 Studies,Indicators,Volume Delta,incomplete,library,src/data/footprint.rs;src/studies/builtin/trade_delta.rs;src/chart/series/trade_delta.rs;src/studies/builtin/mod.rs;src/studies/builtin/volume_delta.rs;src/studies/builtin/lower_interval.rs, Studies,Indicators,Volume Weighted Average Price,incomplete,library,src/studies/builtin/vwap.rs;src/studies/settings.rs;src/studies/template.rs;src/widget/studies.rs;src/studies/indicator_trait.rs;src/chart/rendering/legend/mod.rs;src/widget/pane/indicator/paint.rs,2337 Studies,Indicators,Volume-Weighted Moving Average,incomplete,library,src/studies/builtin/vwma.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Vortex Indicator,incomplete,library,src/studies/builtin/vortex.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Weighted Moving Average,unverified,library,src/studies/builtin/wma.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, -Studies,Indicators,Williams %R,incomplete,library,src/studies/builtin/williams_r.rs;src/studies/builtin/smoothing.rs;src/studies/factory/mod.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs,2410 +Studies,Indicators,Williams %R,unverified,library,src/studies/builtin/williams_r.rs;src/studies/builtin/smoothing.rs;src/studies/factory/mod.rs;src/studies/settings.rs;src/ui/dialogs/indicator_dialog/settings.rs;src/widget/pane/indicator/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs,2410 Studies,Indicators,Williams Alligator,unverified,library,src/studies/builtin/williams_alligator.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Williams Fractal,verified,library,src/studies/builtin/williams_fractals.rs;src/studies/factory/mod.rs;src/widget/studies.rs;src/chart/rendering/indicator.rs, Studies,Indicators,Woodies CCI,incomplete,library,src/studies/builtin/woodies_cci.rs,1118 @@ -915,7 +916,7 @@ Terminal,Templates and layouts,"Image sharing, hosted links and social posting", Terminal,Templates and layouts,Indicator templates,incomplete,library,src/studies/template.rs;src/ui/dialogs/templates/dialog.rs;src/ui/top_toolbar/toolbar.rs;src/widget/study_templates.rs;terminal/src/compare.rs;src/studies/settings.rs;src/studies/indicator_trait.rs,2333;2335;2337;2523;1485 Terminal,Templates and layouts,Multi-chart layouts,incomplete,library,src/widget/layout.rs;src/widget/history.rs;src/ui/top_toolbar/components/chart_grid_selector.rs;terminal/src/layouts.rs;examples/demo/layouts.rs;examples/demo/replay.rs,2036;2052;2077;2505;2527;2688;2689 Terminal,Templates and layouts,Open a saved layout; layout list with favourites and delete,unverified,library,src/ui/top_toolbar/components/layout_menu.rs;src/services/settings.rs;terminal/src/layouts.rs;src/widget/snapshot.rs,2182;2472;2476 -Terminal,Templates and layouts,Persist preferences,incomplete,library,src/services/settings.rs;src/ui/top_toolbar/components/timeframe_selector/mod.rs;terminal/src/time.rs;src/ui/drawing_toolbar/state.rs;examples/demo/controller.rs,205;383;2078 +Terminal,Templates and layouts,Persist preferences,incomplete,library,src/services/settings.rs;src/ui/top_toolbar/components/timeframe_selector/mod.rs;terminal/src/time.rs;src/ui/drawing_toolbar/state.rs;examples/demo/controller.rs;src/ui/top_toolbar/components/chart_type_selector.rs,205;383;2078 Terminal,Templates and layouts,Save chart layout,incomplete,library,src/widget/snapshot.rs;src/ui/top_toolbar/components/layout_menu.rs;src/ui/top_toolbar/toolbar.rs;src/ui/top_toolbar/buttons.rs;src/widget/series/options.rs;terminal/src/layouts.rs;examples/demo/storage.rs;examples/demo/layouts.rs;src/widget/palette.rs;src/studies/template.rs;src/studies/settings.rs;src/studies/indicator_trait.rs;src/widget/time_scale.rs;src/model/timescale.rs,2182;2472;2476;2486;2523;1869;2497 Terminal,Templates and layouts,Share a layout by link,unverified,host,src/services/sharing.rs;src/ui/share_controls.rs;src/ui/top_toolbar/components/layout_menu.rs, Terminal,Templates and layouts,Snapshot: copy image to clipboard,unverified,library,src/ui/export.rs;src/ui/top_toolbar/toolbar.rs;src/ui_kit/section/mod.rs,1556 @@ -923,9 +924,9 @@ Terminal,Templates and layouts,Snapshot: download the chart image,unverified,lib Terminal,Templates and layouts,Sync between charts,unverified,library,src/widget/layout.rs;src/widget/layout/drawings.rs;src/widget/sync.rs;src/model/timescale.rs;src/widget/frame/mod.rs,2474 Terminal,Toolbars and panels,Bottom time bar,unverified,library,src/ui/timeframe_toolbar/toolbar.rs;src/ui/top_toolbar/buttons.rs;src/theme/mod.rs;terminal/src/time.rs;src/model/date_range.rs;src/ui/timeframe_toolbar/range_switcher.rs;terminal/src/compare.rs;src/widget/feed/mod.rs;src/data/mod.rs;src/model/instrument.rs;examples/demo/feeds.rs;examples/demo/controller.rs;examples/demo/sampledata.rs,1926 Terminal,Toolbars and panels,Chart settings button and applying the dialog,unverified,library,src/ui/top_toolbar/toolbar.rs;src/widget/settings/apply.rs, -Terminal,Toolbars and panels,Chart type menu,incomplete,library,src/ui/top_toolbar/toolbar.rs;src/ui/top_toolbar/components/chart_type_selector.rs;src/styles/mod.rs,1556 +Terminal,Toolbars and panels,Chart type menu,incomplete,library,src/ui/top_toolbar/toolbar.rs;src/ui/top_toolbar/components/chart_type_selector.rs;src/styles/mod.rs;src/services/settings.rs;terminal/src/time.rs,1556 Terminal,Toolbars and panels,Compare / add symbol dialog,unverified,library,src/ui/dialogs/symbol_search/compare.rs;src/ui/dialogs/symbol_search/row.rs;src/ui/dialogs/symbol_search/service.rs;terminal/src/compare.rs;src/widget/series/options.rs;src/widget/studies_data.rs;src/services/search.rs,2027;2193;2194;2195 -Terminal,Toolbars and panels,Custom intervals,unverified,library,src/ui/top_toolbar/components/timeframe_selector/mod.rs;src/ui/top_toolbar/toolbar.rs;src/model/timeframe.rs;src/model/session/exchange.rs;terminal/src/time.rs, +Terminal,Toolbars and panels,Custom intervals,unverified,library,src/ui/top_toolbar/components/timeframe_selector/mod.rs;src/ui/top_toolbar/toolbar.rs;src/model/timeframe.rs;src/model/session/exchange.rs;terminal/src/time.rs;src/services/settings.rs, Terminal,Toolbars and panels,Data window,unverified,library,src/ui/widget_bar/panels/object_tree/data_window.rs;src/scales/horizontal.rs;src/scales/time_formatter.rs;terminal/src/panels.rs;src/widget/frame/mod.rs;terminal/src/drawings.rs;src/widget/format.rs,1939;2483 Terminal,Toolbars and panels,Demo showcase menu,unverified,library,examples/demo/commands.rs;examples/demo/controller.rs;examples/demo/annotations.rs;examples/demo/formatting.rs;src/ui/top_toolbar/toolbar.rs,1943;1994;2013;1928 Terminal,Toolbars and panels,Depth ladder for analysis without a trading account,incomplete,library,src/ui/trading/dom.rs;src/ui/widget_bar/panels/mod.rs;examples/demo/controller.rs;examples/demo/live.rs,1756 @@ -934,7 +935,7 @@ Terminal,Toolbars and panels,Favourite intervals pinned to the toolbar,verified, Terminal,Toolbars and panels,Fullscreen,unverified,library,src/ui/top_toolbar/toolbar.rs, Terminal,Toolbars and panels,Indicators button,unverified,library,src/ui/top_toolbar/toolbar.rs, Terminal,Toolbars and panels,Interval menu presets,incomplete,library,src/ui/top_toolbar/components/timeframe_selector/mod.rs;src/ui/top_toolbar/toolbar.rs;terminal/src/time.rs;src/ui_kit/section/mod.rs;src/styles/mod.rs,1556 -Terminal,Toolbars and panels,Keyboard shortcuts for application actions,incomplete,library,src/widget/keyboard.rs;terminal/src/alerts.rs, +Terminal,Toolbars and panels,Keyboard shortcuts for application actions,incomplete,library,src/widget/keyboard.rs;terminal/src/alerts.rs;terminal/src/commands.rs, Terminal,Toolbars and panels,Left drawing toolbar shell,unverified,library,src/ui/drawing_toolbar/toolbar/mod.rs;terminal/src/drawings.rs;src/ui/drawing_toolbar/components/svg_helpers.rs;src/ui/drawing_toolbar/components/icon_button.rs;src/ui/drawing_toolbar/components/separator.rs;src/ui/top_toolbar/buttons.rs;src/ui/drawing_toolbar/state.rs;src/ui/drawing_toolbar/utilities/hide_menu.rs;examples/demo/controller.rs, Terminal,Toolbars and panels,Marker and price line sample editor,unverified,library,examples/demo/annotations.rs;examples/demo/commands.rs;src/widget/series/mod.rs;src/widget/change_marks.rs,1942 Terminal,Toolbars and panels,Notifications / toasts,unverified,library,src/ui/widget_bar/panels/alerts_panel.rs;src/ui/trading/mod.rs;src/ui/trading/events.rs;src/ui_kit/notifications/panel.rs;src/ui_kit/notifications/toasts.rs;terminal/src/panels.rs, @@ -942,7 +943,7 @@ Terminal,Toolbars and panels,Numeric horizontal scale samples,unverified,library Terminal,Toolbars and panels,Object tree panel,unverified,library,src/ui/widget_bar/panels/object_tree/chart_actions.rs;src/ui/widget_bar/panels/object_tree/folders.rs;src/ui/widget_bar/panels/object_tree/panel.rs;terminal/src/drawings.rs;src/ui/widget_bar/panels/object_tree/context_menu.rs;src/ui/widget_bar/panels/object_tree/item_row.rs;examples/demo/controller.rs;examples/demo/comparison.rs;src/widget/layout/drawings.rs;examples/demo/layouts.rs;src/ui/widget_bar/panels/object_tree/state.rs;src/widget/layout.rs;src/widget/history.rs,1916;2313;2314;2527 Terminal,Toolbars and panels,Order-flow panels and layouts offered only for symbols whose feed supplies their data,missing,host,,1757 Terminal,Toolbars and panels,Primitive and custom renderer sample,unverified,library,examples/demo/primitive_scene.rs;examples/demo/commands.rs,1936 -Terminal,Toolbars and panels,Quick search / command palette,unverified,library,src/ui/top_toolbar/toolbar.rs;src/ui_kit/command_palette/palette.rs, +Terminal,Toolbars and panels,Quick search / command palette,unverified,library,src/ui/top_toolbar/toolbar.rs;src/ui_kit/command_palette/palette.rs;terminal/src/commands.rs, Terminal,Toolbars and panels,Right widget bar icon strip,unverified,library,src/ui/widget_bar/toolbar.rs;src/theme/presets.rs;terminal/src/panels.rs;examples/demo/controller.rs,2013;1928 Terminal,Toolbars and panels,Sample study editor,incomplete,library,src/ui/study_editor.rs;examples/demo/study_editor.rs;examples/demo/storage.rs;examples/demo/commands.rs,1937 Terminal,Toolbars and panels,Selected drawing toolbar,unverified,library,src/ui/floating_toolbar/toolbar.rs;src/widget/tool_interaction/mod.rs;src/drawings/rendering/measurements.rs;src/ui/context_menu/drawing.rs;terminal/src/drawings.rs;examples/demo/controller.rs,2324;2603 @@ -950,7 +951,7 @@ Terminal,Toolbars and panels,Strategy Report panel,unverified,library,src/ui/str Terminal,Toolbars and panels,Symbol search dialog with asset tabs and filters,incomplete,host,src/ui/dialogs/symbol_search/mod.rs;src/ui/dialogs/symbol_search/row.rs;src/ui/dialogs/symbol_search/service.rs;src/ui_kit/tab_bar/mod.rs;terminal/src/studies.rs;src/services/search.rs;src/model/instrument.rs;examples/demo/feeds.rs;examples/demo/controller.rs,2027;2193;2195 Terminal,Toolbars and panels,Time and sales panel,unverified,library,;src/ui/widget_bar/panels/time_and_sales.rs;src/widget/feed/mod.rs;terminal/src/panels.rs,1755 Terminal,Toolbars and panels,Top toolbar: symbol button,unverified,library,src/ui/top_toolbar/toolbar.rs, -Terminal,Toolbars and panels,Undo / redo,incomplete,library,src/widget/history.rs;src/widget/feed/mod.rs;src/widget/series/options.rs;terminal/src/core.rs;examples/demo/controller.rs;src/ui/top_toolbar/toolbar.rs;src/ui/top_toolbar/buttons.rs;src/widget/series/mod.rs;src/widget/replay.rs;terminal/src/compare.rs;src/widget/layout.rs;src/scales/pricescale.rs;src/widget/studies_data.rs;src/widget/studies.rs;src/studies/settings.rs,1053;2316;2321;2505;2520;2527;2522;2688;2689 +Terminal,Toolbars and panels,Undo / redo,unverified,library,src/widget/history.rs;src/widget/feed/mod.rs;src/widget/series/options.rs;terminal/src/core.rs;examples/demo/controller.rs;src/ui/top_toolbar/toolbar.rs;src/ui/top_toolbar/buttons.rs;src/widget/series/mod.rs;src/widget/replay.rs;terminal/src/compare.rs;src/widget/layout.rs;src/scales/pricescale.rs;src/widget/studies_data.rs;src/widget/studies.rs;src/studies/settings.rs,1053;2316;2321;2505;2520;2527;2522;2688;2689;2812;2813;2844 Terminal,Toolbars and panels,Zoom in / zoom out buttons in the drawing toolbar,unverified,library,src/ui/drawing_toolbar/utilities/zoom.rs;src/widget/mod.rs;terminal/src/drawings.rs, Terminal,Trading panel,Account manager,unverified,host,src/ui/trading/mod.rs;src/ui/trading/account_panel/mod.rs;src/ui/trading/account_panel/view.rs;terminal/src/trading.rs, Terminal,Trading panel,Bottom trading panel container,unverified,library,src/ui/trading/account_panel/mod.rs;src/ui/trading/account_panel/view.rs;terminal/src/trading.rs;terminal/src/layout.rs, @@ -973,6 +974,7 @@ Terminal,Trading panel,Trading notifications,unverified,host,src/ui/trading/mod. Terminal,Watchlists and screeners,Add to watchlist from the chart context menu,unverified,library,src/ui/context_menu/mod.rs;src/ui/widget_bar/panels/watchlist.rs;terminal/src/panels.rs, Terminal,Watchlists and screeners,Advanced watchlist view,incomplete,library,src/ui/widget_bar/panels/watchlist.rs;src/ui/widget_bar/panels/market_details.rs;src/ui/widget_bar/panels/symbol_details.rs;terminal/src/panels.rs, Terminal,Watchlists and screeners,Colour flags and the flagged list,unverified,library,src/ui/widget_bar/panels/watchlist.rs;src/model/watchlist.rs, +Terminal,Watchlists and screeners,Company financials in place of the chart,unverified,host,src/data/financials.rs;src/data/mod.rs;src/ui/financials.rs;src/ui/widget_bar/panels/symbol_details.rs;terminal/src/panels.rs;terminal/src/layout.rs,205 Terminal,Watchlists and screeners,"ETF, bond, crypto coin, CEX pair and DEX pair screeners",unverified,host,src/ui/widget_bar/panels/screener.rs;src/data/market.rs;src/services/storage.rs;src/ui/dialogs/templates/store.rs;terminal/src/panels.rs, Terminal,Watchlists and screeners,Flip through list symbols on the chart,incomplete,library,src/ui/widget_bar/panels/watchlist.rs;terminal/src/panels.rs, Terminal,Watchlists and screeners,Hotlists,incomplete,host,src/ui/widget_bar/panels/hotlists.rs;terminal/src/panels.rs;examples/demo/feeds.rs;examples/demo/live.rs;examples/demo/controller.rs, diff --git a/vendor/egui-charts/docs/site/astro.config.mjs b/vendor/egui-charts/docs/site/astro.config.mjs index 876bb3a..06ed229 100644 --- a/vendor/egui-charts/docs/site/astro.config.mjs +++ b/vendor/egui-charts/docs/site/astro.config.mjs @@ -34,7 +34,7 @@ export default defineConfig({ { label: 'Status', link: '/progress/' }, { label: 'Learning', - items: ['installation', 'first-chart', 'tutorial/second-series', { slug: 'builder-guide', label: 'Builder tutorial' }, 'data-model', 'data'], + items: ['installation', 'first-chart', 'tutorial/second-series', { slug: 'builder-guide', label: 'Builder tutorial' }, 'data-model', 'data', 'own-data'], }, { label: 'Chart concepts', diff --git a/vendor/egui-charts/docs/site/package-lock.json b/vendor/egui-charts/docs/site/package-lock.json index f946576..a7e1319 100644 --- a/vendor/egui-charts/docs/site/package-lock.json +++ b/vendor/egui-charts/docs/site/package-lock.json @@ -8,7 +8,7 @@ "dependencies": { "@astrojs/markdown-remark": "7.3.5", "@astrojs/starlight": "0.42.8", - "astro": "7.4.4", + "astro": "7.4.12", "parse5": "8.1.0" } }, @@ -325,6 +325,16 @@ "node": ">=22.22.0" } }, + "node_modules/@astrojs/runtime": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@astrojs/runtime/-/runtime-0.1.1.tgz", + "integrity": "sha512-2Tr9IJ4aQBPDFzlSLq139eWS9OZnuhL0yU2al8cCpnTE/RszygSyGIP8piBmEio1zDUaItb/+YxxsrmldUCBmg==", + "license": "MIT", + "dependencies": { + "@oslojs/encoding": "^1.1.0", + "clsx": "^2.1.1" + } + }, "node_modules/@astrojs/sitemap": { "version": "3.7.4", "resolved": "https://registry.npmjs.org/@astrojs/sitemap/-/sitemap-3.7.4.tgz", @@ -395,6 +405,42 @@ "node": ">=22.23.4" } }, + "node_modules/@astrojs/vite-plugin-astro": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@astrojs/vite-plugin-astro/-/vite-plugin-astro-0.1.3.tgz", + "integrity": "sha512-yj+xGnr3HeHUtIdra/tWizJuisBoxAuWlBTElMlf22FpSxinrTwTl/dqftG0D2BsQTcn4/shgCCUwcnkcZ8buA==", + "license": "MIT", + "dependencies": { + "@astrojs/compiler-rs": "^0.5.1", + "@astrojs/internal-helpers": "^0.13.2", + "@astrojs/runtime": "^0.1.1", + "common-ancestor-path": "^2.0.0", + "devalue": "^6.0.2", + "magic-string": "^1.4.2", + "rolldown": "~1.2.16", + "smol-toml": "^1.9.0", + "zod": "^4.6.5" + }, + "peerDependencies": { + "vite": "^8.3.3" + } + }, + "node_modules/@astrojs/vite-plugin-astro/node_modules/@astrojs/internal-helpers": { + "version": "0.13.2", + "resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.13.2.tgz", + "integrity": "sha512-SWiNS+OMrhwWYzJENTekHUyUCMKB+tdU6D4v1ZNIU1ZHh2mScQ8WIs0J6AJ8KPXkIrs9+EZU7Rm2CstfThyVnw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.5", + "@types/mdast": "^4.0.4", + "picomatch": "^4.0.7", + "retext-smartypants": "^6.2.0", + "shiki": "^4.6.0", + "smol-toml": "^1.9.1", + "unified": "^11.0.5", + "yaml": "^2.9.1" + } + }, "node_modules/@babel/helper-string-parser": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", @@ -441,6 +487,19 @@ "node": ">=6.9.0" } }, + "node_modules/@bruits/satteri-android-arm64": { + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/@bruits/satteri-android-arm64/-/satteri-android-arm64-0.11.7.tgz", + "integrity": "sha512-ej+1rIKs+yb6/OtcIe1SO22OXjJV0qqUopl5VNZF8Sqc/Pj4m1DXoqBQsPxW5OUYYiDUymIy6hnnn8M78VYk2w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, "node_modules/@bruits/satteri-darwin-arm64": { "version": "0.10.5", "resolved": "https://registry.npmjs.org/@bruits/satteri-darwin-arm64/-/satteri-darwin-arm64-0.10.5.tgz", @@ -467,6 +526,19 @@ "darwin" ] }, + "node_modules/@bruits/satteri-freebsd-x64": { + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/@bruits/satteri-freebsd-x64/-/satteri-freebsd-x64-0.11.7.tgz", + "integrity": "sha512-EFlqw+RDRo3wYdy1ZSR/dNYhfWjuZL86PYwRcpLWWEZskjfpNnhIdxS13Xw2QJE1hSjTGVq4aZaVvlUjoj8p5A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, "node_modules/@bruits/satteri-linux-arm64-gnu": { "version": "0.10.5", "resolved": "https://registry.npmjs.org/@bruits/satteri-linux-arm64-gnu/-/satteri-linux-arm64-gnu-0.10.5.tgz", @@ -1333,9 +1405,9 @@ } }, "node_modules/@napi-rs/wasm-runtime": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.5.tgz", - "integrity": "sha512-HshSvXzmBxNzqejd3k/KemgQ3hdREUYFRRrgxOZ+gPljDIsO2SDZrVZMd4Z/HsxudQbE62OVyVFE8z9BCurfjA==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", "license": "MIT", "optional": true, "dependencies": { @@ -1349,8 +1421,8 @@ "url": "https://github.com/sponsors/Brooooooklyn" }, "peerDependencies": { - "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", - "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" } }, "node_modules/@oslojs/encoding": { @@ -1360,9 +1432,9 @@ "license": "MIT" }, "node_modules/@oxc-project/types": { - "version": "0.154.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.154.0.tgz", - "integrity": "sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA==", + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/oxc-project" @@ -1466,9 +1538,9 @@ ] }, "node_modules/@rolldown/binding-android-arm-eabi": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.14.tgz", - "integrity": "sha512-aWR+XKH9+rW7m5fWq/5360J3mHycrx/o6xZM2DQFdJnTMdyP7/WzxPjhtLbVWdKo2y612/4U1bWqb3HQhiF7vg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", "cpu": [ "arm" ], @@ -1482,9 +1554,9 @@ } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.14.tgz", - "integrity": "sha512-QiVxHofl6A8lQU7WAtOUY4QMVZXohxwz7WJJoeh8NBEUyKfIkMRKhYyq8az/1RypNiIXzNTtiS6KwHz0erxYRQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", "cpu": [ "arm64" ], @@ -1498,9 +1570,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.14.tgz", - "integrity": "sha512-lTQOzHuBIooh3jIr5XINQkjPGEuGy+Dsy0meXDr6Sjty0b99kYgGh4uBC/8mJX1T0kC8d6S0aPP1Y+bHkh6aBw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", "cpu": [ "arm64" ], @@ -1514,9 +1586,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.14.tgz", - "integrity": "sha512-hyMKEGatjmBYCs/Q4sbIcL/GqpFEqsX3wc+HYVQ/85A4rxc1o7rPm4DUI4GV4k/h0ITddwFSGpqQunI14GXjTA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", "cpu": [ "x64" ], @@ -1530,9 +1602,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.14.tgz", - "integrity": "sha512-u371GbXoVXrEgP20PwzoGNOdAOqAMhzo19JzzY+V4YmmnC+DTOoqdbMu+O+54emM59Mik/UdrtWgcuEDKWRPKA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", "cpu": [ "x64" ], @@ -1546,9 +1618,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.14.tgz", - "integrity": "sha512-BqwKsdZQf6EqVWr8fv2MrDYzAvOZ7+NYFSJESRGs87fkseEhs0TU9TXgRJTkZoRRkxTizyEg1LKUXfU3/78uqg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", "cpu": [ "arm" ], @@ -1562,9 +1634,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.14.tgz", - "integrity": "sha512-SD9kY8M009x/7s57Z1dgUVlP5+uYBgKQK0Tkr1WIWngrtUJmRCW1RJFMY7QDla2khXhmg2i5Io7MUjcmZNZ/KQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", "cpu": [ "arm64" ], @@ -1581,9 +1653,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.14.tgz", - "integrity": "sha512-BJ2CL19M6uuWesMgnqJzgxoI+N+eV7b0A9O9vLV42y+gitC41fNa8KElau1tHVzuLWX5GzEuxMPhAO0tQXQMkg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", "cpu": [ "arm64" ], @@ -1600,9 +1672,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.14.tgz", - "integrity": "sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", "cpu": [ "ppc64" ], @@ -1619,9 +1691,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.14.tgz", - "integrity": "sha512-V/h8ePq1fKDrmtFMz6xcCN3DKvuvMRrwwD1q0PkBeeo4DpK64biaKvqWGVxqCeYKqeRk7gE7/iKPxLCn08O97A==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", "cpu": [ "s390x" ], @@ -1638,9 +1710,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.14.tgz", - "integrity": "sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", "cpu": [ "x64" ], @@ -1657,9 +1729,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.14.tgz", - "integrity": "sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", "cpu": [ "x64" ], @@ -1676,9 +1748,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.14.tgz", - "integrity": "sha512-qyr5XiNGxm2ytx17vvtcJ9nXn6v1gENETi503bJx3OGwZ1tSonj7BosxbMa/xeAfSl5iS9X6KjEWYXLu6v1L7Q==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", "cpu": [ "arm64" ], @@ -1691,10 +1763,59 @@ "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.14.tgz", - "integrity": "sha512-oA4o5o0S2yB199YyYXDzKUv1Z56Rc+mgOjwm7Z/vJ9Z8igiDPYvoOuDyo6g7AK/ZaF09nPhDKVnGBcYHO11GXA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", "cpu": [ "arm64" ], @@ -1708,9 +1829,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.14.tgz", - "integrity": "sha512-9mE94bf2GZUaR/fUSXCMpBoWkctu421Mi0ORpm4zqfbkjKep7RxzPFa5etcGs5h+2KApoWBOA/hAJa/7saGgEQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", "cpu": [ "x64" ], @@ -1730,29 +1851,29 @@ "license": "MIT" }, "node_modules/@shikijs/core": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.5.0.tgz", - "integrity": "sha512-6CIgwq+bt2JZ3OSjb/nBkkwEf/CfpHcbam+Mg5Pllco7HAGRQ2/EFhZrrJtbyNTgKwknfVS+llsXGygiDGwJWw==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.6.0.tgz", + "integrity": "sha512-bfd4OKgvoyXYiYmMRuleA656P4V7M/Du9lcTl38Ngm6KszMj7bq4J1IGZwSYR4c95Tv5UQALtYNWUwaI9UT3xw==", "license": "MIT", "dependencies": { - "@shikijs/primitive": "4.5.0", - "@shikijs/types": "4.5.0", - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/primitive": "4.6.0", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5", - "hast-util-to-html": "^9.0.5" + "hast-util-to-html": "^9.0.6" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/engine-javascript": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.5.0.tgz", - "integrity": "sha512-Ed6UdEj84LyYkwnxM5CvSMWAD+id9ExTYri0/+x41U9zrgNifPSS9lZm0JqBP0VfYI8yr8tY5nbNq9+p9R0kFA==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.6.0.tgz", + "integrity": "sha512-K0oqxFoL+kEMdz89mHLFO15Tsbv3kFZ6WR1cXZKMvLSc+oqaM00A6pyga1qSeXB22dP0tTiSApRcGBaKWsEccg==", "license": "MIT", "dependencies": { - "@shikijs/types": "4.5.0", - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", "oniguruma-to-es": "^4.3.6" }, "engines": { @@ -1760,38 +1881,38 @@ } }, "node_modules/@shikijs/engine-oniguruma": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.5.0.tgz", - "integrity": "sha512-dKVmbJecVdB9recl8a/CU4jdpNXyjJQrIcesIkpS70s5HS02ohpnCSpMUbotPnEUzbAcLQ+S4hwZYbkBBiTcJw==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.6.0.tgz", + "integrity": "sha512-aggd6Q7SuJOXNnsUbfG2XesxBJKBMAw/PDTUo9PyRjMaaJJ2dNrI+q0C+25ARXAK9yLHAlwxc9oRT2u68YKZ7w==", "license": "MIT", "dependencies": { - "@shikijs/types": "4.5.0", - "@shikijs/vscode-textmate": "^10.0.2" + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/langs": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.5.0.tgz", - "integrity": "sha512-wwBTqwduXSz0X4v9Qa2EWeFaYJEw1clCncWjoRNQRbVDu3SPRTRWucnouYapKj3b8Q+sk/41Vbc4B5c8nuYzLA==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.6.0.tgz", + "integrity": "sha512-1yMEX3oCVV54LUq/ovfpRkDQoYDkcvjSWFFa/YLUDMiSoRzMi2uxLJYbv41ahT8Lu9lFMaa7hecd3Q39trqUyg==", "license": "MIT", "dependencies": { - "@shikijs/types": "4.5.0" + "@shikijs/types": "4.6.0" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/primitive": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.5.0.tgz", - "integrity": "sha512-UM7ShlA8oz0OWxLLO8BmO9Ip6fVqdkt8yF0EH7nOCqHfrx1eEAzF0ZUVK7L+I8NEgeu1PEWSRlxaiPPeCb4iDg==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.6.0.tgz", + "integrity": "sha512-c54+TQEo9ToqgfL/AU8FpjnV09+GA9Oa7M5ROkkXteZfp5XzpAJGXjjvZQFQioJOwm/w/6Z3lIzQstAkl8coag==", "license": "MIT", "dependencies": { - "@shikijs/types": "4.5.0", - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" }, "engines": { @@ -1799,24 +1920,24 @@ } }, "node_modules/@shikijs/themes": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.5.0.tgz", - "integrity": "sha512-zGb87H3UBbpuI4yoh5UguB1XbU+2BDU3kflM7UfZ+Cy2hWo9lBtqjSVK20gmLY6ukYl040hAypGXMgud9vul8Q==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.6.0.tgz", + "integrity": "sha512-qHAVAs80RiGD+IRuH9G+JPDOEc9A/kHsng4EzCUCwB9bLzW6Z0y9WETh2YyCcADJBmfrIaJ1Jp7KBNP6FHkgtQ==", "license": "MIT", "dependencies": { - "@shikijs/types": "4.5.0" + "@shikijs/types": "4.6.0" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.5.0.tgz", - "integrity": "sha512-drtPrtD8N0DENyD2cyt6Ajy+IWsiCLgMxODwLTpvH1UsN6a9jf90tNTPjqwHvA+0Lzu9e0txk8DjfqH1p9UJRw==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.6.0.tgz", + "integrity": "sha512-+ENG1adsKt/X7cRYw1Nl7BEpBmPOjmQ7bR/eGmHuMlT8gtOFf3KEi5l31DJYyAWhW6Y6bjP1plU7FmaxWGENFw==", "license": "MIT", "dependencies": { - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" }, "engines": { @@ -1824,9 +1945,9 @@ } }, "node_modules/@shikijs/vscode-textmate": { - "version": "10.0.2", - "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz", - "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==", + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.1.0.tgz", + "integrity": "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ==", "license": "MIT" }, "node_modules/@tybys/wasm-util": { @@ -2037,15 +2158,17 @@ } }, "node_modules/astro": { - "version": "7.4.4", - "resolved": "https://registry.npmjs.org/astro/-/astro-7.4.4.tgz", - "integrity": "sha512-e+BzhGCaIY/H1tV/BQPTbOPZVZ8wuu6+bbpc+3oSMH2UgoB1l9peSGASk6nswtYra9PO9OoMREhldKtQkZ5TVw==", + "version": "7.4.12", + "resolved": "https://registry.npmjs.org/astro/-/astro-7.4.12.tgz", + "integrity": "sha512-DKX+Ds0rqV49HrLwEB9JFrCyfvQeC16FCe1HrPK8S3osiJH/e2vQ22CHIDOpI48UaeiPbxPT26peXgGTy6w0ig==", "license": "MIT", "dependencies": { - "@astrojs/compiler-rs": "^0.5.1", - "@astrojs/internal-helpers": "0.13.0", - "@astrojs/markdown-satteri": "0.4.6", - "@astrojs/telemetry": "3.4.2", + "@astrojs/compiler-rs": "^0.5.2", + "@astrojs/internal-helpers": "^0.13.2", + "@astrojs/markdown-satteri": "^0.4.10", + "@astrojs/runtime": "^0.1.1", + "@astrojs/telemetry": "^3.4.2", + "@astrojs/vite-plugin-astro": "^0.1.3", "@capsizecss/unpack": "^4.0.1", "@clack/prompts": "^1.8.1", "@oslojs/encoding": "^1.1.0", @@ -2053,13 +2176,11 @@ "aria-query": "^5.3.2", "axobject-query": "^4.1.0", "ci-info": "^4.4.0", - "clsx": "^2.1.1", - "common-ancestor-path": "^2.0.0", - "cookie": "^2.0.1", - "devalue": "^6.0.2", + "cookie": "^2.0.2", + "devalue": "^6.0.3", "diff": "^9.0.0", "dset": "^3.1.4", - "es-module-lexer": "^3.0.3", + "es-module-lexer": "^3.0.4", "flattie": "^1.1.1", "fontace": "~0.4.1", "get-tsconfig": "5.0.0-beta.6", @@ -2067,33 +2188,33 @@ "html-escaper": "3.0.3", "http-cache-semantics": "^4.3.0", "jsonc-parser": "^3.3.1", - "magic-string": "^1.4.3", + "magic-string": "^1.4.5", "magicast": "^0.5.5", + "mri": "^1.2.0", "mrmime": "^2.0.1", "neotraverse": "^1.0.1", "obug": "^3.0.0", "p-limit": "^7.3.3", - "p-queue": "^9.3.5", + "p-queue": "^10.0.0", "package-manager-detector": "^1.9.0", "piccolore": "^0.1.3", "picomatch": "^4.0.7", - "rolldown": "^1.2.14", - "shiki": "^4.5.0", + "rolldown": "~1.2.16", + "shiki": "^4.6.0", "smol-toml": "^1.9.1", "svgo": "^4.1.0", "tinyclip": "^1.0.3", "tinyexec": "^1.3.1", "tinyglobby": "^0.2.17", - "tinyps": "^0.5.0", + "tinyps": "^0.5.1", "ultrahtml": "^1.7.0", "unifont": "^1.0.3", - "unstorage": "^1.17.5", + "unstorage": "^1.17.6", "verkit": "^0.5.0", - "vite": "^8.3.5", + "vite": "^8.3.6", "vitefu": "^1.1.3", "xxhash-wasm": "^1.1.0", - "yargs-parser": "^22.0.0", - "zod": "^4.6.6" + "zod": "^4.6.7" }, "bin": { "astro": "bin/astro.mjs" @@ -2132,16 +2253,32 @@ "astro": "^4.0.0-beta || ^5.0.0-beta || ^3.3.0 || ^6.0.0-beta || ^7.0.0" } }, + "node_modules/astro/node_modules/@astrojs/internal-helpers": { + "version": "0.13.2", + "resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.13.2.tgz", + "integrity": "sha512-SWiNS+OMrhwWYzJENTekHUyUCMKB+tdU6D4v1ZNIU1ZHh2mScQ8WIs0J6AJ8KPXkIrs9+EZU7Rm2CstfThyVnw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.5", + "@types/mdast": "^4.0.4", + "picomatch": "^4.0.7", + "retext-smartypants": "^6.2.0", + "shiki": "^4.6.0", + "smol-toml": "^1.9.1", + "unified": "^11.0.5", + "yaml": "^2.9.1" + } + }, "node_modules/astro/node_modules/@astrojs/markdown-satteri": { - "version": "0.4.6", - "resolved": "https://registry.npmjs.org/@astrojs/markdown-satteri/-/markdown-satteri-0.4.6.tgz", - "integrity": "sha512-6biKp2lEAYycF3jhv91br+Otyf4EgDFkF1oRL9ks0u/m/YRGmI7XkGQ2MgaM35DslT03f7NtozKtlqfBNkp6bw==", + "version": "0.4.10", + "resolved": "https://registry.npmjs.org/@astrojs/markdown-satteri/-/markdown-satteri-0.4.10.tgz", + "integrity": "sha512-3h/wheVjZIcP/m295nkiUjOvCsCs6QpvZ3l4BfDU4ghNQcrcFrNVu1+K+I+YT61hH9tuCDQiGdF8QDzfDoG42w==", "license": "MIT", "dependencies": { - "@astrojs/internal-helpers": "0.13.0", - "@astrojs/prism": "4.1.2", + "@astrojs/internal-helpers": "^0.13.2", + "@astrojs/prism": "^4.1.2", "github-slugger": "^2.0.0", - "satteri": "^0.10.5" + "satteri": "^0.11.6" } }, "node_modules/astro/node_modules/@astrojs/prism": { @@ -2156,6 +2293,217 @@ "node": ">=22.23.4" } }, + "node_modules/astro/node_modules/@bruits/satteri-darwin-arm64": { + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/@bruits/satteri-darwin-arm64/-/satteri-darwin-arm64-0.11.7.tgz", + "integrity": "sha512-yllQOX1kVWrwqL7tamQlp4NP0loIb4KuadjuNrAe4JEOerHpgYISPRDb8DqLipgvP7Ks4e87LydZpdakMR1rhQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/astro/node_modules/@bruits/satteri-darwin-x64": { + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/@bruits/satteri-darwin-x64/-/satteri-darwin-x64-0.11.7.tgz", + "integrity": "sha512-RMQrKzEZRZSiYyLFifiSuk0nBH6uAY1TVMNR/h/aE4rr2OS6l82e4MJTpC6H/tqSMoE+3CwbkUKBQGLHIweYlg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/astro/node_modules/@bruits/satteri-linux-arm64-gnu": { + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/@bruits/satteri-linux-arm64-gnu/-/satteri-linux-arm64-gnu-0.11.7.tgz", + "integrity": "sha512-aeH365GHaqv01wRSiHaGUlpL28U8e9UnV9LxjIF6BOyTj71/M5bop4HKomcis4VxFZjd68fDqNyU22yFkF/h7A==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/astro/node_modules/@bruits/satteri-linux-arm64-musl": { + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/@bruits/satteri-linux-arm64-musl/-/satteri-linux-arm64-musl-0.11.7.tgz", + "integrity": "sha512-72WlBhuwOHm+2Nv4Qf1WzfS75PHOLz81sYkDJnmj0Rm2C4Xax5faSiTDt7vWo1IcK6rDlkuRDNnWIw8uIKWuVQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/astro/node_modules/@bruits/satteri-linux-x64-gnu": { + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/@bruits/satteri-linux-x64-gnu/-/satteri-linux-x64-gnu-0.11.7.tgz", + "integrity": "sha512-gDp4v1jjckeNCetLtrMUfDV4CKGYL6fayDPdoaQq09nkDCSrclxEFK7kAmRuHhoalgsao4bZMFqQr3HQtN2NEQ==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/astro/node_modules/@bruits/satteri-linux-x64-musl": { + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/@bruits/satteri-linux-x64-musl/-/satteri-linux-x64-musl-0.11.7.tgz", + "integrity": "sha512-zqzSpQLA6V3J/TO2Vjuc1VRQPIQQdoSYmzKKFL+3GwGlbXiFQP2ZUDSLw9xlm0tTKXkCM9ANr4jMiDASZ+JGUw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/astro/node_modules/@bruits/satteri-wasm32-wasi": { + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/@bruits/satteri-wasm32-wasi/-/satteri-wasm32-wasi-0.11.7.tgz", + "integrity": "sha512-L46f6rtlaBR4fsTWGCTFcXtbtka2GyM3l9TsmE0FgTxjXGq+sndYg5X3hzlhWDkNvJpRtCHCmgTRJ5+cIi4o3A==", + "cpu": [ + "wasm32" + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "1.11.1", + "@emnapi/runtime": "1.11.1", + "@napi-rs/wasm-runtime": "^1.2.7" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/astro/node_modules/@bruits/satteri-win32-arm64-msvc": { + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/@bruits/satteri-win32-arm64-msvc/-/satteri-win32-arm64-msvc-0.11.7.tgz", + "integrity": "sha512-R2+o6EbJK4pqbd086H9BGUVYAyZ5F6FnShfoyRIu0Zu9DTE3H6EU/Z+ua7p9dmYf6JQQbE9DCwwavi4xiaGAhQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/astro/node_modules/@bruits/satteri-win32-x64-msvc": { + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/@bruits/satteri-win32-x64-msvc/-/satteri-win32-x64-msvc-0.11.7.tgz", + "integrity": "sha512-OIyBFJ35uMu5CH5RWnIR3bKsZwScKZ7vXmhCohZ+qonT1SkxmHCEf4H8YRWThRL2EXdVDjkjhfOsaiA4O24Vvw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/astro/node_modules/@emnapi/core": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz", + "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.2", + "tslib": "^2.4.0" + } + }, + "node_modules/astro/node_modules/@emnapi/runtime": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz", + "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/astro/node_modules/@emnapi/wasi-threads": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz", + "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/astro/node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.7.tgz", + "integrity": "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" + } + }, + "node_modules/astro/node_modules/satteri": { + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/satteri/-/satteri-0.11.7.tgz", + "integrity": "sha512-xDOSxkc1ew3z3IovIjmsqJaVHRXTGYJkPvx0LL/U6o90km8kSU+pmrZVvnWd5creJeE0UnvMEienlkPuYQdJaA==", + "license": "MIT", + "dependencies": { + "@types/estree-jsx": "^1.0.5", + "@types/hast": "^3.0.5", + "@types/mdast": "^4.0.4", + "@types/unist": "^3.0.3" + }, + "optionalDependencies": { + "@bruits/satteri-android-arm64": "0.11.7", + "@bruits/satteri-darwin-arm64": "0.11.7", + "@bruits/satteri-darwin-x64": "0.11.7", + "@bruits/satteri-freebsd-x64": "0.11.7", + "@bruits/satteri-linux-arm64-gnu": "0.11.7", + "@bruits/satteri-linux-arm64-musl": "0.11.7", + "@bruits/satteri-linux-x64-gnu": "0.11.7", + "@bruits/satteri-linux-x64-musl": "0.11.7", + "@bruits/satteri-wasm32-wasi": "0.11.7", + "@bruits/satteri-win32-arm64-msvc": "0.11.7", + "@bruits/satteri-win32-x64-msvc": "0.11.7" + } + }, "node_modules/axobject-query": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", @@ -2334,9 +2682,9 @@ } }, "node_modules/cookie": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.1.tgz", - "integrity": "sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.2.tgz", + "integrity": "sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw==", "license": "MIT", "engines": { "node": ">=22" @@ -2805,12 +3153,6 @@ "@types/estree": "^1.0.0" } }, - "node_modules/eventemitter3": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", - "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", - "license": "MIT" - }, "node_modules/expressive-code": { "version": "0.44.2", "resolved": "https://registry.npmjs.org/expressive-code/-/expressive-code-0.44.2.tgz", @@ -3244,9 +3586,9 @@ } }, "node_modules/hast-util-to-html": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz", - "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==", + "version": "9.0.6", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.6.tgz", + "integrity": "sha512-1SZUxCN3TtJAE7e2BQN2MBHsoZ1gnmi9GoCP5Di59CSWptIezSAW09yDZyVbanb78V9eCwrKqdQsjtfVTxYHWA==", "license": "MIT", "dependencies": { "@types/hast": "^3.0.0", @@ -3835,9 +4177,9 @@ } }, "node_modules/magic-string": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", - "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==", + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", "license": "MIT", "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" @@ -4965,6 +5307,15 @@ ], "license": "MIT" }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/mrmime": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz", @@ -5110,28 +5461,12 @@ } }, "node_modules/p-queue": { - "version": "9.3.5", - "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-9.3.5.tgz", - "integrity": "sha512-Lki/zhXFVmDhesBUn/yHRLW9Bte7mE7xoFHzTR8sIomV7a2z+LxYAPkGvdfidNiu4fKSfjtawixxSHcZci5QcQ==", + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-10.0.0.tgz", + "integrity": "sha512-P2wrCri3bhGLPo3kX7qYVXbo/5GvaVATU0DpO24CbeT53Y4z35t8JUWku04ERpXHUYB5rPMi3TkWE3fmJgx5rA==", "license": "MIT", - "dependencies": { - "eventemitter3": "^5.0.4", - "p-timeout": "^7.0.0" - }, "engines": { - "node": ">=20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-timeout": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-7.0.2.tgz", - "integrity": "sha512-prbX4Z3YszrFNgH+MW5Zoeq3baXrMtP/MQnFeET90UB/GtGcGDQ5Usg9OCy6ETjTTntOw1SL2z9fMPUppN3Guw==", - "license": "MIT", - "engines": { - "node": ">=20" + "node": ">=22" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -5241,9 +5576,9 @@ } }, "node_modules/postcss": { - "version": "8.5.31", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.31.tgz", - "integrity": "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==", + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", "funding": [ { "type": "opencollective", @@ -5680,12 +6015,12 @@ } }, "node_modules/rolldown": { - "version": "1.2.14", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.14.tgz", - "integrity": "sha512-eTBTTqMR6uHKLgcUqpJP8ntzDI6V4LYA8negAMBEI7gkgVvOdrx6VsvS2Ym+83KhOPdLCHWJu0w7UQFJZhHKNw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.154.0", + "@oxc-project/types": "=0.156.0", "@rolldown/pluginutils": "^1.0.0" }, "bin": { @@ -5695,21 +6030,22 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm-eabi": "1.2.14", - "@rolldown/binding-android-arm64": "1.2.14", - "@rolldown/binding-darwin-arm64": "1.2.14", - "@rolldown/binding-darwin-x64": "1.2.14", - "@rolldown/binding-freebsd-x64": "1.2.14", - "@rolldown/binding-linux-arm-gnueabihf": "1.2.14", - "@rolldown/binding-linux-arm64-gnu": "1.2.14", - "@rolldown/binding-linux-arm64-musl": "1.2.14", - "@rolldown/binding-linux-ppc64-gnu": "1.2.14", - "@rolldown/binding-linux-s390x-gnu": "1.2.14", - "@rolldown/binding-linux-x64-gnu": "1.2.14", - "@rolldown/binding-linux-x64-musl": "1.2.14", - "@rolldown/binding-openharmony-arm64": "1.2.14", - "@rolldown/binding-win32-arm64-msvc": "1.2.14", - "@rolldown/binding-win32-x64-msvc": "1.2.14" + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" } }, "node_modules/satteri": { @@ -5808,18 +6144,18 @@ } }, "node_modules/shiki": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.5.0.tgz", - "integrity": "sha512-OcRW72ngQvc+MSVWBRIovC/BTW589iUE/Vxav7VeM4RcY9MUjqB+IR6ILG1k9nuW6LiG/nct9uma4/MBtnZbmQ==", - "license": "MIT", - "dependencies": { - "@shikijs/core": "4.5.0", - "@shikijs/engine-javascript": "4.5.0", - "@shikijs/engine-oniguruma": "4.5.0", - "@shikijs/langs": "4.5.0", - "@shikijs/themes": "4.5.0", - "@shikijs/types": "4.5.0", - "@shikijs/vscode-textmate": "^10.0.2", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.6.0.tgz", + "integrity": "sha512-imjLsVHgPuWhvpU3P+zOekvMYqnel7QmKsFC4Sn0fCuAvaaalBsxwKEsrU8Ko5BdFnZA6Go/8a0RzahS634UgA==", + "license": "MIT", + "dependencies": { + "@shikijs/core": "4.6.0", + "@shikijs/engine-javascript": "4.6.0", + "@shikijs/engine-oniguruma": "4.6.0", + "@shikijs/langs": "4.6.0", + "@shikijs/themes": "4.6.0", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" }, "engines": { @@ -5995,9 +6331,9 @@ } }, "node_modules/tinyps": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/tinyps/-/tinyps-0.5.0.tgz", - "integrity": "sha512-Llu7nEtVOGHh7jok32l6+udlu+4Np5vsYVB7zeTK614coSsro2qjwte7MFt/ouLM/h4kXqbGXktSMMvMsttSDw==", + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/tinyps/-/tinyps-0.5.2.tgz", + "integrity": "sha512-sYhvdbpuo2rGE7u/jPUMiZz4H2LCaOodUtRD9ot4DLNFQbr884g9zozoJnxLI+1r4hXqWkmdHUl8Yig2Rllxxw==", "license": "MIT" }, "node_modules/trim-lines": { @@ -6396,15 +6732,15 @@ } }, "node_modules/vite": { - "version": "8.3.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", - "integrity": "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==", + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", "license": "MIT", "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", - "postcss": "^8.5.30", - "rolldown": "~1.2.14", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", "tinyglobby": "^0.2.17" }, "bin": { @@ -6522,15 +6858,6 @@ "url": "https://github.com/sponsors/eemeli" } }, - "node_modules/yargs-parser": { - "version": "22.0.0", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", - "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==", - "license": "ISC", - "engines": { - "node": "^20.19.0 || ^22.12.0 || >=23" - } - }, "node_modules/yocto-queue": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.2.tgz", diff --git a/vendor/egui-charts/docs/site/package.json b/vendor/egui-charts/docs/site/package.json index f36f57e..39af6c5 100644 --- a/vendor/egui-charts/docs/site/package.json +++ b/vendor/egui-charts/docs/site/package.json @@ -9,7 +9,7 @@ "dependencies": { "@astrojs/markdown-remark": "7.3.5", "@astrojs/starlight": "0.42.8", - "astro": "7.4.4", + "astro": "7.4.12", "parse5": "8.1.0" } } diff --git a/vendor/egui-charts/docs/site/src/content/docs/accessibility.mdx b/vendor/egui-charts/docs/site/src/content/docs/accessibility.mdx index 46d0cdc..bef0d3e 100644 --- a/vendor/egui-charts/docs/site/src/content/docs/accessibility.mdx +++ b/vendor/egui-charts/docs/site/src/content/docs/accessibility.mdx @@ -24,8 +24,8 @@ should supply equivalent HTML controls. | Default key | Chart action | | --- | --- | -| Left / Right | Pan by `pan_amount` bars. | -| Ctrl+Left / Ctrl+Right (Command on macOS) | Pan by a page. | +| Left / Right | Scroll back / forward in time by `pan_amount` bars: Left shows earlier bars, Right later ones. | +| Ctrl+Left / Ctrl+Right (Command on macOS) | Scroll back / forward in time by a page. | | + or = / -; Ctrl+Up / Ctrl+Down (Command on macOS) | Zoom in / out using `zoom_step`. | | Alt+R | Reset the chart view. | | Escape | Cancel an active interaction or selection. | diff --git a/vendor/egui-charts/docs/site/src/content/docs/chart-types.mdx b/vendor/egui-charts/docs/site/src/content/docs/chart-types.mdx index 7d03539..cf9436e 100644 --- a/vendor/egui-charts/docs/site/src/content/docs/chart-types.mdx +++ b/vendor/egui-charts/docs/site/src/content/docs/chart-types.mdx @@ -46,7 +46,7 @@ variants. “Added” describes `SeriesOptions::chart_type` on a normal time-bas | `Kagi` | Close or high/low history, reversal size and size method | Converted to `Line` | | `LineBreak` | Close or high/low history and reversal lookback | Converted to `Line` | | `PointAndFigure` | High/low by default, or close; box size, size method and reversal count | Converted to `Line` | -| `Range` | Executions when retained; otherwise an OHLC path approximation; range size | Converted to `Line` | +| `Range` | Retained executions, after an OHLC path approximation of the bars before the one holding the first; that approximation alone without executions; range size | Converted to `Line` | | `TimePriceOpportunity` | Timestamped OHLC ranges, session rules and TPO row/period settings; counts time at price | Converted to `Line` | | `VolumeFootprint` | Executions with aggressor side and instrument tick size, plus bars | Candles only | | `SessionVolumeProfile` | Same execution inputs as footprint, session rules and the `studies` feature | Candles only | @@ -85,8 +85,9 @@ Footprint and Session Volume Profile are accepted as options but the added-serie renderer draws their bars as candles; it does not build a second execution view. Added series share the main time axis, including its whitespace slots. Supply -the main history, or explicit whitespace, to cover their timestamps. On a -time-independent main chart, added series are retained but hidden; their bar -timestamps cannot share the brick or column axis. [Transforms](/egui-charts/docs/chart-types/transforms/) -explains the other overlays hidden on that axis. Use the [series lifecycle](series.mdx#lifecycle) +the main history, or explicit whitespace, to cover their timestamps. On Renko, +Kagi, Line Break, Point and Figure and Range charts the axis holds one slot per +element, and each bar of an added series is placed by its time on that axis, so +the series is drawn. [Transforms](/egui-charts/docs/chart-types/transforms/) +describes that placement and the other overlays on those types. Use the [series lifecycle](series.mdx#lifecycle) to retain and update each series by id, and [scales](scales.mdx) to choose its price scale. diff --git a/vendor/egui-charts/docs/site/src/content/docs/chart-types/transforms.mdx b/vendor/egui-charts/docs/site/src/content/docs/chart-types/transforms.mdx index 49ce641..6f4dbb4 100644 --- a/vendor/egui-charts/docs/site/src/content/docs/chart-types/transforms.mdx +++ b/vendor/egui-charts/docs/site/src/content/docs/chart-types/transforms.mdx @@ -67,12 +67,14 @@ These main renderers share the parameter workflow above: | --- | --- | --- | | `Kagi` | Close by default, or `kagi_source` high/low; `kagi_reversal` in price units and `kagi_size_method` | Chart up/down colours and `styles.kagi` thick/thin widths; [`KagiConfig`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/model/kagi/struct.KagiConfig.html) | | `LineBreak` | Close by default, or `line_break_source` high/low; `line_break_count` reversal lookback, 1 to 10 | Chart up/down colours; [`LineBreakConfig`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/model/line_break/struct.LineBreakConfig.html) | -| `Range` | Retained executions in order, or an OHLC path approximation when no trades are held; `range_size` and `range_size_method` | Chart up/down colours; [`RangeBarSource`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/model/range_bar/enum.RangeBarSource.html), [`RangeBarConfig`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/model/range_bar/struct.RangeBarConfig.html) | +| `Range` | Retained executions in order, after the OHLC path approximation of the bars before the one holding the first retained trade, or that approximation alone when no trades are held; `range_size` and `range_size_method` | Chart up/down colours; [`RangeBarSource`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/model/range_bar/enum.RangeBarSource.html), [`RangeBarConfig`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/model/range_bar/struct.RangeBarConfig.html) | [`ChartTypeParams`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/model/struct.ChartTypeParams.html) holds all these fields. For high/low input, intrabar order is unknown: continuation takes priority over reversal and at most one direction is processed per source bar. OHLC range bars are an approximation; original executions give their actual path. +When trades start after OHLC history, the approximated range bars stay in front of the +bars built from the trades, and the range in progress at the first trade gives way to them. See the [order-flow guide](../../../../../order-flow.md) for supplying executions. ## Sizes, styles and axis restrictions @@ -94,8 +96,15 @@ are specific to `Candles`; they are not universal transform settings. Renko, Kagi, Line Break, Point and Figure, and Range have one time-scale slot per displayed element. Chart indices on those types count elements, not source bars. -Studies, drawings, markers and added price series remain stored but are hidden; -studies continue updating. Volume is also hidden. Returning to a time-based type -shows these overlays again. These five types cannot be added series: +Studies, drawings and markers are drawn at the element that contains their time: +an element covers the interval up to its completion, and a Point and Figure column +also covers the quiet bars up to the next column. A time before the loaded +elements or outside the source history has no slot, so nothing is drawn for it. +Studies are calculated from the element values and keep updating. Added price +series are drawn too: each bar is placed by its time on the element axis, at the +slot of an element with the same completion time, between two slots in proportion +to the time between those completions, and past either end at that end's spacing. +Volume is hidden on these types. Returning to a time-based type restores the +time axis of the source bars. These five types cannot be added series: [`SeriesOptions::chart_type`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.SeriesOptions.html#structfield.chart_type) converts them to `Line`. See [all added-series restrictions](../chart-types.mdx#added-series-restrictions). diff --git a/vendor/egui-charts/docs/site/src/content/docs/migration.mdx b/vendor/egui-charts/docs/site/src/content/docs/migration.mdx index 9e280b9..592e496 100644 --- a/vendor/egui-charts/docs/site/src/content/docs/migration.mdx +++ b/vendor/egui-charts/docs/site/src/content/docs/migration.mdx @@ -204,7 +204,7 @@ existed in 0.2.0: | --- | --- | | `chart::builder::ChartBuilder` | `ChartBuilder` or `widget::ChartBuilder` | | `chart::selection::{SeriesId, ChartElementId}` | `widget::{SeriesId, ChartElementId}` | -| `model::{ChartState, ZoomState}` | `studies::{ChartState, ZoomState}` | +| `model::{ChartState, ZoomState}` | `studies::ChartState`; `ZoomState` is removed | | `ext::UiExt` | `ui_kit::ext::UiExt` (feature `ui`) | | `ui::top_toolbar::Timeframe` | `model::Timeframe` | diff --git a/vendor/egui-charts/docs/site/src/content/docs/own-data.mdx b/vendor/egui-charts/docs/site/src/content/docs/own-data.mdx new file mode 100644 index 0000000..32e2d50 --- /dev/null +++ b/vendor/egui-charts/docs/site/src/content/docs/own-data.mdx @@ -0,0 +1,440 @@ +--- +title: Your own data in the demo +--- + +The [demo](https://userfrm.github.io/egui-charts/demo/) can chart your own market data +without a line of code. You describe a REST history endpoint and a WebSocket stream in a +dialog, map their JSON fields to bars and trades by clicking them, and the chart then runs +on that data. This is meant for evaluating the library on the data you know. + +The demo builds a [`Datafeed`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/data/trait.Datafeed.html) +of its own from the description. That mapped feed is part of the demo, not of the library's +API: its source is in +[`examples/demo/owndata`](https://github.com/userFRM/egui-charts/tree/main/examples/demo/owndata). +To connect a source in your own application, write a feed as +[historical and streaming data](data.mdx) describes. + +Not covered: quotes, depth, orders, signed requests and the symbol search of a service. + +## Open the dialog + +On the first visit the demo asks whether to *Use synthetic data* or to +*Connect my own data*. The answer is remembered and the question is not asked again. +*Data source* in the top-left menu opens the dialog at any time. + +The dialog has three steps, *Source*, *History* and *Live*. *Save* stores the profile +without connecting, *Connect* stores it and shows it on the chart, and *Cancel* closes the +dialog and keeps what you typed. While your own data is on the chart, *Use synthetic data* +in the *Source* step brings the synthetic session back as you left it. + +## Ready profiles + +Ready profiles are listed first under *Profile*. They chart public market data that needs no +account or key, so they connect with nothing typed. + +### Binance spot (public) + +The spot market data Binance publishes for everyone: + +- **Symbols.** BTCUSDT, ETHUSDT, SOLUSDT and BNBUSDT, with a price step of 0.01. +- **Intervals.** 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 1w and 1M: every interval + Binance serves from one minute to one month except 3d, whose bars do not open where the + chart's three-day slots do. The interval menu lists 6h, 8h and 12h once *Custom interval…* + adds them. +- **History.** `https://data-api.binance.vision/api/v3/klines`, up to 1000 bars a request, back + to the first bar Binance holds for the symbol. +- **Live data.** One connection to `wss://data-stream.binance.vision` carries the symbol's kline + stream for the chart's interval and its aggregate trade stream. The kline stream sets the bar + in progress about every two seconds. Each aggregate trade continues the bar and reaches time + and sales, the footprint and the order-flow studies with its side: Binance's `m` is `true` + when the buyer was the maker, a sell, and `false` for a buy. + +A ready profile is read-only. *Connect* uses it as the demo ships it and stores no copy, so a +later version of the demo updates it. To start a profile of your own from it, give it another +name and *Save*. Where Binance refuses your region, the dialog and the chart show its answer as +for any endpoint, such as `HTTP 451`. + +## Describe the source + +A profile is the description of one source. The *Source* step holds what it is and what it +offers: + +- **Name.** How the profile is listed. Saved profiles have different names. +- **Symbols.** Spelled as the service expects them. The symbol search offers these and no + others, and the chart opens on the first. +- **Intervals.** A table of chart intervals and, for each, the text the service expects, + such as `1m`, `60` or `60000`. The text is sent as typed. Only intervals with a duration + can be listed, and the chart opens on the first row. +- **Time zone.** The zone of every time that names none and of bounds printed as dates. + It is UTC unless you change it. +- **Price step.** The smallest price change of the symbols, such as `0.01`. The footprint + and the volume profiles group trades by it. Without it the volume footprint and session + volume profile charts draw candles, and the volume profile studies keep their estimate + from bars. One step serves every symbol of the profile. +- **Keys.** A name and a value. Write the name in braces, such as `{key}`, where the value + belongs in an address, a header, a body or a message. Values are sent only to the + endpoints of the profile. *Keep keys in this browser*, *Keep keys on this device* in the + native demo, is off unless you tick it. A kept key is plain text in the browser's storage + for the site or, in the native demo, in its settings file `app.ron`: in + `~/.local/share/egui-chartsdemo` on Linux (under `$XDG_DATA_HOME` when that is set), + `~/Library/Application Support/egui-charts-demo` on macOS and + `%APPDATA%\egui-charts demo\data` on Windows. + +A key typed straight into an address, a header or a message, instead of as a name in +braces, is part of the profile. It is saved and exported with it. + +## History over REST + +### The request + +The address is a template. The demo fills these placeholders: + +| Placeholder | Filled with | +| --- | --- | +| `{symbol}` | The symbol on the chart | +| `{symbol_lower}` | The symbol on the chart in lower case, such as `btcusdt` for `BTCUSDT` | +| `{interval}` | The text of the interval table for the chart's interval | +| `{from}` | The start of the range asked for | +| `{to}` | The end of the range asked for | +| `{limit}` | The number of bars asked for, at most the page size | +| `{name}` | The value of the key of that name | + +Values are percent-encoded in the address and sent as typed in headers and in the body. +Headers are rows of a name and a value. An empty body sends `GET`. An address, and a +header that carries a key: + +```text +https://api.example.com/v1/bars?symbol={symbol}&interval={interval}&to={to}&limit={limit} +Authorization: Bearer {key} +``` + +Any other body is sent with `POST`, as `application/json` unless a header names another +content type. The braces of JSON need no escaping: + +```text +{"symbol": "{symbol}", "resolution": "{interval}", "end": {to}, "count": {limit}} +``` + +### Bounds and paging + +`{from}` and `{to}` are printed in one of seven forms: + +| Form | Example | +| --- | --- | +| Unix seconds | `1794407400` | +| Unix milliseconds | `1794407400000` | +| Unix microseconds | `1794407400000000` | +| Unix nanoseconds | `1794407400000000000` | +| ISO 8601 | `2026-11-11T14:30:00Z` | +| Date | `2026-11-11` | +| Date | `20261111` | + +`{to}` is the first instant that is not asked for. In the two date forms it is the last day +asked for, in the profile's time zone. + +The page size is the most bars asked for in one request. Scrolling to the left pages back +in time: + +- With `{to}` alone, the demo asks for the bars before the oldest one it holds until the + service answers an empty page. +- With `{from}` as well, it asks in windows of page size times interval. An empty window, + such as a weekend, is crossed. 64 empty windows in a row, or a year without a bar, end + history. +- Without either, the chart shows the newest bars only. + +With dates as bounds on an interval shorter than a day, set the page size to at least the +bars of one day, or use one of the other forms. Otherwise a day with more bars than the +page size can leave a hole. For sparse data a larger page size widens the windows. + +### Response shapes + +A response is read as one of four layouts. Rows may sit at the root or under a path such as +`data.candles`. In a profile file, a key of that path can be `{symbol}` or `{symbol_lower}`, +for a service that files the rows under the symbol, such as `["result", "{symbol}"]`. + +A list of objects, with fields named by their keys: + +```json +[{"t": 1794407400, "o": 100.75, "h": 103.0, "l": 100.5, "c": 102.5, "v": 1500}] +``` + +A list of arrays, with fields named by their column number: + +```json +[[1794407400, 100.75, 103.0, 100.5, 102.5, 1500]] +``` + +A list of arrays whose columns a header array elsewhere in the response names: + +```json +{"columns": ["time", "open", "high", "low", "close", "volume"], + "rows": [[1794407400, 100.75, 103.0, 100.5, 102.5, 1500]]} +``` + +Columns as parallel arrays: + +```json +{"t": [1794407400], "o": [100.75], "h": [103.0], "l": [100.5], "c": [102.5], "v": [1500]} +``` + +A page without rows is one whose list is absent, `null` or empty. + +### Fields + +A bar has a time, an open, a high, a low, a close and a volume. The volume may be left +unmapped. Numbers may arrive as text. + +- A row without a readable time is skipped. +- A row whose four prices are all missing is an empty slot. +- A row with some prices missing, or with a high below its close, is dropped by the chart + and counted in the status line of the dialog. +- Rows may come in any order. Of two rows for one slot the later one wins. + +### Test and map + +*Test* fetches the newest page and shows the response as a tree. The demo proposes the +place of the rows, their layout and the fields it recognises by name. To change the +mapping, click a slot, such as `rows`, `time` or `volume`, and then the field in the tree: +the place of the rows under *Response*, a field under *First row*. + +The preview shows the first five bars and the last one, their count and the rows skipped. +Beside the `time` slot the dialog prints the time of the first row as it is read, in the +profile's zone and in UTC. A wrong unit shows there before anything is charted. + +## Times + +| Reading | Value | +| --- | --- | +| Unix seconds, milliseconds, microseconds or nanoseconds | A number or numeric text | +| ISO 8601 text with `Z` or an offset | An instant | +| ISO 8601 text without an offset | A wall time in the profile's zone | +| ISO 8601 text that is a bare date | A bar dated on that day | +| A date, `20261111` or `2026-11-11` | A bar dated on that day | +| A date and a time of day | A wall time in the profile's zone | + +The time of day is milliseconds since midnight, seconds since midnight or text such as +`09:30:00`. A click on the field picks the reading its value has: text that is a time of +day, else seconds below 86,400, else milliseconds. The choice beside the field changes it. +It is a reading of the wall clock: 09:30 is the same value on every day of the +year. When clocks go back, a wall time that occurs twice is its first occurrence. When +clocks go forward, a wall time that does not occur is the moment of the change. + +Bars of a day, a week or a month are dated, not timed. The date is the row's date field, +or the day of its instant in the profile's zone. Set the zone to the exchange's when the +service stamps such bars at local midnight, and leave it at UTC when it stamps them at +00:00 UTC. [Time zones and sessions](time-zones.mdx) explains how the chart displays them. + +- With the chart's display zone west of UTC-10:00 or at UTC+14:00, such bars are dated one + day off. +- A change of the display zone loads the bars again and dates them in the new zone. +- A time far ahead of the clock is dropped, which is what a wrong unit looks like. + +## Live data over WebSocket + +### The connection + +The address starts with `ws://` or `wss://` and takes `{symbol}`, `{symbol_lower}`, `{interval}` +and the names of the keys. Offer a subprotocol only when the service answers with it: a connection +that offers subprotocols ends when the server selects none. + +Connect messages are sent in their order every time the socket opens: the login first, then +the subscribe message. + +```json +{"action": "auth", "key": "{key}"} +``` + +```json +{"action": "subscribe", "symbol": "{symbol}", "interval": "{interval}"} +``` + +A keep-alive message is sent at its period for as long as the socket is open. + +A browser sends no headers when it opens a WebSocket, and the native demo sends none +either, so a key travels in one of three places: the address, a subprotocol or a connect +message. + +- The subscribe message is sent right after the login, without waiting for its answer. +- A hidden browser tab slows timers, so a keep-alive period under a minute is not kept + there. +- Every chart, study data stream and alert that subscribes opens a connection of its own. + A service that allows one connection per key refuses the second. + +### Test and the log + +*Test* connects and lists each message with the route it takes. *Stop* ends the Test. The +first message without a route stays in view above the log until every record of it has +one. While your own data is on the chart, *Test* opens a second connection beside the +chart's. + +### Records and routes + +A message holds one record or several. The `records` slot is their place in the message: +a list there is one record per element, an object is one record, and a message without +that place is itself the record. + +The `route by` slot is the field that tells the kinds of message apart. It is looked up in +the record and then in the message. Each route has a value of that field and is one of +*Ignore*, *Bars* or *Trades*. A message that is not JSON, such as a plain `pong`, is routed +by its own text. For a stream with one kind of message, *Route every message here* makes a +route that takes every record. + +Binary messages that are not text, as a stream that compresses its messages itself sends, +cannot be mapped. + +### Bars + +A bar route maps a time and the five values. A bar takes the place of the bar with the +same open time. The bars must be those of the chart's interval, so the subscribe message +carries `{interval}`, and a stream of one fixed interval serves charts of that interval +only. A stream can carry bars and trades for the same chart, as the ready Binance profile +does: each bar of the bars route becomes the bar the trades after it continue, and a trade +the service had counted in that bar before sending it is counted again until its next bar. + +### Trades and conditions + +A trades route maps a time, a price, a size and, optionally, a condition, which may be one +value or a list, and a side. Trades are folded into bars of the chart's interval. Each +condition value has one of three rules: + +| Rule | Effect on the bar | Effect on the trades | +| --- | --- | --- | +| *Price and volume* | The price moves high, low and close, and the size is added to the volume | Listed and counted | +| *Volume only* | The size is added to the volume | Listed and counted at its price | +| *Ignore* | None | Left out | + +With several conditions the strictest rule applies. The list fills from the log, and a +value that is not listed counts price and volume. A *Volume only* trade that opens a slot +shows as a flat bar at the last close. + +Trades reach the chart as trades too, so time and sales, the footprint, the volume bubbles +and the order-flow studies follow them. The side field names the trade's aggressor: type +the value that marks a buy and the value that marks a sell beside it, compared as text, so +`true` and `false` work as well as `B` and `S`. A trade without the field, or with another +value, has an unknown side, and the footprint and the delta studies count it for neither +side. + +- A trade for a slot older than the bar being built is dropped, and a trade the service + sends twice is counted twice. +- A trade between the history page and the first trade of the stream is in neither until + the symbol is loaded again. With a bars route beside it, the stream's next bar counts it + in the bar, though not in time and sales or the footprint. +- A trade older than the trade before it is in its bar and in time and sales, but not in + the footprint or the studies. +- The bars a reconnect or a resume loads from REST hold no trades: the footprint and the + studies show that span as if nothing traded. + +## Reconnecting, pausing and changing symbol + +After a drop the demo waits one second, then twice as long each time up to a minute, sends +the connect messages again and loads the bars it missed from REST. *Pause data feed* in +the menu closes the socket, and resuming loads what the pause missed. A change of symbol +or interval asks history again and moves the subscription. + +- A gap longer than one page is filled for its newest page only, and a profile without + REST history fills nothing. +- A connection that dies without a close is noticed late. A keep-alive message shortens + that. + +## Profiles + +A profile is saved by *Save* and by *Connect*, where the keys are kept (see *Keys* above). +*Export* shows the whole file before it saves it; the file holds no key value. In another +browser or on another device, *Import* the file, enter the keys and *Connect*. An imported +profile never replaces a saved one, and a file written by a newer version of the demo is +refused. + +## What the browser requires + +### Requests to another origin + +A browser lets a page read a response from another origin only when the server allows it. +For a `GET` without headers of your own, the response must carry +`Access-Control-Allow-Origin`. For a request with a header such as `Authorization`, or a +`POST` with a JSON body, the browser first sends an `OPTIONS` request. Its answer must +carry `Access-Control-Allow-Origin`, `Access-Control-Allow-Methods` and +`Access-Control-Allow-Headers` with every header name used, `Content-Type` included. + +The demo sends no cookies, so `*` is accepted as the origin. A refusal shows in the dialog +as `no response (..)`: a browser does not tell the page why. + +### Allow the demo's origin on a local server + +The origin is `https://userfrm.github.io`, or the address a locally served build runs at. +The answer to `OPTIONS`: + +```http +HTTP/1.1 204 No Content +Access-Control-Allow-Origin: https://userfrm.github.io +Access-Control-Allow-Methods: GET, POST, OPTIONS +Access-Control-Allow-Headers: Authorization, Content-Type +``` + +The answer with the data: + +```http +HTTP/1.1 200 OK +Access-Control-Allow-Origin: https://userfrm.github.io +Content-Type: application/json +``` + +A server that cannot be changed is used from the native demo, which has no such rule: + +```text +cargo run --manifest-path examples/demo/Cargo.toml +``` + +### Secure pages + +The demo is served over HTTPS, so a remote endpoint must be `https://` or `wss://`. +`localhost` and `127.0.0.1` may be plain. A browser may ask for permission before a public +page reaches a local address. + +### WebSocket + +No headers can be sent. The server sees the page's origin in `Origin` and may refuse it. A +connection that fails gives the page no cause, so the dialog names what to check. The +browser's own console shows the address of a failed connection, with a key that travels in +it. + +## While own data is on + +The demo shows one chart, in the profile's zone. + +- **Keeps working:** chart types, studies, drawings, the data table, the exports, go to + date, the settings and the paper order ticket. +- **Off, and says so:** alerts, compare, layouts, replay, the samples, the strategy tester + and watchlists. The market panels show an empty state, except time and sales, which lists + the trades of a trades route. The liquidity heatmap, the price unit and the market + recording are unavailable. + +Studies and drawings made on own data are not saved, and connecting a changed profile +starts a new chart. The paper account is the same on both data sources and is priced at +the chart's last close. Extended hours, dividend adjustment and currency conversion are +not sent: the bars are shown as the service returns them. The price-based chart types take +their sizes from the first page of history, so a profile without REST history keeps the +default sizes. + +## Errors + +Every error is the endpoint, without its query and with each key value written as its name +in braces, then the reason. + +| Reason | Meaning | Check | +| --- | --- | --- | +| `no response (..)` | No response arrived. In a browser the sentence adds that the server is unreachable or does not allow this page's origin or these request headers. | The address, and the cross-origin answers above | +| `rejected as unauthorised (HTTP 401): check the key and where it is sent` | The service refused the key. The same for 403. | The key and its place | +| `HTTP 500` | Any other status outside 200 to 299 | The service | +| `unreadable response: ..` | The body is not JSON, the rows are not where the mapping says, or no row has a readable time | The mapping, in the tree of the response | +| `not a usable WebSocket address (..)` | The address does not parse, or the browser refuses to open it | The address, and `wss://` on a secure page | +| `cannot connect (..)` | No address resolves or connects | The address | +| `handshake failed (..)` | TLS or the handshake failed | The address and the subprotocols | +| `handshake refused (HTTP ..)` | The service answered the handshake with a status | The address and the key | +| `no answer to the handshake within 10 seconds` | The service accepted the connection and stayed silent | The service | +| `could not connect. The browser gives no cause: ..` | A browser's connection failed before it opened | The address, that the server accepts this page, and the key | +| `closed by the server (code ..)` | The service ended the connection | The connect messages and the key | +| `connection lost` | The connection ended without a close | The network | + +While your own data is on the chart, the dialog shows a status line: the profile, then +`live`, `connecting`, `disconnected, reconnecting` or `no live stream`, and the count of +bars dropped as invalid. diff --git a/vendor/egui-charts/docs/site/src/content/docs/panes.mdx b/vendor/egui-charts/docs/site/src/content/docs/panes.mdx index 7bfbc84..e165e0c 100644 --- a/vendor/egui-charts/docs/site/src/content/docs/panes.mdx +++ b/vendor/egui-charts/docs/site/src/content/docs/panes.mdx @@ -32,10 +32,18 @@ returned by [`add_series`](https://userfrm.github.io/egui-charts/docs/api/egui_c then create a destination with [`add_pane`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.Chart.html#method.add_pane). [`move_series_to_pane`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.Chart.html#method.move_series_to_pane) -accepts an added series or study and its destination -[`PaneId`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.PaneId.html). -It returns `false` for the main series, unknown IDs or a custom study that -rejects the placement. Use `PaneId::MAIN` to move an added series back while the original pane exists. +moves the main series, an added series or a study to another pane. Pass the main +series' [`SeriesId::MAIN`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/chart/series/selection/struct.SeriesId.html) +and the destination [`PaneId`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.PaneId.html); +`PaneId::MAIN` brings a series back to the price pane while it exists. Each series keeps its price scale +and the shared time mapping. It returns `false` for an unknown series or pane and for a +study whose custom presentation rejects the placement. + +```rust +let pane = chart.add_pane(); +chart.move_series_to_pane(SeriesId::MAIN, pane); // true: the candles move to the new pane +chart.move_series_to_pane(SeriesId::MAIN, PaneId::MAIN); // true: they return +``` In every pane, the added series follows [`SeriesOptions::scale`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.SeriesOptions.html#structfield.scale). diff --git a/vendor/egui-charts/docs/site/src/content/docs/price-scale.mdx b/vendor/egui-charts/docs/site/src/content/docs/price-scale.mdx index bcc6d28..84c91b7 100644 --- a/vendor/egui-charts/docs/site/src/content/docs/price-scale.mdx +++ b/vendor/egui-charts/docs/site/src/content/docs/price-scale.mdx @@ -58,9 +58,12 @@ For example, a move from 100 to 110 reads +10% or 110 indexed. Prices 100, 200 and 400 have equal vertical spacing on a logarithmic scale because each step doubles the price. **Logarithmic rendering requires strictly positive prices**; zero and negative prices have no finite log coordinate. Choose Normal for data -that can cross zero. A missing, non-finite or zero relative reference falls back -to ordinary prices. Each series keeps its own first-visible-close reference, -even when several share a relative scale. +that can cross zero. A logarithmic scale fits the positive values in view, and +while every value in view is at or below zero it shows ordinary prices, as +Normal does, until positive values come back into view. A view without any +value keeps the units the scale shows. A missing, non-finite or zero relative +reference falls back to ordinary prices. Each series keeps its own +first-visible-close reference, even when several share a relative scale. After changing a mode through [`PriceScale::options_mut`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/scales/struct.PriceScale.html#method.options_mut), diff --git a/vendor/egui-charts/docs/site/src/content/docs/theming.mdx b/vendor/egui-charts/docs/site/src/content/docs/theming.mdx index 8b5fb65..2b09695 100644 --- a/vendor/egui-charts/docs/site/src/content/docs/theming.mdx +++ b/vendor/egui-charts/docs/site/src/content/docs/theming.mdx @@ -131,8 +131,9 @@ accepts an `Arc` for custom time labels. Its [`format_tick`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/scales/trait.TimeFormatter.html#method.format_tick) receives the active locale and can return `None` for the built-in tick text. A supplied formatter otherwise replaces the built-in locale and date format. -Inputs already contain the selected zone's wall-clock fields: do not shift -them a second time. [`format_time`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.Chart.html#method.format_time) +Inputs already contain wall-clock fields, in the selected zone or, when it is +behind UTC, in UTC for the daily and longer bars described in +[Time zones and sessions](time-zones.mdx): do not shift them a second time. [`format_time`](https://userfrm.github.io/egui-charts/docs/api/egui_charts/widget/struct.Chart.html#method.format_time) lets a host readout use the chart's time presentation. Choose the formatter for the values being displayed: diff --git a/vendor/egui-charts/docs/site/src/content/docs/time-zones.mdx b/vendor/egui-charts/docs/site/src/content/docs/time-zones.mdx index ac473ae..3f0e98f 100644 --- a/vendor/egui-charts/docs/site/src/content/docs/time-zones.mdx +++ b/vendor/egui-charts/docs/site/src/content/docs/time-zones.mdx @@ -7,7 +7,9 @@ import presentation from '../../../../../examples/docs/scenes/theme.rs?raw'; Store historical bars, streaming updates and shared time ranges as UTC instants. The display zone changes calendar and clock labels; changing it does not rewrite -the supplied timestamps or move bars to a new instant. +the supplied timestamps or move bars to a new instant. Bars of a day or longer +given without a feed keep the date of a 00:00 UTC stamp, or of a stamp at the +display zone's midnight, as the sessions section below describes. ## Choose a display zone @@ -108,6 +110,17 @@ For feed-built bars, keep the feed's and session metadata consistent with the venue. Changing display labels cannot reaggregate prebuilt historical OHLC bars. Daily and longer bars identify trading dates; follow the [data contract](data-model.mdx) rather than applying an offset -to every bar. Synchronize charts using the +to every bar. The bars of the chart's own feed read their dates on the bar clock +of the display zone. Bars given with `Chart::new`, `ChartBuilder` or +`Chart::set_data` read in UTC when the display zone is behind UTC, unless they +sit at its midnight, and in the display zone otherwise, which gives a 00:00 UTC +stamp the same date. A bar stamped at 00:00 UTC on its trading date therefore +keeps that date in the crosshair, the tooltip, `Chart::format_time` and the time +axis marks in every display zone. `Chart::bar_clock` runs on the same dates, so +bar replay completes such a bar when its date ends and forms the bar of the +cursor's date there, and studies group the bars into weeks and months by those +dates; pass it to `ReplayController::cutoff`. Intraday bars always read in the +display zone. +Synchronize charts using the [UTC time range](time-scale.mdx#logical-indices-and-utc-instants), even when their display clocks differ. diff --git a/vendor/egui-charts/examples/demo/Cargo.lock b/vendor/egui-charts/examples/demo/Cargo.lock index 538d14f..8d971d8 100644 --- a/vendor/egui-charts/examples/demo/Cargo.lock +++ b/vendor/egui-charts/examples/demo/Cargo.lock @@ -391,6 +391,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bit-set" version = "0.10.0" @@ -421,6 +427,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -694,6 +709,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -715,6 +739,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "csv" version = "1.4.0" @@ -742,12 +776,28 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "data-url" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -906,15 +956,19 @@ dependencies = [ "egui", "egui-charts", "egui_extras", + "ehttp", "image", "log", "maudio", "rfd", + "rustls", "serde", "serde_json", + "tungstenite", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "webpki-roots", ] [[package]] @@ -994,6 +1048,20 @@ dependencies = [ "winit", ] +[[package]] +name = "ehttp" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d1c51126a4e8242c5b3bcd4c5b350ed3540f0c13c10e0c3c840a3833fa3474c" +dependencies = [ + "document-features", + "js-sys", + "ureq", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "either" version = "1.19.0" @@ -1321,6 +1389,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -1331,6 +1409,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1522,6 +1611,22 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -2505,7 +2610,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ "phf_shared 0.11.3", - "rand", + "rand 0.8.8", ] [[package]] @@ -2707,6 +2812,15 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -2785,7 +2899,27 @@ version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", ] [[package]] @@ -2794,6 +2928,15 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -2894,6 +3037,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "ron" version = "0.12.2" @@ -2961,6 +3118,41 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -3066,6 +3258,17 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -3246,6 +3449,12 @@ dependencies = [ "float-cmp", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "svgtypes" version = "0.15.3" @@ -3474,6 +3683,22 @@ dependencies = [ "petgraph", ] +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror 2.0.21", +] + [[package]] name = "type-map" version = "0.5.1" @@ -3489,6 +3714,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "uds_windows" version = "1.2.1" @@ -3536,6 +3767,41 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + [[package]] name = "url" version = "2.5.8" @@ -3554,7 +3820,7 @@ version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" dependencies = [ - "base64", + "base64 0.22.1", "data-url", "flate2", "imagesize", @@ -3570,6 +3836,12 @@ dependencies = [ "xmlwriter", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -3630,6 +3902,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -3866,6 +4144,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -4530,6 +4817,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/vendor/egui-charts/examples/demo/Cargo.toml b/vendor/egui-charts/examples/demo/Cargo.toml index 6369cc0..19f5ea7 100644 --- a/vendor/egui-charts/examples/demo/Cargo.toml +++ b/vendor/egui-charts/examples/demo/Cargo.toml @@ -29,6 +29,12 @@ rfd = "0.17.2" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] egui_extras = { version = "0.37.0", default-features = false, features = ["file"] } maudio = "0.1.15" +# Own data: REST history and the WebSocket stream of a visitor's source. The browser build +# uses the page's own fetch and WebSocket instead. +ehttp = "0.7.2" +tungstenite = { version = "0.29.0", default-features = false, features = ["handshake"] } +rustls = { version = "0.23.40", default-features = false, features = ["ring", "std", "tls12"] } +webpki-roots = "1.0.7" eframe = { version = "0.37.0", default-features = false, features = ["accesskit", "clipboard", "glow", "links", "x11", "wayland"] } [target.'cfg(target_arch = "wasm32")'.dependencies] @@ -36,7 +42,7 @@ eframe = { version = "0.37.0", default-features = false, features = ["accesskit" rfd = { version = "0.17.2", features = ["file-handle-inner"] } wasm-bindgen = "0.2.108" wasm-bindgen-futures = "0.4.58" -web-sys = { version = "0.3.85", features = ["Window", "Document", "Element", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "AudioContext", "AudioBuffer", "AudioBufferSourceNode", "AudioDestinationNode", "AudioNode", "AudioContextState"] } +web-sys = { version = "0.3.85", features = ["Window", "Document", "Element", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "AudioContext", "AudioBuffer", "AudioBufferSourceNode", "AudioDestinationNode", "AudioNode", "AudioContextState", "WebSocket", "MessageEvent", "CloseEvent", "BinaryType", "RequestInit", "RequestMode", "Response", "Headers"] } console_error_panic_hook = "0.1.7" # `index.html` builds the web release with this profile; native builds keep `release`. diff --git a/vendor/egui-charts/examples/demo/commands.rs b/vendor/egui-charts/examples/demo/commands.rs index 10a71d3..5e55523 100644 --- a/vendor/egui-charts/examples/demo/commands.rs +++ b/vendor/egui-charts/examples/demo/commands.rs @@ -1,13 +1,17 @@ //! Demo menu controls and sample commands shared with quick search. -use super::{DemoApp, TopToolbarAction}; +use super::{ + DemoApp, DrawingToolbarAction, RightBarIcon, TimeframeToolbarAction, TopToolbarAction, +}; use eframe::egui; +use egui_charts::config::KeyboardAction; use egui_charts::drawings::DrawingToolType; use egui_charts::icons::{Icon, icons}; use egui_charts::studies::IndicatorFactory; use egui_charts::theme::ThemeExt; -use egui_charts::ui_kit::command_palette::Command; +use egui_charts::ui_kit::command_palette::{Command, CommandPaletteHandler}; use egui_charts::ui_kit::list_item::ListItem; +use egui_charts::widget::ShortcutMap; /// A top-left menu row with an icon and an optional trailing icon at the right edge. pub(super) fn menu_item( @@ -94,7 +98,7 @@ const SAMPLES: &[(&str, &str, &str)] = &[ ( "targets", "Analyst price targets", - "Requires SAMPLE on the daily interval.", + "Synthetic high, average and low targets for SAMPLE on the daily interval.", ), ( "financials", @@ -103,7 +107,42 @@ const SAMPLES: &[(&str, &str, &str)] = &[ ), ]; -pub(super) fn quick_search_commands() -> Vec { +/// The quick search rows whose action has a key binding. +const ROW_KEYS: &[(&str, KeyboardAction)] = &[ + ("symbols", KeyboardAction::OpenSymbolSearch), + ("indicators", KeyboardAction::OpenIndicatorSearch), + ("reset", KeyboardAction::ResetChart), + ("date", KeyboardAction::GoToDate), + ("help", KeyboardAction::ShowKeyboardHelp), + ("log", KeyboardAction::ToggleLogScale), + ("invert", KeyboardAction::InvertScale), + ("grid", KeyboardAction::ToggleGrid), + ("undo", KeyboardAction::Undo), + ("redo", KeyboardAction::Redo), + ("snapshot", KeyboardAction::Snapshot), + ("alert", KeyboardAction::CreateAlert), + ("interval", KeyboardAction::OpenIntervalSearch), + ("percent", KeyboardAction::TogglePercentageScale), + ("auto-scale", KeyboardAction::ToggleAutoScale), + ("data-window", KeyboardAction::OpenDataWindow), + ("fullscreen", KeyboardAction::MaximizeChart), + ("save-layout", KeyboardAction::SaveLayout), + ("open-layout", KeyboardAction::OpenLayout), + ("hide-drawings", KeyboardAction::ToggleDrawings), +]; + +/// The quick search rows. A row whose action has a key shows the first one bound in `shortcuts`, +/// and each saved indicator template of `templates` (id and name) has a row of its own. +pub(super) fn quick_search_commands( + shortcuts: &ShortcutMap, + templates: &[(String, String)], +) -> Vec { + let keyed = |command: Command, action: Option| match action + .and_then(|action| shortcuts.shortcut(action)) + { + Some(shortcut) => command.shortcut(shortcut), + None => command, + }; let mut commands: Vec<_> = [ ("symbols", "Symbol search", "Actions"), ("indicators", "Indicators", "Actions"), @@ -119,10 +158,45 @@ pub(super) fn quick_search_commands() -> Vec { ("samples", "Toggle all sample overlays", "Showcase"), ("heatmap", "Market heatmap", "Actions"), ("price-workspace", "Return to price chart", "Showcase"), + ("undo", "Undo", "Actions"), + ("redo", "Redo", "Actions"), + ("snapshot", "Take a snapshot", "Actions"), + ("alert", "Create alert", "Actions"), + ("compare", "Compare or add symbol", "Actions"), + ("interval", "Change interval", "Actions"), + ("timezone", "Time zone", "Settings"), + ("session", "Trading session", "Settings"), + ("percent", "Toggle percent scale", "Settings"), + ("auto-scale", "Toggle auto scale", "Settings"), + ("data-window", "Data window", "Actions"), + ("object-tree", "Object tree", "Actions"), + ("watchlist", "Watchlist", "Actions"), + ("fullscreen", "Toggle fullscreen", "Actions"), + ("save-layout", "Save layout", "Actions"), + ("open-layout", "Open layout", "Actions"), + ("hide-drawings", "Hide all drawings", "Drawing tools"), + ("remove-drawings", "Remove all drawings", "Drawing tools"), + ("lock-drawings", "Lock all drawings", "Drawing tools"), + ("magnet", "Toggle magnet", "Drawing tools"), + ("remove-indicators", "Remove all indicators", "Studies"), + ("save-template", "Save indicator template", "Studies"), ] .into_iter() - .map(|(id, label, category)| Command::new(id, label).category(category)) + .map(|(id, label, category)| { + let action = ROW_KEYS + .iter() + .find(|(row, _)| *row == id) + .map(|(_, key)| *key); + keyed(Command::new(id, label).category(category), action) + }) .collect(); + commands.extend(templates.iter().map(|(id, name)| { + Command::new( + format!("template:{id}"), + format!("Indicator template: {name}"), + ) + .category("Studies") + })); commands.extend(SAMPLES.iter().map(|(id, label, description)| { Command::new(*id, *label) .category("Showcase") @@ -141,11 +215,12 @@ pub(super) fn quick_search_commands() -> Vec { for category in DrawingToolType::categories() { for tool in DrawingToolType::by_category(category) { if !tool.is_cursor() { - commands.push( + commands.push(keyed( Command::new(format!("tool:{}", tool.data_name()), tool.as_str()) .category("Drawing tools") .keywords([*category]), - ); + Some(KeyboardAction::DrawingTool(tool)), + )); } } } @@ -171,6 +246,10 @@ impl DemoApp { ("Formatting", &icons::TEXT), ("Showcase", &icons::WIDGET_BAR_HIGHLIGHTS), ] { + // Both act on the synthetic feed. + if self.own_data.is_some() && matches!(label, "Price unit" | "Market recording") { + continue; + } let response = menu_item(ui, label, icon, Some(&icons::CHEVRON_RIGHT)); egui::containers::menu::SubMenu::new() .config( @@ -197,8 +276,26 @@ impl DemoApp { } } + /// Opens quick search with the chart's current key bindings and saved templates. + pub(super) fn open_quick_search(&mut self) { + self.quick_search = CommandPaletteHandler::new(quick_search_commands( + self.chart.shortcuts(), + &self.top_toolbar.indicator_templates, + )); + self.quick_search.open(); + } + pub(super) fn execute_search_command(&mut self, ctx: &egui::Context, id: &str) { - self.user_action(|app| app.execute_search_edit(ctx, id)); + // The appearance is the interface's, on every chart: choosing it is no chart's edit. + if id.starts_with("appearance:") { + return self.execute_search_edit(ctx, id); + } + // Undo and redo step through the history, so they cannot run inside an edit. + match id { + "undo" => self.handle_top_toolbar(ctx, TopToolbarAction::Undo), + "redo" => self.handle_top_toolbar(ctx, TopToolbarAction::Redo), + _ => self.user_action(|app| app.execute_search_edit(ctx, id)), + } } fn execute_search_edit(&mut self, ctx: &egui::Context, id: &str) { @@ -222,6 +319,13 @@ impl DemoApp { } return; } + if let Some(template) = id.strip_prefix("template:") { + self.handle_top_toolbar( + ctx, + TopToolbarAction::ApplyIndicatorTemplate(template.to_owned()), + ); + return; + } if let Some(name) = id.strip_prefix("study:") { if let Some(study) = IndicatorFactory::new().create(name) { let inputs = super::study_input_summary(study.as_ref()); @@ -252,10 +356,86 @@ impl DemoApp { self.sample_scene = None; return; } + let drawing_action = match id { + "hide-drawings" => { + // The toolbar's hide menu flips its state before it reports the choice. + let state = &mut self.drawing_toolbar.state; + state.hide_drawings = !state.hide_drawings; + Some(DrawingToolbarAction::HideAllDrawings) + } + "remove-drawings" => Some(DrawingToolbarAction::RemoveAllDrawings), + "lock-drawings" => Some(DrawingToolbarAction::LockAllDrawings), + "magnet" => Some(DrawingToolbarAction::ToggleMagnet), + "remove-indicators" => Some(DrawingToolbarAction::RemoveAllIndicators), + _ => None, + }; + if let Some(action) = drawing_action { + self.handle_drawing_toolbar(action); + return; + } + let shortcut = match id { + "interval" => Some(KeyboardAction::OpenIntervalSearch), + "data-window" => Some(KeyboardAction::OpenDataWindow), + "open-layout" => Some(KeyboardAction::OpenLayout), + _ => None, + }; + if let Some(action) = shortcut { + self.handle_shortcut_action(ctx, action); + return; + } + // These switch to a catalog symbol or show the sample annotations. + if matches!( + id, + "options-volume" + | "targets" + | "financials" + | "tape" + | "markers" + | "signals" + | "samples" + ) && self.synthetic_only("Samples") + { + return; + } let action = match id { "symbols" => TopToolbarAction::OpenSymbolSearch, "indicators" => TopToolbarAction::OpenIndicators, "settings" => TopToolbarAction::OpenSettings, + "snapshot" => TopToolbarAction::TakeScreenshot, + "alert" => TopToolbarAction::CreateAlert, + "compare" => TopToolbarAction::OpenCompare, + "fullscreen" => TopToolbarAction::ToggleFullscreen, + "save-layout" => TopToolbarAction::Save, + "save-template" => TopToolbarAction::SaveIndicatorTemplate, + "timezone" | "session" => { + self.handle_timeframe_toolbar(if id == "timezone" { + TimeframeToolbarAction::OpenTimezoneMenu + } else { + TimeframeToolbarAction::OpenSessionMenu + }); + return; + } + "percent" | "auto-scale" => { + // The scale boxes of the chart settings, applied as their Ok button does. + let mut settings = self.chart_settings_state(); + let scales = &mut settings.scales_and_lines; + if id == "percent" { + scales.percentage_scale = !scales.percentage_scale; + scales.log_scale &= !scales.percentage_scale; + } else { + scales.auto_scale = !scales.auto_scale; + } + self.apply_chart_settings(settings); + return; + } + "object-tree" | "watchlist" => { + self.toggle_panel(if id == "watchlist" { + RightBarIcon::Watchlist + } else { + RightBarIcon::ObjectTree + }); + return; + } "export" => { self.screenshot_requested = None; self.export_dialog.open(); @@ -328,8 +508,26 @@ impl DemoApp { return; } "targets" => { - if self.chart.symbol() != "SAMPLE" { - self.notify("Analyst targets require SAMPLE. Select SAMPLE, then try again."); + let symbol = self.chart.symbol().to_owned(); + if symbol != super::live::TARGETS_SYMBOL { + self.notify(format!( + "{symbol} has no analyst targets in this demo. Select {}, then try again.", + super::live::TARGETS_SYMBOL + )); + return; + } + if self.chart.chart_type().is_time_independent() { + self.notify( + "Analyst targets need a time-based chart type, such as candles. Change \ + the chart type, then try again.", + ); + return; + } + if !self.chart.is_main_series_visible() { + self.notify( + "Analyst targets start at the last close. Show the price series, then try \ + again.", + ); return; } self.switch_timeframe(egui_charts::model::Timeframe::Day1); @@ -451,7 +649,7 @@ impl DemoApp { }); }); if search { - self.quick_search.open(); + self.open_quick_search(); } if let Some(id) = self.quick_search.show(ui.ctx()) { self.sample_scene = None; @@ -512,6 +710,7 @@ impl DemoApp { mod tests { use super::*; use egui::{Event, RawInput}; + use egui_charts::model::ChartType; use egui_charts::widget::{Chart, ChartLayoutMode, ImageExportOptions}; fn choose_scope(app: &mut DemoApp, ctx: &egui::Context, label: &str) { @@ -764,6 +963,7 @@ mod tests { "Liquidity heatmap", "Largest order profile", "Pause synthetic feed", + "Data source", "Order flow", "Research", "Copy symbol", @@ -838,6 +1038,11 @@ mod tests { click_at_width(&mut app, &ctx, "Copy symbol", width); assert!(!egui::Popup::is_any_open(&ctx)); click_at_width(&mut app, &ctx, "Menu", width); + click_at_width(&mut app, &ctx, "Data source", width); + assert!(app.data_source.is_open() && app.keyboard_dialog_open()); + click_at_width(&mut app, &ctx, "Cancel", width); + assert!(!app.data_source.is_open()); + click_at_width(&mut app, &ctx, "Menu", width); click_at_width(&mut app, &ctx, "Order flow", width); assert!(app.open_panel == Some(super::super::SidePanel::OrderFlow)); assert!(app.widget_bar.active_widget.is_none()); @@ -949,6 +1154,12 @@ mod tests { ] { click(&mut app, &ctx, label); } + // The restarted application has storage: its first-visit choice is already answered. + let answered = super::super::owndata::store::Saved { + asked: true, + ..Default::default() + }; + answered.save(&app.storage); let mut storage = super::super::tests::AppStorage::default(); app.save(&mut storage); egui::Popup::close_all(&ctx); @@ -1077,7 +1288,22 @@ mod tests { #[test] fn showcase_routes_enable_samples_once_and_check_target_prerequisite() { - let commands = quick_search_commands(); + // A row shows the key its action is bound to now, and no key once the binding is gone. + let mut shortcuts = ShortcutMap::default(); + let edited = egui::KeyboardShortcut::new(egui::Modifiers::ALT, egui::Key::U); + for (key, action) in &mut shortcuts.bindings { + if *action == KeyboardAction::Undo { + *key = edited; + } + } + shortcuts + .bindings + .retain(|(_, action)| *action != KeyboardAction::Snapshot); + let commands = quick_search_commands(&shortcuts, &[]); + let shortcut = |id: &str| commands.iter().find(|row| row.id == id).unwrap().shortcut; + assert_eq!(shortcut("undo"), Some(edited)); + assert_eq!(shortcut("snapshot"), None); + assert!(shortcut("percent").is_some()); let ids: std::collections::HashSet<_> = commands.iter().map(|command| &command.id).collect(); assert_eq!(ids.len(), commands.len(), "commands must have unique ids"); @@ -1124,10 +1350,54 @@ mod tests { ); } assert!(app.open_panel == Some(super::super::SidePanel::TimeAndSales)); - app.switch_symbol("BTCUSD"); - let before = app.state.timeframe; + let refused = [ + ( + "BTCUSD", + ChartType::Candles, + true, + "BTCUSD has no analyst targets", + ), + ("SAMPLE", ChartType::Renko, true, "time-based chart type"), + ("SAMPLE", ChartType::Candles, false, "Show the price series"), + ]; + for (symbol, kind, series, reason) in refused { + app.switch_symbol(symbol); + app.chart.set_chart_type(kind); + app.chart.set_main_series_visible(series); + frame(&mut app, &ctx, vec![]).drop_without_applying_deltas(); + let (interval, range) = (app.state.timeframe, app.chart.visible_logical_range()); + app.execute_search_command(&ctx, "targets"); + assert_eq!(app.state.timeframe, interval, "{symbol} {kind:?}"); + assert_eq!( + app.chart.visible_logical_range(), + range, + "{symbol} {kind:?}" + ); + assert!(!app.chart.price_targets_visible(), "{symbol} {kind:?}"); + assert!( + app.toasts + .toasts() + .last() + .is_some_and(|toast| toast.message.contains(reason)), + "{reason}" + ); + } + app.chart.set_main_series_visible(true); app.execute_search_command(&ctx, "targets"); - assert_eq!(app.state.timeframe, before); - assert!(!app.chart.price_targets_visible()); + let output = frame(&mut app, &ctx, vec![]); + for name in ["High ", "Average ", "Low "] { + assert!( + output.shapes.iter().any(|shape| matches!(&shape.shape, + egui::Shape::Text(text) if text.galley.text().starts_with(name))), + "{name}" + ); + } + output.drop_without_applying_deltas(); + let horizon = app.chart.price_targets().unwrap().horizon; + let horizon = horizon.and_hms_opt(0, 0, 0).unwrap().and_utc(); + assert!( + f64::from(app.chart.visible_logical_range().unwrap().right) + >= app.chart.time_to_index(horizon).unwrap() + ); } } diff --git a/vendor/egui-charts/examples/demo/comparison.rs b/vendor/egui-charts/examples/demo/comparison.rs index 8475d5d..6e965da 100644 --- a/vendor/egui-charts/examples/demo/comparison.rs +++ b/vendor/egui-charts/examples/demo/comparison.rs @@ -919,6 +919,9 @@ impl DemoApp { /// Charts a spread picked in symbol search, such as `AAPL-MSFT`, as candles in a pane of its /// own, from feeds of its symbols. pub(super) fn add_spread(&mut self, symbol: &str) { + if self.synthetic_only("Compare") { + return; + } let Ok(expression) = SymbolExpression::parse(symbol) else { return; }; @@ -944,6 +947,9 @@ impl DemoApp { /// Feeds another symbol as candles in a pane of its own, above the price pane, on the left /// scale once moved to the price pane. pub(super) fn add_series_pane(&mut self) { + if self.synthetic_only("Compare") { + return; + } let Some(symbol) = DemoSymbol::catalog() .iter() .map(|spec| spec.symbol) diff --git a/vendor/egui-charts/examples/demo/controller.rs b/vendor/egui-charts/examples/demo/controller.rs index 0daa946..8fa05ef 100644 --- a/vendor/egui-charts/examples/demo/controller.rs +++ b/vendor/egui-charts/examples/demo/controller.rs @@ -31,6 +31,8 @@ use layouts::{DemoChart, LayoutTab}; mod comparison; #[path = "marks.rs"] mod marks; +#[path = "owndata/mod.rs"] +mod owndata; #[path = "replay.rs"] mod replay; #[path = "storage.rs"] @@ -63,7 +65,7 @@ use egui_charts::Chart; use egui_charts::chart::overlays::{BookProfile, OrderBookView}; use egui_charts::data::{DepthHistory, DepthHistoryConfig, OrderFilter, OrderSizeTiers}; use egui_charts::model::{Alert, AlertCondition}; -use egui_charts::model::{Bar, BarData, ChartType, RenkoConfig, Timeframe}; +use egui_charts::model::{Bar, BarData, BoxSizeMethod, ChartType, Tick, Timeframe}; use egui_charts::theme::Theme; use egui_charts::ui::app_state::ChartAppState; use egui_charts::ui::context_menu::{ @@ -101,6 +103,7 @@ use egui_charts::ui::widget_bar::{ WatchlistAction, WatchlistPanel, WidgetBarSection, WidgetBarWidget, }; use egui_charts::ui::widget_bar::{RightBarIcon, WidgetBar, WidgetBarAction}; +use egui_charts::ui_kit::EmptyState; use egui_charts::ui_kit::notifications::{NotificationPanel, Toasts}; use egui_charts::widget::settings::ChartSettingsState; use egui_charts::widget::{ChartLayoutMode, LayoutCopy, SeriesId}; @@ -148,8 +151,12 @@ fn study_input_summary(study: &dyn egui_charts::studies::Indicator) -> String { }) .collect(); // An anchor or session choice identifies the study, which names its price only once edited. + // Flags, which the caption leaves out, can precede that choice. let anchored = matches!( - inputs.first().map(|input| &input.kind), + inputs + .iter() + .map(|input| &input.kind) + .find(|kind| !matches!(kind, InputKind::Toggle)), Some(InputKind::Choice(_)) ); let edited = inputs @@ -534,6 +541,10 @@ pub struct DemoApp { api_samples: bool, annotation_editor: bool, annotation_series: SeriesId, + /// Set while the chart shows a visitor's own data. + own_data: Option, + /// The Data source dialog. + data_source: owndata::dialog::DataSourceDialog, } fn sample_widgets() -> [WidgetBarWidget; 2] { @@ -602,6 +613,9 @@ impl DemoApp { chart.config_mut().candle_width = 0.75; chart.config_mut().right_axis_width = 59.0; chart.config_mut().skip_background = true; + // The library hides the navigation row by default; the demo shows where it is. + chart.config_mut().navigation_buttons = egui_charts::config::NavigationButtons::OnHover; + size_by_atr(&mut chart); chart.set_event_visibility( cc.storage .and_then(|storage| eframe::get_value(storage, "event_visibility")) @@ -618,6 +632,7 @@ impl DemoApp { chart.set_timeframe(timeframe); let storage = Arc::new(storage::DemoStorage::restore(cc.storage)); chart.set_storage(storage.clone()); + chart.set_post_source(Some(Arc::new(feeds::DemoPosts))); let notification_host: Arc = Arc::default(); let mut top_toolbar = TopToolbar::new().with_config( @@ -727,13 +742,19 @@ impl DemoApp { comparisons: Vec::new(), spreads: Vec::new(), settings: egui_charts::services::SettingsStore::new(storage.clone()), + own_data: None, + data_source: owndata::dialog::DataSourceDialog::new( + storage.clone(), + cc.storage.is_some(), + ), storage, workspace_recovery: storage::WorkspaceRecovery::default(), grid_edits: 0, study_templates: TemplateDialog::new(StoreKind::StudyTemplates), drawing_templates: TemplateDialog::new(StoreKind::DrawingTemplates), + // Filled from the chart's bindings each time it opens. quick_search: egui_charts::ui_kit::command_palette::CommandPaletteHandler::new( - commands::quick_search_commands(), + Vec::new(), ), sample_scene: None, sample_study: Default::default(), @@ -1021,6 +1042,19 @@ impl DemoApp { // --- data helpers ------------------------------------------------------ fn switch_timeframe(&mut self, tf: Timeframe) { + if let Some(own) = &self.own_data { + if own.profile.service_interval(tf).is_none() { + self.toasts + .error(format!("The data source has no interval {tf}")); + return; + } + self.copied_drawing = None; + self.state.timeframe = tf; + self.chart.set_timeframe(tf); + self.timeframe_toolbar.state.timeframe = tf; + self.refresh_interval_control(); + return; + } self.copied_drawing = None; self.state.timeframe = tf; self.chart.set_timeframe(tf); @@ -1037,6 +1071,21 @@ impl DemoApp { } pub(crate) fn switch_symbol(&mut self, symbol: &str) { + if let Some(own) = &self.own_data { + // The profile lists what the visitor chose to offer. Nothing else reaches the service. + if !own.profile.symbols.iter().any(|listed| listed == symbol) { + self.toasts + .error(format!("{symbol} is not a symbol of this data source")); + return; + } + if symbol != self.chart.symbol() { + self.user_action(|app| { + app.chart.set_symbol(symbol); + app.sync_symbol(); + }); + } + return; + } if let Some(row) = DemoSymbol::symbols() .into_iter() .find(|row| row.symbol == symbol) @@ -1059,9 +1108,13 @@ impl DemoApp { fn sync_symbol(&mut self) { self.copied_drawing = None; + self.time_and_sales.clear(); + if self.own_data.is_some() { + self.state.symbol = self.chart.symbol().to_owned(); + return; + } let spec = DemoSymbol::find(self.chart.symbol()); self.live.set_symbol(spec.symbol); - self.time_and_sales.clear(); self.watchlist.set_selected(spec.symbol); self.timeframe_toolbar.state.session_menu_open = false; self.state.symbol = spec.symbol.to_string(); @@ -1073,60 +1126,45 @@ impl DemoApp { .set_control_visible(control, DemoSymbol::has_hours(spec.symbol)); } self.timeframe_toolbar - .set_session(if matches!(spec.exchange, "Crypto" | "Forex") { - SessionType::Full24x7 - } else { - SessionType::RTH - }); + .set_session(opening_session(spec.symbol)); self.sync_depth_history(); } fn regenerate_bars(&mut self) { self.apply_session(); - self.size_price_based_charts(); + self.size_range_interval(); } - /// The sizes of the price-based charts are in price units: take them from the bars on show. - fn size_price_based_charts(&mut self) { - let chart = &mut self.chart; - let mut params = chart.chart_type_params().clone(); - let size = RenkoConfig::from_atr(chart.bars(SeriesId::MAIN), 14, 0.5).brick_size; - if size > 0.0 && size.is_finite() { - params.renko_brick_size = size; - params.kagi_reversal = size; + /// A range interval names the size of its bars, in ticks of the instrument. The other + /// price-based sizes stay as the chart settings have them. + fn size_range_interval(&mut self) { + let Timeframe::Range(ticks) = self.state.timeframe else { + return; + }; + let size = ticks.get() as f64 * self.live.instrument().tick_size.unwrap_or(0.01); + let params = self.chart.chart_type_params(); + if params.range_size != size || params.range_size_method != BoxSizeMethod::Fixed { + let mut params = params.clone(); params.range_size = size; - params.pnf_box_size = size; - } - if let Timeframe::Range(ticks) = self.state.timeframe { - let tick_size = self.live.instrument().tick_size.unwrap_or(0.01); - params.range_size = ticks.get() as f64 * tick_size; - params.range_size_method = egui_charts::model::BoxSizeMethod::Fixed; + params.range_size_method = BoxSizeMethod::Fixed; + self.chart.set_chart_type_params(params); } - chart.set_chart_type_params(params); } fn apply_session(&mut self) { + if self.own_data.is_some() { + return; + } // Recorded prices and metadata already have their final session and price basis. if self.chart.replay_driver().is_some() { return; } - self.live.set_view( + load_view( + &mut self.chart, + &self.live, self.timeframe_toolbar.state.session_type, self.timeframe_toolbar.state.adjust_for_dividends, ); - let cents = self - .chart - .conversion() - .is_some_and(|c| c.starts_with("cents")); - self.live.set_price_unit(cents); - self.chart.set_conversion(replay::conversion( - cents, - self.timeframe_toolbar.state.adjust_for_dividends, - )); - self.chart.reload_feed(); - self.chart.set_instrument(Some(self.live.instrument())); - self.chart - .set_extended_hours(self.timeframe_toolbar.state.session_type != SessionType::RTH); self.loading_bars = true; self.bars = self.live.snapshot( self.state.timeframe, @@ -1147,6 +1185,9 @@ impl DemoApp { // --- alerts ------------------------------------------------------------ fn open_alert(&mut self, price: Option) { + if self.synthetic_only("Alerts") { + return; + } self.list_alert_sources(); let price = price .or_else(|| self.chart.bars(SeriesId::MAIN).last().map(|b| b.close)) @@ -1174,6 +1215,9 @@ impl DemoApp { } fn quick_price_alert(&mut self, symbol: String, price: f64) { + if self.synthetic_only("Alerts") { + return; + } let mut alert = Alert::new(symbol, AlertCondition::Crossing(price)); alert.timeframe = Some(self.state.timeframe); self.chart.prepare_alert(&mut alert); @@ -1181,6 +1225,9 @@ impl DemoApp { } fn monitor_alerts(&mut self, ctx: &egui::Context) { + if self.own_data.is_some() { + return; + } let now = chrono::Utc::now(); let paused = if self.replay.is_some() { self.live_was_paused @@ -1219,16 +1266,17 @@ impl DemoApp { // --- selection / context helpers -------------------------------------- + /// The chart settings as the dialog shows them, with the settings the demo keeps itself. + fn chart_settings_state(&self) -> ChartSettingsState { + let mut state = ChartSettingsState::from_chart(&self.chart); + state.alerts = self.settings_state.alerts.clone(); + state.trading = self.trading.display.clone(); + state.adjust_for_dividends = self.timeframe_toolbar.state.adjust_for_dividends; + state + } + fn open_chart_settings_dialog(&mut self) { - let (alerts, trading) = ( - self.settings_state.alerts.clone(), - self.trading.display.clone(), - ); - self.settings_state = ChartSettingsState::from_chart(&self.chart); - self.settings_state.alerts = alerts; - self.settings_state.trading = trading; - self.settings_state.adjust_for_dividends = - self.timeframe_toolbar.state.adjust_for_dividends; + self.settings_state = self.chart_settings_state(); self.settings_dialog .offer_apply_to_all(self.layout_has_other_charts()); self.settings_dialog.open(self.settings_state.clone()); @@ -1255,8 +1303,13 @@ impl DemoApp { if let Some(id) = self.quick_search.show(ctx) { self.execute_search_command(ctx, &id); } + // The metrics of the study dialog are those of the synthetic feed. + let metrics: Option> = match self.own_data { + Some(_) => None, + None => Some(self.live.clone()), + }; self.indicator_dialog - .set_metric_source(Some(self.live.clone()), self.chart.symbol()); + .set_metric_source(metrics, self.chart.symbol()); // Indicators: add the study the dialog created. if let IndicatorDialogAction::AddIndicator(study) = self.indicator_dialog.show(ctx, &self.theme) @@ -1310,7 +1363,16 @@ impl DemoApp { } self.show_layout_copy_prompt(ctx); - let symbols = DemoSymbol::symbols(); + // On own data the search offers the symbols of the profile and no others. + let symbols = match &self.own_data { + Some(own) => own + .profile + .symbols + .iter() + .map(|symbol| egui_charts::model::Instrument::new(symbol.as_str())) + .collect(), + None => DemoSymbol::symbols(), + }; self.sync_comparisons(); let action = self.compare_dialog.show(ctx, &symbols); self.handle_comparison(action); @@ -1390,6 +1452,7 @@ impl DemoApp { DatePickerAction::Cancel | DatePickerAction::None => {} _ => {} } + self.show_data_source(ctx); } fn apply_chart_settings(&mut self, state: ChartSettingsState) { @@ -1529,18 +1592,28 @@ impl DemoApp { }); } + /// Shows the days `start` to `end`, both included, as the active chart's time axis counts + /// them. fn set_date_range(&mut self, start: chrono::NaiveDate, end: chrono::NaiveDate) { + let Some((from, next)) = day_start(&self.chart, start) + .zip(end.succ_opt().and_then(|next| day_start(&self.chart, next))) + else { + return; + }; let range = egui_charts::widget::VisibleTimeRange { - from: start.and_hms_opt(0, 0, 0).unwrap().and_utc(), - to: end.and_hms_opt(23, 59, 59).unwrap().and_utc(), + from, + to: next - chrono::TimeDelta::seconds(1), }; let mut charts: Vec<_> = self.extra_charts.iter_mut().map(|c| &mut c.chart).collect(); charts.insert(self.layout_slot, &mut self.chart); self.layout.apply_date_range(&mut charts, range); } + /// Scrolls to the first bar of `date` on the chart's time axis. fn go_to_date(&mut self, date: chrono::NaiveDate) { - let start = date.and_hms_opt(0, 0, 0).unwrap().and_utc(); + let Some(start) = day_start(&self.chart, date) else { + return; + }; let target = self .bars .iter() @@ -1596,7 +1669,9 @@ impl DemoApp { fn write_export(&mut self, save_path: Option, extension: &str, out: &[u8]) { let from_dialog = save_path.is_some(); let path = save_path.unwrap_or_else(|| { - let filename = format!("{}_export.{extension}", self.state.symbol); + // A symbol of a visitor's own data must not carry a path into the file name. + let stem = owndata::store::file_stem(&self.state.symbol); + let filename = format!("{stem}_export.{extension}"); #[cfg(not(target_arch = "wasm32"))] return std::env::temp_dir().join(filename); #[cfg(target_arch = "wasm32")] @@ -1862,6 +1937,9 @@ impl eframe::App for DemoApp { impl DemoApp { fn sync_depth_history(&mut self) { + if self.own_data.is_some() { + return; + } // Replay hides the live history, which must survive for its exit. if self.chart.replay_time().is_some() || !ChartSettingsState::from_chart(&self.chart) @@ -1905,7 +1983,10 @@ impl DemoApp { let mut heatmap_enabled = order_flow.show_heatmap; let mut largest_profile = order_flow.order_book.profile == BookProfile::LargestOrder; - let mut paused = self.live.paused(); + let mut paused = self + .own_data + .as_ref() + .map_or(self.live.paused(), |own| own.paused); let mut study_permission = None; let mut toolbar = std::mem::take(&mut self.top_toolbar); let state = self.state.clone(); @@ -2036,12 +2117,15 @@ impl DemoApp { } }); ui.separator(); - menu_toggle( - ui, - "Liquidity heatmap", - &icons::LIQUIDITY_HEATMAP, - &mut heatmap_enabled, - ); + // The mapped feed of own data has no depth to draw. + ui.add_enabled_ui(self.own_data.is_none(), |ui| { + menu_toggle( + ui, + "Liquidity heatmap", + &icons::LIQUIDITY_HEATMAP, + &mut heatmap_enabled, + ); + }); ui.add_enabled_ui(heatmap_enabled || order_flow.show_order_book, |ui| { menu_toggle( ui, @@ -2052,8 +2136,17 @@ impl DemoApp { }); ui.separator(); ui.add_enabled_ui(self.replay.is_none(), |ui| { - menu_toggle(ui, "Pause synthetic feed", &icons::MEDIA_PAUSE, &mut paused); + let label = if self.own_data.is_some() { + "Pause data feed" + } else { + "Pause synthetic feed" + }; + menu_toggle(ui, label, &icons::MEDIA_PAUSE, &mut paused); }); + if menu_item(ui, "Data source", &icons::DATABASE, None).clicked() { + self.data_source.open(); + ui.close(); + } ui.separator(); if menu_item(ui, "Order flow", &icons::CHART_VOLUME_FOOTPRINT, None).clicked() { panel_action = Some(SidePanel::OrderFlow); @@ -2109,7 +2202,15 @@ impl DemoApp { if show_help { self.keyboard_shortcuts.toggle(); } - self.live.set_paused(paused); + if let Some(own) = &mut self.own_data { + // Pausing the chart ends its subscription, which closes the socket. + if own.paused != paused { + own.paused = paused; + self.chart.set_feed_paused(paused); + } + } else { + self.live.set_paused(paused); + } if heatmap_enabled != order_flow.show_heatmap { self.chart.user_action(|chart| { chart.set_liquidity_heatmap(heatmap_enabled); @@ -2190,6 +2291,11 @@ impl DemoApp { self.sync_chart_history(); return; } + // The theme is the interface's, on every chart: switching it is no chart's edit. + TopToolbarAction::ThemeToggle => { + self.toggle_theme(ctx); + return; + } _ => {} } @@ -2201,14 +2307,19 @@ impl DemoApp { TopToolbarAction::ChartStyleSelected(ct) => { self.state.chart_type = ct; self.chart.set_chart_type(ct); - self.size_price_based_charts(); + self.size_range_interval(); } TopToolbarAction::IntervalSelected(tf) => self.switch_timeframe(tf), TopToolbarAction::OpenSymbolSearch => self .symbol_search .open_with_selected_query(self.chart.symbol().to_owned()), - TopToolbarAction::OpenCompare => self.compare_dialog.open(), - TopToolbarAction::OpenQuickSearch => self.quick_search.open(), + TopToolbarAction::OpenCompare => { + if self.synthetic_only("Compare") { + return; + } + self.compare_dialog.open(); + } + TopToolbarAction::OpenQuickSearch => self.open_quick_search(), TopToolbarAction::OpenIndicators => { self.indicator_dialog.open_for_chart(&self.chart, None); } @@ -2256,9 +2367,8 @@ impl DemoApp { self.load_study_template(&template); } } - // Light/dark toggle is a real, cheap visual change. - TopToolbarAction::ThemeToggle => self.toggle_theme(ctx), TopToolbarAction::Layout(_) + | TopToolbarAction::ThemeToggle | TopToolbarAction::Save | TopToolbarAction::ToggleTrading | TopToolbarAction::Host(_) @@ -2294,6 +2404,7 @@ impl DemoApp { CrosshairStyle::Arrow | CrosshairStyle::Hidden => CursorType::Arrow, CrosshairStyle::Demonstration => CursorType::Demonstration, CrosshairStyle::Magic => CursorType::Magic, + _ => CursorType::Cross, }, eraser_mode_enabled: dm.is_eraser_mode(), stay_in_drawing_mode: dm.stay_in_drawing_mode, @@ -2625,6 +2736,37 @@ impl DemoApp { }), ) .show(ui, |ui| match which { + SidePanel::TimeAndSales + if self + .own_data + .as_ref() + .is_some_and(|own| !own.profile.has_trades()) => + { + EmptyState::new("No trades") + .description( + "The data source maps no trades. A trades route in its Live step \ + lists them here.", + ) + .show(ui); + } + SidePanel::Alerts + | SidePanel::Watchlist + | SidePanel::OrderFlow + | SidePanel::Highlights + | SidePanel::Screener + | SidePanel::Hotlists + | SidePanel::MarketHeatmap + | SidePanel::Calendar + | SidePanel::News + if self.own_data.is_some() => + { + EmptyState::new("Synthetic data only") + .description( + "This panel shows the demo's synthetic market. Open Data source in \ + the menu to switch back.", + ) + .show(ui); + } SidePanel::ObjectTree => self.show_object_tree(ui), SidePanel::Alerts => self.show_alerts_panel(ui), SidePanel::Watchlist => { @@ -2869,6 +3011,12 @@ impl DemoApp { /// passes the chart symbol's quote on to the details panel and the order ticket. Feeds time /// and sales the executions of the live feed and reports matching filters as notifications. fn feed_market_panels(&mut self, ctx: &egui::Context) { + if let Some(own) = &self.own_data { + let (symbol, timeframe) = (self.chart.symbol(), self.chart.timeframe()); + let tape = own.feed.drain_tape(symbol, timeframe); + self.feed_time_and_sales(tape); + return; + } // The simulation clock rather than the wall clock, which the pause freezes: a paused // demo must be able to go idle instead of repainting for a market that stands still. let now = self.live.now(); @@ -2941,9 +3089,17 @@ impl DemoApp { .set_timezone(timezone.unwrap_or_default()); self.highlights.set_symbol(&chart_symbol); self.news.set_symbol(&chart_symbol); + let tape = self.live.drain_tape(); + self.feed_time_and_sales(tape); + } + + /// Lists `tape`, the trades the chart's feed received since the last frame, in time and + /// sales, notifies a size filter that matched, and formats the panel for the chart's + /// instrument and the chosen zone. + fn feed_time_and_sales(&mut self, tape: Vec) { let instrument = self.chart.instrument(); let mut alert = None; - for trade in self.live.drain_tape() { + for trade in tape { if self.time_and_sales.push(trade.clone()).is_some() { alert = Some(trade); } @@ -2986,6 +3142,10 @@ impl DemoApp { /// Shows `symbol` on the chart when the demo has data for it. fn open_catalog_symbol(&mut self, symbol: &str) { + if self.own_data.is_some() { + self.switch_symbol(symbol); + return; + } if DemoSymbol::catalog() .iter() .any(|spec| spec.symbol.eq_ignore_ascii_case(symbol)) @@ -3237,11 +3397,13 @@ impl DemoApp { fn handle_timeframe_toolbar(&mut self, action: TimeframeToolbarAction) { match action { TimeframeToolbarAction::DateRangeChanged(range) => { - self.explain_history_limit(range); + if self.own_data.is_none() { + self.explain_history_limit(range); + } let visible = visible_bars_for_range(range, self.chart.bars(SeriesId::MAIN)); let width = self.chart.get_rendered_price_rect().width(); // Include the latest slot in the scale's exclusive data range. - let spacing = width.max(1.0) / (visible.max(1) as f32 + 0.5); + let spacing = (width - 1.0).max(1.0) / (visible.max(1) as f32 + 0.5); self.chart.disable_tracking_mode(); self.chart.apply_synced_time_scale(spacing, 0.5); if self.layout.sync.sync_date_range @@ -3311,7 +3473,17 @@ impl DemoApp { .resizable(false) .open(&mut open) .show(ctx, |ui| { - for label in ["UTC", "America/New_York"] { + // On own data the zone of the profile is offered too, to return to it. + let own_zone = self + .own_data + .as_ref() + .map(|own| own.profile.time_zone.name().to_owned()); + let labels = ["UTC", "America/New_York"].into_iter().chain( + own_zone + .as_deref() + .filter(|zone| !matches!(*zone, "UTC" | "America/New_York")), + ); + for label in labels { if ui .selectable_label(self.timeframe_toolbar.state.timezone == label, label) .clicked() @@ -3369,13 +3541,28 @@ impl DemoApp { { Self::show_pointer_readout(ui, pointer); } + let symbols: Vec<_> = self + .extra_charts + .iter() + .map(|c| c.chart.symbol().to_owned()) + .collect(); let mut charts: Vec<_> = self.extra_charts.iter_mut().map(|c| &mut c.chart).collect(); charts.insert(self.layout_slot, &mut self.chart); self.layout.show(ui, &mut charts); + // A chart that follows a linked symbol change shows the bars it would show had + // the symbol been chosen on it. + for (extra, symbol) in self.extra_charts.iter_mut().zip(symbols) { + if extra.chart.symbol() != symbol && extra.chart.replay_driver().is_none() { + extra.live.set_symbol(extra.chart.symbol()); + let session = opening_session(extra.chart.symbol()); + let (_, adjusted) = extra.live.view(false); + load_view(&mut extra.chart, &extra.live, session, adjusted); + } + } self.highlight_strategy_trade(ui); let mapping = self.chart.get_chart_mapping(); - if self.settings_state.alerts.show_alerts { + if self.settings_state.alerts.show_alerts && self.own_data.is_none() { let decimals = self .chart .instrument() @@ -3414,7 +3601,7 @@ impl DemoApp { if self.chart.take_event_click().is_some() { self.notify("Synthetic session: generated example data"); } - if self.replay.is_some() + if (self.replay.is_some() || self.own_data.is_some()) && let Some(bar) = self .chart .bars(SeriesId::MAIN) @@ -3481,7 +3668,7 @@ impl DemoApp { { self.bars = self.chart.bars(SeriesId::MAIN).to_vec(); self.loading_bars = false; - self.size_price_based_charts(); + self.size_range_interval(); self.annotate(); } if !self.keyboard_dialog_open() @@ -3503,6 +3690,7 @@ impl DemoApp { let mut replay_click = None; let mut open_settings = false; let mut drawing_settings = None; + let mut size = false; for event in self.chart.drain_events() { match event { egui_charts::widget::ChartEvent::ImageRequested(request) => { @@ -3541,10 +3729,37 @@ impl DemoApp { | egui_charts::widget::ChartEvent::TimeframeChanged(_) => { self.last_chart_click = None; self.pointer_readout = None; + if let Some(own) = &mut self.own_data { + own.sizing = true; + } + } + // The first bars of a symbol or interval of own data size a range interval, as + // the end of a synthetic load does. + egui_charts::widget::ChartEvent::DataLoaded { + series: SeriesId::MAIN, + bars, + } if bars > 0 => { + if let Some(own) = &mut self.own_data + && std::mem::take(&mut own.sizing) + { + size = true; + } + } + egui_charts::widget::ChartEvent::LinkClick { link, .. } => { + // Any typed text can be a link; open web addresses only. + let web = link.split_once("://").is_some_and(|(scheme, _)| { + scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") + }); + if web { + ctx.open_url(egui::OpenUrl::new_tab(link)); + } } _ => {} } } + if size { + self.size_range_interval(); + } if let Some(index) = replay_click.and_then(|pos| self.replay_start_bar(pos)) { let time = self.chart.state().shown()[index].time; self.handle_replay_bar_click(ctx, time); @@ -3646,6 +3861,9 @@ impl DemoApp { ) { match action { StudyContextMenuAction::AddAlert(mut alert) => { + if self.synthetic_only("Alerts") { + return; + } self.chart.prepare_alert(&mut alert); self.alerts.save(*alert); } @@ -3696,6 +3914,9 @@ impl DemoApp { } ContextMenuAction::AddAlert { symbol, price } => self.quick_price_alert(symbol, price), ContextMenuAction::AddToWatchlist { list, symbol } => { + if self.synthetic_only("Watchlists") { + return; + } if !self.watchlist.add_symbol_to(list, &symbol) { self.notify(format!("{symbol} is already in that watchlist")); } @@ -3933,10 +4154,10 @@ impl DemoApp { || self.date_picker.is_open || self.replay_start.is_open || self.replay_selecting + || self.data_source.is_open() } fn handle_keyboard(&mut self, ctx: &egui::Context) { - use egui_charts::config::KeyboardAction as A; use egui_charts::widget::ShortcutRequest; self.chart.dispatch_shortcuts(ctx); self.sync_chart_history(); @@ -3952,94 +4173,103 @@ impl DemoApp { self.interval_entry = Some(text); self.interval_focus = true; } - ShortcutRequest::Action(action) => match action { - A::OpenQuickSearch => self.quick_search.open(), - A::ShowKeyboardHelp => self.keyboard_shortcuts.toggle(), - A::OpenIndicatorSearch => { - self.indicator_dialog.open_for_chart(&self.chart, None); - } - A::OpenSymbolSearch => self - .symbol_search - .open_with_selected_query(self.chart.symbol().to_owned()), - A::OpenIntervalSearch => { - self.interval_entry = Some(String::new()); - self.interval_focus = true; - } - A::GoToDate => self.date_picker.open(), - A::Snapshot => self.handle_top_toolbar(ctx, TopToolbarAction::TakeScreenshot), - A::SaveLayout => self.handle_top_toolbar(ctx, TopToolbarAction::Save), - A::OpenLayout => self.open_layout = true, - A::OpenDataWindow => self.open_panel = Some(SidePanel::DataWindow), - A::ToggleSession if DemoSymbol::has_hours(&self.state.symbol) => { - let session = - if self.timeframe_toolbar.state.session_type == SessionType::RTH { - SessionType::ETH - } else { - SessionType::RTH - }; - self.timeframe_toolbar.set_session(session); - self.stop_replay(); - self.apply_session(); - } - A::CreateAlert => { - let mapping = self.chart.get_chart_mapping(); - if let Some(pos) = ctx - .pointer_hover_pos() - .filter(|pos| mapping.rect.contains(*pos)) - { - if ctx - .layer_id_at(pos) - .is_some_and(|layer| layer.order == egui::Order::Background) - { - let price = mapping.y_to_price(pos.y); - if price.is_finite() { - self.quick_price_alert(self.chart.symbol().to_owned(), price); - } - } - } else { - self.open_alert(None); + ShortcutRequest::Action(action) => self.handle_shortcut_action(ctx, action), + _ => {} + } + } + } + + /// Runs a key binding the chart leaves to the host, as its key press would. + fn handle_shortcut_action( + &mut self, + ctx: &egui::Context, + action: egui_charts::config::KeyboardAction, + ) { + use egui_charts::config::KeyboardAction as A; + match action { + A::OpenQuickSearch => self.open_quick_search(), + A::ShowKeyboardHelp => self.keyboard_shortcuts.toggle(), + A::OpenIndicatorSearch => { + self.indicator_dialog.open_for_chart(&self.chart, None); + } + A::OpenSymbolSearch => self + .symbol_search + .open_with_selected_query(self.chart.symbol().to_owned()), + A::OpenIntervalSearch => { + self.interval_entry = Some(String::new()); + self.interval_focus = true; + } + A::GoToDate => self.date_picker.open(), + A::Snapshot => self.handle_top_toolbar(ctx, TopToolbarAction::TakeScreenshot), + A::SaveLayout => self.handle_top_toolbar(ctx, TopToolbarAction::Save), + A::OpenLayout => { + self.handle_layout_action(egui_charts::ui::top_toolbar::LayoutAction::OpenLayout) + } + A::OpenDataWindow => self.open_panel = Some(SidePanel::DataWindow), + A::ToggleSession if DemoSymbol::has_hours(&self.state.symbol) => { + let session = if self.timeframe_toolbar.state.session_type == SessionType::RTH { + SessionType::ETH + } else { + SessionType::RTH + }; + self.timeframe_toolbar.set_session(session); + self.stop_replay(); + self.apply_session(); + } + A::CreateAlert => { + let mapping = self.chart.get_chart_mapping(); + if let Some(pos) = ctx + .pointer_hover_pos() + .filter(|pos| mapping.rect.contains(*pos)) + { + if ctx + .layer_id_at(pos) + .is_some_and(|layer| layer.order == egui::Order::Background) + { + let price = mapping.y_to_price(pos.y); + if price.is_finite() { + self.quick_price_alert(self.chart.symbol().to_owned(), price); } } - A::MaximizeChart => { - self.handle_top_toolbar(ctx, TopToolbarAction::ToggleFullscreen) - } - A::CopyDrawing => match self.chart.copy_selected_drawings() { - Ok(Some(text)) => { - ctx.copy_text(text.clone()); - self.copied_drawing = Some(text); - self.copied_study = None; - } - Ok(None) => { - if let Some(egui_charts::widget::ChartElementId::Indicator(id)) = - self.chart.selected_element() - { - self.copy_study(ctx, id); - } - } - Err(error) => { - self.toasts - .error(format!("Could not copy drawings: {error}")); - } - }, - A::PasteDrawing => self.paste_drawing(), - A::CycleChartFocus | A::CycleChartFocusBack => { - let count = self - .layout - .mode - .chart_count() - .min(self.extra_charts.len() + 1); - let delta = if action == A::CycleChartFocus { - 1 - } else { - count - 1 - }; - self.activate_chart_slot((self.layout_slot + delta) % count); - self.layout.set_active(self.layout_slot); + } else { + self.open_alert(None); + } + } + A::MaximizeChart => self.handle_top_toolbar(ctx, TopToolbarAction::ToggleFullscreen), + A::CopyDrawing => match self.chart.copy_selected_drawings() { + Ok(Some(text)) => { + ctx.copy_text(text.clone()); + self.copied_drawing = Some(text); + self.copied_study = None; + } + Ok(None) => { + if let Some(egui_charts::widget::ChartElementId::Indicator(id)) = + self.chart.selected_element() + { + self.copy_study(ctx, id); } - _ => {} - }, - _ => {} + } + Err(error) => { + self.toasts + .error(format!("Could not copy drawings: {error}")); + } + }, + A::PasteDrawing => self.paste_drawing(), + A::CycleChartFocus | A::CycleChartFocusBack => { + let count = self + .layout + .mode + .chart_count() + .min(self.extra_charts.len() + 1); + let delta = if action == A::CycleChartFocus { + 1 + } else { + count - 1 + }; + self.activate_chart_slot((self.layout_slot + delta) % count); + self.layout.set_active(self.layout_slot); } + _ => {} } } @@ -4224,6 +4454,72 @@ fn panel_frame(bg: egui::Color32) -> egui::Frame { .inner_margin(egui::Margin::ZERO) } +/// Gives the price-based chart types of `chart` half the 14-bar average true range of the bars +/// on show, which suits any symbol, until a size is entered in the chart settings. +fn size_by_atr(chart: &mut Chart) { + let mut params = chart.chart_type_params().clone(); + let half_atr = BoxSizeMethod::Atr { + period: 14, + multiplier: 0.5, + }; + params.renko_size_method = half_atr; + params.kagi_size_method = half_atr; + params.range_size_method = half_atr; + params.pnf_size_method = half_atr; + chart.set_chart_type_params(params); +} + +/// The session a symbol opens in: around the clock where its market never closes, otherwise +/// the regular session. +fn opening_session(symbol: &str) -> SessionType { + if matches!(DemoSymbol::find(symbol).exchange, "Crypto" | "Forex") { + SessionType::Full24x7 + } else { + SessionType::RTH + } +} + +/// Reloads `chart` from `live` in `session`, with prices adjusted for dividends or not, in the +/// price unit the chart shows. +fn load_view(chart: &mut Chart, live: &LiveFeed, session: SessionType, adjusted: bool) { + live.set_view(session, adjusted); + let cents = chart.conversion().is_some_and(|c| c.starts_with("cents")); + live.set_price_unit(cents); + chart.set_conversion(replay::conversion(cents, adjusted)); + chart.reload_feed(); + chart.set_instrument(Some(live.instrument())); + chart.set_extended_hours(session != SessionType::RTH); +} + +/// The first instant of `date` on the chart's time axis. Where a clock change skips midnight +/// the day starts at the first time that exists, and a repeated midnight counts the first time. +fn day_start(chart: &Chart, date: chrono::NaiveDate) -> Option> { + use chrono::TimeZone; + use egui_charts::config::TimezoneMode; + let zone = match &chart.chart_options().time_scale.timezone { + TimezoneMode::Local => None, + // An instrument with a zone of its own is shown in it. + TimezoneMode::Exchange(fallback) => Some( + chart + .instrument() + .and_then(|instrument| instrument.time_zone.clone()) + .unwrap_or_else(|| fallback.clone()), + ), + zone => Some(zone.to_tz().unwrap_or_default()), + }; + let midnight = date.and_time(chrono::NaiveTime::MIN); + (0..=24 * 60 * 60).find_map(|second| { + let time = midnight.checked_add_signed(chrono::TimeDelta::seconds(second))?; + Some(match &zone { + Some(zone) => zone.from_local_datetime(&time).earliest()?.to_utc(), + None => chrono::Local + .from_local_datetime(&time) + .earliest()? + .to_utc(), + }) + }) +} + fn apply_timezone(chart: &mut Chart, toolbar: &mut TimeframeToolbar, name: &str) { use egui_charts::config::TimezoneMode; let timezone = if name == "UTC" { @@ -5079,6 +5375,116 @@ mod tests { } } + /// A card linking to a demo story shows that story, and its Open row opens only web links. + #[test] + fn post_cards_show_demo_stories_and_open_only_web_links() { + use egui_charts::drawings::DrawingToolType as Tool; + use egui_charts::model::PostLink; + for (link, content, opens) in [ + ( + "https://example.com/news/AAPL-0", + Some(( + "Apple Inc. extends gains as buyers return", + "Demo Wire", + "AAPL rose through the morning on steady volume, recovering the losses of the \ + previous session. Buyers held the price above the opening range into the \ + afternoon.", + )), + true, + ), + ("javascript://%0aalert(1)", None, false), + ] { + let ctx = egui::Context::default(); + let mut app = DemoApp::new_at( + &eframe::CreationContext::_new_kittest(ctx.clone()), + "2026-10-27T19:29:50Z".parse().unwrap(), + true, + ); + settle(&mut app, &ctx); + let frame = |app: &mut DemoApp, events| { + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(1440.0, 900.0), + )), + time: Some(ctx.input(|i| i.time) + 0.1), + events, + ..Default::default() + }, + |ui| { + app.chart.show(ui); + app.drain_chart_events(ui.ctx()); + }, + ); + let painted = std::mem::take(&mut output.shapes); + let commands = std::mem::take(&mut output.platform_output.commands); + output.drop_without_applying_deltas(); + (painted, commands) + }; + let button = |pos, pressed| egui::Event::PointerButton { + pos, + pressed, + button: egui::PointerButton::Primary, + modifiers: egui::Modifiers::NONE, + }; + frame(&mut app, vec![]); + app.chart + .drawings_mut() + .start_post_insertion(Tool::Tweet, PostLink::new(link)); + let rect = app.chart.get_rendered_price_rect(); + let pos = rect.min + rect.size() * egui::vec2(0.2, 0.3); + frame(&mut app, vec![egui::Event::PointerMoved(pos)]); + frame(&mut app, vec![button(pos, true)]); + frame(&mut app, vec![button(pos, false)]); + // The answer arrives at once and the next frame applies it; the clicks also expire. + let mut painted = Vec::new(); + for _ in 0..4 { + painted = frame(&mut app, vec![]).0; + } + let card = app + .chart + .drawings() + .drawings + .iter() + .find(|drawing| drawing.tool_type == Tool::Tweet) + .and_then(|drawing| drawing.post.as_ref()) + .expect("the placed card"); + let shown = card.content.as_ref(); + assert_eq!( + shown.map(|c| (c.title.as_str(), c.author.as_str(), c.text.as_str())), + content, + "{link}" + ); + assert!(shown.is_none_or(|c| c.picture.is_none())); + let open = painted + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) + if text.galley.text() == "Open" && rect.contains(text.pos) => + { + Some(egui::Rect::from_min_size(text.pos, text.galley.size()).center()) + } + _ => None, + }) + .expect("the card's Open row"); + let mut commands = frame( + &mut app, + vec![egui::Event::PointerMoved(open), button(open, true)], + ) + .1; + commands.extend(frame(&mut app, vec![button(open, false)]).1); + assert_eq!( + commands.iter().any(|command| matches!( + command, + egui::OutputCommand::OpenUrl(url) if url.url == link && url.new_tab + )), + opens, + "{link}" + ); + } + } + #[test] fn advancing_a_paused_sample_keeps_intermediate_bars() { let ctx = egui::Context::default(); @@ -6003,6 +6409,43 @@ mod tests { } } + /// Switching the theme, from the toolbar or by a search command, is no chart's undo step: + /// the Undo after it brings back the grid hidden and the axis text recoloured before it and + /// leaves both charts on the new theme's colours. + #[test] + fn switching_the_theme_is_no_undo_step_of_a_chart() { + let ctx = egui::Context::default(); + let mut app = DemoApp::new(&eframe::CreationContext::_new_kittest(ctx.clone())); + app.ensure_chart_slots(egui_charts::widget::ChartLayoutMode::TwoHorizontal); + settle(&mut app, &ctx); + for by_command in [false, true] { + // The theme replaces an edited colour, which must not make the switch a step either. + app.chart.user_action(|chart| { + chart.config_mut().show_grid = false; + chart.config_mut().text_color = egui::Color32::BLUE; + }); + let dark = app.theme.dark; + if by_command { + let command = if dark { + "appearance:light" + } else { + "appearance:dark" + }; + app.execute_search_command(&ctx, command); + } else { + app.handle_top_toolbar(&ctx, TopToolbarAction::ThemeToggle); + } + assert_ne!(app.theme.dark, dark, "by command {by_command}"); + app.handle_top_toolbar(&ctx, TopToolbarAction::Undo); + assert!(app.chart.config().show_grid, "by command {by_command}"); + for chart in [&app.chart, &app.extra_charts[0].chart] { + assert!(!chart.can_undo(), "by command {by_command}"); + assert_eq!(chart.config().background_color, app.theme.chart.bg); + assert_eq!(chart.config().text_color, app.theme.chart.axis_text); + } + } + } + #[test] fn legacy_themes_follow_system_and_new_choices_survive_restart() { // Repeated construction used to overflow this stack before checking the saved theme. @@ -6568,37 +7011,43 @@ mod tests { } } - /// A bare number enters minutes and Enter applies it through the normal host path. + /// Keys arrive one a frame, as a keyboard sends them. A bare number enters minutes, a comma + /// opens the field for an interval with a unit, and Enter applies either through the normal + /// host path. #[test] fn typed_interval_entry_applies_minutes() { use eframe::App; - let ctx = egui::Context::default(); - let mut app = DemoApp::new(&eframe::CreationContext::_new_kittest(ctx.clone())); - app.live.set_paused(true); - for events in [ - vec![egui::Event::Text("15".into())], - vec![], - vec![egui::Event::Key { + let typed = |keys: &[&str]| { + let ctx = egui::Context::default(); + let mut app = DemoApp::new(&eframe::CreationContext::_new_kittest(ctx.clone())); + app.live.set_paused(true); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE, - }], - ] { - ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(1440.0, 900.0), - )), - events, - ..Default::default() - }, - |ui| app.ui(ui, &mut eframe::Frame::_new_kittest()), - ) - .drop_without_applying_deltas(); - } + }; + let keys = keys.iter().map(|key| egui::Event::Text((*key).into())); + for event in keys.chain([enter]) { + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(1440.0, 900.0), + )), + events: vec![event], + ..Default::default() + }, + |ui| app.ui(ui, &mut eframe::Frame::_new_kittest()), + ) + .drop_without_applying_deltas(); + } + (ctx, app) + }; + let (_, app) = typed(&[",", "2", "h"]); + assert_eq!(app.state.timeframe.duration_ms(), 7_200_000); + let (ctx, mut app) = typed(&["1", "5"]); assert_eq!(app.state.timeframe, Timeframe::Min15); assert_eq!(app.state.timeframe.duration_ms(), 900_000); assert_eq!(app.chart.timeframe(), Some(Timeframe::Min15)); @@ -6703,6 +7152,9 @@ mod tests { "Yield curve", "Primitives and custom series", "Sample study editor", + "Undo", + "Take a snapshot", + "Toggle percent scale", ] .into_iter() .flat_map(|query| { @@ -6718,7 +7170,11 @@ mod tests { app.live.set_paused(true); if matches!( query, - "RSI" | "Volatility smile" | "Yield curve" | "Primitives and custom series" + "RSI" + | "Volatility smile" + | "Yield curve" + | "Primitives and custom series" + | "Undo" ) { app.chart.user_action(|chart| { let dm = chart.drawings_mut(); @@ -6824,6 +7280,12 @@ mod tests { app.chart.drawings().active_tool(), Some(egui_charts::drawings::DrawingToolType::TrendLine) ), + "Undo" => assert!(app.chart.drawings().drawings.is_empty()), + "Take a snapshot" => assert!(app.screenshot_requested.is_some()), + "Toggle percent scale" => assert_eq!( + app.chart.state().price_scale().options().mode, + egui_charts::scales::PriceScaleMode::Percentage + ), "Sample backtest" => { let output = ctx.run_ui(RawInput::default(), |ui| { app.ui(ui, &mut eframe::Frame::_new_kittest()); @@ -7734,7 +8196,7 @@ mod tests { state.grid_lines.vertical_color = egui::Color32::BLUE; state.margins.top_percent = 12.5; state.margins.bottom_percent = 7.5; - state.margins.right_bars = 17; + state.margins.right_bars = 17.0; state.trading.show_positions = false; state.trading.show_orders = false; state.trading.show_executions = false; @@ -8664,12 +9126,11 @@ mod tests { account_size: 10_000.0, percent: 1.0, }); - settings.position_sizing = PositionSizing { - point_value: 50.0, - lot_size: 10.0, - quantity_step: 0.01, - leverage: 5.0, - }; + settings.position_sizing = PositionSizing::default(); + settings.position_sizing.point_value = 50.0; + settings.position_sizing.lot_size = 10.0; + settings.position_sizing.quantity_step = 0.01; + settings.position_sizing.leverage = 5.0; let sizing = settings.position_sizing; settings.volume_profile = VolumeProfileConfig::new(48, 0.8); settings.regression_trend = RegressionTrendConfig::new(3.0); @@ -9231,7 +9692,7 @@ mod tests { let (shown_start, shown_end) = app.chart.state().visible_range(); assert_eq!(shown_end, end, "{range:?}"); assert!(shown_start.abs_diff(start) <= 1, "{range:?}"); - let expected = app.chart.get_rendered_price_rect().width() + let expected = (app.chart.get_rendered_price_rect().width() - 1.0) / ((end - start) as f32 + 0.5); assert!((app.chart.get_time_scale_state().0 - expected).abs() < 0.001); assert_eq!(app.replay.is_some(), replay); @@ -9276,6 +9737,141 @@ mod tests { } } } + + /// A size entered in the chart settings is the user's: no chart type, interval or symbol + /// choice replaces it. The types without an entered size keep a size taken from the bars on + /// show. + #[test] + fn entered_price_based_sizes_survive_navigation() { + let ctx = egui::Context::default(); + let mut app = DemoApp::new(&eframe::CreationContext::_new_kittest(ctx.clone())); + settle(&mut app, &ctx); + app.handle_top_toolbar(&ctx, TopToolbarAction::ChartStyleSelected(ChartType::Kagi)); + let mut settings = ChartSettingsState::from_chart(&app.chart); + let params = settings.chart_type_params.as_mut().unwrap(); + params.kagi_size_method = BoxSizeMethod::Fixed; + params.kagi_reversal = 12.5; + app.apply_chart_settings(settings); + assert_eq!(app.chart.chart_type_params().kagi_reversal, 12.5); + let sample_brick = app.chart.chart_type_params().renko_brick_size; + for change in ["Point and Figure", "Kagi", "one hour", "BTCUSD"] { + match change { + "Point and Figure" => app.handle_top_toolbar( + &ctx, + TopToolbarAction::ChartStyleSelected(ChartType::PointAndFigure), + ), + "Kagi" => app.handle_top_toolbar( + &ctx, + TopToolbarAction::ChartStyleSelected(ChartType::Kagi), + ), + "one hour" => app + .handle_top_toolbar(&ctx, TopToolbarAction::IntervalSelected(Timeframe::Hour1)), + symbol => app.switch_symbol(symbol), + } + settle(&mut app, &ctx); + let params = app.chart.chart_type_params(); + assert_eq!(params.kagi_size_method, BoxSizeMethod::Fixed, "{change}"); + assert_eq!(params.kagi_reversal, 12.5, "{change}"); + } + // Bitcoin trades far above the sample symbol, and its bricks are sized to match. + let close = app.chart.bars(SeriesId::MAIN).last().unwrap().close; + let brick = app.chart.chart_type_params().renko_brick_size; + assert!( + brick > sample_brick && brick < close / 10.0, + "{sample_brick} {brick} {close}" + ); + } + + /// A chart that follows a linked symbol change loads the symbol in the session its market + /// trades, as the active chart does, and both keep the same bars at a linked interval. + #[test] + fn linked_symbol_change_loads_the_new_symbols_session() { + let ctx = egui::Context::default(); + let mut app = DemoApp::new(&eframe::CreationContext::_new_kittest(ctx.clone())); + app.live.set_paused(true); + settle(&mut app, &ctx); + app.ensure_chart_slots(egui_charts::widget::ChartLayoutMode::TwoHorizontal); + app.layout.sync.sync_symbol = true; + app.layout.sync.sync_timeframe = true; + app.top_toolbar.chart_grid_selector.sync = app.layout.sync.clone(); + settle(&mut app, &ctx); + let span = |chart: &Chart| { + let bars = chart.bars(SeriesId::MAIN); + let times = bars.first().zip(bars.last()).map(|(a, b)| (a.time, b.time)); + (chart.symbol().to_owned(), bars.len(), times) + }; + for step in ["MSFT", "one hour"] { + if step == "MSFT" { + app.switch_symbol("MSFT"); + } else { + app.handle_top_toolbar(&ctx, TopToolbarAction::IntervalSelected(Timeframe::Hour1)); + } + settle(&mut app, &ctx); + assert_eq!(span(&app.extra_charts[0].chart), span(&app.chart), "{step}"); + } + } + + /// A new session shows the navigation row while the pointer is over the main pane only. + #[test] + fn new_session_shows_navigation_buttons_on_hover() { + use eframe::App; + let ctx = egui::Context::default(); + let mut app = DemoApp::new(&eframe::CreationContext::_new_kittest(ctx.clone())); + app.live.set_paused(true); + settle(&mut app, &ctx); + let pane = app.chart.get_rendered_price_rect().center(); + for (pointer, shown) in [(pane, true), (egui::pos2(700.0, 15.0), false)] { + let output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(1440.0, 900.0), + )), + events: vec![egui::Event::PointerMoved(pointer)], + ..Default::default() + }, + |ui| app.ui(ui, &mut eframe::Frame::_new_kittest()), + ); + // The row's logarithmic toggle is the only "log" the demo paints. + let painted = output.shapes.iter().any(|shape| { + matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == "log") + }); + output.drop_without_applying_deltas(); + assert_eq!(painted, shown, "{pointer:?}"); + } + } + + /// A day picked in the dialog is a day on the chart's clock. New York is five hours behind + /// UTC in November, so its 10 November starts at 05:00 UTC, and the days 9 and 10 November + /// run from 05:00 UTC on the 9th to 05:00 UTC on the 11th. + #[test] + fn date_picker_days_follow_the_chart_time_zone() { + let ctx = egui::Context::default(); + let cc = eframe::CreationContext::_new_kittest(ctx.clone()); + let mut app = DemoApp::new_at(&cc, "2026-11-12T15:00:00Z".parse().unwrap(), true); + settle(&mut app, &ctx); + apply_timezone( + &mut app.chart, + &mut app.timeframe_toolbar, + "America/New_York", + ); + let day = |day| chrono::NaiveDate::from_ymd_opt(2026, 11, day).unwrap(); + let near = |time: chrono::DateTime, expected: &str| { + let expected: chrono::DateTime = expected.parse().unwrap(); + (time - expected).abs() <= chrono::TimeDelta::minutes(5) + }; + app.go_to_date(day(10)); + settle(&mut app, &ctx); + let span = app.chart.visible_time_range().unwrap(); + let centre = span.from + (span.to - span.from) / 2; + assert!(near(centre, "2026-11-10T05:00:00Z"), "{span:?}"); + app.set_date_range(day(9), day(10)); + settle(&mut app, &ctx); + let span = app.chart.visible_time_range().unwrap(); + assert!(near(span.from, "2026-11-09T05:00:00Z"), "{span:?}"); + assert!(near(span.to, "2026-11-11T05:00:00Z"), "{span:?}"); + } + /// Selecting seconds must rebuild the same executions, including the current partial minute. #[test] fn interval_switch_rebuilds_the_same_executions() { @@ -9313,7 +9909,7 @@ mod tests { let mut params = app.chart.chart_type_params().clone(); params.range_size = 1.0; app.chart.set_chart_type_params(params); - app.size_price_based_charts(); + app.size_range_interval(); assert!((app.chart.chart_type_params().range_size - ticks * tick_size).abs() < 1e-10); } app.switch_timeframe(Timeframe::Min1); diff --git a/vendor/egui-charts/examples/demo/feeds.rs b/vendor/egui-charts/examples/demo/feeds.rs index 528a6be..171a97d 100644 --- a/vendor/egui-charts/examples/demo/feeds.rs +++ b/vendor/egui-charts/examples/demo/feeds.rs @@ -10,9 +10,9 @@ use egui_charts::data::{ Importance, NewsQuery, NewsStory, Reply, ScreenerColumn, ScreenerColumnSet, ScreenerOp, ScreenerQuery, ScreenerRow, }; -use egui_charts::model::{Bar, Quote}; +use egui_charts::model::{Bar, PostContent, Quote}; use egui_charts::services::{ - ChatEvent, ChatMessage, Chats, Events, Notification, Notifications, Quotes, + ChatEvent, ChatMessage, Chats, Events, Notification, Notifications, Posts, Quotes, }; use egui_charts::ui::widget_bar::{PeriodReturn, Seasonality, SeasonalityMonth}; @@ -296,26 +296,30 @@ const HIGHLIGHTS: &[(&str, &str)] = &[ /// Up to `query.limit` synthetic stories, newest first, published on the hour before `now`. pub(super) fn news(query: &NewsQuery, now: DateTime) -> Vec { - let symbols: Vec<&DemoSymbol> = if query.symbols.is_empty() { + let mut stories = stories(&query.symbols, query.highlights, now); + stories.sort_by(|a, b| b.time.cmp(&a.time)); + stories.truncate(query.limit); + stories +} + +/// The synthetic headlines, or highlights, of `symbols`, or of every catalog symbol when it is +/// empty, published on the hour before `now`. +fn stories(symbols: &[String], highlights: bool, now: DateTime) -> Vec { + let specs: Vec<&DemoSymbol> = if symbols.is_empty() { DemoSymbol::catalog().iter().collect() } else { DemoSymbol::catalog() .iter() .filter(|spec| { - query - .symbols + symbols .iter() .any(|symbol| spec.symbol.eq_ignore_ascii_case(symbol)) }) .collect() }; - let templates = if query.highlights { - HIGHLIGHTS - } else { - HEADLINES - }; + let templates = if highlights { HIGHLIGHTS } else { HEADLINES }; let hour = now.duration_trunc(TimeDelta::hours(1)).unwrap_or(now); - let mut stories: Vec = symbols + specs .iter() .flat_map(|spec| { templates @@ -336,10 +340,28 @@ pub(super) fn news(query: &NewsQuery, now: DateTime) -> Vec { story }) }) - .collect(); - stories.sort_by(|a, b| b.time.cmp(&a.time)); - stories.truncate(query.limit); - stories + .collect() +} + +/// Resolves the links of post and idea cards that name a demo news story into that story, as a +/// host would from its own feed. The demo has no content for other links. +pub(super) struct DemoPosts; + +impl Posts for DemoPosts { + fn resolve(&self, link: &str, reply: Reply) { + let story = stories(&[], false, Utc::now()) + .into_iter() + .find(|story| story.url.as_deref() == Some(link)); + reply.send( + story + .map(|story| { + let mut content = PostContent::new(story.source, story.time, story.body); + content.title = story.headline; + content + }) + .ok_or(FeedError::NotSupported), + ); + } } /// The countries the demo calendar knows. @@ -991,23 +1013,16 @@ mod tests { crate::sampledata::us_equity_session(), false, ); + let mut shifted = daily.clone(); + shifted.time = "2026-11-02T05:00:00Z".parse().unwrap(); assert_eq!( crate::sampledata::calendar_history(&[daily.clone()], &[], clock.clone()), - vec![Bar { - time: "2026-11-02T05:00:00Z".parse().unwrap(), - ..daily.clone() - }] + vec![shifted] ); + let mut sunday = daily; + sunday.time = "2026-11-01T00:00:00Z".parse().unwrap(); assert!( - crate::sampledata::calendar_history( - &[Bar { - time: "2026-11-01T00:00:00Z".parse().unwrap(), - ..daily - }], - &[], - clock - ) - .is_empty(), + crate::sampledata::calendar_history(&[sunday], &[], clock).is_empty(), "a shifted stock calendar must not invent Sunday bars" ); let feed = Arc::new(LiveFeed::new("SAMPLE", now)); diff --git a/vendor/egui-charts/examples/demo/interval.rs b/vendor/egui-charts/examples/demo/interval.rs index 409dfc8..66141b5 100644 --- a/vendor/egui-charts/examples/demo/interval.rs +++ b/vendor/egui-charts/examples/demo/interval.rs @@ -17,14 +17,24 @@ impl super::DemoApp { .show(ctx, &mut open, |ui| { ui.label("Minutes, or an interval such as 30s, 2h, 1D, 10T, 100V, 10R or 100delta"); let input_id = egui::Id::unique("interval_entry_input"); - if std::mem::take(&mut self.interval_focus) { + // The dialog is laid out unseen in its first frame, where a field cannot take + // focus: ask until the field has it, with the caret after the typed text. + if self.interval_focus { ui.memory_mut(|memory| memory.request_focus(input_id)); + let mut state = + egui::TextEdit::load_state(ui.ctx(), input_id).unwrap_or_default(); + let end = egui::text::CCursor::end_of_str(&text); + state + .cursor + .set_char_range(Some(egui::text::CCursorRange::one(end))); + state.store(ui.ctx(), input_id); } - ui.add( + let field = ui.add( egui::TextEdit::singleline(&mut text) .id(input_id) .desired_width(ui.available_width()), ); + self.interval_focus &= !field.has_focus(); apply = DialogFooter::new("Apply").show(ui).0 || ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); }); diff --git a/vendor/egui-charts/examples/demo/layouts.rs b/vendor/egui-charts/examples/demo/layouts.rs index a36b0ac..3b3b998 100644 --- a/vendor/egui-charts/examples/demo/layouts.rs +++ b/vendor/egui-charts/examples/demo/layouts.rs @@ -155,6 +155,7 @@ impl DemoApp { .then(|| self.notification_host.clone()), times: Default::default(), }))); + chart.set_post_source(Some(Arc::new(super::feeds::DemoPosts))); if let Some(scale) = source.series_scale(SeriesId::MAIN) { chart.set_series_scale(SeriesId::MAIN, scale); } else { @@ -250,7 +251,7 @@ impl DemoApp { } } - fn refresh_active_chart(&mut self) { + pub(super) fn refresh_active_chart(&mut self) { self.comparison_settings = None; self.refresh_strategy_signals(); self.last_chart_click = None; @@ -267,8 +268,10 @@ impl DemoApp { egui_charts::ui::Control::Session, egui_charts::ui::Control::DividendAdjustment, ] { - self.timeframe_toolbar - .set_control_visible(control, DemoSymbol::has_hours(&self.state.symbol)); + self.timeframe_toolbar.set_control_visible( + control, + self.own_data.is_none() && DemoSymbol::has_hours(&self.state.symbol), + ); } let (session, adjusted) = self.live.view(self.chart.extended_hours()); self.timeframe_toolbar.set_session(session); @@ -282,7 +285,7 @@ impl DemoApp { } pub(super) fn show_layout_tabs(&mut self, ui: &mut egui::Ui) { - if self.layout_tabs.len() <= 1 { + if self.layout_tabs.len() <= 1 || self.own_data.is_some() { return; } let bars = self.chart.bars(SeriesId::MAIN); @@ -381,7 +384,43 @@ impl DemoApp { }); self.layout_tab = index; self.refresh_layout_menu(); - // Other tabs may have edited the same symbol since this tab was last shown. + self.refresh_workspace(); + } + + /// Sets the active tab's workspace aside in the tab's own slot, where an inactive tab keeps + /// its workspace, and shows `chart` alone. Theme and number format changes therefore keep + /// reaching the charts set aside. Nothing is saved or stopped here. + pub(super) fn park_workspace(&mut self, chart: Chart) { + let workspace = Workspace { + chart: std::mem::replace(&mut self.chart, chart), + live: self.live.clone(), + comparisons: std::mem::take(&mut self.comparisons), + spreads: std::mem::take(&mut self.spreads), + extra: std::mem::take(&mut self.extra_charts), + layout: std::mem::take(&mut self.layout), + slot: std::mem::take(&mut self.layout_slot), + }; + self.layout_tabs[self.layout_tab].workspace = Some(workspace); + } + + /// Brings back the workspace `park_workspace` set aside and points the toolbars at it. + pub(super) fn resume_workspace(&mut self) { + let Some(workspace) = self.layout_tabs[self.layout_tab].workspace.take() else { + return; + }; + self.chart = workspace.chart; + self.live = workspace.live; + self.comparisons = workspace.comparisons; + self.spreads = workspace.spreads; + self.extra_charts = workspace.extra; + self.layout = workspace.layout; + self.layout_slot = workspace.slot; + self.refresh_workspace(); + } + + /// Points storage, the toolbars and the grid selector at the workspace on show. + fn refresh_workspace(&mut self) { + // Other tabs may have edited the same symbol since this workspace was last shown. self.chart.set_storage(self.storage.clone()); for chart in &mut self.extra_charts { chart.chart.set_storage(self.storage.clone()); @@ -484,6 +523,15 @@ impl DemoApp { } pub(super) fn handle_layout_action(&mut self, action: LayoutAction) { + // While own data is on, nothing selects, creates, restores or saves a layout: the + // synthetic workspace waits in the slot of the active tab. + if !matches!( + action, + LayoutAction::DownloadData | LayoutAction::DownloadImage | LayoutAction::None + ) && self.synthetic_only("Layouts") + { + return; + } match action { LayoutAction::SelectGrid(mode) => { self.grid_edits += 1; @@ -637,6 +685,9 @@ impl DemoApp { /// Saves the open layout under its tab's name. fn save_layout(&mut self) { + if self.own_data.is_some() { + return; + } let name = self.layout_tabs[self.layout_tab].name.clone(); match self.capture_layout() { Ok(layout) => match self.save_comparisons(&name) { @@ -791,12 +842,12 @@ impl DemoApp { } self.refresh_active_chart(); self.apply_formatting(); - self.settings_state = egui_charts::widget::settings::ChartSettingsState { - alerts: self.settings_state.alerts.clone(), - trading: self.trading.display.clone(), - adjust_for_dividends: self.timeframe_toolbar.state.adjust_for_dividends, - ..egui_charts::widget::settings::ChartSettingsState::from_chart(&self.chart) - }; + let mut settings = + egui_charts::widget::settings::ChartSettingsState::from_chart(&self.chart); + settings.alerts = self.settings_state.alerts.clone(); + settings.trading = self.trading.display.clone(); + settings.adjust_for_dividends = self.timeframe_toolbar.state.adjust_for_dividends; + self.settings_state = settings; true } @@ -807,6 +858,13 @@ impl DemoApp { settings.theme = self.theme_choice.clone(); settings.symbol = Some(self.state.symbol.clone()); settings.interval = Some(self.state.timeframe); + if self.own_data.is_some() + && let Some(parked) = &self.layout_tabs[self.layout_tab].workspace + { + // The visitor's symbol is not a symbol of the synthetic session. + settings.symbol = Some(parked.chart.symbol().to_owned()); + settings.interval = parked.chart.timeframe(); + } let toolbar = &self.drawing_toolbar.state; settings.drawing_favorites = toolbar.favorites.clone(); settings.cursor_favorites = toolbar.cursor_favorites.clone(); @@ -1186,13 +1244,13 @@ mod tests { app.chart .user_action(|chart| chart.drawings_mut().add_synced_drawing(drawing).unwrap()); assert!(app.chart.flush_stored_drawings()); - app.chart.drawings_mut().registry.set_availability( - egui_charts::drawings::DrawingToolType::TrendLine, - egui_charts::drawings::ToolAvailability { - visible: false, - enabled: false, - }, - ); + let mut hidden = egui_charts::drawings::ToolAvailability::default(); + hidden.visible = false; + hidden.enabled = false; + app.chart + .drawings_mut() + .registry + .set_availability(egui_charts::drawings::DrawingToolType::TrendLine, hidden); app.chart.set_main_series_visible(false); app.chart .set_event_visibility(egui_charts::model::EventVisibility { diff --git a/vendor/egui-charts/examples/demo/live.rs b/vendor/egui-charts/examples/demo/live.rs index f1049a1..fa5da4b 100644 --- a/vendor/egui-charts/examples/demo/live.rs +++ b/vendor/egui-charts/examples/demo/live.rs @@ -38,6 +38,9 @@ const CHURN_PER_TRADE: usize = 6; /// The instrument whose feed sends individual orders instead of aggregate depth. pub(super) const ORDER_LEVEL_SYMBOL: &str = "ESZ2026"; +/// The only demo symbol whose feed answers analyst price targets. +pub(super) const TARGETS_SYMBOL: &str = "SAMPLE"; + /// Driven by the UI timer on both native and web; there is no background worker. pub(super) struct LiveFeed( Mutex, @@ -1424,17 +1427,18 @@ fn push_snapshot(sub: &Subscription, market: &Market, orders: Option<&Orders>, t } fn live_signal(time: DateTime, price: f64) -> Signal { - Signal { - id: SignalId("live".into()), - shape: SignalShape::Marker { + let mut signal = Signal::new( + SignalId("live".into()), + SignalShape::Marker { time, price: Some(price), direction: Direction::Neutral, }, - category: "Live analytics".into(), - label: Some("Host tick".into()), - tooltip: Some("Synthetic analytics updated by the demo host.".into()), - } + "Live analytics", + ); + signal.label = Some("Host tick".into()); + signal.tooltip = Some("Synthetic analytics updated by the demo host.".into()); + signal } impl Signals for LiveFeed { @@ -1447,28 +1451,30 @@ impl Signals for LiveFeed { if let Some(last) = bars.last() { events.push(SignalEvent::Upsert(live_signal(last.time, last.close))); let first = &bars[bars.len().saturating_sub(20)]; - events.push(SignalEvent::Upsert(Signal { - id: SignalId("zone".into()), - shape: SignalShape::Zone { + let mut signal = Signal::new( + SignalId("zone".into()), + SignalShape::Zone { from: first.time, to: Some(last.time), low: first.low, high: first.high, }, - category: "Zones".into(), - label: Some("Host zone".into()), - tooltip: Some("A price zone supplied by the demo host.".into()), - })); - events.push(SignalEvent::Upsert(Signal { - id: SignalId("level".into()), - shape: SignalShape::Level { + "Zones", + ); + signal.label = Some("Host zone".into()); + signal.tooltip = Some("A price zone supplied by the demo host.".into()); + events.push(SignalEvent::Upsert(signal)); + let mut signal = Signal::new( + SignalId("level".into()), + SignalShape::Level { price: first.high, from: Some(first.time), }, - category: "Levels".into(), - label: Some("Host level".into()), - tooltip: Some("A level supplied by the demo host.".into()), - })); + "Levels", + ); + signal.label = Some("Host level".into()); + signal.tooltip = Some("A level supplied by the demo host.".into()); + events.push(SignalEvent::Upsert(signal)); } self.state().signals.push(events); } @@ -1548,7 +1554,7 @@ impl Datafeed for LiveFeed { } fn price_targets(&self, symbol: &str, reply: Reply) { - if symbol != "SAMPLE" { + if symbol != TARGETS_SYMBOL { reply.send(Err(FeedError::NotSupported)); return; } diff --git a/vendor/egui-charts/examples/demo/marks.rs b/vendor/egui-charts/examples/demo/marks.rs index 9494678..330626a 100644 --- a/vendor/egui-charts/examples/demo/marks.rs +++ b/vendor/egui-charts/examples/demo/marks.rs @@ -22,6 +22,9 @@ impl DemoApp { /// fill and a stop marked at their prices, marks of the live changes of the close, signal bar /// marks, a watermark of the symbol and its company and the demo level at the recent high. pub(super) fn annotate(&mut self) { + if self.own_data.is_some() { + return; + } let samples = self.api_samples; self.refresh_strategy_signals(); self.chart.set_mark_source(Some(Arc::new(DemoMarks { diff --git a/vendor/egui-charts/examples/demo/owndata/app.rs b/vendor/egui-charts/examples/demo/owndata/app.rs new file mode 100644 index 0000000..873019a --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/app.rs @@ -0,0 +1,342 @@ +//! The application's side of own data: entering and leaving it, the Data source dialog's place +//! in the frame, and the one question the rest of the demo asks, whether a feature belongs to +//! the synthetic session. + +use std::sync::Arc; + +use egui_charts::ui::top_toolbar::LayoutAction; +use egui_charts::ui::top_toolbar::components::SymbolSearchDialog; +use egui_charts::widget::SeriesId; + +use super::super::DemoApp; +use super::Secrets; +use super::dialog::Outcome; +use super::feed::MappedFeed; +use super::profile::Profile; + +/// What the application keeps while the chart shows a visitor's own data. +pub(crate) struct OwnData { + /// The profile on the chart. + pub(crate) profile: Profile, + /// The feed of the chart, read by time and sales. + pub(crate) feed: Arc, + /// Whether the user paused the feed from the menu. The chart has no getter for it. + pub(crate) paused: bool, + /// Whether the synthetic feed was paused when own data was entered. Leaving restores it. + pub(crate) synthetic_paused: bool, + /// The feed error shown last, so that a standing error is notified once. + pub(crate) reported: Option, + /// True from a symbol or interval change until its first bars arrive. A range interval + /// then takes its size in ticks of the instrument. + pub(crate) sizing: bool, + /// The symbol search of the synthetic session, set aside while own data is on. + pub(crate) search: SymbolSearchDialog, +} + +impl DemoApp { + /// Draws the Data source dialog and carries out what it decides. Its first call also asks + /// the dialog what the saved state wants at the start, and every call notifies a new error + /// of the own-data feed. Called as the last statement of `show_dialogs`. + pub(crate) fn show_data_source(&mut self, ctx: &egui::Context) { + if let Some(outcome) = self.data_source.startup() { + self.carry_out(outcome); + } + let running = match self.own_data { + Some(_) => self.chart.feed_state(SeriesId::MAIN), + None => None, + }; + if let Some(outcome) = self.data_source.show(ctx, running) { + self.carry_out(outcome); + } + if let Some(own) = &mut self.own_data { + let feed = self.chart.feed_state(SeriesId::MAIN); + let error = feed.and_then(|feed| feed.last_error.as_ref()); + let error = error.map(ToString::to_string); + // A standing error is notified once, and again when it comes back after a recovery. + if error != own.reported { + if let Some(error) = &error { + self.toasts.error(error.clone()); + } + own.reported = error; + } + } + } + + /// Carries out what the Data source dialog decided. + fn carry_out(&mut self, outcome: Outcome) { + match outcome { + Outcome::Connect { profile, secrets } => self.connect_own_data(*profile, secrets), + Outcome::Synthetic => self.leave_own_data(), + Outcome::Export { file, text } => self.save_text(&file, &text), + } + } + + /// Sets the synthetic workspace aside and shows `profile` on one chart, read with + /// `secrets`. While own data is already on, only the chart is replaced. + pub(crate) fn connect_own_data(&mut self, profile: Profile, secrets: Secrets) { + // The dialog connects only a profile without a problem. This keeps the indexing below + // safe for every other caller. + if profile.problem().is_some() { + return; + } + if self.own_data.is_none() { + // What a layout switch does first, so that the synthetic workspace is stored as it + // is left. + self.stop_replay(); + if self.top_toolbar.layout_menu.autosave { + self.handle_layout_action(LayoutAction::Save); + } + self.checkpoint_workspace(); + // These show synthetic figures outside the workspace. They are closed, not set + // aside. + self.stop_live_strategy(); + self.strategy_report.set_report(None, &[]); + self.strategy_trade = None; + self.refresh_strategy_signals(); + self.financials = None; + self.watchlist_wide = false; + self.annotation_editor = false; + self.timeframe_toolbar.state.session_menu_open = false; + self.loading_bars = false; + } + // A reconnect stays on the symbol and interval on show when the profile still offers + // them. + let shown = self.own_data.as_ref(); + let symbol = shown.map(|_| self.chart.symbol().to_owned()); + let symbol = symbol.filter(|symbol| profile.symbols.contains(symbol)); + let symbol = symbol.unwrap_or_else(|| profile.symbols[0].clone()); + let timeframe = shown.and_then(|_| self.chart.timeframe()); + let timeframe = + timeframe.filter(|timeframe| profile.service_interval(*timeframe).is_some()); + let timeframe = timeframe.unwrap_or(profile.intervals[0].chart); + let intervals = profile.intervals.iter().map(|interval| interval.chart); + let intervals = intervals.collect(); + let feed = Arc::new(MappedFeed::new(profile.clone(), secrets)); + let mut chart = egui_charts::ChartBuilder::new() + .with_feed(feed.clone()) + .with_symbol(symbol) + .with_timeframe(timeframe) + .with_theme(self.theme.clone()) + .with_config(self.chart.config().clone()) + .with_chart_options(self.chart.chart_options().clone()) + .with_drawing_registry(self.chart.drawings().registry.clone()) + .with_visible_candles(0) + .build(); + self.formatting.apply(&mut chart); + super::super::size_by_atr(&mut chart); + chart.set_event_visibility(self.chart.event_visibility().clone()); + chart.drawings_mut().tool_defaults = self.chart.drawings().tool_defaults.clone(); + // Bars are dated in the profile's zone, so the chart starts in it. + let zone = profile.time_zone.name(); + super::super::apply_timezone(&mut chart, &mut self.timeframe_toolbar, zone); + if let Some(own) = &mut self.own_data { + // Dropping the previous chart ends its subscriptions, which closes its socket. + self.chart = chart; + own.profile = profile; + own.feed = feed; + own.paused = false; + own.reported = None; + own.sizing = true; + } else { + let synthetic_paused = self.live.paused(); + self.live.set_paused(true); + self.park_workspace(chart); + let search = std::mem::replace(&mut self.symbol_search, SymbolSearchDialog::new()); + self.own_data = Some(OwnData { + profile, + feed, + paused: false, + synthetic_paused, + reported: None, + sizing: true, + search, + }); + } + let selector = &mut self.top_toolbar.timeframe_selector; + selector.set_supported_timeframes(Some(intervals)); + self.refresh_active_chart(); + let grid = &mut self.top_toolbar.chart_grid_selector; + grid.set_layout(self.layout.mode); + grid.sync = self.layout.sync.clone(); + } + + /// Drops the own-data chart, which closes its stream, and brings the synthetic workspace + /// back as it was left. Does nothing on synthetic data. + pub(crate) fn leave_own_data(&mut self) { + let Some(own) = self.own_data.take() else { + return; + }; + // Preferences the application saves from the chart on show: they follow it both ways. + let events = self.chart.event_visibility().clone(); + let tool_defaults = self.chart.drawings().tool_defaults.clone(); + self.symbol_search = own.search; + let selector = &mut self.top_toolbar.timeframe_selector; + selector.set_supported_timeframes(None); + // Drops the own-data chart: its subscriptions end and its socket closes. + self.resume_workspace(); + self.chart.set_event_visibility(events); + self.chart.drawings_mut().tool_defaults = tool_defaults; + self.live.set_paused(own.synthetic_paused); + let zone = self.chart.chart_options().time_scale.timezone.to_tz(); + let zone = zone.map_or_else(|| "UTC".to_owned(), |zone| zone.name().to_owned()); + self.timeframe_toolbar.set_timezone(zone); + // The frame then reads the bars, sizes the price-based chart types and annotates, + // once. + self.loading_bars = true; + } + + /// True while own data is on, after telling the user that `feature` works on synthetic + /// data only. Every entry point of a feature that reads the synthetic session starts with + /// `if self.synthetic_only("..") { return; }`. + pub(crate) fn synthetic_only(&mut self, feature: &str) -> bool { + if self.own_data.is_none() { + return false; + } + self.toasts.info(format!( + "{feature}: available on synthetic data only. Open Data source in the menu to \ + switch back." + )); + true + } +} + +#[cfg(test)] +mod tests { + use egui_charts::Chart; + use egui_charts::model::Timeframe; + use egui_charts::ui::top_toolbar::CompareAction; + + use super::super::super::tests::{AppStorage, settle}; + use super::super::feed::tests::{Server, Shown, pages, profile, shown, until}; + use super::*; + + /// Entering own data shows one chart on the visitor's data and leaves the synthetic session + /// untouched: stored as it was left, paused, and back exactly as it was when the visitor + /// leaves. In between, what belongs to the synthetic session refuses. + #[test] + fn own_data_sets_the_synthetic_workspace_aside_and_brings_it_back() { + const J3: &str = r#"{"t":1794407580,"o":100.75,"h":103.0,"l":100.5,"c":102.5,"v":1500}"#; + const J4: &str = r#"{"t":1794407640,"o":102.5,"h":102.75,"l":101.0,"c":101.25,"v":800}"#; + const J5: &str = r#"{"t":1794407700,"o":101.25,"h":101.5,"l":100.0,"c":100.25,"v":700}"#; + const B3: Shown = (1794407580, Some([100.75, 103.0, 100.5, 102.5, 1500.0])); + const B4: Shown = (1794407640, Some([102.5, 102.75, 101.0, 101.25, 800.0])); + const B5: Shown = (1794407700, Some([101.25, 101.5, 100.0, 100.25, 700.0])); + let ctx = egui::Context::default(); + let mut app = DemoApp::new(&eframe::CreationContext::_new_kittest(ctx.clone())); + settle(&mut app, &ctx); + // A synthetic workspace that is not the default one: two charts, a comparison, a study. + app.ensure_chart_slots(egui_charts::widget::ChartLayoutMode::TwoHorizontal); + app.handle_comparison(CompareAction::AddSymbol("AAPL".into(), Default::default())); + app.chart + .add_indicator(Box::new(egui_charts::studies::SMA::new(7))); + settle(&mut app, &ctx); + // The open layout as its document. A layout stamps the drawings of each chart with the + // time it is captured at, which two captures do not share. + let layout = |app: &mut DemoApp| { + let text = app.capture_layout().unwrap().to_json().unwrap(); + let mut document: serde_json::Value = serde_json::from_str(&text).unwrap(); + for chart in document["charts"].as_array_mut().unwrap() { + let stamps = chart["drawings"]["metadata"].as_object_mut().unwrap(); + stamps.remove("created_at"); + stamps.remove("modified_at"); + } + document + }; + let before = layout(&mut app); + let symbol = app.state.symbol.clone(); + assert!(!app.live.paused()); + // The unnamed workspace as the browser would keep it. + let workspace = |app: &DemoApp| { + let mut kept = AppStorage::default(); + app.storage.persist(&mut kept); + let documents: std::collections::HashMap = + eframe::get_value(&kept, "templates").unwrap(); + documents["workspace"].clone() + }; + let notified = |app: &DemoApp, start: &str| { + let mut toasts = app.toasts.toasts().iter(); + toasts.any(|toast| toast.message.starts_with(start)) + }; + let complete = |chart: &Chart| { + let feed = chart.feed_state(SeriesId::MAIN); + feed.is_some_and(|feed| feed.history_complete) + }; + + // Entering: one chart on the visitor's data; the synthetic session is set aside and + // paused. + let server = Server::start(pages(vec![ + format!("[{J3},{J4},{J5}]"), + "[]".to_owned(), + "[]".to_owned(), + "[]".to_owned(), + ])); + let mut own = profile(&server.origin); + own.symbols.push("XYZ".to_owned()); + app.connect_own_data(own, Secrets::new()); + assert!(app.own_data.is_some() && app.live.paused()); + assert!(app.extra_charts.is_empty() && app.comparisons.is_empty()); + until(&ctx, &mut app.chart, "the visitor's history", complete); + assert_eq!(shown(&app.chart), [B3, B4, B5]); + + // A second of whole frames later, what is stored is still the synthetic workspace. + let parked = workspace(&app); + let later = egui::RawInput { + time: Some(ctx.input(|input| input.time) + 2.0), + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(1440.0, 900.0), + )), + ..Default::default() + }; + ctx.run_ui(later, |ui| { + eframe::App::ui(&mut *app, ui, &mut eframe::Frame::_new_kittest()); + }) + .drop_without_applying_deltas(); + assert_eq!(workspace(&app), parked); + assert_eq!(app.user_settings().symbol.as_deref(), Some(symbol.as_str())); + + // What belongs to the synthetic session refuses, and says so. + app.toggle_replay(); + assert!(!app.state.replay_active); + assert!(notified(&app, "Replay: available on synthetic data only.")); + let tabs = app.layout_tabs.len(); + app.handle_layout_action(LayoutAction::CreateNew); + assert_eq!(app.layout_tabs.len(), tabs); + assert!(notified(&app, "Layouts: available on synthetic data only.")); + // A symbol outside the profile is refused. One of the profile is asked of its service. + app.switch_symbol("AAPL"); + assert_eq!(app.chart.symbol(), "ABC"); + assert!(notified(&app, "AAPL is not a symbol of this data source")); + app.switch_symbol("XYZ"); + until(&ctx, &mut app.chart, "the other symbol", complete); + assert_eq!( + (app.chart.symbol(), app.state.symbol.as_str()), + ("XYZ", "XYZ") + ); + app.switch_timeframe(Timeframe::Day1); + until(&ctx, &mut app.chart, "the other interval", complete); + let lines: Vec = server.seen().iter().map(|seen| seen.line.clone()).collect(); + assert_eq!(lines.len(), 4, "{lines:?}"); + assert!( + lines[2].starts_with("GET /bars?symbol=XYZ&interval=1m&to="), + "{lines:?}" + ); + assert!( + lines[3].starts_with("GET /bars?symbol=XYZ&interval=1d&to="), + "{lines:?}" + ); + + // Leaving: the synthetic workspace is back as it was left. + app.leave_own_data(); + assert!(app.own_data.is_none() && !app.live.paused()); + // The charts read their stored drawings again when they come back, as after a layout + // switch, and a layout is captured once they have. + app.chart.flush_stored_drawings(); + for extra in &mut app.extra_charts { + extra.chart.flush_stored_drawings(); + } + assert_eq!(layout(&mut app), before); + assert_eq!((app.extra_charts.len(), app.comparisons.len()), (1, 1)); + assert_eq!(app.state.symbol, symbol); + } +} diff --git a/vendor/egui-charts/examples/demo/owndata/bars.rs b/vendor/egui-charts/examples/demo/owndata/bars.rs new file mode 100644 index 0000000..aaa114f --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/bars.rs @@ -0,0 +1,517 @@ +//! Bars from history rows, from stream records and from trades. + +use chrono::{DateTime, NaiveDate, NaiveTime, TimeDelta, Utc}; +use egui_charts::model::{Bar, BarClock, OrderSide, Timeframe, TimezoneId}; +use serde_json::Value; + +use super::profile::{BarFields, ConditionRule, FieldPath, Segment, TradeFields, at, number, text}; +use super::time::{Stamp, stamp, wall}; + +/// The milliseconds of a day. +pub(crate) const DAY_MS: i64 = 86_400_000; + +/// Whether bars of `timeframe` are whole days, weeks or months: a duration of at least one day +/// that is a multiple of a day. Such a bar is dated, not timed: it carries a trading date. +pub(crate) fn calendar(timeframe: Timeframe) -> bool { + let duration = timeframe.duration_ms(); + duration >= DAY_MS && duration % DAY_MS == 0 +} + +/// The first calendar date of the period of a chart's clock that opens at `open`: the UTC date +/// of `open` when its UTC time of day is 10:00 or earlier, otherwise the next UTC date. +// shortcut: exact for chart time zones from UTC-10:00 to UTC+13:45, because `BarClock` does not +// expose its zone. Upgrade when the clock can name the local date of an instant. +pub(crate) fn period_date(open: DateTime) -> NaiveDate { + let date = open.date_naive(); + if open.time() <= NaiveTime::MIN + TimeDelta::hours(10) { + date + } else { + date.succ_opt().unwrap_or(date) + } +} + +/// The open of the period of `clock` that holds `date`: the period `clock` opens for 10:00 UTC +/// on the date, with the limit stated on [`period_date`]. +pub(crate) fn period_open(clock: &BarClock, date: NaiveDate) -> DateTime { + let ten = date.and_time(NaiveTime::MIN + TimeDelta::hours(10)); + clock.bar_open(ten.and_utc()) +} + +/// The time a bar of a calendar interval carries for the trading date `date`: the later of +/// 00:00 UTC on the date and the open of the period of `clock` that holds the date, which is +/// what `HistoryPage::bars` asks of a feed. The period is the one `clock` opens for 10:00 UTC +/// on the date, with the limit stated on [`period_date`]. +pub(crate) fn dated(clock: &BarClock, date: NaiveDate) -> DateTime { + let midnight = date.and_time(NaiveTime::MIN).and_utc(); + period_open(clock, date).max(midnight) +} + +/// Whether the slot that opens at `open` is too far ahead of `now` to be real: it opens more +/// than a minute after `now` (two weeks for an interval of a day or longer) and at least two +/// slots after the slot of `now`. This is the test the chart applies to pushed bars +/// (`Sink::set_server_time`), applied before a wrong time can move the bar being built. +pub(crate) fn ahead( + clock: &BarClock, + timeframe: Timeframe, + open: DateTime, + now: DateTime, +) -> bool { + let allowance = if timeframe.duration_ms() < DAY_MS { + TimeDelta::minutes(1) + } else { + TimeDelta::weeks(2) + }; + let beyond = now + .checked_add_signed(allowance) + .is_some_and(|limit| open > limit); + // The slot before the one of `open` is later than the slot of `now`. + beyond + && open + .checked_sub_signed(TimeDelta::milliseconds(1)) + .is_some_and(|before| clock.bar_open(before) > clock.bar_open(now)) +} + +/// The value of a mapped field of `record`: `None` when the field is not mapped, missing or +/// `null`. +fn field<'a>(record: &'a Value, path: &[Segment]) -> Option<&'a Value> { + if path.is_empty() { + return None; + } + at(record, path).filter(|value| !value.is_null()) +} + +/// The bar in `record`, which is a history row or a stream record. `None` when its time is +/// missing or unreadable. +/// +/// On a calendar interval the bar is stamped by [`dated`] on the row's date: the date field, +/// or the day of its instant in `zone`. On any other interval it keeps its instant; a row that +/// has only a date opens at midnight of that date in `zone`. +/// +/// A price that is missing, `null` or unreadable is NaN. When all four are, the result is +/// `Bar::whitespace`; otherwise the chart drops a bar with a NaN price and counts it. Volume is +/// zero when it is not mapped, missing or `null`, and NaN when it is unreadable. +pub(crate) fn bar( + record: &Value, + fields: &BarFields, + zone: &TimezoneId, + clock: &BarClock, + timeframe: Timeframe, +) -> Option { + let time = match (stamp(record, &fields.time, zone)?, calendar(timeframe)) { + (Stamp::On(date), true) => dated(clock, date), + (Stamp::At(instant), true) => dated(clock, instant.with_timezone(zone).date_naive()), + (Stamp::At(instant), false) => instant, + (Stamp::On(date), false) => wall(date.and_time(NaiveTime::MIN), zone)?, + }; + let price = |path: &FieldPath| { + let value = field(record, path).and_then(number); + value.unwrap_or(f64::NAN) + }; + let [open, high, low, close] = [&fields.open, &fields.high, &fields.low, &fields.close]; + let [open, high, low, close] = [open, high, low, close].map(price); + if [open, high, low, close].into_iter().all(f64::is_nan) { + return Some(Bar::whitespace(time)); + } + let volume = field(record, &fields.volume); + let volume = volume.map_or(0.0, |value| number(value).unwrap_or(f64::NAN)); + Some(Bar::new(time, open, high, low, close, volume)) +} + +/// One trade of the stream. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Trade { + pub(crate) time: DateTime, + pub(crate) price: f64, + pub(crate) size: f64, + /// What its conditions let it change. With several conditions the strictest rule applies: + /// `Ignore` before `VolumeOnly` before `PriceAndVolume`. + pub(crate) rule: ConditionRule, + /// The side of its aggressor: `None` when the route maps no side or the value is neither of + /// the two it names. + pub(crate) side: Option, +} + +/// The trade in `record`. `None` when its time is missing, unreadable or a date without a time +/// of day, when its price or size is missing or unreadable, or when its size is negative. +pub(crate) fn trade(record: &Value, fields: &TradeFields, zone: &TimezoneId) -> Option { + read_trade(record, fields, zone).ok() +} + +/// The trade in `record`, or the part of it that cannot be read: its time, its price or its +/// size. The feed names that part in its log. +pub(crate) fn read_trade( + record: &Value, + fields: &TradeFields, + zone: &TimezoneId, +) -> Result { + let Some(Stamp::At(time)) = stamp(record, &fields.time, zone) else { + return Err("time"); + }; + let amount = |path: &FieldPath| field(record, path).and_then(number); + let price = amount(&fields.price).ok_or("price")?; + let size = amount(&fields.size).filter(|size| *size >= 0.0); + let size = size.ok_or("size")?; + // A value that is not listed counts price and volume, as a trade without a condition does. + let rule = |value: &String| { + let listed = fields.conditions.iter().find(|(listed, _)| listed == value); + listed.map_or(ConditionRule::PriceAndVolume, |(_, rule)| *rule) + }; + let strictness = |rule: &ConditionRule| match rule { + ConditionRule::PriceAndVolume => 0, + ConditionRule::VolumeOnly => 1, + ConditionRule::Ignore => 2, + }; + let rules = conditions(record, fields); + let rule = rules.iter().map(rule).max_by_key(strictness); + // An empty value names no side, also for a field that holds empty text. + let named = |listed: &String, value: &String| !listed.is_empty() && listed == value; + let side = field(record, &fields.side).and_then(text); + let side = side.and_then(|value| { + if named(&fields.buy, &value) { + Some(OrderSide::Buy) + } else if named(&fields.sell, &value) { + Some(OrderSide::Sell) + } else { + None + } + }); + Ok(Trade { + time, + price, + size, + rule: rule.unwrap_or_default(), + side, + }) +} + +/// The condition values of `record` as the rule list compares them: one for a single value, +/// one per element for a list. Empty when no condition field is mapped or the record has none. +/// The dialog fills its condition list from these. +pub(crate) fn conditions(record: &Value, fields: &TradeFields) -> Vec { + match field(record, &fields.condition) { + Some(Value::Array(values)) => values.iter().filter_map(text).collect(), + Some(value) => text(value).into_iter().collect(), + None => Vec::new(), + } +} + +/// Builds the bars of one subscription from its trades, under the rule of each trade's +/// conditions, continuing the newest bar of history. +pub(crate) struct Aggregator { + clock: BarClock, + timeframe: Timeframe, + building: Option, +} + +/// The bar being built and what the rules of [`Aggregator::add`] need to know of it. +struct Building { + bar: Bar, + /// The open of the bar's slot. + slot: DateTime, + /// The times of the earliest and of the latest trade that moved the prices. + traded: Option<(DateTime, DateTime)>, + /// History supplied the prices, so the open is the service's and stays. + supplied: bool, + /// The bar has prices of its own: it is neither an empty slot nor flat at the close of the + /// bar before it. + priced: bool, +} + +impl Aggregator { + /// An aggregator for bars of `timeframe` on the slots of `clock`. It holds no bar yet. + pub(crate) fn new(clock: BarClock, timeframe: Timeframe) -> Self { + Self { + clock, + timeframe, + building: None, + } + } + + /// Starts from `bar`, the newest bar that history holds, or from nothing. Whatever was + /// being built is forgotten. + pub(crate) fn start(&mut self, bar: Option) { + self.building = bar.map(|bar| Building { + slot: self.clock.bar_open(bar.time), + traded: None, + supplied: true, + priced: !bar.is_whitespace(), + bar, + }); + } + + /// Continues from `bar`, a bar the stream's bars route sent. The service counted the trades + /// of its slot up to the moment it sent it, so the trades after it continue it. A bar of a + /// slot older than the one being built is left out: that slot is closed. + pub(crate) fn follow(&mut self, bar: &Bar) { + let slot = self.clock.bar_open(bar.time); + if self + .building + .as_ref() + .is_some_and(|building| slot < building.slot) + { + return; + } + self.start(Some(bar.clone())); + } + + /// Folds `trade` in and returns the bar to push, in its state after the trade. `None` when + /// the trade changes nothing: its rule is `Ignore`, its slot is older than the bar being + /// built, its slot opens too far after `now` (see [`ahead`]), or it counts volume only and no + /// price is known yet. + pub(crate) fn add(&mut self, trade: &Trade, now: DateTime) -> Option { + let slot = self.clock.bar_open(trade.time); + if trade.rule == ConditionRule::Ignore || ahead(&self.clock, self.timeframe, slot, now) { + return None; + } + let counted = trade.rule == ConditionRule::PriceAndVolume; + let (price, size) = (trade.price, trade.size); + match &mut self.building { + // The trade is late: its bar is closed. + Some(building) if slot < building.slot => return None, + Some(building) if slot == building.slot => { + let bar = &mut building.bar; + if !counted { + if bar.is_whitespace() { + return None; + } + bar.volume += size; + } else if !building.priced { + // The first price of an empty slot or of a flat bar is all four prices. + let volume = if bar.is_whitespace() { 0.0 } else { bar.volume }; + *bar = Bar::new(bar.time, price, price, price, price, volume + size); + building.traded = Some((trade.time, trade.time)); + (building.supplied, building.priced) = (false, true); + } else { + // Until its first trade, every trade is the latest of a bar from history. + let (first, last) = building.traded.unwrap_or((trade.time, trade.time)); + bar.high = bar.high.max(price); + bar.low = bar.low.min(price); + bar.volume += size; + if trade.time >= last { + bar.close = price; + } + if !building.supplied && trade.time < first { + bar.open = price; + } + building.traded = Some((first.min(trade.time), last.max(trade.time))); + } + } + // A newer slot, or no bar yet. + left => { + // A trade that counts volume only opens a flat bar at the close before it. + let carried = left.as_ref().map(|left| &left.bar); + let carried = carried.filter(|bar| !bar.is_whitespace()); + let at = if counted { price } else { carried?.close }; + let time = if calendar(self.timeframe) { + dated(&self.clock, period_date(slot)) + } else { + slot + }; + *left = Some(Building { + bar: Bar::new(time, at, at, at, at, size), + slot, + traded: counted.then_some((trade.time, trade.time)), + supplied: false, + priced: counted, + }); + } + } + self.bar().cloned() + } + + /// The bar being built: the newest bar this subscription knows. + pub(crate) fn bar(&self) -> Option<&Bar> { + self.building.as_ref().map(|building| &building.bar) + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::super::profile::{DateFormat, TimeSpec, TimeUnit}; + use super::*; + + #[test] + fn trades_build_bars_by_condition_rule() { + use ConditionRule::{Ignore, PriceAndVolume, VolumeOnly}; + let key = |name: &str| vec![Segment::Key(name.to_owned())]; + let fields = TradeFields { + time: TimeSpec::Instant { + field: key("t"), + unit: TimeUnit::Milliseconds, + }, + price: key("p"), + size: key("s"), + condition: key("c"), + conditions: vec![("T".to_owned(), VolumeOnly), ("X".to_owned(), Ignore)], + ..TradeFields::default() + }; + let utc = TimezoneId::utc(); + // 14:30:00 UTC on 11 November 2026 in milliseconds. A row gives its time as an offset. + const T: i64 = 1_794_407_400_000; + // The slots of 14:30 and 14:31 in seconds. + const M30: i64 = 1_794_407_400; + const M31: i64 = 1_794_407_460; + let instant = |offset: i64| DateTime::::from_timestamp_millis(T + offset).unwrap(); + // What a row compares: the time of the returned bar in seconds and its five values. + type Seen = Option<(i64, [f64; 5])>; + let seen = |bar: Option| -> Seen { + bar.map(|bar| { + let values = [bar.open, bar.high, bar.low, bar.close, bar.volume]; + (bar.time.timestamp(), values) + }) + }; + let bar = |slot: i64, values: [f64; 5]| -> Seen { Some((slot, values)) }; + let none = || json!(null); + // Reads each row as the feed reads a record and folds it in with the clock at its time. + let run = |minutes: &mut Aggregator, rows: &[(i64, f64, f64, Value, Seen)]| { + for (offset, price, size, condition, expected) in rows { + let record = json!({"t": T + offset, "p": price, "s": size, "c": condition}); + let read = trade(&record, &fields, &utc).unwrap(); + let returned = seen(minutes.add(&read, instant(*offset))); + assert_eq!(returned, *expected, "trade at {offset} ms"); + } + }; + + let mut minutes = Aggregator::new(BarClock::new(Timeframe::Min1), Timeframe::Min1); + // Ten trades from nothing. `T` counts volume only and `X` is ignored. + minutes.start(None); + #[rustfmt::skip] + let from_nothing = [ + (1_000, 100.0, 10.0, none(), bar(M30, [100.0, 100.0, 100.0, 100.0, 10.0])), + (2_000, 101.5, 5.0, none(), bar(M30, [100.0, 101.5, 100.0, 101.5, 15.0])), + // Volume only: the prices stay. + (3_000, 99.0, 7.0, json!("T"), bar(M30, [100.0, 101.5, 100.0, 101.5, 22.0])), + (4_000, 50.0, 1000.0, json!("X"), None), + // Earlier than the first trade: the open moves, the close does not. + (500, 99.5, 3.0, none(), bar(M30, [99.5, 101.5, 99.5, 101.5, 25.0])), + // Volume only in a new slot: a flat bar at the close before it. + (60_000, 98.0, 4.0, json!("T"), bar(M31, [101.5, 101.5, 101.5, 101.5, 4.0])), + // The first price of the flat bar is all four prices. + (62_000, 102.0, 6.0, none(), bar(M31, [102.0, 102.0, 102.0, 102.0, 10.0])), + // A trade of the slot before is late. + (59_000, 100.0, 1.0, none(), None), + // `@` is not listed and `T` is the stricter of the two. + (65_000, 103.0, 2.0, json!(["@", "T"]), bar(M31, [102.0, 102.0, 102.0, 102.0, 12.0])), + (66_000, 103.0, 2.0, json!(["T", "X"]), None), + ]; + run(&mut minutes, &from_nothing); + // Three trades from a bar of history: its open is the service's and stays. + minutes.start(Some(Bar::new(instant(0), 100.0, 102.0, 99.0, 101.0, 500.0))); + #[rustfmt::skip] + let from_history = [ + (40_000, 101.5, 5.0, none(), bar(M30, [100.0, 102.0, 99.0, 101.5, 505.0])), + // Earlier than the trade before it: the close stays. + (10_000, 98.0, 1.0, none(), bar(M30, [100.0, 102.0, 98.0, 101.5, 506.0])), + (-1_000, 97.0, 1.0, none(), None), + ]; + run(&mut minutes, &from_history); + // From a slot that history holds empty. + minutes.start(Some(Bar::whitespace(instant(0)))); + #[rustfmt::skip] + let from_an_empty_slot = [ + (5_000, 99.0, 7.0, json!("T"), None), + (6_000, 100.0, 2.0, none(), bar(M30, [100.0, 100.0, 100.0, 100.0, 2.0])), + ]; + run(&mut minutes, &from_an_empty_slot); + + // A time in the wrong unit lands far ahead: 14:40:00 with the clock at 14:30:06 is more + // than a minute and nine slots ahead. It must not become the bar being built. + let far = json!({"t": T + 600_000, "p": 500.0, "s": 1.0}); + let far = trade(&far, &fields, &utc).unwrap(); + assert_eq!(seen(minutes.add(&far, instant(6_000))), None); + let after = bar(M30, [100.0, 100.5, 100.0, 100.5, 3.0]); + run(&mut minutes, &[(7_000, 100.5, 1.0, none(), after)]); + // The next slot is not far ahead, also with a clock half a second behind it. + let next = json!({"t": T + 60_000, "p": 101.0, "s": 1.0}); + let next = trade(&next, &fields, &utc).unwrap(); + assert_eq!( + seen(minutes.add(&next, instant(59_500))), + bar(M31, [101.0, 101.0, 101.0, 101.0, 1.0]) + ); + + // On a daily chart the bar of a trade is dated, not timed. The trade is at 14:30:01 UTC + // on 11 November, whose midnight UTC is second 1,794,355,200. In New York that day + // opened at 05:00 UTC, 18,000 seconds later. In Tokyo it opened at 15:00 UTC on the + // 10th, so the stamp is 00:00 UTC on its date. + let first = json!({"t": T + 1_000, "p": 100.0, "s": 10.0}); + let first = trade(&first, &fields, &utc).unwrap(); + for (zone, stamp) in [ + ("America/New_York", 1_794_373_200), + ("Asia/Tokyo", 1_794_355_200), + ] { + let clock = BarClock::new(Timeframe::Day1).with_timezone(zone.parse().unwrap()); + let mut days = Aggregator::new(clock, Timeframe::Day1); + days.start(None); + let dated = bar(stamp, [100.0, 100.0, 100.0, 100.0, 10.0]); + assert_eq!(seen(days.add(&first, first.time)), dated, "{zone}"); + } + + // What is not a trade: no time, no price, no size, a number that is none, a negative + // size. + for record in [ + json!({"p": 100.0, "s": 1.0}), + json!({"t": "soon", "p": 100.0, "s": 1.0}), + json!({"t": T, "s": 1.0}), + json!({"t": T, "p": "NaN", "s": 1.0}), + json!({"t": T, "p": 100.0}), + json!({"t": T, "p": 100.0, "s": -1.0}), + ] { + assert_eq!(trade(&record, &fields, &utc), None, "{record}"); + } + // A date without a time of day is the time of a bar, not of a trade. + let by_date = TradeFields { + time: TimeSpec::Wall { + date: key("d"), + format: DateFormat::Compact, + clock: None, + }, + ..fields.clone() + }; + let dated = json!({"d": 20261111, "p": 100.0, "s": 1.0}); + assert_eq!(trade(&dated, &by_date, &utc), None); + // Numbers sent as text are numbers, and a size of zero is a trade. + let texts = json!({"t": T.to_string(), "p": "100.5", "s": "0"}); + let read = Trade { + time: instant(0), + price: 100.5, + size: 0.0, + rule: PriceAndVolume, + side: None, + }; + assert_eq!(trade(&texts, &fields, &utc), Some(read)); + // The side, read as text: `false` marks a buy and `true` a sell, as a field "the buyer + // made the market" does. Anything else, or no field, is unknown. + let sided = TradeFields { + side: key("m"), + buy: "false".to_owned(), + sell: "true".to_owned(), + ..fields.clone() + }; + use egui_charts::model::OrderSide::{Buy, Sell}; + let side = |record: &Value, fields: &TradeFields| { + trade(record, fields, &utc).map(|trade| trade.side) + }; + for (value, read) in [ + (json!(false), Some(Buy)), + (json!(true), Some(Sell)), + (json!("true"), Some(Sell)), + (json!("x"), None), + (json!(null), None), + (json!([true]), None), + ] { + let record = json!({"t": T, "p": 100.0, "s": 1.0, "m": value}); + assert_eq!(side(&record, &sided), Some(read), "{record}"); + } + let unsided = json!({"t": T, "p": 100.0, "s": 1.0}); + assert_eq!(side(&unsided, &sided), Some(None)); + // An empty value marks nothing, also for a field that holds empty text. + let half = TradeFields { + buy: String::new(), + ..sided.clone() + }; + let empty = json!({"t": T, "p": 100.0, "s": 1.0, "m": ""}); + assert_eq!(side(&empty, &half), Some(None)); + } +} diff --git a/vendor/egui-charts/examples/demo/owndata/dialog.rs b/vendor/egui-charts/examples/demo/owndata/dialog.rs new file mode 100644 index 0000000..cc383c2 --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/dialog.rs @@ -0,0 +1,3917 @@ +//! The Data source dialog: the first-visit choice, and the steps that describe a profile, +//! test it against the service and connect it. + +use std::collections::VecDeque; +use std::fmt::Write as _; +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::sync::{Arc, Mutex, PoisonError}; + +use chrono::{DateTime, Utc}; +use egui::{RichText, TextEdit}; +use egui_charts::data::{FeedError, FeedState, FeedStatus}; +use egui_charts::model::{Bar, BarClock, OrderSide, Timeframe, TimezoneId}; +use egui_charts::theme::ThemeExt as _; +use egui_charts::ui_kit::alert::Alert; +use egui_charts::ui_kit::buttons::Button; +use egui_charts::ui_kit::dialog::DialogFooter; +use egui_charts::ui_kit::ext::UiExt as _; +use egui_charts::ui_kit::form::{FormGrid, FormRow}; +use egui_charts::ui_kit::modal::Modal; +use egui_charts::ui_kit::tab_bar::{TabBar, TabLabel}; +use serde_json::Value; + +use super::super::storage::DemoStorage; +use super::feed::{self, Reading}; +use super::profile::{ + self, BarFields, Clock, ClockUnit, ConditionRule, DateFormat, FieldPath, History, Interval, + Layout, PLACEHOLDERS, Profile, RangeFormat, Route, RouteKind, Rows, Segment, Stream, TimeSpec, + TimeUnit, TradeFields, at, +}; +use super::shape::{self, Proposal}; +use super::store::{self, Saved}; +use super::stream::{self, Routed, Session, StreamEvent}; +use super::time::{self, Stamp}; +use super::{Failure, Secrets, bars, conceal, endpoint, http, tree}; + +/// The height the footer takes below the steps. +const FOOTER: f32 = 64.0; +/// The height of the line above the footer. +const LINE: f32 = 24.0; +/// The height of a tree that scrolls. A nested scroll area would otherwise take only what is +/// left of the dialog's view below it. +const TREE: f32 = 200.0; +/// The height of the log once it scrolls. +const LOG: f32 = 140.0; +/// The lines the log keeps. +const LOG_LINES: usize = 200; +/// The largest file an import reads. +const LARGEST_FILE: u64 = 1 << 20; +/// What the dialog says about `Connect` while own data is on. +const RECONNECTS: &str = + "Connect reconnects with this profile. Studies and drawings on the chart are not kept."; +/// The first-visit sentence. The web build runs in a browser, the native build on the device. +const CHOICE: &str = if cfg!(target_arch = "wasm32") { + "This demo runs on synthetic data. You can also chart your own REST history and WebSocket \ + stream, mapped here in your browser." +} else { + "This demo runs on synthetic data. You can also chart your own REST history and WebSocket \ + stream, mapped here on this device." +}; +/// The choice that keeps the key values. +const KEEP: &str = if cfg!(target_arch = "wasm32") { + "Keep keys in this browser" +} else { + "Keep keys on this device" +}; +/// Where a kept key is stored. +const KEPT: &str = if cfg!(target_arch = "wasm32") { + "Kept as plain text in this browser's storage for this site." +} else { + "Kept as plain text in the demo's settings file on this device." +}; +/// Why a key of the stream travels elsewhere than in a header. +const NO_HEADERS: &str = if cfg!(target_arch = "wasm32") { + "A browser sends no headers when it opens a WebSocket." +} else { + "The stream sends no headers when it opens." +}; + +/// What the dialog asks the application to do. +pub(crate) enum Outcome { + /// Show `profile` on the chart, read with the key values `secrets`. + Connect { + profile: Box, + secrets: Secrets, + }, + /// Go back to the synthetic session. + Synthetic, + /// Write `text` to a file named `file`: an exported profile. + Export { file: String, text: String }, +} + +/// The dialog and everything it edits. Its tests against the service (a history request, a +/// stream session) belong to it and end when it closes. +pub(crate) struct DataSourceDialog { + storage: Arc, + can_save: bool, + /// The saved state as it was last written. + saved: Saved, + /// The ready profiles whose name no saved profile has, first in the profile list. + ready: Vec, + open: bool, + /// Whether `startup` has acted. + started: bool, + view: View, + step: Step, + draft: Draft, + /// What the check before a Test or a connection found. Nothing is sent while it holds a + /// line. + report: Vec, + /// Why the last import gave no profile. + notice: Option, + /// Where the text of a picked file arrives. + import: Option, + /// The symbol and the interval of both Tests, as places in the lists of the draft. + symbol: usize, + interval: usize, + history: HistoryTest, + live: LiveTest, +} + +/// What the file picker answers: the text of the file, nothing when the user gave up, or why +/// the file was not read. +type Picked = Receiver, String>>; + +/// Where the answer of a history Test arrives. +type Answer = Arc>>>; + +/// What decides the route of a record and the condition values it offers. +type Basis = (FieldPath, FieldPath, Vec); + +/// The events of a session, each with the time it arrived. +type Events = Arc, StreamEvent)>>>; + +/// What the dialog shows. +#[derive(Clone, Copy, PartialEq)] +enum View { + /// The first-visit choice. + Choice, + /// The steps that describe a profile. + Steps, + /// The text of the file an export writes. + Export, +} + +/// One of the three steps. +#[derive(Clone, Copy, PartialEq)] +enum Step { + Source, + History, + Live, +} + +impl TabLabel for Step { + fn tab_label(&self) -> &str { + match self { + Self::Source => "Source", + Self::History => "History", + Self::Live => "Live", + } + } +} + +/// What the dialog edits. Nothing of it reaches the chart or the saved state before `Save` or +/// `Connect`. +struct Draft { + profile: Profile, + /// The value of each key, in the order of `profile.keys`. + values: Vec, + /// Whether the key values are kept: the box [`KEEP`]. + keep: bool, + /// The name of the saved profile the draft was loaded from. `None` for a new or an + /// imported one. + origin: Option, + /// The symbols as typed. + symbols: String, + /// The time zone as typed. The profile keeps the last valid one. + zone: String, + /// The price step as typed. The profile keeps the last valid one. + step: String, + /// The history and the stream as they were when their switch was turned off. + history_off: Option, + stream_off: Option, +} + +impl Draft { + /// A draft of `profile` with the key values `values`. + fn of(profile: Profile, mut values: Vec, keep: bool, origin: Option) -> Self { + values.resize(profile.keys.len(), String::new()); + Self { + symbols: profile.symbols.join(", "), + zone: profile.time_zone.name().to_owned(), + step: profile + .tick_size + .map(|step| step.to_string()) + .unwrap_or_default(), + profile, + values, + keep, + origin, + history_off: None, + stream_off: None, + } + } + + /// A new profile. + fn blank() -> Self { + Self::of(Profile::default(), Vec::new(), false, None) + } + + /// The saved profile `profile`, with the values of its keys when they were kept. + fn saved(saved: &Saved, profile: &Profile) -> Self { + let kept = saved.keys.iter().find(|(name, _)| *name == profile.name); + let kept = kept.map(|(_, secrets)| secrets); + let value = |key: &String| { + let held = kept.and_then(|secrets| secrets.iter().find(|(name, _)| name == key)); + held.map(|(_, value)| value.clone()).unwrap_or_default() + }; + let values = profile.keys.iter().map(value).collect(); + let origin = Some(profile.name.clone()); + Self::of(profile.clone(), values, kept.is_some(), origin) + } + + /// The profile in use, else the one used last, saved or ready, else a new one. + fn current(saved: &Saved, ready: &[Profile]) -> Self { + let mut listed = saved.profiles.iter().chain(ready); + let named = |name: &String| listed.find(|profile| profile.name == *name); + let profile = saved.current.as_ref().and_then(named); + profile.map_or_else(Self::blank, |profile| Self::saved(saved, profile)) + } + + /// The key values, one pair per key in the order of the profile. + fn secrets(&self) -> Secrets { + let pairs = self.profile.keys.iter().zip(&self.values); + pairs + .map(|(name, value)| (name.clone(), value.clone())) + .collect() + } +} + +/// The templates a check covers. +#[derive(Clone, Copy, PartialEq)] +enum Scope { + History, + Stream, + Both, +} + +/// A place a click on a tree node fills. +#[derive(Clone, Copy, PartialEq)] +enum Slot { + Rows, + Header, + Records, + RouteBy, + Time, + Clock, + Open, + High, + Low, + Close, + Volume, + Price, + Size, + Condition, + Side, +} + +impl Slot { + fn label(self) -> &'static str { + match self { + Self::Rows => "rows", + Self::Header => "header", + Self::Records => "records", + Self::RouteBy => "route by", + Self::Time => "time", + Self::Clock => "time of day", + Self::Open => "open", + Self::High => "high", + Self::Low => "low", + Self::Close => "close", + Self::Volume => "volume", + Self::Price => "price", + Self::Size => "size", + Self::Condition => "condition", + Self::Side => "side", + } + } +} + +/// The reading of a time field, as the choice beside the slot names it. +#[derive(Clone, Copy, PartialEq)] +enum TimeForm { + Seconds, + Milliseconds, + Microseconds, + Nanoseconds, + Iso8601, + Compact, + Dashed, +} + +impl TimeForm { + const ALL: [Self; 7] = [ + Self::Seconds, + Self::Milliseconds, + Self::Microseconds, + Self::Nanoseconds, + Self::Iso8601, + Self::Compact, + Self::Dashed, + ]; + + fn label(self) -> &'static str { + match self { + Self::Seconds => "Unix seconds", + Self::Milliseconds => "Unix milliseconds", + Self::Microseconds => "Unix microseconds", + Self::Nanoseconds => "Unix nanoseconds", + Self::Iso8601 => "ISO 8601 text", + Self::Compact => "Date 20261111", + Self::Dashed => "Date 2026-11-11", + } + } + + /// The form `spec` reads its field in. + fn of(spec: &TimeSpec) -> Self { + match spec { + TimeSpec::Instant { unit, .. } => match unit { + TimeUnit::Seconds => Self::Seconds, + TimeUnit::Milliseconds => Self::Milliseconds, + TimeUnit::Microseconds => Self::Microseconds, + TimeUnit::Nanoseconds => Self::Nanoseconds, + TimeUnit::Iso8601 => Self::Iso8601, + }, + TimeSpec::Wall { format, .. } => match format { + DateFormat::Compact => Self::Compact, + DateFormat::Dashed => Self::Dashed, + }, + } + } + + /// Reads the field of `spec` in this form. A time of day stays with a date. + fn apply(self, spec: &mut TimeSpec) { + let (field, clock) = match std::mem::take(spec) { + TimeSpec::Instant { field, .. } => (field, None), + TimeSpec::Wall { date, clock, .. } => (date, clock), + }; + let instant = |unit| TimeSpec::Instant { + field: field.clone(), + unit, + }; + let wall = |format| TimeSpec::Wall { + date: field.clone(), + format, + clock: clock.clone(), + }; + *spec = match self { + Self::Seconds => instant(TimeUnit::Seconds), + Self::Milliseconds => instant(TimeUnit::Milliseconds), + Self::Microseconds => instant(TimeUnit::Microseconds), + Self::Nanoseconds => instant(TimeUnit::Nanoseconds), + Self::Iso8601 => instant(TimeUnit::Iso8601), + Self::Compact => wall(DateFormat::Compact), + Self::Dashed => wall(DateFormat::Dashed), + }; + } +} + +/// The time and the fields of a bar or of a trade, by slot. +struct Fields<'a> { + time: &'a mut TimeSpec, + paths: Vec<(Slot, &'a mut FieldPath)>, +} + +impl<'a> Fields<'a> { + /// The slots of a bar. + fn bar(fields: &'a mut BarFields) -> Self { + let BarFields { + time, + open, + high, + low, + close, + volume, + } = fields; + let paths = vec![ + (Slot::Open, open), + (Slot::High, high), + (Slot::Low, low), + (Slot::Close, close), + (Slot::Volume, volume), + ]; + Self { time, paths } + } + + /// The slots of a trade. + fn trade(fields: &'a mut TradeFields) -> Self { + let paths = vec![ + (Slot::Price, &mut fields.price), + (Slot::Size, &mut fields.size), + (Slot::Condition, &mut fields.condition), + (Slot::Side, &mut fields.side), + ]; + Self { + time: &mut fields.time, + paths, + } + } + + /// The slots of the records of a route, when they carry any. + fn route(kind: &'a mut RouteKind) -> Option { + match kind { + RouteKind::Ignore => None, + RouteKind::Bars(fields) => Some(Self::bar(fields)), + RouteKind::Trades(fields) => Some(Self::trade(fields)), + } + } + + /// The slots, in the order they are drawn. A date has a time of day beside it. + fn slots(&self) -> Vec { + let mut slots = vec![Slot::Time]; + if matches!(self.time, TimeSpec::Wall { .. }) { + slots.push(Slot::Clock); + } + slots.extend(self.paths.iter().map(|(slot, _)| *slot)); + slots + } + + /// The path `slot` holds, empty when nothing is mapped. `None` for a slot these fields do + /// not have. + fn path(&self, slot: Slot) -> Option { + match (slot, &*self.time) { + (Slot::Time, TimeSpec::Instant { field, .. }) => Some(field.clone()), + (Slot::Time, TimeSpec::Wall { date, .. }) => Some(date.clone()), + (Slot::Clock, TimeSpec::Wall { clock, .. }) => Some( + clock + .as_ref() + .map(|clock| clock.field.clone()) + .unwrap_or_default(), + ), + _ => { + let held = self.paths.iter().find(|(held, _)| *held == slot); + held.map(|(_, path)| FieldPath::clone(path)) + } + } + } + + /// Maps `slot` to the node at `path`, whose value is `value`. The form of a time or a time + /// of day is the one its value reads in. + fn assign(&mut self, slot: Slot, path: FieldPath, value: &Value) { + match slot { + Slot::Time => *self.time = time::guess(path, value), + Slot::Clock => { + if let TimeSpec::Wall { clock, .. } = &mut *self.time { + let held = clock.take().map(|clock| clock.unit).unwrap_or_default(); + let unit = time::clock_unit(value, held); + *clock = Some(Clock { field: path, unit }); + } + } + _ => { + if let Some((_, held)) = self.paths.iter_mut().find(|(held, _)| *held == slot) { + **held = path; + } + } + } + } + + /// Leaves `slot` unmapped. + fn clear(&mut self, slot: Slot) { + match slot { + Slot::Time => *self.time = TimeSpec::default(), + Slot::Clock => { + if let TimeSpec::Wall { clock, .. } = &mut *self.time { + *clock = None; + } + } + _ => { + if let Some((_, held)) = self.paths.iter_mut().find(|(held, _)| *held == slot) { + held.clear(); + } + } + } + } + + /// The slot that becomes active once `slot` is filled: the next empty one, or `slot` + /// itself. The time of day is optional and is never chosen this way. + fn next(&self, slot: Slot) -> Slot { + let order: Vec = self.slots(); + let order: Vec = order + .into_iter() + .filter(|held| *held != Slot::Clock) + .collect(); + let from = order.iter().position(|held| *held == slot); + let after = &order[from.map_or(0, |at| at + 1)..]; + let empty = |held: &&Slot| self.path(**held).is_some_and(|path| path.is_empty()); + after.iter().find(empty).copied().unwrap_or(slot) + } + + /// The mapped nodes and the names of their slots. + fn marks(&self) -> Vec<(FieldPath, &'static str)> { + let named = |slot: Slot| { + Some(( + self.path(slot).filter(|path| !path.is_empty())?, + slot.label(), + )) + }; + self.slots().into_iter().filter_map(named).collect() + } + + /// Draws one row of a slot grid per slot, read on `record`. + fn rows(&mut self, ui: &mut egui::Ui, record: Option<&Value>, active: &mut Slot) { + for slot in self.slots() { + let path = self.path(slot).unwrap_or_default(); + slot_cells(ui, slot, active, &path, false, record); + if clear_button(ui, !path.is_empty()) { + self.clear(slot); + } + ui.end_row(); + } + } + + /// The form of the mapped time and of its time of day, and the time `record` holds. They + /// follow the slot grid, whose rows leave no room for them on a phone. + fn forms(&mut self, ui: &mut egui::Ui, record: Option<&Value>, zone: &TimezoneId) { + let timed = self.path(Slot::Time).is_some_and(|path| !path.is_empty()); + let clocked = matches!(self.time, TimeSpec::Wall { clock: Some(_), .. }); + if !timed && !clocked { + return; + } + ui.horizontal_wrapped(|ui| { + if timed { + let mut form = TimeForm::of(self.time); + let label = |form: &TimeForm| form.label().to_owned(); + let chosen = ui.name_inputs("Form of the time", |ui| { + ui.combo_select("time_form", &mut form, TimeForm::ALL, label) + }); + if chosen { + form.apply(self.time); + } + } + if let TimeSpec::Wall { + clock: Some(clock), .. + } = &mut *self.time + { + let units = [ClockUnit::Milliseconds, ClockUnit::Seconds, ClockUnit::Text]; + let label = |unit: &ClockUnit| clock_label(unit).to_owned(); + ui.name_inputs("Form of the time of day", |ui| { + ui.combo_select("clock_unit", &mut clock.unit, units, label); + }); + } + if timed && let Some(record) = record { + ui.weak(stamp_text(record, self.time, zone)); + } + }); + } +} + +/// The Test of the History step and what it found. +struct HistoryTest { + /// Where the answer of the request in flight arrives, the endpoint it was sent to and its + /// symbol. + pending: Option<(Answer, String, String)>, + /// The endpoint of the last answer. + endpoint: String, + /// The symbol of the last sample. A key of the rows path can name it. + symbol: String, + /// Why the last Test gave no sample. + error: Option, + /// Whether the last Test proposed the mapping. + proposed: bool, + /// The last response that was JSON. + sample: Option, + /// Counts the samples, so that each one gets trees of its own. + samples: u64, + /// The ways the sample can be read. + proposals: Vec, + /// The sample read with the mapping of the draft. + preview: Option, + /// The active slot. + slot: Slot, +} + +impl Default for HistoryTest { + fn default() -> Self { + Self { + pending: None, + endpoint: String::new(), + symbol: String::new(), + error: None, + proposed: false, + sample: None, + samples: 0, + proposals: Vec::new(), + preview: None, + slot: Slot::Rows, + } + } +} + +/// A sample read with a mapping, kept until one of the two changes. +struct Preview { + history: History, + zone: TimezoneId, + timeframe: Timeframe, + samples: u64, + /// The first row, laid out as the mapping says. + row: Option, + reading: Result, +} + +/// The Test of the Live step and its log. +struct LiveTest { + /// The session of the Test that runs. Dropping it closes its socket. + session: Option, + /// Where the events of the session arrive. Every Test has its own. + queue: Events, + /// The address of the Test without its query. + endpoint: String, + /// Whether a socket of the Test has opened. + opened: bool, + /// The last close, while no socket of the Test has opened. + failure: Option, + /// The newest lines, oldest first. + log: VecDeque, + /// Counts the lines of the Test. + lines: u64, + /// What the lines were last routed with. + basis: Option, + /// The oldest message that has a record without a route. It is kept apart from the log, so + /// that it cannot scroll away. + unrouted: Option, + /// The number of the selected line. + selected: Option, + /// The record of the selected message that is shown, counted from zero. + record: usize, + /// The selected route. + route: usize, + /// The active slot. + slot: Slot, + /// A condition value being typed. + condition: String, +} + +impl Default for LiveTest { + fn default() -> Self { + Self { + session: None, + queue: Arc::default(), + endpoint: String::new(), + opened: false, + failure: None, + log: VecDeque::new(), + lines: 0, + basis: None, + unrouted: None, + selected: None, + record: 0, + route: 0, + slot: Slot::RouteBy, + condition: String::new(), + } + } +} + +/// One line of the log. +struct Line { + number: u64, + at: DateTime, + kind: LineKind, +} + +/// What a line of the log reports. +enum LineKind { + /// The connection opened or closed, or a message could not be read. + Note { + badge: &'static str, + text: String, + /// Whether the line reports a fault. + fault: bool, + }, + Message(Message), +} + +/// One message of the stream. +#[derive(Clone)] +struct Message { + text: String, + /// The parsed message, or its text when it is not JSON. + root: Value, + /// Its records as the stream of the draft routes them. + routed: Vec, +} + +impl Message { + /// Whether a record of the message matches no route. + fn unrouted(&self) -> bool { + let lost = |record: &Routed| matches!(record, Routed::Unrouted { .. }); + self.routed.iter().any(lost) + } +} + +impl DataSourceDialog { + /// A closed dialog over the state saved in `storage`. `can_save` is false when the + /// application runs without storage: the first-visit choice is then not offered, because + /// its answer could not be remembered, and nothing is saved. + pub(crate) fn new(storage: Arc, can_save: bool) -> Self { + let saved = Saved::load(&storage); + let mut ready = store::ready(); + // A saved profile of that name, made before the ready one shipped, stays the visitor's. + ready.retain(|profile| !saved.profiles.iter().any(|held| held.name == profile.name)); + Self { + draft: Draft::current(&saved, &ready), + storage, + can_save, + saved, + ready, + open: false, + started: false, + view: View::Steps, + step: Step::Source, + report: Vec::new(), + notice: None, + import: None, + symbol: 0, + interval: 0, + history: HistoryTest::default(), + live: LiveTest::default(), + } + } + + /// Whether the dialog is on screen. The application leaves the keyboard to it. + pub(crate) fn is_open(&self) -> bool { + self.open + } + + /// Opens the dialog on the profile in use, else on the one used last, else on a new one. + pub(crate) fn open(&mut self) { + self.open = true; + self.view = View::Steps; + } + + /// What the saved state asks for when the application starts. It acts on its first call + /// and returns `None` on every later one. It opens the first-visit choice when that was + /// never answered. When own data was in use it returns the connection to make if the keys + /// of its profile were kept, and otherwise opens the dialog on that profile so that the + /// keys can be entered. + pub(crate) fn startup(&mut self) -> Option { + if std::mem::replace(&mut self.started, true) || !self.can_save { + return None; + } + if !self.saved.asked { + self.open = true; + self.view = View::Choice; + return None; + } + if !self.saved.own { + return None; + } + let current = self.saved.current.as_ref(); + let mut listed = self.saved.profiles.iter().chain(&self.ready); + let named = |name: &String| listed.find(|saved| saved.name == *name); + let Some(profile) = current.and_then(named) else { + // The profile that was in use is gone. + self.saved.own = false; + self.saved.save(&self.storage); + return None; + }; + let draft = Draft::saved(&self.saved, profile); + let secrets = draft.secrets(); + let report = findings(&draft.profile, &secrets, Scope::Both); + if draft.profile.problem().is_none() && report.is_empty() { + let profile = Box::new(draft.profile); + return Some(Outcome::Connect { profile, secrets }); + } + // The chart stays synthetic until the keys are entered and the profile connects. + self.draft = draft; + self.forget_tests(); + self.report = report; + self.step = Step::Source; + self.open(); + None + } + + /// Draws the dialog while it is open and returns what the user decided in this frame. + /// `running` is the state of the chart's feed while own data is on; the dialog shows its + /// status and its last error above the steps. + pub(crate) fn show( + &mut self, + ctx: &egui::Context, + running: Option<&FeedState>, + ) -> Option { + if !self.open { + return None; + } + self.poll_import(); + self.poll_history(); + self.poll_live(); + let mut open = true; + let mut outcome = None; + let modal = Modal::new("data_source", "Data source"); + let modal = match self.view { + View::Choice => modal.width(420.0), + View::Steps | View::Export => modal.width(860.0).height(620.0), + }; + modal.show(ctx, &mut open, |ui| match self.view { + View::Choice => self.choice(ui), + View::Steps => outcome = self.steps(ui, running), + View::Export => outcome = self.export(ui), + }); + // The close button, Escape or a click beside the dialog. A button of the dialog that + // closed it has done so itself. + if !open && self.open { + self.close(); + } + outcome + } + + /// Closes the dialog. The draft stays in memory; the Tests end. + fn close(&mut self) { + if self.view == View::Choice { + // Closing the choice counts as the answer `Use synthetic data`. + self.saved.asked = true; + self.saved.save(&self.storage); + } + self.open = false; + self.view = View::Steps; + self.live.session = None; + self.history.pending = None; + } + + /// Forgets the Tests of the draft that was replaced: their samples, their log and the + /// session, whose socket closes. + fn forget_tests(&mut self) { + self.history = HistoryTest::default(); + self.live = LiveTest::default(); + self.symbol = 0; + self.interval = 0; + self.report.clear(); + } + + /// The first-visit choice. + fn choice(&mut self, ui: &mut egui::Ui) { + ui.label(CHOICE); + let footer = DialogFooter::new("Connect my own data").secondary("Use synthetic data"); + let (own, synthetic) = footer.show(ui); + ui.weak("You can change this later under Data source in the menu."); + if own { + // The answer is saved at the click, so a visitor who gives up is not asked again. + self.saved.asked = true; + self.saved.save(&self.storage); + self.draft = Draft::blank(); + self.forget_tests(); + self.step = Step::Source; + self.view = View::Steps; + } + if synthetic { + self.close(); + } + } + + /// The text of the file an export writes, before it is saved. + fn export(&mut self, ui: &mut egui::Ui) -> Option { + let text = store::export(&self.draft.profile); + ui.label( + "This is the whole file: the addresses, headers and messages as typed. Key values \ + are not in it.", + ); + let height = (ui.available_height() - FOOTER).max(0.0); + let scroll = egui::ScrollArea::vertical().id_salt("data_source_file"); + scroll + .auto_shrink([false, false]) + .max_height(height) + .show(ui, |ui| { + let mut shown = text.as_str(); + ui.add( + TextEdit::multiline(&mut shown) + .code_editor() + .desired_width(f32::INFINITY), + ); + }); + let (save, back) = DialogFooter::new("Save file").secondary("Back").show(ui); + if save || back { + self.view = View::Steps; + } + let file = format!("{}.json", store::file_stem(&self.draft.profile.name)); + save.then_some(Outcome::Export { file, text }) + } + + /// The steps, with the status above them and the footer below. + fn steps(&mut self, ui: &mut egui::Ui, running: Option<&FeedState>) -> Option { + let ctx = ui.ctx().clone(); + if let Some(running) = running { + self.status(ui, running); + } + if !self.report.is_empty() { + Alert::warning(self.report.join("\n")).show(ui); + } + let dismissed = self.notice.as_ref().is_some_and(|notice| { + let alert = Alert::error(notice).with_title("Import").dismissible(true); + alert.show(ui).dismissed + }); + if dismissed { + self.notice = None; + } + TabBar::new(&[Step::Source, Step::History, Step::Live], &mut self.step).show(ui); + + let problem = self.draft.profile.problem(); + let taken = self.name_taken(); + let line = problem.is_some() || running.is_some(); + let below = FOOTER + if line { LINE } else { 0.0 }; + let height = (ui.available_height() - below).max(0.0); + let mut outcome = None; + let scroll = egui::ScrollArea::both().id_salt("data_source_step"); + scroll + .auto_shrink([false, false]) + .max_height(height) + .show(ui, |ui| { + // The margin keeps the fields clear of the scroll bar. + let margin = egui::Margin { + right: 12, + ..egui::Margin::ZERO + }; + egui::Frame::new() + .inner_margin(margin) + .show(ui, |ui| match self.step { + Step::Source => outcome = self.source(ui, &ctx, running.is_some()), + Step::History => self.history(ui, &ctx), + Step::Live => self.live(ui, &ctx), + }); + }); + + if let Some(problem) = &problem { + let warning = ui.active_theme().ui.warning; + ui.add(egui::Label::new(RichText::new(problem).color(warning)).truncate()); + } else if running.is_some() { + ui.add(egui::Label::new(RichText::new(RECONNECTS).weak()).truncate()); + } + let mut save = false; + let footer = DialogFooter::new("Connect").secondary("Cancel"); + let footer = footer.primary_enabled(problem.is_none() && !taken); + let (connect, cancel) = footer.show_with_left(ui, |ui| { + if self.can_save { + let named = + !self.draft.profile.name.is_empty() && !taken && self.ready_draft().is_none(); + save = ui + .add(Button::new("Save").outlined().enabled(named)) + .clicked(); + } + }); + if cancel { + self.close(); + } + if save { + self.store_draft(); + } + if connect { + outcome = self.connect(); + } + outcome + } + + /// The state of the chart's feed while own data is on. + fn status(&self, ui: &mut egui::Ui, running: &FeedState) { + let state = match running.status { + None => "no live stream", + Some(FeedStatus::Live) => "live", + Some(FeedStatus::Connecting) => "connecting", + // Disconnected. The session opens the connection again by itself. + Some(_) => "disconnected, reconnecting", + }; + let name = self.saved.current.clone().unwrap_or_default(); + let mut parts = vec![name, state.to_owned()]; + if running.loading_history { + parts.push("loading history".to_owned()); + } + if running.rejected_bars > 0 { + let bars = usize::try_from(running.rejected_bars).unwrap_or(usize::MAX); + parts.push(format!("{} dropped as invalid", counted(bars, "bar"))); + } + // The chart keeps its most recent error. A connection error no longer describes a stream + // that is live again. + let live = running.status == Some(FeedStatus::Live); + let error = running.last_error.as_ref(); + let error = error.filter(|error| !(live && matches!(error, FeedError::Network(_)))); + ui.horizontal_wrapped(|ui| { + ui.label(parts.join(" · ")); + if let Some(error) = error { + ui.error_label(error.to_string()); + } + }); + } + + /// Whether another saved profile has the name of the draft, or a ready profile that the + /// draft no longer equals: a ready profile is never saved, so a changed one needs another + /// name. + fn name_taken(&self) -> bool { + let draft = &self.draft; + let other = |saved: &Profile| { + saved.name == draft.profile.name && Some(&saved.name) != draft.origin.as_ref() + }; + self.saved.profiles.iter().any(other) + || self + .ready_draft() + .is_some_and(|ready| *ready != draft.profile) + } + + /// The ready profile with the draft's name. + fn ready_draft(&self) -> Option<&Profile> { + let name = &self.draft.profile.name; + self.ready.iter().find(|ready| ready.name == *name) + } + + /// Stores the draft: it replaces the saved profile it was loaded from, or is appended when + /// it is new or imported. Its key values are kept when the box is ticked and forgotten + /// otherwise. + fn store_draft(&mut self) { + let profile = self.draft.profile.clone(); + let name = profile.name.clone(); + let origin = self.draft.origin.as_ref(); + let saved = &mut self.saved; + let place = + origin.and_then(|origin| saved.profiles.iter().position(|held| held.name == *origin)); + match place { + Some(at) => { + let old = std::mem::replace(&mut saved.profiles[at], profile).name; + if old != name { + // A changed name renames: the kept keys and the profile in use follow it. + for (kept, _) in &mut saved.keys { + if *kept == old { + kept.clone_from(&name); + } + } + if saved.current.as_ref() == Some(&old) { + saved.current = Some(name.clone()); + } + } + } + None => saved.profiles.push(profile), + } + // Key values are kept only by choice. + saved.keys.retain(|(kept, _)| *kept != name); + if self.draft.keep { + saved.keys.push((name.clone(), self.draft.secrets())); + } + self.draft.origin = Some(name); + self.saved.save(&self.storage); + } + + /// Checks the templates, stores the draft and asks the application to connect it. + fn connect(&mut self) -> Option { + let secrets = self.draft.secrets(); + self.report = findings(&self.draft.profile, &secrets, Scope::Both); + if !self.report.is_empty() { + return None; + } + // A ready profile connects as shipped and is not stored. + if self.ready_draft().is_none() { + self.store_draft(); + } + self.saved.own = true; + self.saved.current = Some(self.draft.profile.name.clone()); + self.saved.save(&self.storage); + self.close(); + let profile = Box::new(self.draft.profile.clone()); + Some(Outcome::Connect { profile, secrets }) + } + + /// Removes the saved profile the draft was loaded from. + fn delete(&mut self) { + let Some(name) = self.draft.origin.take() else { + return; + }; + let saved = &mut self.saved; + saved.profiles.retain(|profile| profile.name != name); + saved.keys.retain(|(kept, _)| *kept != name); + if saved.current.as_ref() == Some(&name) { + saved.current = None; + } + saved.save(&self.storage); + self.draft = Draft::current(&self.saved, &self.ready); + self.forget_tests(); + } + + /// The Source step: what the profile is and what it offers. + fn source(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, on: bool) -> Option { + /// What a button beside the profile list asks for. + #[derive(Clone, Copy)] + enum Pick { + Load, + New, + Import, + Export, + Delete, + } + let profiles = self.ready.iter().chain(&self.saved.profiles); + let names = profiles.map(|profile| Some(profile.name.clone())); + let names: Vec> = names.collect(); + let mut chosen = self.draft.origin.clone(); + // The profile on the chart stays, and a ready one is never stored. + let on_chart = self.saved.own && self.saved.current == chosen; + let ready = |name: &String| self.ready.iter().any(|ready| ready.name == *name); + let deletable = chosen.as_ref().is_some_and(|name| !ready(name)) && !on_chart; + let idle = self.import.is_none(); + let mut pick = None; + FormRow::new("Profile").show(ui, |ui| { + // On a phone the buttons go on below the list. + ui.horizontal_wrapped(|ui| { + let label = + |name: &Option| name.clone().unwrap_or_else(|| "New profile".into()); + if ui.combo_select("data_source_profile", &mut chosen, names, label) { + pick = Some(Pick::Load); + } + let buttons = [ + ("New", Pick::New, true), + ("Import", Pick::Import, idle), + ("Export", Pick::Export, true), + ("Delete", Pick::Delete, deletable), + ]; + for (label, action, enabled) in buttons { + if ui + .add(Button::new(label).outlined().small().enabled(enabled)) + .clicked() + { + pick = Some(action); + } + } + }); + }); + match pick { + Some(Pick::Load) => { + let mut listed = self.saved.profiles.iter().chain(&self.ready); + let named = |name: String| listed.find(|saved| saved.name == name); + if let Some(profile) = chosen.and_then(named) { + self.draft = Draft::saved(&self.saved, profile); + self.forget_tests(); + } + } + Some(Pick::New) => { + self.draft = Draft::blank(); + self.forget_tests(); + } + Some(Pick::Import) => self.pick_file(ctx), + Some(Pick::Export) => self.view = View::Export, + Some(Pick::Delete) => self.delete(), + None => {} + } + + let taken = self.name_taken().then(|| match self.ready_draft() { + Some(_) => "A ready profile has this name. Rename it to save your own copy.", + None => "Another saved profile has this name.", + }); + let draft = &mut self.draft; + FormRow::new("Name").show(ui, |ui| { + ui.add(TextEdit::singleline(&mut draft.profile.name).desired_width(f32::INFINITY)); + }); + if let Some(taken) = taken { + ui.error_label(taken); + } + let symbols = FormRow::new("Symbols").description( + "Spelled as the service expects them, separated by commas or line ends. The chart \ + opens on the first.", + ); + symbols.show(ui, |ui| { + let field = TextEdit::multiline(&mut draft.symbols).desired_rows(2); + if ui.add(field.desired_width(f32::INFINITY)).changed() { + draft.profile.symbols = listed(&draft.symbols); + } + }); + let intervals = FormRow::new("Intervals").description( + "A chart interval and the text the service expects for it, such as 1m, 60 or 60000. \ + The chart opens on the first row.", + ); + // The table takes the full width below its label, so that a row fits a phone. Out of + // the row, its controls take the label as their name. + intervals.show(ui, |_| {}); + ui.name_inputs("Intervals", |ui| { + interval_rows(ui, &mut draft.profile.intervals); + }); + let zone = FormRow::new("Time zone").description( + "The zone of every time that names none, and of bounds printed as dates: UTC, a \ + name such as America/New_York or an offset such as +05:30.", + ); + zone.show(ui, |ui| { + if ui + .add(TextEdit::singleline(&mut draft.zone).desired_width(240.0)) + .changed() + && let Ok(zone) = draft.zone.trim().parse() + { + draft.profile.time_zone = zone; + } + }); + if draft.zone.trim().parse::().is_err() { + let kept = draft.profile.time_zone.name(); + ui.error_label(format!("This is not a time zone. {kept} stays in use.")); + } + let step = FormRow::new("Price step").description( + "The smallest price change of the symbols, such as 0.01. The footprint groups \ + trades by it; without it the footprint draws candles.", + ); + step.show(ui, |ui| { + let field = TextEdit::singleline(&mut draft.step).hint_text("0.01"); + if ui.add(field.desired_width(120.0)).changed() + && let Some(step) = price_step(&draft.step) + { + draft.profile.tick_size = step; + } + }); + if price_step(&draft.step).is_none() { + ui.error_label("A price step is a number above zero, or nothing."); + } + let keys = FormRow::new("Keys").description( + "Written as {name} in an address, a header, a body or a message. A key typed \ + there as it is becomes part of the profile and is saved and exported with it.", + ); + keys.show(ui, |_| {}); + key_rows(ui, &mut draft.profile.keys, &mut draft.values); + let keep = egui::Checkbox::new(&mut draft.keep, KEEP); + ui.add_enabled(self.can_save, keep); + if draft.keep { + ui.weak(KEPT); + } + ui.weak("Keys are sent only to the endpoints of this profile and are never exported."); + + if on + && ui + .add(Button::new("Use synthetic data").outlined()) + .clicked() + { + self.saved.own = false; + self.saved.save(&self.storage); + self.close(); + return Some(Outcome::Synthetic); + } + None + } + + /// Opens the system's file picker. Its answer arrives through `self.import`. + fn pick_file(&mut self, ctx: &egui::Context) { + let (answer, picked) = std::sync::mpsc::channel(); + self.import = Some(picked); + let ctx = ctx.clone(); + let too_large = || "The file is larger than 1 MiB.".to_owned(); + #[cfg(not(target_arch = "wasm32"))] + std::thread::spawn(move || { + let read = || -> Result, String> { + let picker = rfd::FileDialog::new().add_filter("Profile", &["json"]); + let Some(path) = picker.pick_file() else { + return Ok(None); + }; + // Refused before it is read. + let size = std::fs::metadata(&path) + .map_err(|error| error.to_string())? + .len(); + if size > LARGEST_FILE { + return Err(too_large()); + } + let text = std::fs::read_to_string(path).map_err(|error| error.to_string())?; + Ok(Some(text)) + }; + let _ = answer.send(read()); + ctx.request_repaint(); + }); + #[cfg(target_arch = "wasm32")] + wasm_bindgen_futures::spawn_local(async move { + let picker = rfd::AsyncFileDialog::new().add_filter("Profile", &["json"]); + let read = match picker.pick_file().await { + Some(file) if file.inner().size() > LARGEST_FILE as f64 => Err(too_large()), + Some(file) => { + let text = String::from_utf8(file.read().await); + text.map(Some) + .map_err(|_| "The file is not UTF-8 text.".to_owned()) + } + None => Ok(None), + }; + let _ = answer.send(read); + ctx.request_repaint(); + }); + } + + /// Takes the answer of the file picker when it has arrived. + fn poll_import(&mut self) { + let Some(picked) = self.import.take() else { + return; + }; + match picked.try_recv() { + Ok(Ok(Some(text))) => self.import_text(&text), + Ok(Ok(None)) => {} + Ok(Err(error)) => self.notice = Some(error), + Err(TryRecvError::Empty) => self.import = Some(picked), + Err(TryRecvError::Disconnected) => { + self.notice = Some("The file selection failed.".to_owned()); + } + } + } + + /// Makes the profile of an exported file the draft, as a new profile without key values. + fn import_text(&mut self, text: &str) { + let mut profile = match store::import(text) { + Ok(profile) => profile, + Err(error) => { + self.notice = Some(error); + return; + } + }; + // An import never replaces a saved profile. + let base = profile.name.clone(); + let mut number = 2; + while self + .saved + .profiles + .iter() + .chain(&self.ready) + .any(|saved| saved.name == profile.name) + { + profile.name = format!("{base} {number}"); + number += 1; + } + self.draft = Draft::of(profile, Vec::new(), false, None); + self.forget_tests(); + self.notice = None; + self.step = Step::Source; + self.view = View::Steps; + // Names the keys to enter. + self.report = findings(&self.draft.profile, &self.draft.secrets(), Scope::Both); + } + + /// The symbol and the interval of the Tests, when the draft lists both. + fn target(&self) -> Option<(String, Timeframe)> { + let profile = &self.draft.profile; + let symbol = profile.symbols.get(self.symbol)?; + Some((symbol.clone(), profile.intervals.get(self.interval)?.chart)) + } + + /// The two choices beside `Test`: a symbol and an interval of the draft. + fn target_choices(&mut self, ui: &mut egui::Ui) { + let profile = &self.draft.profile; + self.symbol = self.symbol.min(profile.symbols.len().saturating_sub(1)); + self.interval = self.interval.min(profile.intervals.len().saturating_sub(1)); + let symbol = |at: &usize| profile.symbols.get(*at).cloned().unwrap_or_default(); + ui.name_inputs("Symbol", |ui| { + let symbols = 0..profile.symbols.len(); + ui.combo_select("test_symbol", &mut self.symbol, symbols, symbol); + }); + let interval = |at: &usize| { + let row = profile.intervals.get(*at); + row.map(|row| row.chart.to_string()).unwrap_or_default() + }; + let rows = 0..profile.intervals.len(); + ui.name_inputs("Interval", |ui| { + ui.combo_select("test_interval", &mut self.interval, rows, interval); + }); + } + + /// The History step: the request, its Test and the mapping of the response. + fn history(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { + let keys = key_names(&self.draft.profile.keys); + let mut on = self.draft.profile.history.is_some(); + if ui.checkbox(&mut on, "Use REST history").changed() { + let draft = &mut self.draft; + if on { + draft.profile.history = Some(draft.history_off.take().unwrap_or_default()); + } else { + draft.history_off = draft.profile.history.take(); + } + } + let Some(history) = &mut self.draft.profile.history else { + return; + }; + FormRow::new("URL").show(ui, |ui| { + let hint = "https://api.example.com/bars?symbol={symbol}&interval={interval}&to={to}"; + let field = TextEdit::singleline(&mut history.url).hint_text(hint); + ui.add(field.desired_width(f32::INFINITY)); + }); + ui.hint_label(format!( + "Placeholders: {{symbol}}, {{symbol_lower}}, {{interval}}, {{from}}, {{to}}, \ + {{limit}}{keys}. A key typed here instead of as {{name}} is saved and exported with \ + the profile." + )); + FormRow::new("Headers").show(ui, |_| {}); + header_rows(ui, &mut history.headers); + let body = FormRow::new("Body").description( + "Empty sends GET. Anything else is sent with POST, as application/json unless a \ + header names another content type.", + ); + body.show(ui, |ui| { + let field = TextEdit::multiline(&mut history.body).desired_rows(2); + ui.add(field.desired_width(f32::INFINITY)); + }); + FormRow::new("Bounds").show(ui, |ui| { + let forms = [ + RangeFormat::Seconds, + RangeFormat::Milliseconds, + RangeFormat::Microseconds, + RangeFormat::Nanoseconds, + RangeFormat::Iso8601, + RangeFormat::Date, + RangeFormat::CompactDate, + ]; + ui.horizontal_wrapped(|ui| { + let label = |form: &RangeFormat| range_label(form).to_owned(); + ui.combo_select("range_format", &mut history.range, forms, label); + ui.weak("the form of {from} and {to}"); + }); + }); + FormRow::new("Page size").show(ui, |ui| { + ui.horizontal_wrapped(|ui| { + ui.add(egui::DragValue::new(&mut history.page_size).range(1..=100_000)); + ui.weak("the most bars asked for in one request"); + }); + }); + + let ready = self.target().is_some(); + let waiting = self.history.pending.is_some(); + let mut test = false; + ui.horizontal_wrapped(|ui| { + self.target_choices(ui); + test = ui + .add(Button::new("Test").primary().enabled(ready)) + .clicked(); + if waiting { + ui.weak("waiting for the response"); + } + }); + if test { + self.test_history(ctx); + } + self.history_mapping(ui); + } + + /// Sends the request a chart's first load sends. The answer arrives through + /// `self.history.pending`. + fn test_history(&mut self, ctx: &egui::Context) { + let secrets = self.draft.secrets(); + self.report = findings(&self.draft.profile, &secrets, Scope::History); + let Some((symbol, timeframe)) = self.target() else { + return; + }; + if !self.report.is_empty() { + return; + } + let profile = &self.draft.profile; + // The clock a chart in the profile's zone has. + let clock = BarClock::new(timeframe).with_timezone(profile.time_zone.clone()); + let test = &mut self.history; + test.proposed = false; + test.error = None; + // A Test in flight is superseded: its answer goes to a slot nothing reads. + test.pending = None; + match feed::latest(profile, &secrets, &symbol, timeframe, &clock, Utc::now()) { + Err(error) => test.error = Some(error), + Ok(request) => { + let answer = Answer::default(); + let shown = conceal(endpoint(&request.url), &secrets); + test.pending = Some((answer.clone(), shown, symbol.clone())); + let repaint = ctx.clone(); + http::fetch(request, move |result| { + // A reason can repeat the endpoint, and a key in its path. + let result = result.map_err(|failure| match failure { + Failure::Refused(reason) => Failure::Refused(conceal(&reason, &secrets)), + failure => failure, + }); + *answer.lock().unwrap_or_else(PoisonError::into_inner) = Some(result); + repaint.request_repaint(); + }); + } + } + } + + /// Takes the answer of the history Test when it has arrived. + fn poll_history(&mut self) { + let test = &mut self.history; + let Some((answer, endpoint, symbol)) = &test.pending else { + return; + }; + let Some(result) = answer.lock().unwrap_or_else(PoisonError::into_inner).take() else { + return; + }; + test.endpoint.clone_from(endpoint); + let symbol = symbol.clone(); + test.pending = None; + let failed = |failure: Failure| format!("{}: {failure}", test.endpoint); + let body = match result { + Ok(body) => body, + Err(failure) => { + test.error = Some(failed(failure)); + return; + } + }; + let sample: Value = match serde_json::from_str(&body) { + Ok(sample) => sample, + Err(error) => { + test.error = Some(failed(Failure::Unreadable(format!("not JSON: {error}")))); + return; + } + }; + test.proposals = shape::propose(&sample); + if let Some(history) = &mut self.draft.profile.history { + // A mapping the visitor made stays. An empty one takes the most likely reading. + let unmapped = history.rows == Rows::default() && history.bar == BarFields::default(); + if unmapped && let Some(first) = test.proposals.first() { + history.rows = first.rows.clone(); + history.bar = first.bar.clone(); + test.proposed = true; + } + test.slot = Fields::bar(&mut history.bar).next(Slot::Rows); + } + test.sample = Some(sample); + test.symbol = symbol; + test.samples += 1; + } + + /// The preview of the sample, its two trees and the slots of the mapping. + fn history_mapping(&mut self, ui: &mut egui::Ui) { + let zone = self.draft.profile.time_zone.clone(); + let symbol = self.history.symbol.clone(); + let timeframe = self + .target() + .map_or(Timeframe::Min1, |(_, timeframe)| timeframe); + let test = &mut self.history; + let Some(history) = &mut self.draft.profile.history else { + return; + }; + if let Some(sample) = &test.sample { + let fresh = |preview: &Preview| { + preview.history == *history + && preview.zone == zone + && preview.timeframe == timeframe + && preview.samples == test.samples + }; + if !test.preview.as_ref().is_some_and(fresh) { + let clock = BarClock::new(timeframe).with_timezone(zone.clone()); + let rows = shape::rows(sample, &history.rows.for_symbol(&symbol)); + test.preview = Some(Preview { + history: history.clone(), + zone: zone.clone(), + timeframe, + samples: test.samples, + row: rows.ok().and_then(|rows| rows.into_iter().next()), + reading: feed::read( + sample, + history, + &symbol, + &zone, + &clock, + timeframe, + Utc::now(), + ), + }); + } + } + + if let Some(error) = &test.error { + Alert::error(error).show(ui); + } else if test.proposed { + Alert::info("Proposed mapping: confirm it or click the fields to use").show(ui); + } + match test.preview.as_ref().map(|preview| &preview.reading) { + Some(Ok(reading)) => preview_table(ui, reading, &zone), + Some(Err(error)) => { + // Shown as a failed request is: the endpoint, then the reason. + let failure = Failure::Unreadable(error.clone()); + Alert::error(format!("{}: {failure}", test.endpoint)).show(ui); + } + None => {} + } + let others = test + .proposals + .iter() + .filter(|proposal| proposal.rows != history.rows); + let others: Vec<&Proposal> = others.collect(); + let mut taken = None; + if !others.is_empty() { + ui.horizontal_wrapped(|ui| { + ui.weak("Other ways to read the response:"); + for proposal in others { + let text = format!( + "{} at {}, {}", + layout_label(&proposal.rows.layout), + place(&proposal.rows.path), + counted(proposal.count, "row") + ); + if ui.add(Button::new(text).outlined().small()).clicked() { + taken = Some((proposal.rows.clone(), proposal.bar.clone())); + } + } + }); + } + if let Some((rows, bar)) = taken { + history.rows = rows; + history.bar = bar; + } + + // The place of the rows in the sample, for the marks and the slots. + let found = history.rows.for_symbol(&symbol); + let row = test + .preview + .as_ref() + .and_then(|preview| preview.row.as_ref()); + let mut clicked_response = None; + let mut clicked_row = None; + if let Some(sample) = &test.sample { + let mut response = vec![(found.path.clone(), Slot::Rows.label())]; + if let Layout::Arrays { + header: Some(header), + } = &found.layout + { + response.push((header.clone(), Slot::Header.label())); + } + let fields = Fields::bar(&mut history.bar).marks(); + let samples = test.samples; + ui.columns(2, |columns| { + columns[0].strong("Response"); + tree_area("response_tree").show(&mut columns[0], |ui| { + let id = egui::Id::unique(("data_source_response", samples)); + clicked_response = tree::show(ui, id, sample, &response); + }); + columns[1].strong("First row"); + match row { + Some(row) => { + tree_area("row_tree").show(&mut columns[1], |ui| { + let id = egui::Id::unique(("data_source_row", samples)); + clicked_row = tree::show(ui, id, row, &fields); + }); + } + None => { + columns[1].weak("The mapping finds no row."); + } + } + }); + } else { + ui.weak("Test fetches the newest page and shows it here, to map by clicking."); + } + + let mut clear = None; + FormGrid::new("history_slots").columns(4).show(ui, |ui| { + slot_cells( + ui, + Slot::Rows, + &mut test.slot, + &found.path, + true, + test.sample.as_ref(), + ); + // The last cell is as wide as the step leaves it, and wraps on a phone. + ui.horizontal_wrapped(|ui| { + if clear_button(ui, !history.rows.path.is_empty()) { + clear = Some(Slot::Rows); + } + ui.weak(layout_label(&history.rows.layout)); + }); + ui.end_row(); + if let Layout::Arrays { header } = &found.layout { + let path = header.clone().unwrap_or_default(); + slot_cells( + ui, + Slot::Header, + &mut test.slot, + &path, + false, + test.sample.as_ref(), + ); + if clear_button(ui, header.is_some()) { + clear = Some(Slot::Header); + } + ui.end_row(); + } + Fields::bar(&mut history.bar).rows(ui, row, &mut test.slot); + }); + Fields::bar(&mut history.bar).forms(ui, row, &zone); + match clear { + Some(Slot::Rows) => history.rows.path.clear(), + Some(_) => history.rows.layout = Layout::Arrays { header: None }, + None => {} + } + + // A click fills the active slot when the node is in the tree of that slot. + if let (Some(path), Some(sample)) = (clicked_response, &test.sample) { + let filled = match test.slot { + Slot::Rows => { + history.rows = rows_at(sample, path, &history.rows.layout); + true + } + Slot::Header => match &mut history.rows.layout { + Layout::Arrays { header } => { + *header = Some(path); + true + } + _ => false, + }, + _ => false, + }; + if filled { + test.slot = Fields::bar(&mut history.bar).next(test.slot); + } + } + if let (Some(path), Some(row)) = (clicked_row, row) { + let mut fields = Fields::bar(&mut history.bar); + if fields.slots().contains(&test.slot) { + let value = at(row, &path).cloned().unwrap_or(Value::Null); + fields.assign(test.slot, path, &value); + test.slot = fields.next(test.slot); + } + } + } + + /// The Live step: the connection, its Test, the log and the routes. + fn live(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { + let keys = key_names(&self.draft.profile.keys); + let mut on = self.draft.profile.stream.is_some(); + if ui.checkbox(&mut on, "Use a WebSocket stream").changed() { + let draft = &mut self.draft; + if on { + draft.profile.stream = Some(draft.stream_off.take().unwrap_or_default()); + } else { + draft.stream_off = draft.profile.stream.take(); + self.live.session = None; + } + } + let Some(stream) = &mut self.draft.profile.stream else { + return; + }; + FormRow::new("URL").show(ui, |ui| { + let field = TextEdit::singleline(&mut stream.url).hint_text("wss://stream.example.com"); + ui.add(field.desired_width(f32::INFINITY)); + }); + ui.hint_label(format!( + "{NO_HEADERS} Write {{name}} in the URL, \ + in a subprotocol or in a connect message to send the key of that name there. \ + Placeholders: {{symbol}}, {{symbol_lower}}, {{interval}}{keys}. A key typed here \ + instead of as {{name}} is saved and exported with the profile." + )); + let protocols = FormRow::new("Subprotocols").description( + "Offer one only when the service answers with it: a connection that offers \ + subprotocols ends when the server selects none.", + ); + protocols.show(ui, |_| {}); + ui.name_inputs("Subprotocols", |ui| { + text_rows(ui, "protocol", &mut stream.protocols, "Add subprotocol"); + }); + let connect = FormRow::new("Connect messages").description( + "Sent as typed, in this order, every time the socket opens: the login first, then \ + the subscribe message.", + ); + connect.show(ui, |_| {}); + ui.name_inputs("Connect messages", |ui| { + text_rows(ui, "connect", &mut stream.connect, "Add message"); + }); + let keep_alive = FormRow::new("Keep-alive") + .description("A message and its period in seconds. An empty message sends none."); + keep_alive.show(ui, |ui| { + // The message leaves room for the period beside it. + let period = ui.spacing().interact_size.x + ui.spacing().item_spacing.x; + let width = (ui.available_width() - period).min(280.0); + ui.add(TextEdit::singleline(&mut stream.keep_alive).desired_width(width)); + ui.add(egui::DragValue::new(&mut stream.keep_alive_every).range(1..=3600)); + }); + + let ready = self.target().is_some(); + let running = self.live.session.is_some(); + let mut pressed = false; + ui.horizontal_wrapped(|ui| { + self.target_choices(ui); + let button = Button::new(if running { "Stop" } else { "Test" }).primary(); + pressed = ui.add(button.enabled(running || ready)).clicked(); + }); + if pressed && running { + self.live.session = None; + } else if pressed { + self.test_live(ctx); + } + self.live_mapping(ui); + } + + /// Starts a session as the feed does for a subscription. Its events arrive through + /// `self.live.queue`. + fn test_live(&mut self, ctx: &egui::Context) { + let secrets = self.draft.secrets(); + self.report = findings(&self.draft.profile, &secrets, Scope::Stream); + let profile = &self.draft.profile; + let (Some((symbol, timeframe)), Some(stream)) = (self.target(), &profile.stream) else { + return; + }; + if !self.report.is_empty() { + return; + } + let interval = profile.service_interval(timeframe).unwrap_or_default(); + let values = profile::stream_values(&symbol, interval, &secrets); + let borrowed: Vec<(&str, &str)> = values + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())) + .collect(); + let url = profile::fill_url(&stream.url, &borrowed); + // A new queue, so that an event of an earlier session cannot reach the new log. + let queue = Events::default(); + let events = queue.clone(); + let repaint = ctx.clone(); + let shown = conceal(endpoint(&url), &secrets); + let session = Session::open(stream.clone(), values, move |event| { + // A reason can repeat the endpoint, and a key in its path. + let event = match event { + StreamEvent::Closed { reason, retry_in } => StreamEvent::Closed { + reason: conceal(&reason, &secrets), + retry_in, + }, + event => event, + }; + let mut events = events.lock().unwrap_or_else(PoisonError::into_inner); + events.push((Utc::now(), event)); + repaint.request_repaint(); + }); + self.live = LiveTest { + session: Some(session), + queue, + endpoint: shown, + route: self.live.route, + slot: self.live.slot, + ..LiveTest::default() + }; + } + + /// Moves the events of the session into the log and routes the log with the stream of the + /// draft, so that it shows what the feed would do with the mapping as it stands. + fn poll_live(&mut self) { + let live = &mut self.live; + let events = + std::mem::take(&mut *live.queue.lock().unwrap_or_else(PoisonError::into_inner)); + let Some(stream) = &mut self.draft.profile.stream else { + return; + }; + for (at, event) in events { + let note = |badge, text, fault| LineKind::Note { badge, text, fault }; + let kind = match event { + StreamEvent::Open { again: false } => { + live.opened = true; + live.failure = None; + note("open", "connected, connect messages sent".to_owned(), false) + } + StreamEvent::Open { again: true } => note( + "open", + "reconnected, connect messages sent again".to_owned(), + false, + ), + StreamEvent::Message { text, .. } => { + let parsed = serde_json::from_str(&text); + let root = parsed.unwrap_or_else(|_| Value::String(text.clone())); + let routed = stream::route(stream, &text); + offer_conditions(stream, &routed); + // A new log selects its first message by itself. + if live.selected.is_none() { + live.selected = Some(live.lines); + } + LineKind::Message(Message { text, root, routed }) + } + StreamEvent::Unreadable { reason } => note("unreadable", reason, true), + StreamEvent::Closed { reason, retry_in } => { + let seconds = retry_in.as_secs(); + let text = format!("{}: {reason}. Reconnecting in {seconds} s", live.endpoint); + if !live.opened { + live.failure = Some(text.clone()); + } + note("closed", text, true) + } + }; + let number = live.lines; + live.log.push_back(Line { number, at, kind }); + live.lines += 1; + if live.log.len() > LOG_LINES { + live.log.pop_front(); + } + } + + // An edit of the place of the records, of the routing field or of a route: every line + // is routed again, and offers its condition values again. + let basis = basis(stream); + if live.basis.as_ref() != Some(&basis) { + for line in &mut live.log { + if let LineKind::Message(message) = &mut line.kind { + message.routed = stream::route(stream, &message.text); + offer_conditions(stream, &message.routed); + } + } + if let Some(message) = &mut live.unrouted { + message.routed = stream::route(stream, &message.text); + } + live.basis = Some(basis); + } + + // The oldest message with a record without a route stays in view until every record of + // it has one. The next one then takes its place. + if live + .unrouted + .as_ref() + .is_some_and(|message| !message.unrouted()) + { + live.unrouted = None; + } + if live.unrouted.is_none() { + let lost = |line: &Line| match &line.kind { + LineKind::Message(message) if message.unrouted() => Some(message.clone()), + _ => None, + }; + live.unrouted = live.log.iter().find_map(lost); + } + } + + /// The first message without a route, the log, its two trees, the routes and their slots. + fn live_mapping(&mut self, ui: &mut egui::Ui) { + let zone = self.draft.profile.time_zone.clone(); + let timeframe = self + .target() + .map_or(Timeframe::Min1, |(_, timeframe)| timeframe); + let live = &mut self.live; + let Some(stream) = &mut self.draft.profile.stream else { + return; + }; + if let Some(failure) = &live.failure { + Alert::error(failure).show(ui); + } + + // The first message without a route. + let mut added = None; + if let Some(message) = &live.unrouted { + let text = cut(&message.text, 300); + Alert::warning(format!("No route for this message:\n{text}")).show(ui); + let lost = message.routed.iter().find_map(|record| match record { + Routed::Unrouted { record } => Some(record), + _ => None, + }); + ui.horizontal_wrapped(|ui| { + if stream.route_by.is_empty() { + let button = Button::new("Route every message here").outlined().small(); + if ui.add(button).clicked() { + added = Some(String::new()); + } + ui.weak("or click the field that tells the kinds of message apart"); + return; + } + match lost.and_then(|record| routing_value(stream, &message.root, record)) { + Some(value) => { + let text = format!("Add route for \"{value}\""); + if ui.add(Button::new(text).outlined().small()).clicked() { + added = Some(value); + } + } + None => { + let field = printed(&stream.route_by); + ui.weak(format!("The record has no field {field}.")); + } + } + }); + } + if let Some(value) = added { + // The new route ignores its records until the visitor chooses its kind. + let kind = RouteKind::Ignore; + stream.routes.push(Route { value, kind }); + live.route = stream.routes.len() - 1; + } + + ui.strong("Log"); + let mut selected = None; + let log = egui::ScrollArea::vertical() + .id_salt("data_source_log") + .max_height(LOG) + .min_scrolled_height(LOG); + log.auto_shrink([false, true]) + .stick_to_bottom(true) + .show(ui, |ui| { + if live.log.is_empty() { + let waiting = live.session.is_some(); + ui.weak(if waiting { + "Waiting for the connection." + } else { + "Test connects and lists every message here." + }); + } + let fault = ui.active_theme().ui.error; + for line in &live.log { + ui.horizontal(|ui| { + let arrived = line.at.with_timezone(&zone).naive_local(); + ui.weak(arrived.format("%H:%M:%S").to_string()); + match &line.kind { + LineKind::Note { + badge, + text, + fault: true, + } => { + ui.label(RichText::new(*badge).small().color(fault)); + ui.add(egui::Label::new(text.as_str()).truncate()); + } + LineKind::Note { badge, text, .. } => { + ui.label(RichText::new(*badge).small()); + ui.add(egui::Label::new(text.as_str()).truncate()); + } + LineKind::Message(message) => { + for (text, dim) in badges(stream, &message.routed) { + let badge = RichText::new(text).small(); + ui.label(if dim { badge.weak() } else { badge.strong() }); + } + let text = RichText::new(message.text.as_str()).monospace(); + let chosen = live.selected == Some(line.number); + let button = egui::Button::new(text).frame(false).truncate(); + if ui.add(button.selected(chosen)).clicked() { + selected = Some(line.number); + } + } + } + }); + } + }); + if let Some(number) = selected { + live.selected = Some(number); + live.record = 0; + } + + // The selected message, and its records as a session splits it. + let chosen = |line: &&Line| Some(line.number) == live.selected; + let message = live + .log + .iter() + .find(chosen) + .and_then(|line| match &line.kind { + LineKind::Message(message) => Some((line.number, message)), + LineKind::Note { .. } => None, + }); + let records = message.map_or_else(Vec::new, |(_, message)| split(stream, &message.text)); + live.record = live.record.min(records.len().saturating_sub(1)); + let shown = live.record; + let record = records.get(shown); + live.route = live.route.min(stream.routes.len().saturating_sub(1)); + + let mut in_message = vec![(stream.records.clone(), Slot::Records.label())]; + let mut in_record = Vec::new(); + if !stream.route_by.is_empty() { + in_message.push((stream.route_by.clone(), Slot::RouteBy.label())); + in_record.push((stream.route_by.clone(), Slot::RouteBy.label())); + } + let route = stream.routes.get_mut(live.route); + if let Some(fields) = route.and_then(|route| Fields::route(&mut route.kind)) { + in_record.extend(fields.marks()); + } + let mut clicked_message = None; + let mut clicked_record = None; + let mut step = 0_isize; + ui.columns(2, |columns| { + columns[0].strong("Message"); + match message { + Some((number, message)) => { + tree_area("message_tree").show(&mut columns[0], |ui| { + let id = egui::Id::unique(("data_source_message", number)); + clicked_message = tree::show(ui, id, &message.root, &in_message); + }); + } + None => { + columns[0].weak("Select a message of the log."); + } + } + columns[1].strong("Record"); + if records.len() > 1 { + columns[1].horizontal(|ui| { + ui.label(format!("record {} of {}", shown + 1, records.len())); + if ui + .add(Button::new("Previous").small().enabled(shown > 0)) + .clicked() + { + step = -1; + } + let more = shown + 1 < records.len(); + if ui.add(Button::new("Next").small().enabled(more)).clicked() { + step = 1; + } + }); + } + if let (Some((number, _)), Some(record)) = (message, record) { + tree_area("record_tree").show(&mut columns[1], |ui| { + let id = egui::Id::unique(("data_source_record", number, shown)); + clicked_record = tree::show(ui, id, record, &in_record); + }); + } + }); + live.record = shown.saturating_add_signed(step); + + let root = message.map(|(_, message)| &message.root); + let mut clear = None; + FormGrid::new("live_slots").columns(4).show(ui, |ui| { + slot_cells( + ui, + Slot::Records, + &mut live.slot, + &stream.records, + true, + root, + ); + if clear_button(ui, !stream.records.is_empty()) { + clear = Some(Slot::Records); + } + ui.end_row(); + // The routing field is looked up in the record and then in the message. + let holder = record.filter(|record| at(record, &stream.route_by).is_some()); + let base = holder.or(root); + slot_cells( + ui, + Slot::RouteBy, + &mut live.slot, + &stream.route_by, + false, + base, + ); + if clear_button(ui, !stream.route_by.is_empty()) { + clear = Some(Slot::RouteBy); + } + ui.end_row(); + }); + match clear { + Some(Slot::Records) => stream.records.clear(), + Some(_) => stream.route_by.clear(), + None => {} + } + + ui.strong("Routes"); + let mut removed = None; + for (index, route) in stream.routes.iter_mut().enumerate() { + ui.push_id(("route", index), |ui| { + // On a phone the kinds go on below the value. + ui.horizontal_wrapped(|ui| { + let name = format!("Route {}", index + 1); + if ui + .add(Button::new(name).small().selected(live.route == index)) + .clicked() + { + live.route = index; + } + let value = TextEdit::singleline(&mut route.value); + ui.add( + value + .hint_text("value of the routing field") + .desired_width(180.0), + ); + let kinds = [ + ("Ignore", RouteKind::Ignore), + ("Bars", RouteKind::Bars(BarFields::default())), + ("Trades", RouteKind::Trades(TradeFields::default())), + ]; + for (label, kind) in kinds { + let held = + std::mem::discriminant(&route.kind) == std::mem::discriminant(&kind); + if ui.add(Button::new(label).small().selected(held)).clicked() && !held { + route.kind = kind; + live.route = index; + // The fields of the new kind are mapped next. + let fields = Fields::route(&mut route.kind); + live.slot = + fields.map_or(live.slot, |fields| fields.next(Slot::Records)); + } + } + if ui.add(Button::new("Remove").small()).clicked() { + removed = Some(index); + } + }); + }); + } + if let Some(index) = removed { + stream.routes.remove(index); + } + if ui + .add(Button::new("Add route").outlined().small()) + .clicked() + { + stream.routes.push(Route::default()); + live.route = stream.routes.len() - 1; + } + + // The slots of the selected route, and what the feed reads from the record shown. + if let Some(route) = stream.routes.get_mut(live.route) { + if let Some(mut fields) = Fields::route(&mut route.kind) { + FormGrid::new("route_slots").columns(4).show(ui, |ui| { + fields.rows(ui, record, &mut live.slot); + }); + fields.forms(ui, record, &zone); + } + if let Some(record) = record { + let clock = BarClock::new(timeframe).with_timezone(zone.clone()); + let read = match &route.kind { + RouteKind::Ignore => None, + RouteKind::Bars(fields) => { + let bar = bars::bar(record, fields, &zone, &clock, timeframe); + Some(bar.map(|bar| bar_text(&bar, &zone))) + } + RouteKind::Trades(fields) => { + let trade = bars::trade(record, fields, &zone); + Some(trade.map(|trade| { + let at = trade.time.with_timezone(&zone).naive_local(); + format!( + "trade at {}, price {}, size {}, {}, {}", + at.format("%Y-%m-%d %H:%M:%S%.3f"), + number(trade.price), + number(trade.size), + rule_label(trade.rule), + side_label(trade.side) + ) + })) + } + }; + if let Some(read) = read { + let read = read.unwrap_or_else(|| "not readable".to_owned()); + ui.label(format!("The feed reads: {read}")); + } + } + if let RouteKind::Trades(fields) = &mut route.kind { + if !fields.condition.is_empty() { + condition_rows(ui, &mut fields.conditions, &mut live.condition); + } + if !fields.side.is_empty() { + side_rows(ui, fields); + } + } + } + + // A click fills the active slot when the node is in the tree of that slot. + let mut filled = false; + if let (Some(path), Some((_, message))) = (clicked_message, message) { + match live.slot { + Slot::Records => { + stream.records = path; + filled = true; + } + Slot::RouteBy if above_records(&stream.records, &message.root, &path) => { + stream.route_by = path; + filled = true; + } + _ => {} + } + } + if let (Some(path), Some(record)) = (clicked_record, record) { + let route = stream.routes.get_mut(live.route); + let fields = route.and_then(|route| Fields::route(&mut route.kind)); + match (live.slot, fields) { + (Slot::RouteBy, _) => { + stream.route_by = path; + filled = true; + } + (slot, Some(mut fields)) if fields.slots().contains(&slot) => { + let value = at(record, &path).cloned().unwrap_or(Value::Null); + fields.assign(slot, path, &value); + live.slot = fields.next(slot); + } + _ => {} + } + } + if filled { + // The fields of the selected route are mapped next. + let route = stream.routes.get_mut(live.route); + if let Some(fields) = route.and_then(|route| Fields::route(&mut route.kind)) { + live.slot = fields.next(live.slot); + } + } + } +} + +/// What keeps the templates of `profile` from being sent as they stand, one sentence per +/// finding: the name of a key that has no value, a name in braces that is neither a +/// placeholder nor a key, and a placeholder of history requests in a template of the stream. +/// Braces around any other text, such as those of a JSON message, are not names. +fn findings(profile: &Profile, secrets: &Secrets, scope: Scope) -> Vec { + let mut found: Vec = Vec::new(); + let mut scan = |template: &str, place: &str, stream: bool| { + for name in names(template) { + let finding = if profile.keys.iter().any(|key| key == name) { + let value = secrets.iter().find(|(key, _)| key == name); + if value.is_some_and(|(_, value)| !value.is_empty()) { + continue; + } + format!("The key \"{name}\" has no value. Enter it under Source.") + } else if !PLACEHOLDERS.contains(&name) { + format!( + "\"{{{name}}}\" in the {place} is neither a placeholder nor a key of this \ + profile. Add the key under Source or correct the text." + ) + } else if stream && matches!(name, "from" | "to" | "limit") { + format!("\"{{{name}}}\" in the {place} is filled for history requests only.") + } else { + continue; + }; + if !found.contains(&finding) { + found.push(finding); + } + } + }; + if let Some(history) = profile.history.as_ref().filter(|_| scope != Scope::Stream) { + scan(&history.url, "history URL", false); + for (name, value) in &history.headers { + scan(value, &format!("history header {name}"), false); + } + scan(&history.body, "history body", false); + } + if let Some(stream) = profile.stream.as_ref().filter(|_| scope != Scope::History) { + scan(&stream.url, "stream URL", true); + for (index, protocol) in stream.protocols.iter().enumerate() { + scan(protocol, &format!("subprotocol {}", index + 1), true); + } + for (index, message) in stream.connect.iter().enumerate() { + scan(message, &format!("connect message {}", index + 1), true); + } + scan(&stream.keep_alive, "keep-alive message", true); + } + found +} + +/// The names a template refers to as `{name}`: lower-case letters, digits and `_` between +/// braces, which is the alphabet of key names. +fn names(template: &str) -> impl Iterator { + template.split('{').skip(1).filter_map(|after| { + let (name, _) = after.split_once('}')?; + let plain = |byte: u8| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_'); + (!name.is_empty() && name.bytes().all(plain)).then_some(name) + }) +} + +/// The key names as the hint line of a step lists them after the placeholders. +fn key_names(keys: &[String]) -> String { + let mut names = String::new(); + for key in keys.iter().filter(|key| !key.is_empty()) { + // Writing into a `String` cannot fail. + let _ = write!(names, ", {{{key}}}"); + } + names +} + +/// The entries of a text split at commas and line ends: each one trimmed, empty and repeated +/// ones dropped. +fn listed(text: &str) -> Vec { + let mut entries: Vec = Vec::new(); + for entry in text.split([',', '\n', '\r']).map(str::trim) { + if !entry.is_empty() && !entries.iter().any(|held| held == entry) { + entries.push(entry.to_owned()); + } + } + entries +} + +/// The price step typed as `text`: `Some(None)` when it is empty, `None` when it is not a number +/// above zero. +fn price_step(text: &str) -> Option> { + let text = text.trim(); + if text.is_empty() { + return Some(None); + } + let step = text + .parse::() + .ok() + .filter(|step| step.is_finite() && *step > 0.0)?; + Some(Some(step)) +} + +/// A path as the dialog prints it: `data.candles`, `[0]`, `t`. +fn printed(path: &[Segment]) -> String { + let mut text = String::new(); + for segment in path { + match segment { + Segment::Key(key) => { + if !text.is_empty() { + text.push('.'); + } + text.push_str(key); + } + Segment::Index(index) => { + // Writing into a `String` cannot fail. + let _ = write!(text, "[{index}]"); + } + } + } + text +} + +/// Where a path leads, in words: the path, or the root for an empty one. +fn place(path: &[Segment]) -> String { + if path.is_empty() { + "the root".to_owned() + } else { + printed(path) + } +} + +/// `count` with its noun: `1 bar`, `3 bars`. +fn counted(count: usize, noun: &str) -> String { + let plural = if count == 1 { "" } else { "s" }; + format!("{count} {noun}{plural}") +} + +/// The first `most` characters of `text`, with an ellipsis when it is longer. +fn cut(text: &str, most: usize) -> String { + if text.chars().count() <= most { + return text.to_owned(); + } + let mut cut: String = text.chars().take(most).collect(); + cut.push('…'); + cut +} + +/// A value in a few characters: a scalar as JSON prints it, a list or an object as its size. +fn brief(value: &Value) -> String { + match value { + Value::Array(list) => format!("[{}]", list.len()), + Value::Object(members) => format!("{{{}}}", members.len()), + scalar => cut(&scalar.to_string(), 40), + } +} + +/// A price or a size as the preview prints it. A value that could not be read is NaN. +fn number(value: f64) -> String { + if value.is_nan() { + "missing".to_owned() + } else { + value.to_string() + } +} + +/// A bar in one line, its time in `zone`. +fn bar_text(bar: &Bar, zone: &TimezoneId) -> String { + let at = bar.time.with_timezone(zone).naive_local(); + let [open, high, low, close, volume] = + [bar.open, bar.high, bar.low, bar.close, bar.volume].map(number); + format!( + "bar at {}, open {open}, high {high}, low {low}, close {close}, volume {volume}", + at.format("%Y-%m-%d %H:%M:%S") + ) +} + +/// What `time::stamp` reads from `record`: an instant in `zone` and in UTC, such as +/// `2026-11-11 09:30:00 America/New_York, 14:30:00 UTC`, so that a wrong unit or zone shows +/// before anything is charted. +fn stamp_text(record: &Value, spec: &TimeSpec, zone: &TimezoneId) -> String { + match time::stamp(record, spec, zone) { + Some(Stamp::At(instant)) => { + let local = instant.with_timezone(zone).naive_local(); + format!( + "{} {}, {} UTC", + local.format("%Y-%m-%d %H:%M:%S"), + zone.name(), + instant.format("%H:%M:%S") + ) + } + Some(Stamp::On(date)) => format!("{date}, a bar dated on that day"), + None => "not readable".to_owned(), + } +} + +fn range_label(form: &RangeFormat) -> &'static str { + match form { + RangeFormat::Seconds => "Unix seconds", + RangeFormat::Milliseconds => "Unix milliseconds", + RangeFormat::Microseconds => "Unix microseconds", + RangeFormat::Nanoseconds => "Unix nanoseconds", + RangeFormat::Iso8601 => "ISO 8601, 2026-11-11T14:30:00Z", + RangeFormat::Date => "Date, 2026-11-11", + RangeFormat::CompactDate => "Date, 20261111", + } +} + +fn clock_label(unit: &ClockUnit) -> &'static str { + match unit { + ClockUnit::Milliseconds => "Milliseconds since midnight", + ClockUnit::Seconds => "Seconds since midnight", + ClockUnit::Text => "Text HH:MM:SS", + } +} + +fn layout_label(layout: &Layout) -> &'static str { + match layout { + Layout::Objects => "list of objects", + Layout::Arrays { header: None } => "list of arrays", + Layout::Arrays { header: Some(_) } => "list of arrays with a header", + Layout::Columns => "object of arrays", + } +} + +fn rule_label(rule: ConditionRule) -> &'static str { + match rule { + ConditionRule::PriceAndVolume => "Price and volume", + ConditionRule::VolumeOnly => "Volume only", + ConditionRule::Ignore => "Ignore", + } +} + +fn side_label(side: Option) -> &'static str { + match side { + Some(OrderSide::Buy) => "buy", + Some(OrderSide::Sell) => "sell", + None => "side unknown", + } +} + +/// The rows at the node `path` of `sample`, laid out as the node says: an object holds one +/// list per field, a list of lists holds arrays, anything else holds objects. A header that +/// was chosen stays with a list of lists. +fn rows_at(sample: &Value, path: FieldPath, held: &Layout) -> Rows { + let layout = match at(sample, &path) { + Some(Value::Object(_)) => Layout::Columns, + Some(Value::Array(list)) if matches!(list.first(), Some(Value::Array(_))) => match held { + Layout::Arrays { header } => Layout::Arrays { + header: header.clone(), + }, + _ => Layout::Arrays { header: None }, + }, + _ => Layout::Objects, + }; + Rows { path, layout } +} + +/// The records of a message, as a session splits it. The routes are left out, so that every +/// record comes back, also one that a route would ignore. +fn split(stream: &Stream, message: &str) -> Vec { + let unrouted = Stream { + records: stream.records.clone(), + ..Stream::default() + }; + let record = |routed: Routed| match routed { + Routed::Unrouted { record } | Routed::Record { record, .. } => Some(record), + Routed::Ignored { .. } => None, + }; + stream::route(&unrouted, message) + .into_iter() + .filter_map(record) + .collect() +} + +/// The value a session routes `record` by: its own, then the one at the root of its message, +/// then the record itself when it is a bare value. +fn routing_value(stream: &Stream, root: &Value, record: &Value) -> Option { + let own = at(record, &stream.route_by).and_then(profile::text); + let named = own.or_else(|| at(root, &stream.route_by).and_then(profile::text)); + named.or_else(|| profile::text(record)) +} + +/// Whether the node at `path` of a message can be the routing field. A node at or below the +/// place of the records cannot: its path would name one record of this message. +fn above_records(records: &[Segment], root: &Value, path: &[Segment]) -> bool { + if records.is_empty() { + // The message is the record, or the list of records. + !root.is_array() + } else { + !path.starts_with(records) + } +} + +/// What decides the route of a record and the condition values it offers: the place of the +/// records, the routing field and the routes without their rule lists and side values. +fn basis(stream: &Stream) -> Basis { + let mut routes = stream.routes.clone(); + for route in &mut routes { + if let RouteKind::Trades(fields) = &mut route.kind { + fields.conditions.clear(); + fields.buy.clear(); + fields.sell.clear(); + } + } + (stream.records.clone(), stream.route_by.clone(), routes) +} + +/// Adds the condition values of the records in `routed` to the rule list of their trades +/// route, as `Price and volume`, in the order first seen. +fn offer_conditions(stream: &mut Stream, routed: &[Routed]) { + for record in routed { + let Routed::Record { route, record } = record else { + continue; + }; + let Some(RouteKind::Trades(fields)) = + stream.routes.get_mut(*route).map(|route| &mut route.kind) + else { + continue; + }; + for value in bars::conditions(record, fields) { + if !fields.conditions.iter().any(|(listed, _)| *listed == value) { + fields + .conditions + .push((value, ConditionRule::PriceAndVolume)); + } + } + } +} + +/// The badges of a message: one per distinct outcome of its records, in message order, with +/// the count when several records share it. The flag dims the badge of a route that ignores. +fn badges(stream: &Stream, routed: &[Routed]) -> Vec<(String, bool)> { + let mut outcomes: Vec<(Option, bool, usize)> = Vec::new(); + for record in routed { + let (route, ignored) = match record { + Routed::Record { route, .. } => (Some(*route), false), + Routed::Ignored { route } => (Some(*route), true), + Routed::Unrouted { .. } => (None, false), + }; + match outcomes.iter_mut().find(|(held, ..)| *held == route) { + Some((.., count)) => *count += 1, + None => outcomes.push((route, ignored, 1)), + } + } + if outcomes.is_empty() { + return vec![("no records".to_owned(), true)]; + } + let badge = |(route, ignored, count): (Option, bool, usize)| { + let value = route.and_then(|route| Some((route, stream.routes.get(route)?))); + let mut text = match value { + Some((route, held)) if held.value.is_empty() => format!("route {}", route + 1), + Some((_, held)) => held.value.clone(), + None => "no route".to_owned(), + }; + if count > 1 { + // Writing into a `String` cannot fail. + let _ = write!(text, " ×{count}"); + } + (text, ignored) + }; + outcomes.into_iter().map(badge).collect() +} + +/// The first three cells of a slot's row: its button, the path it holds and the value found +/// there below `base`. `whole` says that an empty path is the whole of `base`, as for the +/// place of the rows; for a field it means that nothing is mapped. +fn slot_cells( + ui: &mut egui::Ui, + slot: Slot, + active: &mut Slot, + path: &[Segment], + whole: bool, + base: Option<&Value>, +) { + let button = Button::new(slot.label()).outlined().small(); + if ui.add(button.selected(*active == slot)).clicked() { + *active = slot; + } + if path.is_empty() && !whole { + ui.weak("not mapped"); + ui.label(""); + return; + } + ui.monospace(place(path)); + match base.map(|base| at(base, path)) { + Some(Some(found)) => ui.monospace(brief(found)), + Some(None) => ui.warning_label("nothing there"), + None => ui.label(""), + }; +} + +/// The `Clear` button of a slot. Returns whether it was clicked. +fn clear_button(ui: &mut egui::Ui, enabled: bool) -> bool { + ui.add(Button::new("Clear").small().enabled(enabled)) + .clicked() +} + +/// A tree's own scroll area, which fills its column. +fn tree_area(salt: &str) -> egui::ScrollArea { + let area = egui::ScrollArea::both().id_salt(salt); + let area = area.max_height(TREE).min_scrolled_height(TREE); + area.auto_shrink([false, true]) +} + +/// The first five bars of a reading and the last one, then how many it holds. +fn preview_table(ui: &mut egui::Ui, reading: &Reading, zone: &TimezoneId) { + let bars = &reading.bars; + let cut = bars.len() > 6; + let shown: Vec<&Bar> = if cut { + bars[..5].iter().chain(bars.last()).collect() + } else { + bars.iter().collect() + }; + FormGrid::new("history_preview").columns(6).show(ui, |ui| { + for heading in ["time", "open", "high", "low", "close", "volume"] { + ui.weak(heading); + } + ui.end_row(); + for (index, bar) in shown.into_iter().enumerate() { + if cut && index == 5 { + ui.weak("…"); + ui.end_row(); + } + let at = bar.time.with_timezone(zone).naive_local(); + ui.monospace(at.format("%Y-%m-%d %H:%M:%S").to_string()); + for value in [bar.open, bar.high, bar.low, bar.close, bar.volume] { + ui.monospace(number(value)); + } + ui.end_row(); + } + }); + let skipped = counted(reading.skipped, "row"); + ui.label(format!("{}, {skipped} skipped", counted(bars.len(), "bar"))); +} + +/// The interval table: per row a chart interval and the text the service expects for it. +fn interval_rows(ui: &mut egui::Ui, rows: &mut Vec) { + ui.vertical(|ui| { + let mut removed = None; + for (index, row) in rows.iter_mut().enumerate() { + ui.push_id(("interval", index), |ui| { + ui.horizontal(|ui| { + let label = |chart: &Timeframe| chart.to_string(); + ui.combo_select("chart", &mut row.chart, Timeframe::all(), label); + let width = (ui.available_width() - 90.0).clamp(60.0, 160.0); + let service = TextEdit::singleline(&mut row.service); + ui.add( + service + .hint_text("as the service spells it") + .desired_width(width), + ); + if ui.add(Button::new("Remove").small()).clicked() { + removed = Some(index); + } + }); + }); + } + if let Some(index) = removed { + rows.remove(index); + } + if ui + .add(Button::new("Add interval").outlined().small()) + .clicked() + { + // The first interval the table does not list yet, from one minute on. + let all = Timeframe::all(); + let minute = all.iter().position(|chart| *chart == Timeframe::Min1); + let mut from_minute = all.iter().cycle().skip(minute.unwrap_or(0)).take(all.len()); + let unused = |chart: &&Timeframe| !rows.iter().any(|row| row.chart == **chart); + let chart = from_minute.find(unused).copied().unwrap_or_default(); + let service = String::new(); + rows.push(Interval { chart, service }); + } + }); +} + +/// The keys: per row a name and a value, which is typed as a password. +fn key_rows(ui: &mut egui::Ui, keys: &mut Vec, values: &mut Vec) { + ui.vertical(|ui| { + let mut removed = None; + for (index, (name, value)) in keys.iter_mut().zip(values.iter_mut()).enumerate() { + ui.push_id(("key", index), |ui| { + ui.horizontal(|ui| { + // Both fields share what the Remove button leaves; on a desktop they keep + // 140 and 240. + let gap = ui.spacing().item_spacing.x; + let room = ui.available_width() - 90.0; + let name_width = ((room - gap) / 2.0).min(140.0); + let value_width = (room - gap - name_width).min(240.0); + ui.add( + TextEdit::singleline(name) + .hint_text("key name") + .desired_width(name_width), + ); + let value = TextEdit::singleline(value).hint_text("key value"); + ui.add(value.password(true).desired_width(value_width)); + if ui.add(Button::new("Remove").small()).clicked() { + removed = Some(index); + } + }); + }); + } + if let Some(index) = removed { + keys.remove(index); + values.remove(index); + } + if ui.add(Button::new("Add key").outlined().small()).clicked() { + keys.push(String::new()); + values.push(String::new()); + } + }); +} + +/// The request headers: per row a name and a value template. +fn header_rows(ui: &mut egui::Ui, rows: &mut Vec<(String, String)>) { + ui.vertical(|ui| { + let mut removed = None; + for (index, (name, value)) in rows.iter_mut().enumerate() { + ui.push_id(("header", index), |ui| { + ui.horizontal(|ui| { + // The name takes at most half of what the Remove button leaves. + let gap = ui.spacing().item_spacing.x; + let room = ui.available_width() - 90.0; + let name_width = ((room - gap) / 2.0).min(160.0); + ui.add( + TextEdit::singleline(name) + .hint_text("name") + .desired_width(name_width), + ); + ui.add( + TextEdit::singleline(value) + .hint_text("value") + .desired_width(room - gap - name_width), + ); + if ui.add(Button::new("Remove").small()).clicked() { + removed = Some(index); + } + }); + }); + } + if let Some(index) = removed { + rows.remove(index); + } + if ui + .add(Button::new("Add header").outlined().small()) + .clicked() + { + rows.push((String::new(), String::new())); + } + }); +} + +/// Rows of text that can be added and removed: the subprotocols and the connect messages. +fn text_rows(ui: &mut egui::Ui, salt: &str, rows: &mut Vec, add: &str) { + ui.vertical(|ui| { + let mut removed = None; + for (index, row) in rows.iter_mut().enumerate() { + ui.push_id((salt, index), |ui| { + ui.horizontal(|ui| { + let width = (ui.available_width() - 90.0).max(80.0); + ui.add(TextEdit::singleline(row).desired_width(width)); + if ui.add(Button::new("Remove").small()).clicked() { + removed = Some(index); + } + }); + }); + } + if let Some(index) = removed { + rows.remove(index); + } + if ui.add(Button::new(add).outlined().small()).clicked() { + rows.push(String::new()); + } + }); +} + +/// The rule of each condition value of a trades route, and a row that adds a value by hand, +/// for one that did not occur during the Test. +fn condition_rows(ui: &mut egui::Ui, rules: &mut Vec<(String, ConditionRule)>, typed: &mut String) { + ui.strong("Conditions"); + let mut removed = None; + for (index, (value, rule)) in rules.iter_mut().enumerate() { + ui.push_id(("condition", index), |ui| { + // On a phone the rules go on below the value. + ui.horizontal_wrapped(|ui| { + ui.monospace(value.as_str()); + let choices = [ + ConditionRule::PriceAndVolume, + ConditionRule::VolumeOnly, + ConditionRule::Ignore, + ]; + for choice in choices { + let button = Button::new(rule_label(choice)).small(); + if ui.add(button.selected(*rule == choice)).clicked() { + *rule = choice; + } + } + if ui.add(Button::new("Remove").small()).clicked() { + removed = Some(index); + } + }); + }); + } + if let Some(index) = removed { + rules.remove(index); + } + ui.horizontal(|ui| { + ui.add( + TextEdit::singleline(typed) + .hint_text("condition value") + .desired_width(140.0), + ); + let new = !typed.is_empty() && !rules.iter().any(|(value, _)| value == typed); + if ui + .add(Button::new("Add condition").outlined().small().enabled(new)) + .clicked() + { + rules.push((std::mem::take(typed), ConditionRule::PriceAndVolume)); + } + }); +} + +/// The values of the side field of a trades route that mark a buy and a sell. Any other value +/// leaves a trade's side unknown. +fn side_rows(ui: &mut egui::Ui, fields: &mut TradeFields) { + ui.strong("Side"); + ui.horizontal_wrapped(|ui| { + let buy = TextEdit::singleline(&mut fields.buy).hint_text("buy value"); + ui.add(buy.desired_width(120.0)); + let sell = TextEdit::singleline(&mut fields.sell).hint_text("sell value"); + ui.add(sell.desired_width(120.0)); + }); +} + +#[cfg(test)] +mod tests { + use std::net::TcpListener; + use std::time::{Duration, Instant}; + + use egui::accesskit; + use egui_charts::ChartBuilder; + use egui_charts::widget::SeriesId; + + use super::super::super::tests::AppStorage; + use super::super::feed::MappedFeed; + use super::super::feed::tests::{Server, pages, profile, shown, until}; + use super::super::stream::tests::{Peer, Step}; + use super::*; + + const SIZE: egui::Vec2 = egui::vec2(1440.0, 900.0); + + /// The headings of the log and of the trees, which scroll on their own below them. + const HEADINGS: [&str; 5] = ["Log", "Response", "First row", "Message", "Record"]; + + /// A control or a label of the dialog, whether or not it is scrolled into view. + #[derive(Clone)] + struct Node { + id: accesskit::NodeId, + role: accesskit::Role, + /// The label of a control, the text of a label or the content of a field. + text: String, + /// The hint of a field. + hint: String, + /// Whether the node has a name: a label, a label it is labelled by or a hint. + named: bool, + rect: egui::Rect, + } + + impl Node { + /// Whether the node is a field that is typed into. + fn field(&self) -> bool { + use accesskit::Role; + let fields = [ + Role::TextInput, + Role::MultilineTextInput, + Role::PasswordInput, + ]; + fields.contains(&self.role) + } + } + + /// A text as it is painted: the text, its place and the part of the screen it is cut to. + type Painted = (String, egui::Rect, egui::Rect); + + /// One frame of the dialog. + struct Screen { + /// The texts painted at least partly where they can be seen. + texts: Vec, + nodes: Vec, + /// What the user decided in the frame. + outcome: Option, + } + + impl Screen { + /// Where `node` can be clicked: the middle of the part of its text that is in view, + /// when enough of it is to be hit. + fn visible(&self, node: &Node) -> Option { + let area = node.rect.expand(2.0); + // An empty text, such as a field's cursor, is no node's: a node without a hint, as in + // a list, would otherwise take it. + let own = |(text, rect, _): &&Painted| { + !text.is_empty() + && (*text == node.text || *text == node.hint) + && area.contains(rect.center()) + }; + let (_, rect, clip) = self.texts.iter().find(own)?; + let shown = rect.intersect(*clip); + (shown.width() >= 4.0 && shown.height() >= 4.0).then(|| shown.center()) + } + + /// Every text of the dialog, also what is scrolled out of view. + fn all(&self) -> Vec { + let painted = self.texts.iter().map(|(text, ..)| text.clone()); + let held = self + .nodes + .iter() + .flat_map(|node| [node.text.clone(), node.hint.clone()]); + painted.chain(held).collect() + } + } + + /// Adds the texts of `shape` that reach into `clip`. + fn painted(shape: &egui::Shape, clip: egui::Rect, texts: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => { + for shape in shapes { + painted(shape, clip, texts); + } + } + egui::Shape::Text(text) => { + let rect = egui::Rect::from_min_size(text.pos, text.galley.size()); + if clip.intersects(rect) { + texts.push((text.galley.text().to_owned(), rect, clip)); + } + } + _ => {} + } + } + + /// One frame of the dialog with `events`. + fn draw( + ctx: &egui::Context, + dialog: &mut DataSourceDialog, + events: Vec, + ) -> Screen { + draw_at(ctx, dialog, events, SIZE) + } + + /// One frame of the dialog with `events` in a window of `size`. + fn draw_at( + ctx: &egui::Context, + dialog: &mut DataSourceDialog, + events: Vec, + size: egui::Vec2, + ) -> Screen { + ctx.enable_accesskit(); + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), + events, + ..Default::default() + }; + let mut outcome = None; + let output = ctx.run_ui(input, |ui| { + if let Some(decided) = dialog.show(ui.ctx(), None) { + outcome = Some(decided); + } + }); + let mut texts = Vec::new(); + for clipped in &output.shapes { + painted(&clipped.shape, clipped.clip_rect, &mut texts); + } + let listed = |(id, node): &(accesskit::NodeId, accesskit::Node)| { + // A label also lists each of its lines as a run of text, which is no widget. + if node.role() == accesskit::Role::TextRun { + return None; + } + let bounds = node.bounds()?; + let corner = |x: f64, y: f64| egui::pos2(x as f32, y as f32); + let given = |text: Option<&str>| text.is_some_and(|text| !text.trim().is_empty()); + Some(Node { + id: *id, + role: node.role(), + text: node.label().or(node.value()).unwrap_or_default().to_owned(), + hint: node.placeholder().unwrap_or_default().to_owned(), + named: given(node.label()) + || !node.labelled_by().is_empty() + || given(node.placeholder()), + rect: egui::Rect::from_min_max( + corner(bounds.x0, bounds.y0), + corner(bounds.x1, bounds.y1), + ), + }) + }; + let update = output.platform_output.accesskit_update.as_ref(); + let nodes = update.map_or_else(Vec::new, |update| { + update.nodes.iter().filter_map(listed).collect() + }); + output.drop_without_applying_deltas(); + Screen { + texts, + nodes, + outcome, + } + } + + /// Asks the scroll area around `node` to bring it into view. The area moves in the frame + /// after the one that asks, and draws its content at the new place in the frame after that. + fn scroll_to(ctx: &egui::Context, dialog: &mut DataSourceDialog, node: &Node) { + let request = egui::Event::AccessKitActionRequest(accesskit::ActionRequest { + action: accesskit::Action::ScrollIntoView, + target_tree: accesskit::TreeId::ROOT, + target_node: node.id, + data: None, + }); + draw(ctx, dialog, vec![request]); + draw(ctx, dialog, vec![]); + } + + /// Scrolls the node `find` picks into view, as a visitor does, and returns where it can be + /// clicked. Waits up to thirty seconds for the node to exist; `what` names it. + fn reveal( + ctx: &egui::Context, + dialog: &mut DataSourceDialog, + what: &str, + find: impl Fn(&Screen) -> Option, + ) -> egui::Pos2 { + let start = Instant::now(); + loop { + let screen = draw(ctx, dialog, vec![]); + let Some(node) = find(&screen) else { + assert!( + start.elapsed() < Duration::from_secs(30), + "missing control: {what}" + ); + std::thread::sleep(Duration::from_millis(5)); + continue; + }; + assert!( + start.elapsed() < Duration::from_secs(30), + "{what} does not scroll into view" + ); + if let Some(at) = screen.visible(&node) { + // The dialog takes a frame to move to its place when its size changes, so a + // control counts as in view where two frames in a row show it. + let again = draw(ctx, dialog, vec![]); + if find(&again).and_then(|node| again.visible(&node)) == Some(at) { + return at; + } + continue; + } + // The step scrolls to it, or the list it is in does. + scroll_to(ctx, dialog, &node); + let screen = draw(ctx, dialog, vec![]); + if find(&screen).is_some_and(|node| screen.visible(&node).is_some()) { + continue; + } + // The log or the tree it is in is itself out of view: the heading above it is + // scrolled into view. + let above = |heading: &&Node| { + heading.role == accesskit::Role::Label + && HEADINGS.contains(&heading.text.as_str()) + && heading.rect.bottom() <= node.rect.top() + 1.0 + }; + let nearest = |a: &&Node, b: &&Node| a.rect.bottom().total_cmp(&b.rect.bottom()); + if let Some(heading) = screen.nodes.iter().filter(above).max_by(nearest) { + scroll_to(ctx, dialog, heading); + } + } + } + + /// Clicks at `at` and returns what the user thereby decided. + fn press( + ctx: &egui::Context, + dialog: &mut DataSourceDialog, + at: egui::Pos2, + ) -> Option { + let moved = draw(ctx, dialog, vec![egui::Event::PointerMoved(at)]); + let button = |pressed| egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }; + let clicked = draw(ctx, dialog, vec![button(true), button(false)]); + moved.outcome.or(clicked.outcome) + } + + /// Clicks the control whose text is `label` and returns what the user thereby decided. + fn click(ctx: &egui::Context, dialog: &mut DataSourceDialog, label: &str) -> Option { + let control = |screen: &Screen| { + let named = |node: &&Node| { + node.text == label && node.role != accesskit::Role::Label && !node.field() + }; + screen.nodes.iter().find(named).cloned() + }; + let at = reveal(ctx, dialog, label, control); + press(ctx, dialog, at) + } + + /// Clicks the node whose text starts with `start` in the tree drawn under `heading`. + fn node(ctx: &egui::Context, dialog: &mut DataSourceDialog, heading: &str, start: &str) { + let in_tree = |screen: &Screen| { + let headings = screen.nodes.iter().filter(|node| { + node.role == accesskit::Role::Label && HEADINGS.contains(&node.text.as_str()) + }); + let headings: Vec<&Node> = headings.collect(); + // A node belongs to the heading that starts nearest above it and not to its right. + let owner = |node: &Node| { + let before = |heading: &&&Node| { + heading.rect.top() <= node.rect.top() + && heading.rect.left() <= node.rect.left() + 1.0 + }; + let nearest = |a: &&&Node, b: &&&Node| { + let (a, b) = (a.rect.left_top(), b.rect.left_top()); + a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)) + }; + headings + .iter() + .filter(before) + .max_by(nearest) + .map(|heading| heading.text.as_str()) + }; + let wanted = |node: &&Node| { + node.role == accesskit::Role::Button + && node.text.starts_with(start) + && owner(node) == Some(heading) + }; + let topmost = |a: &&Node, b: &&Node| a.rect.top().total_cmp(&b.rect.top()); + screen.nodes.iter().filter(wanted).min_by(topmost).cloned() + }; + let at = reveal(ctx, dialog, start, in_tree); + press(ctx, dialog, at); + } + + /// Clicks `label` in the row that shows `row`: the kind in the row of a route, the rule in + /// the row of a condition. + fn choose(ctx: &egui::Context, dialog: &mut DataSourceDialog, row: &str, label: &str) { + let in_row = |screen: &Screen| { + let rows = screen + .nodes + .iter() + .filter(|node| node.text == row && node.role != accesskit::Role::Button); + let rows: Vec<&Node> = rows.collect(); + let wanted = |node: &&Node| { + let middle = node.rect.center().y; + node.role == accesskit::Role::Button + && node.text == label + && rows + .iter() + .any(|shown| shown.rect.y_range().contains(middle)) + }; + screen.nodes.iter().find(wanted).cloned() + }; + let at = reveal(ctx, dialog, label, in_row); + press(ctx, dialog, at); + } + + /// Draws frames until a text that contains `part` is in the dialog, scrolls it into view + /// and returns it. Panics after thirty seconds, naming `part`. + fn wait(ctx: &egui::Context, dialog: &mut DataSourceDialog, part: &str) -> String { + let holds = |screen: &Screen| { + screen + .nodes + .iter() + .find(|node| node.text.contains(part)) + .cloned() + }; + reveal(ctx, dialog, part, holds); + let screen = draw(ctx, dialog, vec![]); + holds(&screen) + .unwrap_or_else(|| panic!("{part} went away")) + .text + } + + /// Clicks the empty field that shows the hint `hint` and types `text` into it. + fn enter(ctx: &egui::Context, dialog: &mut DataSourceDialog, hint: &str, text: &str) { + let field = |screen: &Screen| { + let empty = |node: &&Node| node.field() && node.hint == hint && node.text.is_empty(); + screen.nodes.iter().find(empty).cloned() + }; + let at = reveal(ctx, dialog, hint, field); + press(ctx, dialog, at); + draw(ctx, dialog, vec![egui::Event::Text(text.to_owned())]); + } + + /// Everything a browser would keep for the demo, as one text. + fn stored(storage: &DemoStorage) -> String { + let mut kept = AppStorage::default(); + storage.persist(&mut kept); + eframe::Storage::get_string(&kept, "templates").unwrap_or_default() + } + + /// A visitor who has typed two addresses and a subscribe message gets from there to a + /// connected profile by clicks and the two values of the side: the proposed layout and + /// fields, one field clicked in the first row, the routes made from the first message + /// without one, the place of the records, the fields of a trade clicked in a record, the + /// values that mark a buy and a sell, and the condition values of the log. + #[test] + fn a_profile_is_mapped_from_a_test_response_and_the_live_log() { + const PAGE: &str = r#"{"data":{"candles":[{"t":1794407580,"o":100.75,"h":103.0,"l":100.5,"c":102.5,"q":1500},{"t":1794407640,"o":102.5,"h":102.75,"l":101.0,"c":101.25,"q":800},{"t":1794407700,"o":101.25,"h":101.5,"l":100.0,"c":100.25,"q":700}]}}"#; + const STATUS: &str = r#"{"type":"status","message":"authenticated"}"#; + const TRADES: &str = r#"{"type":"trade","data":[{"c":"@","m":false,"p":101.75,"s":3,"t":1794407710000},{"c":"T","m":true,"p":99.75,"s":2,"t":1794407715000}]}"#; + let server = Server::start(|_, _| (200, PAGE.to_owned())); + let peer = Peer::start(vec![vec![ + Step::Receive(1), + Step::Send(STATUS), + Step::Send(TRADES), + Step::UntilClosed, + ]]); + let key = |name: &str| vec![Segment::Key(name.to_owned())]; + + // What the visitor typed and saved: a name, a symbol, an interval, two addresses and + // the subscribe message. No rows, no fields, no routes. + let typed = Profile { + name: "Local".to_owned(), + symbols: vec!["ABC".to_owned()], + intervals: vec![Interval { + chart: Timeframe::Min1, + service: "1m".to_owned(), + }], + history: Some(History { + url: format!( + "{}/bars?symbol={{symbol}}&interval={{interval}}&to={{to}}&limit={{limit}}", + server.origin + ), + page_size: 3, + ..History::default() + }), + stream: Some(Stream { + url: format!("{}/stream", peer.url), + connect: vec![r#"{"action":"subscribe","symbol":"{symbol}"}"#.to_owned()], + ..Stream::default() + }), + ..Profile::default() + }; + let storage = Arc::new(DemoStorage::default()); + let returning = Saved { + asked: true, + current: Some("Local".to_owned()), + profiles: vec![typed.clone()], + ..Saved::default() + }; + returning.save(&storage); + let ctx = egui::Context::default(); + let mut dialog = DataSourceDialog::new(storage.clone(), true); + dialog.open(); + + // History: Test proposes the place of the rows, their layout and the fields it knows. + click(&ctx, &mut dialog, "History"); + click(&ctx, &mut dialog, "Test"); + wait( + &ctx, + &mut dialog, + "Proposed mapping: confirm it or click the fields to use", + ); + wait(&ctx, &mut dialog, "3 bars, 0 rows skipped"); + // The volume is mapped by a click on its field in the first row. + click(&ctx, &mut dialog, "volume"); + node(&ctx, &mut dialog, "First row", "q:"); + + // Live: Test connects, and the first message without a route is kept in view. + click(&ctx, &mut dialog, "Live"); + click(&ctx, &mut dialog, "Test"); + wait(&ctx, &mut dialog, "No route for this message:"); + // The field that tells the kinds of message apart, clicked in the first message. + click(&ctx, &mut dialog, "route by"); + node(&ctx, &mut dialog, "Message", "type:"); + // The status message gets a route that ignores it. The trades get a route of their + // own, whose kind is chosen in its row. + click(&ctx, &mut dialog, r#"Add route for "status""#); + click(&ctx, &mut dialog, r#"Add route for "trade""#); + choose(&ctx, &mut dialog, "trade", "Trades"); + // The records of the trades message are the elements of its `data`. + let line = wait(&ctx, &mut dialog, r#"{"type":"trade""#); + click(&ctx, &mut dialog, &line); + click(&ctx, &mut dialog, "records"); + node(&ctx, &mut dialog, "Message", "data"); + // The fields of a trade, clicked in the record. Each click moves on to the next empty + // slot. + click(&ctx, &mut dialog, "time"); + for field in ["t:", "p:", "s:", "c:", "m:"] { + node(&ctx, &mut dialog, "Record", field); + } + // The values of the side field that mark a buy and a sell, typed beside it. + enter(&ctx, &mut dialog, "buy value", "false"); + enter(&ctx, &mut dialog, "sell value", "true"); + // Both condition values of the log are listed. `T` gets another rule in its row. + choose(&ctx, &mut dialog, "T", "Volume only"); + + let Some(Outcome::Connect { profile, secrets }) = click(&ctx, &mut dialog, "Connect") + else { + panic!("Connect did not connect"); + }; + let expected = Profile { + history: Some(History { + rows: Rows { + path: vec![ + Segment::Key("data".to_owned()), + Segment::Key("candles".to_owned()), + ], + layout: Layout::Objects, + }, + bar: BarFields { + time: TimeSpec::Instant { + field: key("t"), + unit: TimeUnit::Seconds, + }, + open: key("o"), + high: key("h"), + low: key("l"), + close: key("c"), + volume: key("q"), + }, + ..typed.history.clone().unwrap() + }), + stream: Some(Stream { + records: key("data"), + route_by: key("type"), + routes: vec![ + Route { + value: "status".to_owned(), + kind: RouteKind::Ignore, + }, + Route { + value: "trade".to_owned(), + kind: RouteKind::Trades(TradeFields { + time: TimeSpec::Instant { + field: key("t"), + unit: TimeUnit::Milliseconds, + }, + price: key("p"), + size: key("s"), + condition: key("c"), + conditions: vec![ + ("@".to_owned(), ConditionRule::PriceAndVolume), + ("T".to_owned(), ConditionRule::VolumeOnly), + ], + side: key("m"), + buy: "false".to_owned(), + sell: "true".to_owned(), + }), + }, + ], + ..typed.stream.clone().unwrap() + }), + ..typed.clone() + }; + assert!(secrets.is_empty()); + assert_eq!(*profile, expected); + // Connecting saved the profile and made own data the source in use. + let saved = Saved::load(&storage); + assert!(saved.own); + assert_eq!(saved.current.as_deref(), Some("Local")); + assert_eq!(saved.profiles, [expected]); + } + + /// At the width of a phone every control and text of each step lies within the step, so + /// nothing has to be scrolled to sideways, and every control keeps its name. + #[test] + fn every_step_fits_a_phone() { + // The steps of the dialog, not those of a test server. + use super::Step; + // A profile with a row in every table of the three steps. + let mut profile = profile("http://127.0.0.1:9"); + profile.keys = vec!["key".to_owned()]; + let history = profile.history.as_mut().unwrap(); + history.headers = vec![("Authorization".to_owned(), "Bearer {key}".to_owned())]; + let key = |name: &str| vec![Segment::Key(name.to_owned())]; + let trades = TradeFields { + time: TimeSpec::Instant { + field: key("t"), + unit: TimeUnit::Milliseconds, + }, + price: key("p"), + condition: key("c"), + conditions: vec![("@".to_owned(), ConditionRule::PriceAndVolume)], + side: key("m"), + buy: "B".to_owned(), + sell: "S".to_owned(), + ..TradeFields::default() + }; + let route = |value: &str, kind| Route { + value: value.to_owned(), + kind, + }; + profile.stream = Some(Stream { + url: "ws://127.0.0.1:9/stream".to_owned(), + protocols: vec!["json".to_owned()], + connect: vec![r#"{"action":"subscribe","symbol":"{symbol}"}"#.to_owned()], + keep_alive: r#"{"action":"ping"}"#.to_owned(), + routes: vec![ + route("trade", RouteKind::Trades(trades)), + route("status", RouteKind::Ignore), + ], + ..Stream::default() + }); + let saved = Saved { + asked: true, + current: Some("Local".to_owned()), + profiles: vec![profile], + keys: vec![( + "Local".to_owned(), + vec![("key".to_owned(), "k-1".to_owned())], + )], + ..Saved::default() + }; + // The step, the text at its top and controls it shows. + #[rustfmt::skip] + let steps = [ + (Step::Source, "Profile", "New, Import, Export, Delete, Remove, Add interval, Add key"), + (Step::History, "Use REST history", "Remove, Add header, Test"), + (Step::Live, "Use a WebSocket stream", + "Remove, Ignore, Volume only, Side, Add route, Test"), + ]; + let checked = [ + accesskit::Role::Label, + accesskit::Role::Button, + accesskit::Role::CheckBox, + accesskit::Role::ComboBox, + accesskit::Role::SpinButton, + accesskit::Role::TextInput, + accesskit::Role::MultilineTextInput, + accesskit::Role::PasswordInput, + ]; + let mut faults = Vec::new(); + for size in [egui::vec2(393.0, 852.0), egui::vec2(360.0, 800.0)] { + for (step, top, controls) in steps { + let storage = Arc::new(DemoStorage::default()); + saved.save(&storage); + let mut dialog = DataSourceDialog::new(storage, true); + dialog.open(); + dialog.step = step; + // An error below the time zone, so that its text is laid out too. + dialog.draft.zone = "Mars/Base".to_owned(); + let ctx = egui::Context::default(); + // The modal takes its place in its second frame, and the step measures what + // it holds in the frame after. + for _ in 0..3 { + draw_at(&ctx, &mut dialog, vec![], size); + } + let screen = draw_at(&ctx, &mut dialog, vec![], size); + let name = format!("{} at {} px", step.tab_label(), size.x); + let (.., area) = screen + .texts + .iter() + .find(|(text, ..)| text == top) + .unwrap_or_else(|| panic!("{name}: no {top}")); + // The step and the footer below it, which shares its width. + let below = + |node: &&Node| checked.contains(&node.role) && node.rect.top() >= area.top(); + for node in screen.nodes.iter().filter(below) { + let inside = node.rect.left() >= area.left() - 0.5 + && node.rect.right() <= area.right() + 0.5; + if !inside { + let (text, rect) = (&node.text, node.rect); + faults.push(format!("{name}: {text:?} at {rect:?}, step at {area:?}")); + } + if egui::accessibility::is_input(node.role) && !node.named { + let (role, text) = (node.role, &node.text); + faults.push(format!("{name}: {role:?} {text:?} has no name")); + } + } + for control in controls.split(", ") { + let shown = screen.nodes.iter().any(|node| node.text == control); + assert!(shown, "{name}: no {control}"); + } + } + } + assert!(faults.is_empty(), "\n{}", faults.join("\n")); + } + + /// A click on a time-of-day field picks the form its value reads in, so the preview reads + /// the bar without a choice by hand. A value that no form reads keeps the form held. + #[test] + fn a_time_of_day_is_read_in_the_form_its_value_has() { + use ClockUnit as C; + use serde_json::json; + let key = |name: &str| vec![Segment::Key(name.to_owned())]; + let at = |text: &str| Some(Stamp::At(text.parse().unwrap())); + // The value of the clicked field, the form held before, the form picked and the time + // of the record {"d": 20261111, "c": value} in UTC. 09:30:00 is second 34,200 and + // millisecond 34,200,000 of the day. 86,400 seconds is a whole day, past the last + // second of one, so 86,400 is read as milliseconds: 1 minute and 26.4 seconds. + #[rustfmt::skip] + let rows = [ + (json!("09:30:00"), None, C::Text, at("2026-11-11T09:30:00Z")), + (json!("09:30"), Some(C::Milliseconds), C::Text, at("2026-11-11T09:30:00Z")), + (json!(34200), Some(C::Text), C::Seconds, at("2026-11-11T09:30:00Z")), + (json!("34200"), None, C::Seconds, at("2026-11-11T09:30:00Z")), + (json!(34200000), Some(C::Text), C::Milliseconds, at("2026-11-11T09:30:00Z")), + (json!(86400), None, C::Milliseconds, at("2026-11-11T00:01:26.400Z")), + (json!(-1), Some(C::Text), C::Text, None), + (json!("soon"), Some(C::Seconds), C::Seconds, None), + (json!(null), None, C::Milliseconds, None), + ]; + for (value, held, unit, expected) in rows { + let clock = held.map(|unit| Clock { + field: key("c"), + unit, + }); + let mut bar = BarFields { + time: TimeSpec::Wall { + date: key("d"), + format: DateFormat::Compact, + clock, + }, + ..BarFields::default() + }; + Fields::bar(&mut bar).assign(Slot::Clock, key("c"), &value); + let TimeSpec::Wall { + clock: Some(clock), .. + } = &bar.time + else { + panic!("{value}: no time of day"); + }; + assert_eq!(clock.unit, unit, "{value}"); + let record = json!({"d": 20261111, "c": value}); + let read = time::stamp(&record, &bar.time, &TimezoneId::utc()); + assert_eq!(read, expected, "{value}"); + } + } + + /// The life of a key: an exported file does not hold it, an import connects once it is + /// entered again, and a browser keeps it only when the box is ticked. + #[test] + fn an_exported_profile_holds_no_key_and_connects_once_the_key_is_entered() { + const SECRET: &str = "s3cret-7f3a"; + const J3: &str = r#"{"t":1794407580,"o":100.75,"h":103.0,"l":100.5,"c":102.5,"v":1500}"#; + const J4: &str = r#"{"t":1794407640,"o":102.5,"h":102.75,"l":101.0,"c":101.25,"v":800}"#; + const J5: &str = r#"{"t":1794407700,"o":101.25,"h":101.5,"l":100.0,"c":100.25,"v":700}"#; + let server = Server::start(pages(vec![format!("[{J3},{J4},{J5}]"), "[]".to_owned()])); + let mut profile = profile(&server.origin); + profile.keys = vec!["key".to_owned()]; + profile.history.as_mut().unwrap().url.push_str("&key={key}"); + let ctx = egui::Context::default(); + + // The first browser: the profile is saved there and its key is kept. + let first = Arc::new(DemoStorage::default()); + let kept = Saved { + asked: true, + current: Some("Local".to_owned()), + profiles: vec![profile.clone()], + keys: vec![( + "Local".to_owned(), + vec![("key".to_owned(), SECRET.to_owned())], + )], + ..Saved::default() + }; + kept.save(&first); + assert!(stored(&first).contains(SECRET)); + let mut dialog = DataSourceDialog::new(first, true); + dialog.open(); + click(&ctx, &mut dialog, "Export"); + let Some(Outcome::Export { file, text }) = click(&ctx, &mut dialog, "Save file") else { + panic!("no file"); + }; + assert_eq!(file, "Local.json"); + assert!(!text.contains(SECRET)); + assert_eq!(store::import(&text), Ok(profile.clone())); + + // A fresh browser: the visitor takes own data at the first-visit choice and imports + // the file. Nothing connects before the key is entered. + let fresh = Arc::new(DemoStorage::default()); + let mut dialog = DataSourceDialog::new(fresh.clone(), true); + assert!(dialog.startup().is_none() && dialog.is_open()); + click(&ctx, &mut dialog, "Connect my own data"); + // The system's file picker cannot be driven: the text of the file is handed over where + // the answer of the picker arrives. + let (picker, picked) = std::sync::mpsc::channel(); + picker.send(Ok(Some(text))).unwrap(); + dialog.import = Some(picked); + wait( + &ctx, + &mut dialog, + r#"The key "key" has no value. Enter it under Source."#, + ); + assert!(click(&ctx, &mut dialog, "Connect").is_none()); + enter(&ctx, &mut dialog, "key value", SECRET); + let Some(Outcome::Connect { + profile: connected, + secrets, + }) = click(&ctx, &mut dialog, "Connect") + else { + panic!("Connect did not connect"); + }; + assert_eq!(*connected, profile); + assert_eq!(secrets, [("key".to_owned(), SECRET.to_owned())]); + // The chart the application then builds loads the history, with the key in the request. + let mut chart = ChartBuilder::new() + .with_feed(Arc::new(MappedFeed::new(*connected, secrets))) + .with_symbol("ABC") + .with_timeframe(Timeframe::Min1) + .with_initial_bars(3) + .build(); + until( + &ctx, + &mut chart, + "the imported profile's history", + |chart| { + let feed = chart.feed_state(SeriesId::MAIN); + feed.is_some_and(|feed| feed.history_complete) + }, + ); + assert_eq!(shown(&chart).len(), 3); + assert!(server.seen()[0].line.ends_with("&key=s3cret-7f3a")); + + // The key was typed and not kept: this browser's storage does not hold it, and its next + // start opens the dialog for the key in place of connecting. + assert!(!stored(&fresh).contains(SECRET)); + let mut dialog = DataSourceDialog::new(fresh.clone(), true); + assert!(dialog.startup().is_none() && dialog.is_open()); + // Kept by choice, the key is stored, and the start after that connects by itself. + enter(&ctx, &mut dialog, "key value", SECRET); + click(&ctx, &mut dialog, "Keep keys on this device"); + let connected = click(&ctx, &mut dialog, "Connect"); + assert!(matches!(connected, Some(Outcome::Connect { .. }))); + assert!(stored(&fresh).contains(SECRET)); + let mut dialog = DataSourceDialog::new(fresh.clone(), true); + let Some(Outcome::Connect { secrets, .. }) = dialog.startup() else { + panic!("the start did not connect"); + }; + assert_eq!(secrets, [("key".to_owned(), SECRET.to_owned())]); + assert!(!dialog.is_open()); + // The box cleared and the profile saved, the key is forgotten. + dialog.open(); + click(&ctx, &mut dialog, "Keep keys on this device"); + click(&ctx, &mut dialog, "Save"); + assert!(!stored(&fresh).contains(SECRET)); + } + + /// A ready profile is listed above the visitor's profiles, connects as shipped without being + /// stored, connects again at the next start, and is saved only as a renamed copy once + /// changed. Opening its steps leaves it unchanged. + #[test] + fn a_ready_profile_connects_as_shipped_and_saves_only_as_a_renamed_copy() { + const READY: &str = "Binance spot (public)"; + let ctx = egui::Context::default(); + let storage = Arc::new(DemoStorage::default()); + let local = Saved { + asked: true, + profiles: vec![profile("http://127.0.0.1:9")], + ..Saved::default() + }; + local.save(&storage); + let names = || -> Vec { + let saved = Saved::load(&storage).profiles.into_iter(); + saved.map(|profile| profile.name).collect() + }; + let mut dialog = DataSourceDialog::new(storage.clone(), true); + dialog.open(); + + // 1. The list shows the ready profile first. + click(&ctx, &mut dialog, "New profile"); + let screen = draw(&ctx, &mut dialog, vec![]); + let top = |text: &str| { + let listed = |node: &&Node| node.text == text && !node.field(); + screen.nodes.iter().find(listed).map(|node| node.rect.top()) + }; + let (ready, local) = (top(READY).unwrap(), top("Local").unwrap()); + assert!(ready < local, "{ready} {local}"); + + // 2. Chosen and its steps opened, it connects as shipped, with no key, and is not stored. + click(&ctx, &mut dialog, READY); + click(&ctx, &mut dialog, "History"); + click(&ctx, &mut dialog, "Live"); + let Some(Outcome::Connect { profile, secrets }) = click(&ctx, &mut dialog, "Connect") + else { + panic!("the ready profile did not connect"); + }; + assert_eq!(*profile, store::ready()[0]); + assert!(secrets.is_empty()); + let saved = Saved::load(&storage); + assert!(saved.own); + assert_eq!(saved.current.as_deref(), Some(READY)); + assert_eq!(names(), ["Local"]); + + // 3. The next start connects it again. + let mut next = DataSourceDialog::new(storage.clone(), true); + let Some(Outcome::Connect { profile, .. }) = next.startup() else { + panic!("the start did not connect the ready profile"); + }; + assert_eq!(profile.name, READY); + + // 4. Changed, it neither connects nor saves under its name; renamed, it saves. + dialog.open(); + click(&ctx, &mut dialog, "Source"); + dialog.draft.profile.symbols.push("XRPUSDT".to_owned()); + wait(&ctx, &mut dialog, "A ready profile has this name"); + assert!(click(&ctx, &mut dialog, "Connect").is_none()); + click(&ctx, &mut dialog, "Save"); + assert_eq!(names(), ["Local"]); + dialog.draft.profile.name = "My Binance".to_owned(); + click(&ctx, &mut dialog, "Save"); + assert_eq!(names(), ["Local", "My Binance"]); + } + + /// The status line shows the connection error while the stream is down, and no longer once it + /// is live again, although the chart keeps the error as its most recent one. + #[test] + fn the_status_line_drops_a_connection_error_once_the_stream_is_live() { + let ctx = egui::Context::default(); + let dialog = DataSourceDialog::new(Arc::new(DemoStorage::default()), true); + let lost = FeedError::Network("ws://127.0.0.1:9/stream: connection lost".to_owned()); + for (status, shown) in [(FeedStatus::Disconnected, true), (FeedStatus::Live, false)] { + let mut running = FeedState::default(); + running.status = Some(status); + running.last_error = Some(lost.clone()); + let output = ctx.run_ui(egui::RawInput::default(), |ui| dialog.status(ui, &running)); + let mut texts = Vec::new(); + for clipped in &output.shapes { + painted(&clipped.shape, clipped.clip_rect, &mut texts); + } + let found = texts + .iter() + .any(|(text, ..)| text.contains("connection lost")); + output.drop_without_applying_deltas(); + assert_eq!(found, shown, "{status:?}"); + } + } + + /// A Test that fails says, in the step where the visitor pressed the button, which + /// endpoint failed and why, and the dialog never shows a key. + #[test] + fn a_failed_test_names_the_endpoint_and_the_reason() { + const SECRET: &str = "s3cret-7f3a"; + /// The answer of the service, a change of the mapping, and what the History step shows + /// after the endpoint. + type Row = ( + &'static str, + Option<(u16, &'static str)>, + fn(&mut Profile), + &'static str, + ); + /// A dialog on the base profile of the feed's tests, its key in the address and kept, + /// changed by `edit`. + fn open(origin: &str, edit: impl FnOnce(&mut Profile)) -> DataSourceDialog { + let mut profile = profile(origin); + profile.keys = vec!["key".to_owned()]; + profile.history.as_mut().unwrap().url.push_str("&key={key}"); + edit(&mut profile); + let storage = Arc::new(DemoStorage::default()); + let kept = Saved { + asked: true, + current: Some("Local".to_owned()), + profiles: vec![profile], + keys: vec![( + "Local".to_owned(), + vec![("key".to_owned(), SECRET.to_owned())], + )], + ..Saved::default() + }; + kept.save(&storage); + let mut dialog = DataSourceDialog::new(storage, true); + dialog.open(); + dialog + } + // An address where nothing listens. + let closed = || { + TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + }; + let ctx = egui::Context::default(); + + let rows: [Row; 4] = [ + ( + "unauthorised", + Some((401, r#"{"error":"bad key"}"#)), + |_| {}, + "rejected as unauthorised (HTTP 401): check the key and where it is sent", + ), + ( + "not JSON", + Some((200, "busy")), + |_| {}, + "unreadable response: not JSON: ", + ), + ( + "rows elsewhere", + Some((200, r#"{"data":{"candles":{"t":[1794407580]}}}"#)), + |profile| { + profile.history.as_mut().unwrap().rows.path = vec![ + Segment::Key("data".to_owned()), + Segment::Key("candles".to_owned()), + ]; + }, + "unreadable response: expected a list at data.candles, found an object", + ), + ("nothing listens", None, |_| {}, "no response ("), + ]; + for (name, answer, edit, reason) in rows { + let server = + answer.map(|(status, body)| Server::start(move |_, _| (status, body.to_owned()))); + let origin = server.as_ref().map_or_else( + || format!("http://{}", closed()), + |server| server.origin.clone(), + ); + let mut dialog = open(&origin, edit); + click(&ctx, &mut dialog, "History"); + click(&ctx, &mut dialog, "Test"); + let line = wait(&ctx, &mut dialog, &format!("{origin}/bars: ")); + assert!( + line.contains(&format!("{origin}/bars: {reason}")), + "{name}: {line}" + ); + let texts = draw(&ctx, &mut dialog, vec![]).all(); + assert!(!texts.iter().any(|text| text.contains(SECRET)), "{name}"); + if let Some(server) = server { + // The key did reach the endpoint, so its absence from the dialog means + // something. + assert!( + server.seen()[0].line.ends_with("&key=s3cret-7f3a"), + "{name}" + ); + } + if name == "rows elsewhere" { + // The response is still drawn as a tree, so the place of the rows can be + // clicked. + assert!( + texts.iter().any(|text| text.starts_with("candles")), + "{name}" + ); + } + } + + // A name in braces that is neither a key nor a placeholder is reported, and nothing is + // sent. + let server = Server::start(|_, _| (200, "[]".to_owned())); + let mut dialog = open(&server.origin, |profile| { + profile + .history + .as_mut() + .unwrap() + .url + .push_str("&token={token}"); + }); + click(&ctx, &mut dialog, "History"); + click(&ctx, &mut dialog, "Test"); + wait( + &ctx, + &mut dialog, + r#""{token}" in the history URL is neither a placeholder nor a key of this profile. Add the key under Source or correct the text."#, + ); + assert!(server.seen().is_empty()); + + // The stream: an address where nothing listens is named without its query, and a key + // in its path by its name. + let address = closed(); + let mut dialog = open(&format!("http://{address}"), |profile| { + profile.stream = Some(Stream { + url: format!("ws://{address}/{{key}}/stream?key={{key}}"), + ..Stream::default() + }); + }); + click(&ctx, &mut dialog, "Live"); + click(&ctx, &mut dialog, "Test"); + let line = wait( + &ctx, + &mut dialog, + &format!("ws://{address}/{{key}}/stream: cannot connect ("), + ); + assert!(!line.contains(SECRET), "{line}"); + click(&ctx, &mut dialog, "Stop"); + } +} diff --git a/vendor/egui-charts/examples/demo/owndata/feed.rs b/vendor/egui-charts/examples/demo/owndata/feed.rs new file mode 100644 index 0000000..93f6515 --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/feed.rs @@ -0,0 +1,1596 @@ +//! The mapped feed: a profile served to the chart through the library's `Datafeed` trait. + +use std::collections::{HashMap, VecDeque}; +use std::sync::{Arc, Mutex, MutexGuard}; + +use chrono::{DateTime, Months, NaiveDate, NaiveTime, TimeDelta, Utc}; +use egui_charts::data::{ + Datafeed, FeedCapabilities, FeedError, FeedStatus, HistoryPage, HistoryRequest, Reply, Sink, + Subscription, SubscriptionId, +}; +use egui_charts::model::{Bar, BarClock, Instrument, Tick, Timeframe, TimezoneId}; +use serde_json::Value; + +use super::bars::{self, Aggregator, DAY_MS}; +use super::http::{self, Request}; +use super::profile::{History, Profile, RangeFormat, RouteKind, fill, fill_url, stream_values}; +use super::stream::{Routed, Session, StreamEvent}; +use super::{Failure, Secrets, conceal, endpoint, shape, time}; + +/// The feed of one profile. It answers history from the REST template and keeps one stream +/// session per subscription. One instance serves every chart of the own-data mode. +pub(crate) struct MappedFeed { + shared: Arc, +} + +/// What the feed's callbacks reach. They hold it weakly: a session lives inside it. +struct Shared { + profile: Profile, + secrets: Secrets, + /// Everything that changes. It is never held while the feed calls out: not across a + /// method of a sink or a reply, a request, or the opening or the drop of a session. + state: Mutex, +} + +#[derive(Default)] +struct State { + subscriptions: HashMap, + /// How the streams of each key join its history. + joins: Vec<(Key, Join)>, + /// The run of empty windows of each symbol and interval. + runs: HashMap<(String, Timeframe), Run>, + /// How many subscriptions have been made, which gives each its number. + subscribed: u64, + /// The trades fed to the charts that time and sales has not taken yet, oldest first, each + /// with the number of the subscription that fed it, at most [`TAPE`]. + tape: VecDeque<(u64, Tick)>, +} + +/// The bars that belong together: those of one symbol and interval on one clock. The clock is +/// part of it because a bar of a day or longer is stamped for one clock. +#[derive(Clone, PartialEq)] +struct Key { + symbol: String, + timeframe: Timeframe, + clock: BarClock, +} + +/// What the latest pages of a key tell its subscriptions. +#[derive(Default)] +struct Join { + /// The newest bar of the last latest page that held bars. + newest: Option, + /// Latest pages being fetched. The subscriptions of the key fold no trade meanwhile. + in_flight: usize, +} + +/// A run of consecutive empty windows. +#[derive(Clone, Copy)] +struct Run { + /// The continuation named last. A request that asks before it continues the run. + next: DateTime, + /// The empty windows so far. + windows: u32, + /// The end of the first window. + began: DateTime, +} + +/// One subscription and its stream. +struct Live { + sink: Sink, + key: Key, + /// Its number in the order the subscriptions were made. + serial: u64, + /// The address of the stream without its query, for errors and log lines. + endpoint: String, + aggregator: Aggregator, + /// The slot of the newest bar pushed from a bar route. + pushed: Option>, + /// How often the socket has opened. + opens: u64, + /// The open count of the gap fill in flight. The subscription folds no trade meanwhile. + filling: Option, + /// Whether a record or a message that cannot be read has been logged. + warned: bool, + /// `None` until `Session::open` has returned. + session: Option, +} + +/// The bars a request asks for: those of `symbol` and `timeframe` that open in +/// `[since, before)` on the slots of `clock`, the newest `count`. +struct Ask { + symbol: String, + timeframe: Timeframe, + clock: BarClock, + before: Option>, + since: Option>, + count: usize, +} + +/// One request to the service: what its template is filled with and where it leads. +struct Window { + /// What `{from}`, `{to}` and `{limit}` become. + from: String, + to: String, + limit: usize, + /// The first instant after the window. + end: DateTime, + /// The open of the first slot of the window. Older bars continue before it. + start: DateTime, + /// Whether the template names `{from}`, so that a window without bars is one window and + /// not everything the service has. + lower: bool, + /// Whether the window is whole days of an interval shorter than a day. The service may + /// then fill its limit from the end of the day, with rows that open after the window. + days: bool, +} + +/// What a response holds for an [`Ask`]. +struct Kept { + /// The bars asked for, oldest first. + bars: Vec, + /// Whether rows open before the slot that holds `since`: older bars exist. + older: bool, + /// Whether rows open at or after `before`. + newer: bool, +} + +/// A run of empty windows ends history with this many windows. +const LONGEST_RUN: u32 = 64; + +/// The most trades the feed keeps for time and sales between two frames, as many as the panel +/// lists. +const TAPE: usize = 10_000; + +/// A run of empty windows also ends history with the first window that starts more than this +/// many days before the end of the run's first window. +const FARTHEST_RUN_DAYS: i64 = 366; + +impl MappedFeed { + /// A feed that reads `profile` with the key values `secrets`. Nothing is sent until a chart + /// asks. + pub(crate) fn new(profile: Profile, secrets: Secrets) -> Self { + Self { + shared: Arc::new(Shared { + profile, + secrets, + state: Mutex::default(), + }), + } + } + + /// The trades fed to the chart of `symbol` and `timeframe` since the last call, oldest + /// first, at most the latest 10,000, for time and sales. A study that reads the chart's + /// symbol, on the chart's interval or another, has a subscription of its own that receives + /// the same trades again, so only those of the first subscription of `symbol` and + /// `timeframe` still held are listed. Trades left from before a change of symbol or + /// interval are dropped. + // shortcut: the first subscription stands for the chart's, which the feed cannot tell from + // a study's on the same interval, so while their sockets differ, as when one reconnects, + // time and sales follows the first; take the chart's own once the Datafeed names it. + pub(crate) fn drain_tape(&self, symbol: &str, timeframe: Option) -> Vec { + let (tape, first) = { + let mut state = self.shared.state(); + let first = state + .subscriptions + .values() + .filter(|live| live.key.symbol == symbol && Some(live.key.timeframe) == timeframe) + .map(|live| live.serial) + .min(); + (std::mem::take(&mut state.tape), first) + }; + let listed = tape.into_iter().filter(|(by, _)| Some(*by) == first); + listed.map(|(_, tick)| tick).collect() + } +} + +impl Datafeed for MappedFeed { + fn capabilities(&self, reply: Reply) { + let timeframes = self.shared.profile.intervals.iter().map(|row| row.chart); + reply.send(Ok(FeedCapabilities::new().with_timeframes(timeframes))); + } + + fn resolve(&self, symbol: &str, reply: Reply) { + // Any symbol resolves. One the service does not know fails there, with its status. + let timeframes = self.shared.profile.intervals.iter().map(|row| row.chart); + let instrument = Instrument::new(symbol).with_supported_timeframes(timeframes); + // The footprint and the volume profiles group trades by the price step. + let instrument = match self.shared.profile.tick_size { + Some(step) => instrument.with_tick_size(step), + None => instrument, + }; + reply.send(Ok(instrument)); + } + + fn history(&self, request: HistoryRequest, reply: Reply) { + let shared = &self.shared; + shared.sweep(); + let end_of_history = || Ok(HistoryPage::new(Vec::new(), true)); + let Some(interval) = service(&shared.profile, request.timeframe) else { + return reply.send(Err(FeedError::NotSupported)); + }; + let Some(history) = &shared.profile.history else { + return reply.send(end_of_history()); + }; + let ask = Ask { + symbol: request.symbol, + timeframe: request.timeframe, + clock: request.clock, + before: request.before, + since: request.since, + count: request.count, + }; + if ask.before.is_some() && !names(history, "{from}") && !names(history, "{to}") { + // The service can only send its newest bars. + return reply.send(end_of_history()); + } + let runs = shared.state().runs.get(&ask.run()).copied(); + let run = runs.filter(|run| Some(run.next) == ask.before); + // A stretch that has shown itself sparse is crossed in the widest windows. + let wanted = match run { + Some(_) => history.page_size, + None => ask.count.min(history.page_size), + }; + let now = Utc::now(); + let Some(window) = window(history, &shared.profile.time_zone, &ask, wanted, now) else { + return reply.send(end_of_history()); + }; + let call = request_for(history, &window, &ask.symbol, interval, &shared.secrets); + let url = conceal(&call.url, &shared.secrets); + if ask.before.is_none() { + shared.state().join(&ask.key()).in_flight += 1; + } + let weak = Arc::downgrade(shared); + http::fetch(call, move |result| { + // A feed that is gone has no chart left to answer. + if let Some(shared) = weak.upgrade() + && let Some(history) = &shared.profile.history + { + reply.send(shared.answer(history, &ask, &window, run, &url, result)); + } + }); + } + + fn subscribe(&self, subscription: Subscription) { + let shared = &self.shared; + shared.sweep(); + let Subscription { + id, + symbol, + timeframe, + clock, + sink, + .. + } = subscription; + let (Some(stream), Some(interval)) = + (&shared.profile.stream, service(&shared.profile, timeframe)) + else { + return; + }; + sink.set_status(FeedStatus::Connecting); + let values = stream_values(&symbol, interval, &shared.secrets); + let filled: Vec<(&str, &str)> = values + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())) + .collect(); + let endpoint = conceal(endpoint(&fill_url(&stream.url, &filled)), &shared.secrets); + let key = Key { + symbol, + timeframe, + clock, + }; + { + let mut state = shared.state(); + let mut aggregator = Aggregator::new(key.clock.clone(), timeframe); + let join = state.join(&key); + if join.in_flight == 0 { + aggregator.start(join.newest.clone()); + } + state.subscribed += 1; + let live = Live { + sink, + key, + serial: state.subscribed, + endpoint, + aggregator, + pushed: None, + opens: 0, + filling: None, + warned: false, + session: None, + }; + state.subscriptions.insert(id, live); + } + let weak = Arc::downgrade(shared); + let session = Session::open(stream.clone(), values, move |event| { + if let Some(shared) = weak.upgrade() { + shared.on_event(id, event); + } + }); + // The session of a subscription that ended meanwhile closes at the end of this call, + // after the lock is released. + let _ended = { + let mut state = shared.state(); + match state.subscriptions.get_mut(&id) { + Some(live) => live.session.replace(session), + None => Some(session), + } + }; + } + + fn unsubscribe(&self, id: SubscriptionId) { + // The session closes at the end of this call, after the lock is released, and the + // close does not wait. + let _ended = self.shared.state().subscriptions.remove(&id); + } +} + +impl Shared { + /// The state, also when a thread panicked while it held the lock. + fn state(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Ends the subscriptions whose owner went away without unsubscribing. + fn sweep(&self) { + let sinks: Vec<(SubscriptionId, Sink)> = { + let state = self.state(); + let held = state.subscriptions.iter(); + held.map(|(id, live)| (*id, live.sink.clone())).collect() + }; + let ended: Vec = sinks + .into_iter() + .filter(|(_, sink)| !sink.is_active()) + .map(|(id, _)| id) + .collect(); + if ended.is_empty() { + return; + } + // Their sessions close at the end of this call, after the lock is released. + let _ended: Vec> = { + let mut state = self.state(); + let ended = ended.iter(); + ended.map(|id| state.subscriptions.remove(id)).collect() + }; + } + + /// The page that answers `ask` with the response to the request for `window`. `run` is the + /// run of empty windows the request continues. + fn answer( + &self, + history: &History, + ask: &Ask, + window: &Window, + run: Option, + url: &str, + result: Result, + ) -> Result { + let kept = result.and_then(|body| self.kept(history, ask, url, &body)); + let mut state = self.state(); + if ask.before.is_none() { + // A latest page. The streams of its key go on from its newest bar, which the chart + // gets with the page. + let key = ask.key(); + let newest = kept.as_ref().ok().and_then(|kept| kept.bars.last()); + let join = state.join(&key); + join.in_flight = join.in_flight.saturating_sub(1); + if let Some(newest) = newest { + join.newest = Some(newest.clone()); + let joining = state.subscriptions.values_mut(); + for live in joining.filter(|live| live.key == key) { + live.aggregator.start(Some(newest.clone())); + } + } + } + let kept = kept.map_err(|failure| reported(&failure, url, &ask.symbol, &self.secrets))?; + if !kept.bars.is_empty() { + state.runs.remove(&ask.run()); + // A page shorter than asked never ends history: the empty page after it does. + return Ok(HistoryPage::new(kept.bars, false)); + } + if let Some(floor) = ask.floor().filter(|_| kept.older) { + return Ok(HistoryPage::default().with_continue_before(floor)); + } + if !(window.lower || (window.days && kept.newer)) { + // The service was asked for the bars before the end and has none. + return Ok(HistoryPage::new(Vec::new(), true)); + } + // An empty window, such as a weekend. Older bars continue before it, until the run of + // such windows is too long to have anything behind it. + let (windows, began) = run.map_or((1, window.end), |run| (run.windows + 1, run.began)); + let reach = began.signed_duration_since(window.start); + if windows >= LONGEST_RUN || reach > TimeDelta::days(FARTHEST_RUN_DAYS) { + state.runs.remove(&ask.run()); + return Ok(HistoryPage::new(Vec::new(), true)); + } + let next = window.start; + let run = Run { + next, + windows, + began, + }; + state.runs.insert(ask.run(), run); + Ok(HistoryPage::default().with_continue_before(next)) + } + + /// The bars of the response `body` that `ask` asks for. + fn kept(&self, history: &History, ask: &Ask, url: &str, body: &str) -> Result { + let response: Value = serde_json::from_str(body) + .map_err(|error| Failure::Unreadable(format!("not JSON: {error}")))?; + let zone = &self.profile.time_zone; + let reading = read( + &response, + history, + &ask.symbol, + zone, + &ask.clock, + ask.timeframe, + Utc::now(), + ) + .map_err(Failure::Unreadable)?; + if reading.skipped > 0 { + log::warn!( + "own data: {} rows of {} were left out: their time is missing, unreadable or \ + too far ahead", + reading.skipped, + endpoint(url) + ); + } + let slot = |bar: &Bar| ask.clock.bar_open(bar.time); + let floor = ask.floor(); + let below = |bar: &Bar| floor.is_some_and(|floor| slot(bar) < floor); + let above = |bar: &Bar| ask.before.is_some_and(|before| slot(bar) >= before); + let mut bars = reading.bars; + let older = bars.iter().any(below); + let newer = bars.iter().any(above); + bars.retain(|bar| !below(bar) && !above(bar)); + let more = bars.len().saturating_sub(ask.count); + bars.drain(..more); + Ok(Kept { bars, older, newer }) + } + + /// What a session of subscription `id` reports. + fn on_event(self: &Arc, id: SubscriptionId, event: StreamEvent) { + match event { + StreamEvent::Open { again } => { + let known = { + let mut state = self.state(); + let Some(live) = state.subscriptions.get_mut(&id) else { + return; + }; + live.opens += 1; + // The newest bar the subscription knows: the one being built, or the + // newest one a bar route pushed. + let building = live.aggregator.bar(); + let building = building.map(|bar| live.key.clock.bar_open(bar.time)); + let newest = building.max(live.pushed); + (live.sink.clone(), live.key.clone(), live.opens, newest) + }; + let (sink, key, opens, newest) = known; + sink.set_status(FeedStatus::Live); + // Records may have been missed since the connection dropped. Without a bar to + // start from, a latest page that is still in flight brings them. + if again && let Some(since) = newest { + self.fill(id, key, opens, since); + } + } + StreamEvent::Message { records, .. } => { + let now = Utc::now(); + let mut pushes = Vec::new(); + let mut unread = None; + let sink = { + let mut state = self.state(); + let Some(live) = state.subscriptions.get(&id) else { + return; + }; + let folding = live.filling.is_none() && !state.fetching(&live.key); + let Some(live) = state.subscriptions.get_mut(&id) else { + return; + }; + let Key { + timeframe, clock, .. + } = &live.key; + let zone = &self.profile.time_zone; + let routes = self.profile.stream.as_ref().map(|stream| &stream.routes); + for routed in records { + let Routed::Record { route, record } = routed else { + continue; + }; + let Some(route) = routes.and_then(|routes| routes.get(route)) else { + continue; + }; + match &route.kind { + RouteKind::Bars(fields) => { + match bars::bar(&record, fields, zone, clock, *timeframe) { + Some(bar) => { + let slot = clock.bar_open(bar.time); + // A time too far ahead is refused by the chart and + // is not the newest bar known. + if !bars::ahead(clock, *timeframe, slot, now) { + live.pushed = live.pushed.max(Some(slot)); + // The trades that follow continue the service's + // own bar. + live.aggregator.follow(&bar); + } + pushes.push((None, bar)); + } + None => unread = unread.or(Some((&route.value, "time"))), + } + } + RouteKind::Trades(fields) => { + match bars::read_trade(&record, fields, zone) { + Ok(trade) if folding => { + if let Some(bar) = live.aggregator.add(&trade, now) { + let (time, price) = (trade.time, trade.price); + let tick = + Tick::new(time, price, trade.size, trade.side); + pushes.push((Some(tick), bar)); + } + } + Ok(_) => {} + Err(part) => unread = unread.or(Some((&route.value, part))), + } + } + RouteKind::Ignore => {} + } + } + if let Some((route, part)) = unread.filter(|_| !live.warned) { + live.warned = true; + // Never the record itself, which may hold a key. + log::warn!( + "own data: a record of the route \"{route}\" of {} has no readable \ + {part}; such records are dropped", + live.endpoint + ); + } + let (sink, serial) = (live.sink.clone(), live.serial); + let fed = pushes.iter().filter_map(|(tick, _)| tick.clone()); + state.tape.extend(fed.map(|tick| (serial, tick))); + let over = state.tape.len().saturating_sub(TAPE); + state.tape.drain(..over); + sink + }; + // A trade goes before its bar: the bar, which already holds the trade, replaces + // what the chart folds the trade into, so its volume is counted once. + for (tick, bar) in pushes { + if let Some(tick) = tick { + sink.push_tick(tick); + } + sink.push_bar(bar); + } + } + StreamEvent::Unreadable { reason } => { + let mut state = self.state(); + if let Some(live) = state.subscriptions.get_mut(&id) + && !live.warned + { + live.warned = true; + log::warn!( + "own data: {} sent {reason}; such messages are dropped", + live.endpoint + ); + } + } + StreamEvent::Closed { reason, .. } => { + let known = { + let state = self.state(); + let live = state.subscriptions.get(&id); + live.map(|live| (live.sink.clone(), live.endpoint.clone())) + }; + if let Some((sink, endpoint)) = known { + sink.set_status(FeedStatus::Disconnected); + let text = conceal(&format!("{endpoint}: {reason}"), &self.secrets); + sink.report_error(FeedError::Network(text)); + } + } + } + } + + /// Loads the bars from the slot `since` on, which a subscription may have missed while its + /// socket was down, and pushes them. `opens` is the open count of the reconnect: the answer + /// counts only while no later reconnect has started a fill of its own. + fn fill(self: &Arc, id: SubscriptionId, key: Key, opens: u64, since: DateTime) { + let (Some(history), Some(interval)) = + (&self.profile.history, service(&self.profile, key.timeframe)) + else { + return; + }; + let now = Utc::now(); + let slots = now.signed_duration_since(since).num_milliseconds() + / key.timeframe.duration_ms().max(1); + let count = usize::try_from(slots).unwrap_or(0).saturating_add(1); + let count = count.min(history.page_size.max(1)); + let ask = Ask { + symbol: key.symbol, + timeframe: key.timeframe, + clock: key.clock, + before: None, + since: Some(since), + count, + }; + let Some(window) = window(history, &self.profile.time_zone, &ask, count, now) else { + return; + }; + let call = request_for(history, &window, &ask.symbol, interval, &self.secrets); + let url = conceal(&call.url, &self.secrets); + // From here on the subscription folds no trade, until the answer has been pushed. + match self.state().subscriptions.get_mut(&id) { + Some(live) if live.opens == opens => live.filling = Some(opens), + _ => return, + } + let weak = Arc::downgrade(self); + http::fetch(call, move |result| { + let Some(shared) = weak.upgrade() else { + return; + }; + let Some(history) = &shared.profile.history else { + return; + }; + let kept = result.and_then(|body| shared.kept(history, &ask, &url, &body)); + // An answer for an older open is discarded: a newer fill is in flight. + let filling = shared + .state() + .filling(id, opens) + .map(|live| live.sink.clone()); + let Some(sink) = filling else { + return; + }; + // The bars go out while the subscription still folds no trade, so that no trade + // can be pushed before the bar it continues. + let newest = match kept { + Ok(kept) => { + let newest = kept.bars.last().cloned(); + for bar in kept.bars { + sink.push_bar(bar); + } + newest + } + Err(failure) => { + sink.report_error(reported(&failure, &url, &ask.symbol, &shared.secrets)); + None + } + }; + if let Some(live) = shared.state().filling(id, opens) { + live.filling = None; + // Without a bar, the subscription folds again on the bar it has. + if newest.is_some() { + live.aggregator.start(newest); + } + } + }); + } +} + +impl State { + /// What is known of the latest pages of `key`. + fn join(&mut self, key: &Key) -> &mut Join { + let held = self.joins.iter().position(|(held, _)| held == key); + let at = held.unwrap_or_else(|| { + self.joins.push((key.clone(), Join::default())); + self.joins.len() - 1 + }); + &mut self.joins[at].1 + } + + /// Whether a latest page of `key` is being fetched. + fn fetching(&self, key: &Key) -> bool { + let mut joins = self.joins.iter(); + joins.any(|(held, join)| held == key && join.in_flight > 0) + } + + /// The subscription `id`, while the gap fill of its open `opens` is the one in flight. + fn filling(&mut self, id: SubscriptionId, opens: u64) -> Option<&mut Live> { + let live = self.subscriptions.get_mut(&id)?; + (live.filling == Some(opens)).then_some(live) + } +} + +impl Ask { + fn key(&self) -> Key { + Key { + symbol: self.symbol.clone(), + timeframe: self.timeframe, + clock: self.clock.clone(), + } + } + + /// What the runs of empty windows are counted by. + fn run(&self) -> (String, Timeframe) { + (self.symbol.clone(), self.timeframe) + } + + /// The open of the slot that holds `since`. That bar is the one the chart is waiting for, + /// so it is answered although it opens before `since`. + fn floor(&self) -> Option> { + self.since.map(|since| self.clock.bar_open(since)) + } +} + +/// What `{interval}` becomes for `timeframe`, when the table has a row for it and the interval +/// has a duration. +fn service(profile: &Profile, timeframe: Timeframe) -> Option<&str> { + profile + .service_interval(timeframe) + .filter(|_| !timeframe.is_trade_based()) +} + +/// Whether a template of `history` names `placeholder`: its URL, a header or its body. +fn names(history: &History, placeholder: &str) -> bool { + let mut headers = history.headers.iter(); + history.url.contains(placeholder) + || history.body.contains(placeholder) + || headers.any(|(_, value)| value.contains(placeholder)) +} + +/// The window of `wanted` slots before the end `ask` names, or before `now` for the newest +/// bars. `None` when it leaves the range of time: there is nothing to ask for. +fn window( + history: &History, + zone: &TimezoneId, + ask: &Ask, + wanted: usize, + now: DateTime, +) -> Option { + let (clock, timeframe) = (&ask.clock, ask.timeframe); + let end = ask.before.unwrap_or(now); + let floor = ask.floor(); + let limit = wanted.max(1); + let slots = i64::try_from(limit).ok()?; + let lower = names(history, "{from}"); + let dates = matches!(history.range, RangeFormat::Date | RangeFormat::CompactDate); + let print = |instant| time::print(instant, &history.range, zone); + let print_day = |day| time::print_day(day, &history.range); + let midnight = |day: NaiveDate| day.and_time(NaiveTime::MIN).and_utc(); + let build = |from, to, limit, start, days| Window { + from, + to, + limit, + end, + start, + lower, + days, + }; + if bars::calendar(timeframe) { + // A bar of a day or longer is dated, so its window is counted in dates. An end that + // opens a period is the open of the chart's oldest bar or a continuation named here. + let last = if clock.bar_open(end) == end { + bars::period_date(end).pred_opt()? + } else { + end.with_timezone(zone).date_naive() + }; + let newest = bars::period_date(bars::period_open(clock, last)); + let back = u32::try_from(slots - 1).ok()?; + let first = match timeframe { + Timeframe::Month1 => newest.checked_sub_months(Months::new(back))?, + Timeframe::Months(count) => { + newest.checked_sub_months(Months::new(count.get().checked_mul(back)?))? + } + _ => { + let days = (timeframe.duration_ms() / DAY_MS).checked_mul(back.into())?; + newest.checked_sub_signed(TimeDelta::try_days(days)?)? + } + }; + let first = bars::period_date(bars::period_open(clock, first)); + let first = floor.map_or(first, |floor| first.max(bars::period_date(floor))); + let start = bars::period_open(clock, first); + let (from, to) = if dates { + (print_day(first), print_day(last)) + } else { + // An instant form names 00:00 UTC on a date, and its end is not part of the range. + (print(midnight(first)), print(midnight(last.succ_opt()?))) + }; + return Some(build(from, to, limit, start, false)); + } + if dates { + // A date cannot name part of a day, so the window is whole days of the profile's zone, + // the last one included. One day can hold more rows than the slots wanted. + let last = end.checked_sub_signed(TimeDelta::milliseconds(1))?; + let last = last.with_timezone(zone).date_naive(); + let days = if lower { + (slots.checked_mul(timeframe.duration_ms())? / DAY_MS).max(1) + } else { + 1 + }; + let first = last.checked_sub_signed(TimeDelta::try_days(days - 1)?)?; + let first = floor.map_or(first, |floor| { + first.max(floor.with_timezone(zone).date_naive()) + }); + let start = time::wall(first.and_time(NaiveTime::MIN), zone)?; + let limit = history.page_size.max(1); + let (from, to) = (print_day(first), print_day(last)); + return Some(build(from, to, limit, start, true)); + } + let span = TimeDelta::try_milliseconds(slots.checked_mul(timeframe.duration_ms())?)?; + let start = end.checked_sub_signed(span)?; + let start = floor.map_or(start, |floor| start.max(floor)); + // `{from}` is printed rounded down and `{to}` rounded up to the unit of the form, so the + // printed window loses no row. What the rounding adds is cut from the answer. + let unit = match history.range { + RangeFormat::Seconds => 1_000_000_000, + RangeFormat::Milliseconds => 1_000_000, + RangeFormat::Microseconds => 1_000, + _ => 1, + }; + let over = i64::from(end.timestamp_subsec_nanos()) % unit; + let up = TimeDelta::nanoseconds((unit - over) % unit); + let to = end.checked_add_signed(up).unwrap_or(end); + Some(build(print(start), print(to), limit, start, false)) +} + +/// The request for `window` of `symbol`, every template of `history` filled. +fn request_for( + history: &History, + window: &Window, + symbol: &str, + interval: &str, + secrets: &Secrets, +) -> Request { + let limit = window.limit.to_string(); + let lower = symbol.to_lowercase(); + let mut values = vec![ + ("symbol", symbol), + ("symbol_lower", lower.as_str()), + ("interval", interval), + ("from", window.from.as_str()), + ("to", window.to.as_str()), + ("limit", limit.as_str()), + ]; + let keys = secrets.iter(); + values.extend(keys.map(|(name, value)| (name.as_str(), value.as_str()))); + let headers = history.headers.iter(); + let mut headers: Vec<(String, String)> = headers + .map(|(name, value)| (name.clone(), fill(value, &values))) + .collect(); + // An empty body template sends `GET`. + let body = (!history.body.is_empty()).then(|| fill(&history.body, &values)); + let typed = |(name, _): &(String, String)| name.eq_ignore_ascii_case("content-type"); + if body.is_some() && !headers.iter().any(typed) { + headers.push(("Content-Type".to_owned(), "application/json".to_owned())); + } + Request { + url: fill_url(&history.url, &values), + headers, + body, + } +} + +/// The error the chart reports for `failure` of a request to `url`: the kind `feed_error` +/// picks, with the endpoint before the reason where the kind carries a text. No key value of +/// `secrets` is shown. +fn reported(failure: &Failure, url: &str, symbol: &str, secrets: &Secrets) -> FeedError { + let text = conceal(&format!("{}: {failure}", endpoint(url)), secrets); + match failure.feed_error(symbol) { + FeedError::Network(_) => FeedError::Network(text), + FeedError::InvalidData(_) => FeedError::InvalidData(text), + other => other, + } +} + +/// What a history response holds when it is read with a mapping. +pub(crate) struct Reading { + /// The bars with a readable time, oldest first. Bars of equal time keep the order of the + /// response. + pub(crate) bars: Vec, + /// Rows left out because their time is missing or unreadable, or lies too far after `now`, + /// as [`bars::ahead`] judges a pushed bar. + pub(crate) skipped: usize, +} + +/// Reads a parsed history response. The feed and the dialog's Test both call it, so the preview +/// cannot disagree with the chart. The rows are looked up for `symbol` ([`Rows::for_symbol`]). +/// The error says why nothing can be read: the rows are not where the mapping says, or no row +/// has a readable time. +/// +/// [`Rows::for_symbol`]: super::profile::Rows::for_symbol +pub(crate) fn read( + response: &Value, + history: &History, + symbol: &str, + zone: &TimezoneId, + clock: &BarClock, + timeframe: Timeframe, + now: DateTime, +) -> Result { + let rows = shape::rows(response, &history.rows.for_symbol(symbol))?; + let read = rows + .iter() + .filter_map(|row| bars::bar(row, &history.bar, zone, clock, timeframe)); + let mut read: Vec = read.collect(); + if read.is_empty() && !rows.is_empty() { + // A wrong time mapping must not look like a window without bars. + let count = rows.len(); + let rows = if count == 1 { "row" } else { "rows" }; + return Err(format!("no row has a readable time ({count} {rows})")); + } + // A time in the wrong unit lands far ahead, where it would be the newest bar. + read.retain(|bar| !bars::ahead(clock, timeframe, clock.bar_open(bar.time), now)); + // A stable sort: rows of one time stay in the order the service sent them, so the chart, + // which keeps the last bar of a slot, takes a correction sent after the row it corrects. + read.sort_by_key(|bar| bar.time); + let skipped = rows.len() - read.len(); + Ok(Reading { + bars: read, + skipped, + }) +} + +/// The request for the newest page of `symbol` at `timeframe`, exactly as the feed sends it for +/// a chart's first load. The dialog's Test sends this request. The error says why none can be +/// built: the profile has no history, or its interval table has no row for `timeframe`. +pub(crate) fn latest( + profile: &Profile, + secrets: &Secrets, + symbol: &str, + timeframe: Timeframe, + clock: &BarClock, + now: DateTime, +) -> Result { + let Some(history) = &profile.history else { + return Err("the profile has no REST history".to_owned()); + }; + let Some(interval) = service(profile, timeframe) else { + return Err(format!("the interval table has no row for {timeframe}")); + }; + let ask = Ask { + symbol: symbol.to_owned(), + timeframe, + clock: clock.clone(), + before: None, + since: None, + count: history.page_size, + }; + let Some(window) = window(history, &profile.time_zone, &ask, ask.count, now) else { + return Err("the newest page lies outside the range of time".to_owned()); + }; + Ok(request_for(history, &window, symbol, interval, secrets)) +} + +#[cfg(test)] +pub(crate) mod tests { + use std::io::{BufRead as _, BufReader, Read as _, Write as _}; + use std::net::TcpListener; + use std::time::{Duration, Instant}; + + use eframe::egui; + use egui_charts::config::{ChartOptions, TimezoneMode}; + use egui_charts::widget::{Chart, ChartBuilder, SeriesId}; + + use super::super::profile::{ + BarFields, DateFormat, Interval, Layout, Rows, Segment, TimeSpec, TimeUnit, + }; + use super::*; + + /// One request the local server received. + #[derive(Clone, Debug, PartialEq, Eq)] + pub(crate) struct Seen { + /// Method and target, such as `GET /bars?symbol=ABC&interval=1m&to=1794407580&limit=3`. + pub(crate) line: String, + /// The request headers, names in lower case, in the order sent. + pub(crate) headers: Vec<(String, String)>, + /// The request body, empty for `GET`. + pub(crate) body: String, + } + + /// A scripted HTTP server on a local port. It answers what `answer` returns for each + /// request and records every request. It never filters, sorts or pages: a test writes each + /// response by hand, so no expected value comes from logic that mirrors the code under + /// test. + pub(crate) struct Server { + /// `http://127.0.0.1:PORT`, without a trailing slash. + pub(crate) origin: String, + seen: Arc>>, + } + + impl Server { + /// `answer` gets the number of the request, counted from zero, and the request, and + /// returns the status and the body. + pub(crate) fn start( + answer: impl Fn(usize, &Seen) -> (u16, String) + Send + 'static, + ) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let seen = Arc::new(Mutex::new(Vec::new())); + let log = seen.clone(); + std::thread::spawn(move || { + for connection in listener.incoming() { + let Ok(mut connection) = connection else { + return; + }; + let mut reader = BufReader::new(connection.try_clone().unwrap()); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + let line = line.trim_end().trim_end_matches(" HTTP/1.1").to_owned(); + let mut headers = Vec::new(); + loop { + let mut header = String::new(); + reader.read_line(&mut header).unwrap(); + let Some((name, value)) = header.trim_end().split_once(':') else { + break; + }; + headers.push((name.to_ascii_lowercase(), value.trim().to_owned())); + } + let length = headers + .iter() + .find(|(name, _)| name == "content-length") + .map_or(0, |(_, value)| value.parse().unwrap()); + let mut body = vec![0; length]; + reader.read_exact(&mut body).unwrap(); + let request = Seen { + line, + headers, + body: String::from_utf8(body).unwrap(), + }; + let number = log.lock().unwrap().len(); + let (status, text) = answer(number, &request); + log.lock().unwrap().push(request); + let _ = write!( + connection, + "HTTP/1.1 {status} Scripted\r\nContent-Type: application/json\r\n\ + Content-Length: {}\r\nConnection: close\r\n\r\n{text}", + text.len() + ); + } + }); + Self { origin, seen } + } + + /// Every request received so far, in order. + pub(crate) fn seen(&self) -> Vec { + self.seen.lock().unwrap().clone() + } + } + + /// The answer of a script: request `n` gets `pages[n]` with status 200. A request beyond + /// the script gets status 400, which ends the chart's paging with an error, so a test that + /// asks one request too many stops and shows the line it asked. + pub(crate) fn pages( + pages: Vec, + ) -> impl Fn(usize, &Seen) -> (u16, String) + Send + 'static { + move |number, _| { + let page = pages.get(number); + page.map_or((400, String::new()), |page| (200, page.clone())) + } + } + + /// Runs frames of `chart` until `done` holds. Panics after thirty seconds, naming `what`. + pub(crate) fn until( + ctx: &egui::Context, + chart: &mut Chart, + what: &str, + done: impl Fn(&Chart) -> bool, + ) { + let start = Instant::now(); + loop { + let size = egui::vec2(800.0, 600.0); + let output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), + ..Default::default() + }, + |ui| { + chart.show(ui); + }, + ); + output.drop_without_applying_deltas(); + if done(chart) { + return; + } + assert!( + start.elapsed() < Duration::from_secs(30), + "timed out waiting for {what}" + ); + std::thread::sleep(Duration::from_millis(5)); + } + } + + /// What a test compares of a bar: its time in Unix seconds and its open, high, low, close + /// and volume, or `None` for a whitespace bar (whose values are NaN and equal nothing). + pub(crate) type Shown = (i64, Option<[f64; 5]>); + + /// The bars of the chart's main series, oldest first. + pub(crate) fn shown(chart: &Chart) -> Vec { + let bars = chart.bars(SeriesId::MAIN).iter(); + bars.map(|bar| { + let values = [bar.open, bar.high, bar.low, bar.close, bar.volume]; + ( + bar.time.timestamp(), + (!bar.is_whitespace()).then_some(values), + ) + }) + .collect() + } + + /// The base profile: objects at the root of the response, `{to}` and `{limit}` in the + /// address, instants in seconds, three bars per request. + pub(crate) fn profile(origin: &str) -> Profile { + let key = |name: &str| vec![Segment::Key(name.to_owned())]; + let interval = |chart, service: &str| Interval { + chart, + service: service.to_owned(), + }; + Profile { + name: "Local".into(), + symbols: vec!["ABC".into()], + intervals: vec![ + interval(Timeframe::Min1, "1m"), + interval(Timeframe::Day1, "1d"), + ], + history: Some(History { + url: format!( + "{origin}/bars?symbol={{symbol}}&interval={{interval}}&to={{to}}&limit={{limit}}" + ), + page_size: 3, + bar: BarFields { + time: TimeSpec::Instant { + field: key("t"), + unit: TimeUnit::Seconds, + }, + open: key("o"), + high: key("h"), + low: key("l"), + close: key("c"), + volume: key("v"), + }, + ..History::default() + }), + ..Profile::default() + } + } + + /// A request as the table writes it: the line, and for a request with a body also its + /// content type and the body. + fn asked(seen: &Seen) -> String { + if seen.body.is_empty() { + return seen.line.clone(); + } + let kind = seen.headers.iter().find(|(name, _)| name == "content-type"); + let kind = kind.map_or("", |(_, value)| value); + format!("{} {kind} {}", seen.line, seen.body) + } + + struct Case { + name: &'static str, + /// What the row changes in the base profile. + edit: fn(&mut Profile), + /// What it changes in the chart. + chart: fn(ChartBuilder) -> ChartBuilder, + /// The answers, in the order of the requests. + answers: Vec, + /// How the first request starts. Its bounds come from the system clock. + first: &'static str, + /// Every later request, in order. + asked: Vec, + /// The chart's bars once history has ended. + bars: Vec, + /// How many bars the chart refused. + rejected: u64, + } + + /// The fixture is one-minute bars of 11 November 2026 from 14:30 UTC (second 1,794,407,400, + /// then every 60 seconds) and three of 10 November from 14:30 UTC (second 1,794,321,000). + /// Every response is written out as a service sends it, and every request line after the + /// first of a chart, whose bounds come from the system clock, is calculated by hand. + #[test] + fn history_maps_every_shape_and_pages_back() { + // The fixture as a service sends it. + const J0: &str = r#"{"t":1794407400,"o":100.0,"h":101.0,"l":99.5,"c":100.5,"v":1000}"#; + const J1: &str = r#"{"t":1794407460,"o":100.5,"h":102.0,"l":100.0,"c":101.5,"v":1200}"#; + const J2: &str = r#"{"t":1794407520,"o":101.5,"h":101.75,"l":100.25,"c":100.75,"v":900}"#; + const J3: &str = r#"{"t":1794407580,"o":100.75,"h":103.0,"l":100.5,"c":102.5,"v":1500}"#; + const J4: &str = r#"{"t":1794407640,"o":102.5,"h":102.75,"l":101.0,"c":101.25,"v":800}"#; + const J5: &str = r#"{"t":1794407700,"o":101.25,"h":101.5,"l":100.0,"c":100.25,"v":700}"#; + const K0: &str = r#"{"t":1794321000,"o":99.0,"h":99.5,"l":98.5,"c":99.25,"v":400}"#; + const K1: &str = r#"{"t":1794321060,"o":99.25,"h":100.0,"l":99.0,"c":99.75,"v":500}"#; + const K2: &str = r#"{"t":1794321120,"o":99.75,"h":100.25,"l":99.5,"c":100.0,"v":600}"#; + // The same bars as the chart shows them. + const B0: Shown = (1794407400, Some([100.0, 101.0, 99.5, 100.5, 1000.0])); + const B1: Shown = (1794407460, Some([100.5, 102.0, 100.0, 101.5, 1200.0])); + const B2: Shown = (1794407520, Some([101.5, 101.75, 100.25, 100.75, 900.0])); + const B3: Shown = (1794407580, Some([100.75, 103.0, 100.5, 102.5, 1500.0])); + const B4: Shown = (1794407640, Some([102.5, 102.75, 101.0, 101.25, 800.0])); + const B5: Shown = (1794407700, Some([101.25, 101.5, 100.0, 100.25, 700.0])); + const A0: Shown = (1794321000, Some([99.0, 99.5, 98.5, 99.25, 400.0])); + const A1: Shown = (1794321060, Some([99.25, 100.0, 99.0, 99.75, 500.0])); + const A2: Shown = (1794321120, Some([99.75, 100.25, 99.5, 100.0, 600.0])); + // The requests most rows expect: the first, then the pages before B3 and before B0. + const FIRST: &str = "GET /bars?symbol=ABC&interval=1m&to="; + const BEFORE_B3: &str = "GET /bars?symbol=ABC&interval=1m&to=1794407580&limit=3"; + const BEFORE_B0: &str = "GET /bars?symbol=ABC&interval=1m&to=1794407400&limit=3"; + + let list = |rows: &[&str]| format!("[{}]", rows.join(",")); + let case = |name, edit, answers: Vec, first, asked: Vec<&str>, bars| Case { + name, + edit, + chart: |chart| chart, + answers, + first, + asked: asked.into_iter().map(str::to_owned).collect(), + bars, + rejected: 0, + }; + let two_pages = || vec![list(&[J3, J4, J5]), list(&[J0, J1, J2]), "[]".to_owned()]; + let all = || vec![B0, B1, B2, B3, B4, B5]; + + #[rustfmt::skip] + let cases = [ + case("objects at the root", |_| {}, two_pages(), FIRST, vec![BEFORE_B3, BEFORE_B0], all()), + case( + "arrays read by column number", + |profile| { + let column = |number| vec![Segment::Index(number)]; + let history = profile.history.as_mut().unwrap(); + history.rows.layout = Layout::Arrays { header: None }; + history.bar = BarFields { + time: TimeSpec::Instant { field: column(0), unit: TimeUnit::Seconds }, + open: column(1), + high: column(2), + low: column(3), + close: column(4), + volume: column(5), + }; + }, + vec![ + "[[1794407580,100.75,103.0,100.5,102.5,1500],[1794407640,102.5,102.75,101.0,101.25,800],\ + [1794407700,101.25,101.5,100.0,100.25,700]]".into(), + "[[1794407400,100.0,101.0,99.5,100.5,1000],[1794407460,100.5,102.0,100.0,101.5,1200],\ + [1794407520,101.5,101.75,100.25,100.75,900]]".into(), + "[]".into(), + ], + FIRST, + vec![BEFORE_B3, BEFORE_B0], + all(), + ), + case( + "arrays named by a header in another order; the empty page comes without its list", + |profile| { + let key = |name: &str| vec![Segment::Key(name.to_owned())]; + profile.history.as_mut().unwrap().rows = + Rows { path: key("rows"), layout: Layout::Arrays { header: Some(key("columns")) } }; + }, + vec![ + r#"{"columns":["t","v","o","c","h","l"],"rows":[[1794407580,1500,100.75,102.5,103.0,100.5],[1794407640,800,102.5,101.25,102.75,101.0],[1794407700,700,101.25,100.25,101.5,100.0]]}"#.into(), + r#"{"columns":["t","v","o","c","h","l"],"rows":[[1794407400,1000,100.0,100.5,101.0,99.5],[1794407460,1200,100.5,101.5,102.0,100.0],[1794407520,900,101.5,100.75,101.75,100.25]]}"#.into(), + r#"{"columns":["t","v","o","c","h","l"]}"#.into(), + ], + FIRST, + vec![BEFORE_B3, BEFORE_B0], + all(), + ), + case( + "columns, beside a member that is not a list", + |profile| profile.history.as_mut().unwrap().rows.layout = Layout::Columns, + vec![ + r#"{"s":"ok","t":[1794407580,1794407640,1794407700],"o":[100.75,102.5,101.25],"h":[103.0,102.75,101.5],"l":[100.5,101.0,100.0],"c":[102.5,101.25,100.25],"v":[1500,800,700]}"#.into(), + r#"{"s":"ok","t":[1794407400,1794407460,1794407520],"o":[100.0,100.5,101.5],"h":[101.0,102.0,101.75],"l":[99.5,100.0,100.25],"c":[100.5,101.5,100.75],"v":[1000,1200,900]}"#.into(), + r#"{"s":"no_data","t":[],"o":[],"h":[],"l":[],"c":[],"v":[]}"#.into(), + ], + FIRST, + vec![BEFORE_B3, BEFORE_B0], + all(), + ), + case( + "rows below data.candles; the empty page is null", + |profile| { + profile.history.as_mut().unwrap().rows.path = + vec![Segment::Key("data".into()), Segment::Key("candles".into())]; + }, + vec![ + format!(r#"{{"data":{{"candles":{}}}}}"#, list(&[J3, J4, J5])), + format!(r#"{{"data":{{"candles":{}}}}}"#, list(&[J0, J1, J2])), + r#"{"data":{"candles":null}}"#.into(), + ], + FIRST, + vec![BEFORE_B3, BEFORE_B0], + all(), + ), + case( + "rows filed under the symbol, and the symbol in lower case in the address", + |profile| { + let history = profile.history.as_mut().unwrap(); + history.url = history.url.replace("{symbol}", "{symbol_lower}"); + history.rows.path = vec![Segment::Key("result".into()), Segment::Key("{symbol}".into())]; + }, + vec![ + format!(r#"{{"error":[],"result":{{"ABC":{},"last":1794407700}}}}"#, list(&[J3, J4, J5])), + format!(r#"{{"error":[],"result":{{"ABC":{},"last":1794407520}}}}"#, list(&[J0, J1, J2])), + r#"{"error":[],"result":{"last":1794407400}}"#.into(), + ], + "GET /bars?symbol=abc&interval=1m&to=", + vec![ + "GET /bars?symbol=abc&interval=1m&to=1794407580&limit=3", + "GET /bars?symbol=abc&interval=1m&to=1794407400&limit=3", + ], + all(), + ), + // Five rows for a limit of three: the newest three are B3 to B5 once sorted. + case( + "rows out of order, and more of them than asked", + |_| {}, + vec![list(&[J2, J5, J1, J4, J3]), list(&[J1, J0, J2]), "[]".into()], + FIRST, + vec![BEFORE_B3, BEFORE_B0], + all(), + ), + case( + "a slot sent twice: the later row is the correction", + |_| {}, + vec![ + list(&[J4, r#"{"t":1794407700,"o":101.25,"h":101.25,"l":101.25,"c":101.25,"v":1}"#, J5]), + "[]".into(), + ], + FIRST, + vec!["GET /bars?symbol=ABC&interval=1m&to=1794407640&limit=3"], + vec![B4, B5], + ), + case( + "partial pages do not end history", + |_| {}, + vec![list(&[J4, J5]), list(&[J1, J2, J3]), list(&[J0]), "[]".into()], + FIRST, + vec![ + "GET /bars?symbol=ABC&interval=1m&to=1794407640&limit=3", + "GET /bars?symbol=ABC&interval=1m&to=1794407460&limit=3", + BEFORE_B0, + ], + all(), + ), + // Windows of three minutes. The one before B5 is empty and is crossed; the next + // holds B0 and B1; then 64 empty windows back from B0 end history. The last of them + // is 1794407400 - 63 * 180 = 1794396060 down to 1794395880. 67 requests in all. + Case { + asked: [ + vec![ + "GET /bars?symbol=ABC&interval=1m&from=1794407520&to=1794407700&limit=3".to_owned(), + "GET /bars?symbol=ABC&interval=1m&from=1794407340&to=1794407520&limit=3".to_owned(), + ], + (0..64) + .map(|window| { + let (from, to) = (1794407220 - window * 180, 1794407400 - window * 180); + format!("GET /bars?symbol=ABC&interval=1m&from={from}&to={to}&limit=3") + }) + .collect(), + ] + .concat(), + ..case( + "an empty window is crossed, and a run of 64 ends history", + |profile| { + let history = profile.history.as_mut().unwrap(); + history.url = history.url.replace("&to=", "&from={from}&to="); + }, + [vec![list(&[J5]), "[]".into(), list(&[J0, J1])], vec!["[]".to_owned(); 64]].concat(), + "GET /bars?symbol=ABC&interval=1m&from=", + vec![], + vec![B0, B1, B5], + ) + }, + case( + "a template without a bound is asked once", + |profile| { + let history = profile.history.as_mut().unwrap(); + history.url = history.url.replace("&to={to}&limit={limit}", ""); + }, + vec![list(&[J3, J4, J5])], + "GET /bars?symbol=ABC&interval=1m", + vec![], + vec![B3, B4, B5], + ), + // A date names a whole day, itself included. The service fills its limit from the + // end of the day, so the page before B3 holds B3 to B5 again, and the feed moves on + // to the day before. The same happens once more on 10 November, and 9 November is + // empty, which ends history for a template without `{from}`. + case( + "dates as bounds on minute bars", + |profile| profile.history.as_mut().unwrap().range = RangeFormat::Date, + vec![ + list(&[J3, J4, J5]), + list(&[J3, J4, J5]), + list(&[K0, K1, K2]), + list(&[K0, K1, K2]), + "[]".into(), + ], + FIRST, + vec![ + "GET /bars?symbol=ABC&interval=1m&to=2026-11-11&limit=3", + "GET /bars?symbol=ABC&interval=1m&to=2026-11-10&limit=3", + "GET /bars?symbol=ABC&interval=1m&to=2026-11-10&limit=3", + "GET /bars?symbol=ABC&interval=1m&to=2026-11-09&limit=3", + ], + vec![A0, A1, A2, B3, B4, B5], + ), + case( + "a body is sent with POST as JSON", + |profile| { + let history = profile.history.as_mut().unwrap(); + history.url = history.url.split('?').next().unwrap().to_owned(); + history.body = r#"{"symbol":"{symbol}","interval":"{interval}","to":{to},"limit":{limit}}"#.into(); + }, + vec![list(&[J3, J4, J5]), "[]".into()], + r#"POST /bars application/json {"symbol":"ABC","interval":"1m","to":"#, + vec![r#"POST /bars application/json {"symbol":"ABC","interval":"1m","to":1794407580,"limit":3}"#], + vec![B3, B4, B5], + ), + case( + "numbers as text", + |_| {}, + vec![ + r#"[{"t":"1794407580","o":"100.75","h":"103.0","l":"100.5","c":"102.5","v":"1500"},{"t":"1794407640","o":" 102.5 ","h":"102.75","l":"101.0","c":"101.25","v":"800"},{"t":"1794407700","o":"101.25","h":"101.5","l":"100.0","c":"100.25","v":"700"}]"#.into(), + "[]".into(), + ], + FIRST, + vec![BEFORE_B3], + vec![B3, B4, B5], + ), + // The second page holds one row per rule for a missing or unreadable field, from + // 14:25 (1794407400 - 300 = 1794407100) to 14:32. A scroll-back asks for 600 bars, so + // the page is not cut. The two rows without a time are skipped. The chart refuses + // five bars: no close, an empty open, and a volume that is "NaN", true or negative. + // Three arrive: a bar without a volume, which is 0, an empty slot and B2. + Case { + rejected: 5, + ..case( + "missing and unreadable fields", + |_| {}, + vec![ + list(&[J3, J4, J5]), + list(&[ + r#"{"o":1,"h":1,"l":1,"c":1,"v":1}"#, + r#"{"t":null,"o":1,"h":1,"l":1,"c":1,"v":1}"#, + r#"{"t":1794407100,"o":100.0,"h":101.0,"l":99.5,"c":100.5}"#, + r#"{"t":1794407160,"o":100.0,"h":101.0,"l":99.5,"v":10}"#, + r#"{"t":1794407220,"o":"","h":101.0,"l":99.5,"c":100.5,"v":10}"#, + r#"{"t":1794407280,"o":null,"h":null,"l":null,"c":null,"v":5}"#, + r#"{"t":1794407340,"o":100.0,"h":101.0,"l":99.5,"c":100.5,"v":"NaN"}"#, + r#"{"t":1794407400,"o":100.0,"h":101.0,"l":99.5,"c":100.5,"v":true}"#, + r#"{"t":1794407460,"o":100.0,"h":101.0,"l":99.5,"c":100.5,"v":-1}"#, + J2, + ]), + "[]".into(), + ], + FIRST, + vec![BEFORE_B3, "GET /bars?symbol=ABC&interval=1m&to=1794407100&limit=3"], + vec![(1794407100, Some([100.0, 101.0, 99.5, 100.5, 0.0])), (1794407280, None), B2, B3, B4, B5], + ) + }, + // Daily rows carry a date. On a chart in New York a day opens at 05:00 UTC in + // November, and that is the stamp: 00:00 UTC on 11 November is 1794355200, so the + // dates 5, 6, 9, 10 and 11 November are 1794355200 - n * 86400 + 18000 for n = 6, 5, + // 2, 1 and 0. The page before 10 November ends on the 9th, and the page before + // 5 November on the 4th. + Case { + chart: |chart| { + let mut options = ChartOptions::default(); + options.time_scale.timezone = TimezoneMode::Timezone("America/New_York".parse().unwrap()); + chart.with_timeframe(Timeframe::Day1).with_chart_options(options) + }, + ..case( + "daily bars dated by the day, on a chart in another zone", + |profile| { + let history = profile.history.as_mut().unwrap(); + history.range = RangeFormat::Date; + history.bar.time = TimeSpec::Wall { + date: vec![Segment::Key("d".into())], + format: DateFormat::Dashed, + clock: None, + }; + }, + vec![ + r#"[{"d":"2026-11-10","o":100.75,"h":103.0,"l":100.5,"c":102.5,"v":1500},{"d":"2026-11-11","o":102.5,"h":102.75,"l":101.0,"c":101.25,"v":800}]"#.into(), + r#"[{"d":"2026-11-05","o":100.0,"h":101.0,"l":99.5,"c":100.5,"v":1000},{"d":"2026-11-06","o":100.5,"h":102.0,"l":100.0,"c":101.5,"v":1200},{"d":"2026-11-09","o":101.5,"h":101.75,"l":100.25,"c":100.75,"v":900}]"#.into(), + "[]".into(), + ], + "GET /bars?symbol=ABC&interval=1d&to=", + vec![ + "GET /bars?symbol=ABC&interval=1d&to=2026-11-09&limit=3", + "GET /bars?symbol=ABC&interval=1d&to=2026-11-04&limit=3", + ], + vec![ + (1793854800, Some([100.0, 101.0, 99.5, 100.5, 1000.0])), + (1793941200, Some([100.5, 102.0, 100.0, 101.5, 1200.0])), + (1794200400, Some([101.5, 101.75, 100.25, 100.75, 900.0])), + (1794286800, Some([100.75, 103.0, 100.5, 102.5, 1500.0])), + (1794373200, Some([102.5, 102.75, 101.0, 101.25, 800.0])), + ], + ) + }, + ]; + + let ctx = egui::Context::default(); + for case in cases { + let server = Server::start(pages(case.answers.clone())); + let mut profile = profile(&server.origin); + (case.edit)(&mut profile); + let builder = ChartBuilder::new() + .with_feed(Arc::new(MappedFeed::new(profile, Secrets::new()))) + .with_symbol("ABC") + .with_timeframe(Timeframe::Min1) + .with_initial_bars(3); + let mut chart = (case.chart)(builder).build(); + until(&ctx, &mut chart, case.name, |chart| { + let feed = chart.feed_state(SeriesId::MAIN); + feed.is_some_and(|feed| feed.history_complete || feed.last_error.is_some()) + }); + let feed = chart.feed_state(SeriesId::MAIN).unwrap(); + assert!( + feed.last_error.is_none(), + "{}: {:?}", + case.name, + feed.last_error + ); + let requests: Vec = server.seen().iter().map(asked).collect(); + assert!( + requests[0].starts_with(case.first), + "{}: {}", + case.name, + requests[0] + ); + assert_eq!(requests[1..], case.asked, "{}", case.name); + assert_eq!(shown(&chart), case.bars, "{}", case.name); + assert_eq!(feed.rejected_bars, case.rejected, "{}", case.name); + } + + // A failed request names its endpoint and its reason on the chart, and never the key. + // The key travels in the address here; `None` is an address where nothing listens. + #[rustfmt::skip] + let failures = [ + ( + "unauthorised", + Some((401, r#"{"error":"bad key"}"#)), + "invalid data: {origin}/bars: rejected as unauthorised (HTTP 401): check the key and where it is sent", + ), + ("another refusal", Some((400, "")), "invalid data: {origin}/bars: HTTP 400"), + ("an unknown symbol", Some((404, "")), "symbol not found: ABC"), + ("too many requests", Some((429, "")), "rate limited"), + ("a server error", Some((500, "")), "network error: {origin}/bars: HTTP 500"), + ( + "not JSON", + Some((200, "busy")), + "invalid data: {origin}/bars: unreadable response: not JSON: ", + ), + ( + "no readable time", + Some((200, r#"[{"t":"soon"},{"t":"soon"},{"t":"soon"}]"#)), + "invalid data: {origin}/bars: unreadable response: no row has a readable time (3 rows)", + ), + ("nothing listens", None, "network error: {origin}/bars: no response ("), + ]; + for (name, answer, expected) in failures { + let server = + answer.map(|(status, body)| Server::start(move |_, _| (status, body.to_owned()))); + let origin = match &server { + Some(server) => server.origin.clone(), + None => { + let unused = TcpListener::bind("127.0.0.1:0").unwrap(); + format!("http://{}", unused.local_addr().unwrap()) + } + }; + let mut profile = profile(&origin); + profile.keys = vec!["key".to_owned()]; + profile.history.as_mut().unwrap().url.push_str("&key={key}"); + let secrets = vec![("key".to_owned(), "s3cret-7f3a".to_owned())]; + let mut chart = ChartBuilder::new() + .with_feed(Arc::new(MappedFeed::new(profile, secrets))) + .with_symbol("ABC") + .with_timeframe(Timeframe::Min1) + .with_initial_bars(3) + .build(); + until(&ctx, &mut chart, name, |chart| { + let feed = chart.feed_state(SeriesId::MAIN); + feed.is_some_and(|feed| feed.last_error.is_some()) + }); + let feed = chart.feed_state(SeriesId::MAIN).unwrap(); + let text = feed.last_error.as_ref().unwrap().to_string(); + assert!( + text.starts_with(&expected.replace("{origin}", &origin)), + "{name}: {text}" + ); + assert!(!text.contains("s3cret-7f3a"), "{name}: {text}"); + if let Some(server) = server { + // The key did reach the endpoint, so its absence from the text means something. + assert!( + server.seen()[0].line.ends_with("&key=s3cret-7f3a"), + "{name}" + ); + } + } + } +} diff --git a/vendor/egui-charts/examples/demo/owndata/http.rs b/vendor/egui-charts/examples/demo/owndata/http.rs new file mode 100644 index 0000000..f754e51 --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/http.rs @@ -0,0 +1,147 @@ +//! One HTTP request to a configured endpoint, on both targets. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; + +use super::{Failure, after, endpoint}; + +/// How long a request waits for its response. +const DEADLINE: Duration = Duration::from_secs(10); + +// shortcut: the 8 MiB cap is applied to the downloaded body, so a larger response is still +// transferred. Upgrade to a streamed read when a profile needs pages that large. +const LARGEST_BODY: usize = 8 << 20; + +/// One request with every placeholder filled. It has no `Debug`, so a key in its URL or its +/// headers cannot reach a log line by accident. +pub(crate) struct Request { + /// Where the request goes. + pub(crate) url: String, + /// The headers of the profile, values filled. The client or the browser adds its own. + pub(crate) headers: Vec<(String, String)>, + /// `None` sends `GET`. A body is sent with `POST`. + pub(crate) body: Option, +} + +/// Sends `request` and calls `done` once, with the text of the response body or with the reason +/// there is none. `done` runs on another thread natively and as a browser task on the web, +/// never inside this call, so a caller may hold a lock while it calls. +/// +/// A status outside 200 to 299 is [`Failure::Status`]. A failed connection, no response within +/// ten seconds and a response the browser withholds are [`Failure::Refused`]. A body over 8 MiB +/// and a body that is not UTF-8 are [`Failure::Unreadable`]. +pub(crate) fn fetch(request: Request, done: impl FnOnce(Result) + Send + 'static) { + // Neither the client nor a browser fetch bounds the wait for the response, so the first of + // the response and the deadline answers and the other is discarded. + let done: Arc>> = Arc::new(Mutex::new(Some(Box::new(done)))); + let take = + |done: &Mutex>| done.lock().unwrap_or_else(PoisonError::into_inner).take(); + let answered = Arc::new(AtomicBool::new(false)); + let late = done.clone(); + after(DEADLINE, answered.clone(), move || { + if let Some(done) = take(&late) { + let seconds = DEADLINE.as_secs(); + done(Err(Failure::Refused(format!( + "no response within {seconds} seconds" + )))); + } + }); + send(request, move |result| { + // Releases the timer. + answered.store(true, Ordering::Release); + if let Some(done) = take(&done) { + done(result); + } + }); +} + +/// The caller's callback, which the response and the deadline race for. +type Done = Box) + Send>; + +/// The text of a response with `status`, whose body is `None` when it is not UTF-8. +fn text(status: u16, body: Option) -> Result { + if !(200..=299).contains(&status) { + return Err(Failure::Status(status)); + } + let body = body.ok_or_else(|| Failure::Unreadable("the body is not UTF-8 text".to_owned()))?; + if body.len() > LARGEST_BODY { + return Err(Failure::Unreadable( + "the body is larger than 8 MiB".to_owned(), + )); + } + Ok(body) +} + +/// Why no response arrived. A client's message can repeat the address, whose query may hold a +/// key, so the address is shown as its endpoint. +fn refused(reason: &str, url: &str) -> Failure { + Failure::Refused(reason.replace(url, endpoint(url))) +} + +/// Sends `request` and calls `respond` from the client's own thread. +#[cfg(not(target_arch = "wasm32"))] +fn send(request: Request, respond: impl FnOnce(Result) + Send + 'static) { + let Request { url, headers, body } = request; + // Not `Request::post`, which adds a content type of its own. The headers are replaced as a + // whole, because `Headers::insert` keeps a second header of the same name. + let mut call = ehttp::Request::get(&url); + call.headers = ehttp::Headers { headers }; + if let Some(body) = body { + call.method = ehttp::Method::POST; + call.body = body.into_bytes(); + } + ehttp::fetch(call, move |result| { + respond(match result { + Ok(response) => text(response.status, String::from_utf8(response.bytes).ok()), + Err(reason) => Err(refused(&reason, &url)), + }); + }); +} + +/// Sends `request` and calls `respond` from a task of the page. +#[cfg(target_arch = "wasm32")] +fn send(request: Request, respond: impl FnOnce(Result) + Send + 'static) { + use wasm_bindgen::JsCast as _; + wasm_bindgen_futures::spawn_local(async move { + respond(match exchange(&request).await { + Ok((status, body)) => text(status, body), + Err(error) => { + let thrown = error.dyn_ref::(); + let reason = thrown.map_or_else( + || error.as_string().unwrap_or_else(|| format!("{error:?}")), + |thrown| String::from(thrown.message()), + ); + Err(refused(&reason, &request.url)) + } + }); + }); +} + +/// The status and the body of the page's fetch of `request`, or what the browser threw: a +/// header name it refuses, or a response it could not get or withholds. +#[cfg(target_arch = "wasm32")] +async fn exchange(request: &Request) -> Result<(u16, Option), wasm_bindgen::JsValue> { + use wasm_bindgen::{JsCast as _, JsValue}; + use wasm_bindgen_futures::JsFuture; + let init = web_sys::RequestInit::new(); + init.set_method(if request.body.is_some() { + "POST" + } else { + "GET" + }); + init.set_mode(web_sys::RequestMode::Cors); + let headers = web_sys::Headers::new()?; + for (name, value) in &request.headers { + headers.set(name, value)?; + } + init.set_headers(&headers); + if let Some(body) = &request.body { + init.set_body(&JsValue::from_str(body)); + } + let window = web_sys::window().ok_or_else(|| JsValue::from_str("the page has no window"))?; + let response = JsFuture::from(window.fetch_with_str_and_init(&request.url, &init)).await?; + let response: web_sys::Response = response.dyn_into()?; + let body = JsFuture::from(response.text()?).await?; + Ok((response.status(), body.as_string())) +} diff --git a/vendor/egui-charts/examples/demo/owndata/mod.rs b/vendor/egui-charts/examples/demo/owndata/mod.rs new file mode 100644 index 0000000..27288ae --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/mod.rs @@ -0,0 +1,154 @@ +//! Own data: a visitor's REST history and WebSocket stream, mapped to bars and trades by a saved +//! profile and served to the chart through the library's `Datafeed` trait. +//! +//! `profile` is the saved description. `feed` answers history and owns the bars of every +//! subscription: it reads REST through `http`, lays responses out with `shape`, reads times with +//! `time` and builds bars with `bars`. `stream` keeps one socket per subscription open through +//! `socket` and hands its records to the feed. `dialog`, `tree` and `store` are the user +//! interface and the saved state. `app` is the application's side: it enters and leaves own data +//! and decides what stays tied to the synthetic session. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use egui_charts::data::FeedError; + +pub(crate) mod app; +pub(crate) mod bars; +pub(crate) mod dialog; +pub(crate) mod feed; +pub(crate) mod http; +pub(crate) mod profile; +pub(crate) mod shape; +pub(crate) mod socket; +pub(crate) mod store; +pub(crate) mod stream; +pub(crate) mod time; +pub(crate) mod tree; + +/// The values of the keys a profile names, as `(name, value)`. They are kept apart from the +/// profile so that a saved or exported profile never holds one. +pub(crate) type Secrets = Vec<(String, String)>; + +/// Why a request to a configured endpoint produced no data. The dialog shows it after the +/// endpoint; the feed turns it into the error the chart reports. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Failure { + /// No response arrived: the connection failed or timed out or, in a browser, the response + /// was withheld under the cross-origin rules. A browser does not tell these apart. + Refused(String), + /// The server answered with a status outside 200 to 299. + Status(u16), + /// A response arrived, but it is not JSON or the mapping finds no row or field to read. + Unreadable(String), +} + +impl std::fmt::Display for Failure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Refused(reason) if cfg!(target_arch = "wasm32") => write!( + f, + "no response ({reason}). The server is unreachable, or it does not allow this \ + page's origin or these request headers (cross-origin rules)" + ), + Self::Refused(reason) => write!(f, "no response ({reason})"), + Self::Status(status @ (401 | 403)) => write!( + f, + "rejected as unauthorised (HTTP {status}): check the key and where it is sent" + ), + Self::Status(status) => write!(f, "HTTP {status}"), + Self::Unreadable(reason) => write!(f, "unreadable response: {reason}"), + } + } +} + +impl Failure { + /// The error the chart reports for a history request on `symbol`. Statuses map as in the + /// library's HTTP feed, so the chart retries what can succeed later and stops on the rest. + pub(crate) fn feed_error(&self, symbol: &str) -> FeedError { + match self { + Self::Status(404) => FeedError::SymbolNotFound(symbol.to_owned()), + Self::Status(429) => FeedError::RateLimited { retry_after: None }, + Self::Refused(_) | Self::Status(408 | 500..=599) => { + FeedError::Network(self.to_string()) + } + Self::Status(_) | Self::Unreadable(_) => FeedError::InvalidData(self.to_string()), + } + } +} + +/// `url` without its query and fragment: the name of an endpoint in an error, a log line or a +/// notification. A key passed in the query is therefore never shown. +pub(crate) fn endpoint(url: &str) -> &str { + url.split(['?', '#']).next().unwrap_or(url) +} + +/// `text` with the value of every key of `secrets` written as its `{name}`, as typed and as an +/// address encodes it. An endpoint keeps its path, and a key can travel there. +pub(crate) fn conceal(text: &str, secrets: &Secrets) -> String { + let mut text = text.to_owned(); + for (name, value) in secrets.iter().filter(|(_, value)| !value.is_empty()) { + let named = format!("{{{name}}}"); + text = text.replace(value.as_str(), &named); + let encoded = profile::fill_url("{v}", &[("v", value)]); + if encoded != *value { + text = text.replace(&encoded, &named); + } + } + text +} + +/// Runs `action` after `delay` unless `cancelled` is set first. It serves the deadline of a +/// request, the keep-alive of a stream and the wait before a reconnect. A cancelled wait is +/// released within a second. `action` runs on a thread of its own natively and as a browser task +/// on the web, never inside this call. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn after( + delay: Duration, + cancelled: Arc, + action: impl FnOnce() + Send + 'static, +) { + std::thread::spawn(move || { + let start = std::time::Instant::now(); + while !cancelled.load(Ordering::Acquire) { + let remaining = delay.saturating_sub(start.elapsed()); + if remaining.is_zero() { + return action(); + } + std::thread::sleep(remaining.min(Duration::from_secs(1))); + } + }); +} + +/// Runs `action` after `delay` unless `cancelled` is set first. It serves the deadline of a +/// request, the keep-alive of a stream and the wait before a reconnect. A cancelled wait is +/// released within a second. `action` runs on a thread of its own natively and as a browser task +/// on the web, never inside this call. +#[cfg(target_arch = "wasm32")] +pub(crate) fn after( + delay: Duration, + cancelled: Arc, + action: impl FnOnce() + Send + 'static, +) { + use wasm_bindgen::{JsCast as _, closure::Closure}; + let Some(window) = web_sys::window() else { + return; + }; + // Wake at least once a second so that a cancelled wait releases what it holds. + let wait = delay.min(Duration::from_secs(1)); + let callback = Closure::once_into_js(move || { + if cancelled.load(Ordering::Acquire) { + return; + } + if delay > wait { + after(delay - wait, cancelled, action); + } else { + action(); + } + }); + let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0( + callback.unchecked_ref(), + wait.as_millis() as i32, + ); +} diff --git a/vendor/egui-charts/examples/demo/owndata/profile.rs b/vendor/egui-charts/examples/demo/owndata/profile.rs new file mode 100644 index 0000000..d214c9a --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/profile.rs @@ -0,0 +1,579 @@ +//! The saved description of a visitor's data source: where history and the stream come from +//! and how their JSON maps to bars and trades. The mapped feed, the stream session and the +//! dialog all read it; it is also the exported file. + +use std::fmt::Write as _; + +use egui_charts::model::{Timeframe, TimezoneId}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::Secrets; + +/// Version written into every profile. A file with a higher version is refused on import. +pub(crate) const VERSION: u32 = 1; + +/// The names every template knows. A key cannot take one of them. +pub(crate) const PLACEHOLDERS: [&str; 6] = + ["symbol", "symbol_lower", "interval", "from", "to", "limit"]; + +/// One step of a path into a JSON value. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum Segment { + /// A member of an object. + Key(String), + /// An element of an array. + Index(usize), +} + +/// The way from a starting value to a field, saved as a JSON array such as `["data", "candles"]` +/// or `[0]`. An empty path is the starting value itself; for an optional field it means that +/// the field is not mapped. +pub(crate) type FieldPath = Vec; + +/// One saved connection. It names the keys it needs and never holds their values. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub(crate) struct Profile { + /// [`VERSION`] when written. + pub(crate) version: u32, + /// Name in the profile list, unique among the saved profiles. + pub(crate) name: String, + /// Symbols the symbol search offers, spelled as the service expects them. The chart opens + /// on the first. + pub(crate) symbols: Vec, + /// Zone of every time that names none: a date with a time of day, ISO 8601 text without an + /// offset, and `{from}` and `{to}` printed as dates. UTC by default. + pub(crate) time_zone: TimezoneId, + /// The price step of the symbols: the smallest change of their price, such as 0.01. The + /// footprint and the volume profiles group trades by it. `None` when unknown; the footprint + /// then draws candles. + // shortcut: one step for every symbol of the profile; upgrade to a step per symbol when a + // profile's symbols need different ones. + pub(crate) tick_size: Option, + /// The interval table, in the order the interval picker offers. The chart opens on the + /// first row. + pub(crate) intervals: Vec, + /// Names of the keys the templates use as `{name}`, such as `key`: lower-case letters, + /// digits and `_`, and none of [`PLACEHOLDERS`]. + pub(crate) keys: Vec, + /// REST history. `None` charts the stream alone. + pub(crate) history: Option, + /// WebSocket stream. `None` charts history alone. + pub(crate) stream: Option, +} + +impl Default for Profile { + fn default() -> Self { + Self { + version: VERSION, + name: String::new(), + symbols: Vec::new(), + time_zone: TimezoneId::utc(), + tick_size: None, + intervals: Vec::new(), + keys: Vec::new(), + history: None, + stream: None, + } + } +} + +/// One row of the interval table. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub(crate) struct Interval { + /// A chart interval with a duration. Intervals counted in trades, volume or range are not + /// offered. + pub(crate) chart: Timeframe, + /// What `{interval}` becomes for it, such as `1m`, `60` or `60000`. Sent as typed and never + /// parsed. + pub(crate) service: String, +} + +/// REST history. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub(crate) struct History { + /// URL template. `{symbol}`, `{symbol_lower}`, `{interval}`, `{from}`, `{to}`, `{limit}` and + /// the key names are replaced, each value percent-encoded. + pub(crate) url: String, + /// Request headers as a name and a value template. Values are sent as typed. + pub(crate) headers: Vec<(String, String)>, + /// Body template. Empty sends `GET`. Anything else is sent with `POST`, as + /// `application/json` unless a header names another content type. + pub(crate) body: String, + /// How `{from}` and `{to}` are printed. + pub(crate) range: RangeFormat, + /// The most bars asked for in one request, the cap of `{limit}`. 1000 by default. + pub(crate) page_size: usize, + /// Where the rows of a response are and how they are laid out. + pub(crate) rows: Rows, + /// The fields of one row. + pub(crate) bar: BarFields, +} + +impl Default for History { + fn default() -> Self { + Self { + url: String::new(), + headers: Vec::new(), + body: String::new(), + range: RangeFormat::default(), + page_size: 1000, + rows: Rows::default(), + bar: BarFields::default(), + } + } +} + +/// How an instant is printed into `{from}` and `{to}`. `{from}` is the first instant asked for +/// and `{to}` the first one not asked for, except for the two date forms. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum RangeFormat { + /// Unix time in whole seconds. The default. + #[default] + Seconds, + /// Unix time in milliseconds. + Milliseconds, + /// Unix time in microseconds. + Microseconds, + /// Unix time in nanoseconds. + Nanoseconds, + /// `2026-11-11T14:30:00Z`. + Iso8601, + /// `2026-11-11`. `{to}` is the last day asked for, itself included. + Date, + /// `20261111`. `{to}` is the last day asked for, itself included. + CompactDate, +} + +/// Where the rows of a history response are. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub(crate) struct Rows { + /// From the root of the response to the rows. Empty when the root holds them. A key may be + /// `{symbol}` or `{symbol_lower}`; see [`Rows::for_symbol`]. + pub(crate) path: FieldPath, + /// How the rows are laid out there. + pub(crate) layout: Layout, +} + +/// The layout of the rows of a history response. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Layout { + /// A list of objects, one per bar. Fields are keys such as `["t"]`. The default. + #[default] + Objects, + /// A list of arrays, one per bar. Without `header`, fields are column numbers such as `[0]`. + /// With it, the array of column names found at that path from the root of the response + /// names the columns, and fields are those names. + Arrays { header: Option }, + /// An object of arrays of equal length, one per field. Bar `i` is element `i` of each, and + /// fields are the keys of those arrays. + Columns, +} + +/// The fields of a bar, each a path inside one history row or one stream record. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub(crate) struct BarFields { + /// The bar's time: its open or any instant inside it. + pub(crate) time: TimeSpec, + pub(crate) open: FieldPath, + pub(crate) high: FieldPath, + pub(crate) low: FieldPath, + pub(crate) close: FieldPath, + /// Empty when the service sends no volume. Bars then carry zero. + pub(crate) volume: FieldPath, +} + +/// How a row or record tells its time. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum TimeSpec { + /// One field that holds an instant. The default, with an empty field and `Seconds`. + Instant { field: FieldPath, unit: TimeUnit }, + /// A calendar date and, optionally, a time of day on the wall clock of the profile's zone. + /// Without a time of day the row is a bar dated on that day. + Wall { + date: FieldPath, + format: DateFormat, + clock: Option, + }, +} + +impl Default for TimeSpec { + fn default() -> Self { + Self::Instant { + field: FieldPath::new(), + unit: TimeUnit::Seconds, + } + } +} + +/// The form of an instant field. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum TimeUnit { + /// Unix time in seconds; a fraction is allowed. The default. + #[default] + Seconds, + /// Unix time in milliseconds; a fraction is allowed. + Milliseconds, + /// Unix time in microseconds. + Microseconds, + /// Unix time in nanoseconds. + Nanoseconds, + /// ISO 8601 text. With an offset or `Z` it is an instant; without one it is a wall-clock + /// time in the profile's zone; a bare date is a bar dated on that day. + Iso8601, +} + +/// The form of a date field. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum DateFormat { + /// `20261111`, as a number or as text. The default. + #[default] + Compact, + /// `2026-11-11`. + Dashed, +} + +/// A time-of-day field. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub(crate) struct Clock { + pub(crate) field: FieldPath, + pub(crate) unit: ClockUnit, +} + +/// The form of a time-of-day field. All three are readings of the wall clock: 09:30:00 is the +/// same value on every day of the year, also on a day with a daylight saving change. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum ClockUnit { + /// Milliseconds since midnight: 09:30:00 is 34,200,000. The default. + #[default] + Milliseconds, + /// Seconds since midnight: 09:30:00 is 34,200. + Seconds, + /// `HH:MM`, `HH:MM:SS` or `HH:MM:SS.fff`. + Text, +} + +/// The WebSocket stream. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub(crate) struct Stream { + /// `ws://` or `wss://` URL template. `{symbol}`, `{symbol_lower}`, `{interval}` and the key + /// names are replaced, each value percent-encoded. + pub(crate) url: String, + /// Subprotocols offered in the handshake, as templates. A browser cannot send headers when + /// it opens a socket, so a key travels in the URL, in a subprotocol or in a connect message. + pub(crate) protocols: Vec, + /// Messages sent in this order every time the socket opens: the login first, then the + /// subscribe message. Templates with `{symbol}`, `{symbol_lower}`, `{interval}` and the key + /// names, sent as typed. + pub(crate) connect: Vec, + /// Keep-alive message, sent as typed. Empty sends none. + pub(crate) keep_alive: String, + /// Seconds between keep-alive messages, at least 1. 30 by default. + pub(crate) keep_alive_every: u32, + /// From the root of a message to its records. Empty takes the root. An array there is one + /// record per element; an object is one record. + pub(crate) records: FieldPath, + /// The field whose value picks the route, looked up in the record and, when the record has + /// none, at the root of the message. Empty sends every record to the first route. + pub(crate) route_by: FieldPath, + /// The routes, tried in order. + pub(crate) routes: Vec, +} + +impl Default for Stream { + fn default() -> Self { + Self { + url: String::new(), + protocols: Vec::new(), + connect: Vec::new(), + keep_alive: String::new(), + keep_alive_every: 30, + records: FieldPath::new(), + route_by: FieldPath::new(), + routes: Vec::new(), + } + } +} + +/// What to do with the records whose routing field has one value. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub(crate) struct Route { + /// The value, compared as text: a string as it is, a number or a boolean as JSON prints it. + pub(crate) value: String, + pub(crate) kind: RouteKind, +} + +/// What a route's records are. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum RouteKind { + /// Status, keep-alive and other messages that carry no data. The default. + #[default] + Ignore, + /// Bars of the chart's interval, merged into the bar with the same open time. + Bars(BarFields), + /// Trades, folded into bars of the chart's interval and fed to the chart as trades. + Trades(TradeFields), +} + +/// The fields of a trade, each a path inside one stream record. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub(crate) struct TradeFields { + pub(crate) time: TimeSpec, + pub(crate) price: FieldPath, + pub(crate) size: FieldPath, + /// Empty when trades carry no condition. The field holds one value or a list of values. + pub(crate) condition: FieldPath, + /// The rule of each condition value, compared as text. A value that is not listed counts + /// price and volume. + pub(crate) conditions: Vec<(String, ConditionRule)>, + /// Empty when trades carry no side. The field holds the side of the trade's aggressor. + pub(crate) side: FieldPath, + /// The value of `side` that marks a buy, compared as text. Empty marks none. + pub(crate) buy: String, + /// The value of `side` that marks a sell, compared as text. Empty marks none. + pub(crate) sell: String, +} + +/// What a trade with a given condition does to the bar it falls in. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum ConditionRule { + /// The price moves high, low and close, and the size is added to the volume. The default. + #[default] + PriceAndVolume, + /// The size is added to the volume; open, high, low and close stay as they are. + VolumeOnly, + /// The bar stays as it is. + Ignore, +} + +impl Profile { + /// The first reason the profile cannot connect, in words for the dialog, or `None` when it + /// can: an empty name, no symbol, no interval, an interval listed twice or one without a + /// duration, neither history nor a stream, a URL that does not start with `http://`, + /// `https://`, `ws://` or `wss://` as its kind needs, a page size or keep-alive period of + /// zero, a price step that is not a number above zero, or a key name that is empty, has + /// other characters than lower-case letters, digits and `_`, or is one of [`PLACEHOLDERS`]. + pub(crate) fn problem(&self) -> Option { + if self.name.trim().is_empty() { + return Some("Give the profile a name.".to_owned()); + } + if self.symbols.is_empty() { + return Some("List at least one symbol.".to_owned()); + } + if self.intervals.is_empty() { + return Some("Add at least one interval.".to_owned()); + } + for (index, interval) in self.intervals.iter().enumerate() { + let chart = interval.chart; + let above = &self.intervals[..index]; + if above.iter().any(|row| row.chart == chart) { + return Some(format!("The interval {chart} is listed twice.")); + } + if chart.is_trade_based() { + return Some(format!("The interval {chart} has no duration.")); + } + } + if self.history.is_none() && self.stream.is_none() { + return Some("Use REST history, a WebSocket stream or both.".to_owned()); + } + if let Some(history) = &self.history + && !(history.url.starts_with("http://") || history.url.starts_with("https://")) + { + return Some("The history URL must start with http:// or https://.".to_owned()); + } + if let Some(stream) = &self.stream + && !(stream.url.starts_with("ws://") || stream.url.starts_with("wss://")) + { + return Some("The stream URL must start with ws:// or wss://.".to_owned()); + } + let page_size = self.history.as_ref().map(|history| history.page_size); + if page_size == Some(0) { + return Some("The page size must be at least 1.".to_owned()); + } + let period = self.stream.as_ref().map(|stream| stream.keep_alive_every); + if period == Some(0) { + return Some("The keep-alive period must be at least 1 second.".to_owned()); + } + if self + .tick_size + .is_some_and(|step| !(step.is_finite() && step > 0.0)) + { + return Some("The price step must be a number above zero.".to_owned()); + } + for key in &self.keys { + if key.is_empty() { + return Some("Every key needs a name.".to_owned()); + } + let plain = |byte: u8| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_'); + if !key.bytes().all(plain) { + return Some(format!( + "The key name \"{key}\" may hold only lower-case letters, digits and _." + )); + } + if PLACEHOLDERS.contains(&key.as_str()) { + return Some(format!( + "The key name \"{key}\" is the name of a placeholder." + )); + } + } + None + } + + /// What `{interval}` becomes for `timeframe`, or `None` when the table has no row for it. + pub(crate) fn service_interval(&self, timeframe: Timeframe) -> Option<&str> { + let row = self.intervals.iter().find(|row| row.chart == timeframe)?; + Some(&row.service) + } + + /// Whether the stream has a trades route, so that the chart receives trades. + pub(crate) fn has_trades(&self) -> bool { + let mut routes = self.stream.iter().flat_map(|stream| &stream.routes); + routes.any(|route| matches!(route.kind, RouteKind::Trades(_))) + } +} + +/// The values of a stream's templates for `symbol` at `interval`: `{symbol}` as listed, +/// `{symbol_lower}` in lower case, `{interval}` as the interval table has it, and the key values +/// of `secrets`. The feed's subscriptions and the dialog's Test fill with them, so a Test opens +/// the socket the chart opens. +pub(crate) fn stream_values( + symbol: &str, + interval: &str, + secrets: &Secrets, +) -> Vec<(String, String)> { + let mut values = vec![ + ("symbol".to_owned(), symbol.to_owned()), + ("symbol_lower".to_owned(), symbol.to_lowercase()), + ("interval".to_owned(), interval.to_owned()), + ]; + values.extend(secrets.iter().cloned()); + values +} + +impl Rows { + /// Where the rows of a response for `symbol` are: `{symbol}` and `{symbol_lower}` in a key + /// of the path, or of the header's path, become the symbol as listed and in lower case, for + /// a service that files the rows under the symbol, such as `["result", "{symbol}"]`. Other + /// keys stay as they are. + pub(crate) fn for_symbol(&self, symbol: &str) -> Rows { + let lower = symbol.to_lowercase(); + let values = [("symbol", symbol), ("symbol_lower", lower.as_str())]; + let filled = |path: &FieldPath| -> FieldPath { + let step = |segment: &Segment| match segment { + Segment::Key(key) => Segment::Key(fill(key, &values)), + index => index.clone(), + }; + path.iter().map(step).collect() + }; + let layout = match &self.layout { + Layout::Arrays { + header: Some(header), + } => Layout::Arrays { + header: Some(filled(header)), + }, + layout => layout.clone(), + }; + Rows { + path: filled(&self.path), + layout, + } + } +} + +/// `template` with every `{name}` of `values` replaced by its value, in one pass. Braces around +/// any other text stay as typed, so a JSON body or message needs no escaping, and a value is +/// never expanded again. +pub(crate) fn fill(template: &str, values: &[(&str, &str)]) -> String { + expand(template, values, |out, value| out.push_str(value)) +} + +/// As [`fill`], for a URL: every byte of a value is percent-encoded except ASCII letters, +/// digits, `-`, `.`, `_` and `~`. +pub(crate) fn fill_url(template: &str, values: &[(&str, &str)]) -> String { + expand(template, values, |out, value| { + for byte in value.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + out.push(char::from(byte)); + } else { + // Writing into a `String` cannot fail. + let _ = write!(out, "%{byte:02X}"); + } + } + }) +} + +/// `template` with every `{name}` of `values` replaced by what `write` appends for its value. +fn expand(template: &str, values: &[(&str, &str)], write: impl Fn(&mut String, &str)) -> String { + let mut out = String::with_capacity(template.len()); + let mut rest = template; + while let Some(open) = rest.find('{') { + out.push_str(&rest[..open]); + let after = &rest[open + 1..]; + let named = values.iter().find_map(|&(name, value)| { + let tail = after.strip_prefix(name)?.strip_prefix('}')?; + // `{}` is an empty JSON object, never a name. + (!name.is_empty()).then_some((value, tail)) + }); + match named { + Some((value, tail)) => { + write(&mut out, value); + rest = tail; + } + None => { + out.push('{'); + rest = after; + } + } + } + out.push_str(rest); + out +} + +/// The value at `path` below `value`: a key steps into an object and an index into an array. +/// `None` when a step does not exist. +pub(crate) fn at<'a>(value: &'a Value, path: &[Segment]) -> Option<&'a Value> { + path.iter().try_fold(value, |value, segment| match segment { + Segment::Key(key) => value.get(key), + Segment::Index(index) => value.get(index), + }) +} + +/// A finite number: a JSON number, or text that holds one, as services that send numbers as +/// strings do. Spaces around the text are allowed. `NaN`, infinities, empty text and every +/// other JSON type give `None`. +pub(crate) fn number(value: &Value) -> Option { + let number = match value { + Value::Number(number) => number.as_f64()?, + Value::String(text) => text.trim().parse().ok()?, + _ => return None, + }; + number.is_finite().then_some(number) +} + +/// The text a routing field or a trade condition is compared by: a string as it is, a number +/// or a boolean as JSON prints it. `None` for null, arrays and objects. +pub(crate) fn text(value: &Value) -> Option { + match value { + Value::String(text) => Some(text.clone()), + Value::Number(_) | Value::Bool(_) => Some(value.to_string()), + _ => None, + } +} diff --git a/vendor/egui-charts/examples/demo/owndata/ready/binance-spot.json b/vendor/egui-charts/examples/demo/owndata/ready/binance-spot.json new file mode 100644 index 0000000..d9ce3ce --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/ready/binance-spot.json @@ -0,0 +1,200 @@ +{ + "version": 1, + "name": "Binance spot (public)", + "symbols": [ + "BTCUSDT", + "ETHUSDT", + "SOLUSDT", + "BNBUSDT" + ], + "time_zone": "UTC", + "tick_size": 0.01, + "intervals": [ + { + "chart": "Min1", + "service": "1m" + }, + { + "chart": { + "Custom": 180 + }, + "service": "3m" + }, + { + "chart": "Min5", + "service": "5m" + }, + { + "chart": "Min15", + "service": "15m" + }, + { + "chart": "Min30", + "service": "30m" + }, + { + "chart": "Hour1", + "service": "1h" + }, + { + "chart": { + "Custom": 7200 + }, + "service": "2h" + }, + { + "chart": "Hour4", + "service": "4h" + }, + { + "chart": { + "Custom": 21600 + }, + "service": "6h" + }, + { + "chart": { + "Custom": 28800 + }, + "service": "8h" + }, + { + "chart": { + "Custom": 43200 + }, + "service": "12h" + }, + { + "chart": "Day1", + "service": "1d" + }, + { + "chart": "Week1", + "service": "1w" + }, + { + "chart": "Month1", + "service": "1M" + } + ], + "keys": [], + "history": { + "url": "https://data-api.binance.vision/api/v3/klines?symbol={symbol}&interval={interval}&endTime={to}&limit={limit}", + "headers": [], + "body": "", + "range": "milliseconds", + "page_size": 1000, + "rows": { + "path": [], + "layout": { + "arrays": { + "header": null + } + } + }, + "bar": { + "time": { + "instant": { + "field": [ + 0 + ], + "unit": "milliseconds" + } + }, + "open": [ + 1 + ], + "high": [ + 2 + ], + "low": [ + 3 + ], + "close": [ + 4 + ], + "volume": [ + 5 + ] + } + }, + "stream": { + "url": "wss://data-stream.binance.vision/stream?streams={symbol_lower}@kline_{interval}/{symbol_lower}@aggTrade", + "protocols": [], + "connect": [], + "keep_alive": "", + "keep_alive_every": 30, + "records": [ + "data" + ], + "route_by": [ + "e" + ], + "routes": [ + { + "value": "kline", + "kind": { + "bars": { + "time": { + "instant": { + "field": [ + "k", + "t" + ], + "unit": "milliseconds" + } + }, + "open": [ + "k", + "o" + ], + "high": [ + "k", + "h" + ], + "low": [ + "k", + "l" + ], + "close": [ + "k", + "c" + ], + "volume": [ + "k", + "v" + ] + } + } + }, + { + "value": "aggTrade", + "kind": { + "trades": { + "time": { + "instant": { + "field": [ + "T" + ], + "unit": "milliseconds" + } + }, + "price": [ + "p" + ], + "size": [ + "q" + ], + "condition": [], + "conditions": [], + "side": [ + "m" + ], + "buy": "false", + "sell": "true" + } + } + } + ] + } +} diff --git a/vendor/egui-charts/examples/demo/owndata/shape.rs b/vendor/egui-charts/examples/demo/owndata/shape.rs new file mode 100644 index 0000000..ce3e184 --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/shape.rs @@ -0,0 +1,253 @@ +//! Where the rows of a history response are, and which layout a response most likely has. + +use serde_json::Value; + +use super::profile::{BarFields, FieldPath, Layout, Rows, Segment, TimeSpec, at, text}; +use super::time; + +/// The rows of `response`, one JSON value per bar, in the order the response lists them. +/// Whatever the layout, a row is a value the paths of [`BarFields`] step into: +/// +/// - `Objects`, and `Arrays` without a header: the elements of the list at `rows.path`, as +/// they are. +/// - `Arrays` with a header: each element paired with the header names into an object. A short +/// row leaves its last fields absent; values beyond the header are dropped. +/// - `Columns`: row `i` is an object that holds element `i` of every list in the object at +/// `rows.path`. Members that are not lists are skipped. The longest list gives the number of +/// rows, and a shorter one leaves its field absent in the rows it does not reach. +/// +/// A path that leads nowhere or to `null` is a page without rows, because services omit the +/// list when a window holds no data. A value of another type than the layout needs is an error +/// that says what was found, such as `expected a list at data.candles, found an object`. +pub(crate) fn rows(response: &Value, rows: &Rows) -> Result, String> { + let Some(found) = at(response, &rows.path).filter(|found| !found.is_null()) else { + return Ok(Vec::new()); + }; + let list = |value: &Value, path: &[Segment]| match value { + Value::Array(list) => Ok(list.clone()), + other => Err(expected("a list", path, Some(other))), + }; + match &rows.layout { + Layout::Objects | Layout::Arrays { header: None } => list(found, &rows.path), + Layout::Arrays { + header: Some(header), + } => { + let names = match at(response, header) { + Some(names) => list(names, header)?, + None => return Err(expected("a list", header, None)), + }; + let named = |row: Value| { + let values = match row { + Value::Array(values) => values, + _ => Vec::new(), + }; + let fields = names.iter().zip(values); + Value::Object( + fields + .filter_map(|(name, value)| Some((text(name)?, value))) + .collect(), + ) + }; + Ok(list(found, &rows.path)?.into_iter().map(named).collect()) + } + Layout::Columns => { + let Value::Object(members) = found else { + return Err(expected("an object", &rows.path, Some(found))); + }; + let columns = || { + members + .iter() + .filter_map(|(name, column)| Some((name, column.as_array()?))) + }; + let count = columns().map(|(_, column)| column.len()).max().unwrap_or(0); + let row = |index: usize| { + let fields = columns() + .filter_map(|(name, column)| Some((name.clone(), column.get(index)?.clone()))); + Value::Object(fields.collect()) + }; + Ok((0..count).map(row).collect()) + } + } +} + +/// The error for a value of the wrong type at `path`: what the layout needs and what is there. +fn expected(needed: &str, path: &[Segment], found: Option<&Value>) -> String { + let steps: Vec = path + .iter() + .map(|step| match step { + Segment::Key(key) => key.clone(), + Segment::Index(index) => index.to_string(), + }) + .collect(); + let place = if steps.is_empty() { + "the root".to_owned() + } else { + steps.join(".") + }; + let found = match found { + None | Some(Value::Null) => "nothing", + Some(Value::Bool(_)) => "a boolean", + Some(Value::Number(_)) => "a number", + Some(Value::String(_)) => "text", + Some(Value::Array(_)) => "a list", + Some(Value::Object(_)) => "an object", + }; + format!("expected {needed} at {place}, found {found}") +} + +/// One way to read a response, which the dialog offers for confirmation. +pub(crate) struct Proposal { + /// Where the rows are and how they are laid out. + pub(crate) rows: Rows, + /// The fields recognised by name. A field that was not recognised has an empty path, for + /// the user to click. + pub(crate) bar: BarFields, + /// How many rows the response holds when it is read this way. + pub(crate) count: usize, +} + +/// The ways `response` can be read, the most likely first. Empty when no list of rows is found +/// within four levels of the root. +pub(crate) fn propose(response: &Value) -> Vec { + let mut proposals = Vec::new(); + walk(response, response, &mut Vec::new(), &mut proposals); + let recognised = |proposal: &Proposal| { + let bar = &proposal.bar; + let time = match &bar.time { + TimeSpec::Instant { field, .. } => field, + TimeSpec::Wall { date, .. } => date, + }; + let fields = [ + time, + &bar.open, + &bar.high, + &bar.low, + &bar.close, + &bar.volume, + ]; + fields.into_iter().filter(|field| !field.is_empty()).count() + }; + // The most fields recognised first, then the shorter path, then the most rows. + proposals.sort_by_key(|proposal| { + let found = std::cmp::Reverse(recognised(proposal)); + ( + found, + proposal.rows.path.len(), + std::cmp::Reverse(proposal.count), + ) + }); + proposals +} + +/// Adds the proposals for `value`, which lies at `path` below `root`, and for the members below +/// it, to a depth of four. +fn walk(root: &Value, value: &Value, path: &mut FieldPath, proposals: &mut Vec) { + let mut propose = |layout: Layout, bar: BarFields| { + let rows = Rows { + path: path.clone(), + layout, + }; + let count = self::rows(root, &rows).map_or(0, |rows| rows.len()); + proposals.push(Proposal { rows, bar, count }); + }; + let scalar = |value: &Value| !value.is_array() && !value.is_object(); + match value { + Value::Array(list) => match list.first() { + Some(Value::Object(first)) => { + let named = first.iter().map(|(name, value)| (name.as_str(), value)); + propose(Layout::Objects, fields(named, key)); + } + Some(Value::Array(first)) if !first.is_empty() && first.iter().all(scalar) => { + let header = header(root, path, first.len()); + let bar = match &header { + Some((_, names)) => fields(names.iter().map(String::as_str).zip(first), key), + // Without names, the usual order of five or six columns. + None if first.len() >= 5 => { + let usual = ["time", "open", "high", "low", "close", "volume"]; + let column = |_: &str, at: usize| vec![Segment::Index(at)]; + fields(usual.into_iter().zip(first), column) + } + None => BarFields::default(), + }; + let header = header.map(|(path, _)| path); + propose(Layout::Arrays { header }, bar); + } + _ => {} + }, + Value::Object(members) => { + let lengths: Vec = members + .values() + .filter_map(|member| Some(member.as_array()?.len())) + .filter(|length| *length > 0) + .collect(); + let equal = |length: &usize| lengths.iter().filter(|other| *other == length).count(); + if lengths.iter().any(|length| equal(length) >= 2) { + let firsts = members.iter().filter_map(|(name, member)| { + Some((name.as_str(), member.as_array()?.first()?)) + }); + propose(Layout::Columns, fields(firsts, key)); + } + if path.len() < 4 { + for (name, member) in members { + path.push(Segment::Key(name.clone())); + walk(root, member, path, proposals); + path.pop(); + } + } + } + _ => {} + } +} + +/// The path of the field called `name`, which is column `at` of its row. +fn key(name: &str, _at: usize) -> FieldPath { + vec![Segment::Key(name.to_owned())] +} + +/// The names of the columns of rows at `path` that are `width` wide: the first list of that +/// many strings among the members of the root and of the object that holds the rows, with its +/// path from the root. +fn header(root: &Value, path: &[Segment], width: usize) -> Option<(FieldPath, Vec)> { + let top: &[Segment] = &[]; + let holder = &path[..path.len().saturating_sub(1)]; + [top, holder].into_iter().find_map(|below| { + let members = at(root, below)?.as_object()?; + members.iter().find_map(|(name, member)| { + let names = member.as_array()?.iter(); + let names: Vec = names + .map(|name| Some(name.as_str()?.to_owned())) + .collect::>()?; + let step = [Segment::Key(name.clone())]; + (names.len() == width).then(|| ([below, step.as_slice()].concat(), names)) + }) + }) +} + +/// The fields of a bar among the named values of the first row, recognised by name whatever +/// the letter case. `path` gives the path of a field from its name and its place in the row. +/// The form of the time comes from its value. +fn fields<'a>( + row: impl Iterator, + path: impl Fn(&str, usize) -> FieldPath, +) -> BarFields { + let row: Vec<(&str, &Value)> = row.collect(); + // The first name of each list that the row has. The names are generic vocabulary. + let find = |names: &[&str]| { + let named = |name: &&str| { + row.iter() + .position(|(held, _)| held.eq_ignore_ascii_case(name)) + }; + let at = names.iter().find_map(named)?; + Some((path(row[at].0, at), row[at].1)) + }; + let field = |names: &[&str]| find(names).map_or_else(FieldPath::new, |(path, _)| path); + let when = find(&["t", "ts", "time", "timestamp", "datetime", "date", "start"]); + BarFields { + time: when.map_or_else(TimeSpec::default, |(path, value)| time::guess(path, value)), + open: field(&["o", "open"]), + high: field(&["h", "high"]), + low: field(&["l", "low"]), + close: field(&["c", "close"]), + volume: field(&["v", "vol", "volume"]), + } +} diff --git a/vendor/egui-charts/examples/demo/owndata/socket.rs b/vendor/egui-charts/examples/demo/owndata/socket.rs new file mode 100644 index 0000000..ae13923 --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/socket.rs @@ -0,0 +1,491 @@ +//! One WebSocket connection: the page's own `WebSocket` in the browser, a blocking client on a +//! thread of its own natively. Text in, text out; nothing here knows about profiles. + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) use native::Socket; +#[cfg(target_arch = "wasm32")] +pub(crate) use web::Socket; + +/// What a socket reports, in order. `Closed` is the last event of a socket. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum SocketEvent { + /// The connection is open and messages can be sent. + Open, + /// A text message, or a binary message that holds UTF-8 text. + Text(String), + /// A binary message of this many bytes that is not UTF-8 text. + Binary(usize), + /// The connection ended or could not be opened. `reason` is written for the user: the + /// close code and text the server sent, or what failed (the address, TLS, the status of + /// the handshake). A browser gives no cause for a failed connection, only code 1006. + Closed { reason: String }, +} + +/// The reason of a close that the server asked for: its code, and its text when it sent one. +fn closed_by_server(code: u16, text: &str) -> String { + if text.is_empty() { + format!("closed by the server (code {code})") + } else { + format!("closed by the server (code {code}): {text}") + } +} + +#[cfg(not(target_arch = "wasm32"))] +mod native { + use std::fmt::Display; + use std::io::{self, Read, Write}; + use std::net::{TcpStream, ToSocketAddrs}; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::mpsc::{self, Receiver, Sender}; + use std::time::Duration; + + use tungstenite::client::IntoClientRequest as _; + use tungstenite::http::Uri; + use tungstenite::{ClientRequestBuilder, Error, HandshakeError, Message, WebSocket}; + + use super::super::{Failure, endpoint}; + use super::{SocketEvent, closed_by_server}; + + /// The longest wait for one address to connect and for each read and write of the handshake. + const PATIENCE: Duration = Duration::from_secs(10); + /// How long a read waits for data before the thread looks at its queue and its flag again. + const TICK: Duration = Duration::from_millis(250); + + /// A plain or a TLS stream behind one type, and the TCP stream under it. + trait Wire: Read + Write { + fn tcp(&self) -> &TcpStream; + } + + impl Wire for TcpStream { + fn tcp(&self) -> &TcpStream { + self + } + } + + impl Wire for rustls::StreamOwned { + fn tcp(&self) -> &TcpStream { + self.get_ref() + } + } + + /// A connection that is open or being opened. Dropping it closes the connection without + /// waiting; no event is started afterwards. + pub(crate) struct Socket { + /// Set by the drop. The thread reads it before every event and at every tick. + closed: Arc, + /// Set by the thread while the connection is open. + is_open: Arc, + /// The texts the thread sends at its next tick. + outgoing: Sender, + } + + impl Socket { + /// Starts connecting to `url` (`ws://` or `wss://`), offering `protocols` as subprotocols. + /// + /// Every outcome arrives through `on_event`, also a URL that cannot be opened at all. + /// `on_event` is never called from inside this function, from [`Socket::send`] or from the + /// drop. Natively it runs on the socket's own thread; in the browser as a task of the page. + pub(crate) fn open( + url: &str, + protocols: &[String], + on_event: impl FnMut(SocketEvent) + Send + 'static, + ) -> Self { + let closed = Arc::new(AtomicBool::new(false)); + let is_open = Arc::new(AtomicBool::new(false)); + let (outgoing, queue) = mpsc::channel(); + let (url, protocols) = (url.to_owned(), protocols.to_vec()); + let flags = (closed.clone(), is_open.clone()); + std::thread::spawn(move || run(&url, &protocols, &flags.0, &flags.1, &queue, on_event)); + Self { + closed, + is_open, + outgoing, + } + } + + /// Sends `text` as one text message. Only an open socket sends: before `Open` and after + /// `Closed` the text is dropped. + pub(crate) fn send(&self, text: &str) { + if self.is_open.load(Ordering::Acquire) { + // The thread is gone when this fails: the text is lost with the connection. + let _ = self.outgoing.send(text.to_owned()); + } + } + } + + impl Drop for Socket { + fn drop(&mut self) { + self.closed.store(true, Ordering::Release); + } + } + + /// The life of one connection, on its own thread. + fn run( + url: &str, + protocols: &[String], + closed: &AtomicBool, + is_open: &AtomicBool, + queue: &Receiver, + mut on_event: impl FnMut(SocketEvent), + ) { + let ended = match connect(url, protocols, closed) { + Ok(mut socket) => { + is_open.store(true, Ordering::Release); + let ended = serve(&mut socket, closed, queue, &mut on_event); + is_open.store(false, Ordering::Release); + if ended.is_none() { + // The socket was dropped: take leave of the server and report nothing. + let _ = socket.close(None); + let _ = socket.flush(); + } + ended + } + Err(reason) => Some(reason), + }; + // The flag is read before every event, so none starts after the drop. + if let Some(reason) = ended + && !closed.load(Ordering::Acquire) + { + // A message of the client library can repeat the address, and a key with it. + let reason = reason.replace(url, endpoint(url)); + on_event(SocketEvent::Closed { reason }); + } + } + + /// Opens the connection: the request, the TCP connection, TLS for `wss`, the handshake and + /// the idle tick. An error is the reason the socket reports. + fn connect( + url: &str, + protocols: &[String], + closed: &AtomicBool, + ) -> Result>, String> { + // Printed, an address without a path gets the `/` that a browser sends. The library + // sends the target as it stands in the address: `ws://host?key=..` would ask for `?key=..`. + let uri = url.parse::().map_err(unusable)?.to_string(); + let uri = uri.parse::().map_err(unusable)?; + let tls = match uri.scheme_str() { + Some("ws") => false, + Some("wss") => true, + _ => return Err(unusable("it starts with neither ws:// nor wss://")), + }; + let request = protocols + .iter() + .fold( + ClientRequestBuilder::new(uri.clone()), + |request, protocol| request.with_sub_protocol(protocol), + ) + .into_client_request() + .map_err(unusable)?; + // An IPv6 address stands in brackets in a URL and without them everywhere else. + let host = uri.host().unwrap_or_default(); + let host = host.trim_start_matches('[').trim_end_matches(']'); + let port = uri.port_u16().unwrap_or(if tls { 443 } else { 80 }); + + let tcp = dial(host, port, closed).map_err(cannot)?; + if closed.load(Ordering::Acquire) { + // Dropped while connecting: nothing more is sent, and this reason is never reported. + return Err(String::new()); + } + let stream: Box = if tls { + let roots = rustls::RootCertStore { + roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(), + }; + // The provider is named here so that the demo does not depend on a process-wide + // default. + let config = rustls::ClientConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .map_err(failed)? + .with_root_certificates(roots) + .with_no_client_auth(); + let name = rustls::pki_types::ServerName::try_from(host.to_owned()).map_err(failed)?; + let connection = + rustls::ClientConnection::new(Arc::new(config), name).map_err(failed)?; + Box::new(rustls::StreamOwned::new(connection, tcp)) + } else { + Box::new(tcp) + }; + let unanswered = || "no answer to the handshake within 10 seconds".to_owned(); + let (socket, _) = tungstenite::client(request, stream).map_err(|error| match error { + HandshakeError::Failure(Error::Http(response)) => match response.status().as_u16() { + // The words of a refused request, so that a wrong key reads the same everywhere. + status @ (401 | 403) => Failure::Status(status).to_string(), + status => format!("handshake refused (HTTP {status})"), + }, + // A read that timed out interrupts the handshake on Unix and fails it on Windows. + HandshakeError::Interrupted(_) => unanswered(), + HandshakeError::Failure(Error::Io(error)) if idle(&error) => unanswered(), + HandshakeError::Failure(error) => failed(error), + })?; + // From here a read that times out is the idle tick of the loop. That is safe: the frame + // reader keeps a partly read frame for the next call, and so does the TLS layer. + // It is set on the stream that reads, not on a clone of it: set through a clone, the + // reads on Windows went on waiting for `PATIENCE`. + socket + .get_ref() + .tcp() + .set_read_timeout(Some(TICK)) + .map_err(lost)?; + Ok(socket) + } + + /// The first address of `host` that answers, with the timeouts that bound the handshake. + fn dial(host: &str, port: u16, closed: &AtomicBool) -> io::Result { + let mut tcp = Err(io::Error::other("the host has no address")); + for address in (host, port).to_socket_addrs()? { + if closed.load(Ordering::Acquire) { + break; + } + tcp = TcpStream::connect_timeout(&address, PATIENCE); + if tcp.is_ok() { + break; + } + } + let tcp = tcp?; + tcp.set_nodelay(true)?; + tcp.set_read_timeout(Some(PATIENCE))?; + tcp.set_write_timeout(Some(PATIENCE))?; + Ok(tcp) + } + + /// Reports the open and every message and sends what is queued, until the connection ends, + /// which gives the reason, or the socket is dropped, which gives `None`. + fn serve( + socket: &mut WebSocket>, + closed: &AtomicBool, + queue: &Receiver, + on_event: &mut impl FnMut(SocketEvent), + ) -> Option { + if !closed.load(Ordering::Acquire) { + on_event(SocketEvent::Open); + } + while !closed.load(Ordering::Acquire) { + for text in queue.try_iter() { + if let Err(error) = socket.send(Message::text(text)) { + return Some(lost(error)); + } + } + let event = match socket.read() { + Ok(Message::Text(text)) => SocketEvent::Text(text.as_str().to_owned()), + Ok(Message::Binary(bytes)) => match std::str::from_utf8(&bytes) { + Ok(text) => SocketEvent::Text(text.to_owned()), + Err(_) => SocketEvent::Binary(bytes.len()), + }, + Ok(Message::Close(frame)) => { + // The library queued the reply to the close frame; this sends it. + let _ = socket.flush(); + // A close frame without a code counts as 1005, as a browser reports it. + return Some(frame.map_or_else( + || closed_by_server(1005, ""), + |frame| closed_by_server(frame.code.into(), &frame.reason), + )); + } + // The library answers a ping itself on this or the next call. + Ok(Message::Ping(_) | Message::Pong(_) | Message::Frame(_)) => continue, + // The idle tick: nothing arrived for `TICK`. + Err(Error::Io(error)) if idle(&error) => continue, + Err(error) => return Some(lost(error)), + }; + if !closed.load(Ordering::Acquire) { + on_event(event); + } + } + None + } + + /// Whether a read or a write ended because its timeout passed: `WouldBlock` on Unix, + /// `TimedOut` on Windows. + fn idle(error: &io::Error) -> bool { + matches!( + error.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut + ) + } + + // The reasons of a socket that ends: sentence parts that follow the name of the endpoint. + + fn unusable(error: impl Display) -> String { + format!("not a usable WebSocket address ({error})") + } + + fn cannot(error: impl Display) -> String { + format!("cannot connect ({error})") + } + + fn failed(error: impl Display) -> String { + format!("handshake failed ({error})") + } + + fn lost(error: impl Display) -> String { + format!("connection lost ({error})") + } +} + +#[cfg(target_arch = "wasm32")] +mod web { + use std::cell::{Cell, RefCell}; + use std::collections::HashMap; + use std::rc::Rc; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + use std::time::Duration; + + use wasm_bindgen::closure::Closure; + use wasm_bindgen::{JsCast as _, JsValue}; + use web_sys::js_sys; + + use super::super::{after, endpoint}; + use super::{SocketEvent, closed_by_server}; + + /// A socket of the page and the handlers it calls, which live as long as the row. + struct Entry { + socket: web_sys::WebSocket, + _on_open: Closure, + _on_message: Closure, + _on_close: Closure, + } + + thread_local! { + /// The page's sockets and their handlers by number. They are not `Send`, so they stay + /// here and `Socket` holds the number: the session and the feed are then the same code + /// and the same `Send` types on both targets. + static SOCKETS: RefCell> = RefCell::default(); + } + + /// The number of the next row. + static NEXT: AtomicU64 = AtomicU64::new(0); + + /// A connection that is open or being opened. Dropping it closes the connection without + /// waiting; no event is started afterwards. + pub(crate) struct Socket { + /// The row of `SOCKETS` that holds the page's socket, if the page could create one. + number: u64, + /// Set by the drop, for the one event that no handler of the page's socket reports. + closed: Arc, + } + + impl Socket { + /// Starts connecting to `url` (`ws://` or `wss://`), offering `protocols` as subprotocols. + /// + /// Every outcome arrives through `on_event`, also a URL that cannot be opened at all. + /// `on_event` is never called from inside this function, from [`Socket::send`] or from the + /// drop. Natively it runs on the socket's own thread; in the browser as a task of the page. + pub(crate) fn open( + url: &str, + protocols: &[String], + mut on_event: impl FnMut(SocketEvent) + Send + 'static, + ) -> Self { + let number = NEXT.fetch_add(1, Ordering::Relaxed); + let closed = Arc::new(AtomicBool::new(false)); + let created = if protocols.is_empty() { + web_sys::WebSocket::new(url) + } else { + let offered: js_sys::Array = protocols.iter().map(JsValue::from).collect(); + web_sys::WebSocket::new_with_str_sequence(url, &offered) + }; + let socket = match created { + Ok(socket) => socket, + Err(error) => { + // The page may not open this address, or a subprotocol is not a token. + let message = error + .dyn_ref::() + .map_or_else(|| format!("{error:?}"), |error| error.message().into()); + let reason = format!("not a usable WebSocket address ({message})") + .replace(url, endpoint(url)); + // In a later task: `on_event` is never called from inside `open`. + after(Duration::ZERO, closed.clone(), move || { + on_event(SocketEvent::Closed { reason }); + }); + return Self { number, closed }; + } + }; + socket.set_binary_type(web_sys::BinaryType::Arraybuffer); + + // No error handler: a browser fires a close event after every error, and the error + // event carries no cause. + let on_event = Rc::new(RefCell::new(on_event)); + let opened = Rc::new(Cell::new(false)); + let (report, flag) = (on_event.clone(), opened.clone()); + let on_open = Closure::::new(move || { + flag.set(true); + (*report.borrow_mut())(SocketEvent::Open); + }); + let report = on_event.clone(); + let on_message = Closure::::new( + move |message: web_sys::MessageEvent| { + let data = message.data(); + let event = match data.as_string() { + Some(text) => SocketEvent::Text(text), + None => match String::from_utf8(js_sys::Uint8Array::new(&data).to_vec()) { + Ok(text) => SocketEvent::Text(text), + Err(error) => SocketEvent::Binary(error.as_bytes().len()), + }, + }; + (*report.borrow_mut())(event); + }, + ); + let address = url.to_owned(); + let on_close = Closure::::new( + move |close: web_sys::CloseEvent| { + let reason = match close.code() { + 1006 if opened.get() => "connection lost".to_owned(), + 1006 => "could not connect. The browser gives no cause: check the \ + address, that the server accepts this page, and the key if it \ + travels in the address or as a subprotocol" + .to_owned(), + code => closed_by_server(code, &close.reason()), + }; + // A text of the server can repeat the address, and a key with it. + let reason = reason.replace(&address, endpoint(&address)); + (*on_event.borrow_mut())(SocketEvent::Closed { reason }); + }, + ); + socket.set_onopen(Some(on_open.as_ref().unchecked_ref())); + socket.set_onmessage(Some(on_message.as_ref().unchecked_ref())); + socket.set_onclose(Some(on_close.as_ref().unchecked_ref())); + let entry = Entry { + socket, + _on_open: on_open, + _on_message: on_message, + _on_close: on_close, + }; + SOCKETS.with_borrow_mut(|sockets| sockets.insert(number, entry)); + Self { number, closed } + } + + /// Sends `text` as one text message. Only an open socket sends: before `Open` and after + /// `Closed` the text is dropped. + pub(crate) fn send(&self, text: &str) { + SOCKETS.with_borrow(|sockets| { + if let Some(entry) = sockets.get(&self.number) + && entry.socket.ready_state() == web_sys::WebSocket::OPEN + { + // A send that fails is a text lost with the connection. + let _ = entry.socket.send_with_str(text); + } + }); + } + } + + impl Drop for Socket { + fn drop(&mut self) { + self.closed.store(true, Ordering::Release); + let number = self.number; + SOCKETS.with_borrow(|sockets| { + if let Some(entry) = sockets.get(&number) { + entry.socket.set_onopen(None); + entry.socket.set_onmessage(None); + entry.socket.set_onclose(None); + let _ = entry.socket.close(); + } + }); + // The row goes in a later task: this drop can run inside one of the row's own + // handlers, and a handler must not be freed while it runs. + after(Duration::ZERO, Arc::default(), move || { + SOCKETS.with_borrow_mut(|sockets| sockets.remove(&number)); + }); + } + } +} diff --git a/vendor/egui-charts/examples/demo/owndata/store.rs b/vendor/egui-charts/examples/demo/owndata/store.rs new file mode 100644 index 0000000..7a7f9e1 --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/store.rs @@ -0,0 +1,92 @@ +//! What the browser keeps about own data: the answer to the first-visit choice, the saved +//! profiles and, when the visitor chose so, the values of their keys. Also the exported file. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::super::storage::DemoStorage; +use super::Secrets; +use super::profile::{Profile, VERSION}; + +/// The saved state: one JSON document of the demo's storage. It has no `Debug`, so a kept key +/// cannot reach a log line by accident. +#[derive(Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub(crate) struct Saved { + /// True once the first-visit choice has been answered. It is then never offered again. + pub(crate) asked: bool, + /// True while own data is the source in use. The demo then connects `current` when it + /// starts. + pub(crate) own: bool, + /// Name of the profile in use, or of the one used last. + pub(crate) current: Option, + /// The saved profiles, in the order they were first saved. Names are unique. + pub(crate) profiles: Vec, + /// The key values of the profiles whose keys the visitor chose to keep, by profile name. + /// The keys of a profile that is not listed are asked for again at every start. + pub(crate) keys: Vec<(String, Secrets)>, +} + +impl Saved { + /// The saved state. The default when nothing is saved yet or the document cannot be read. + pub(crate) fn load(storage: &DemoStorage) -> Self { + let document = storage.own_data(); + let saved = document.and_then(|document| serde_json::from_str(&document).ok()); + saved.unwrap_or_default() + } + + /// Writes the state as the own-data document. The demo's storage persists it at the end + /// of the frame. + pub(crate) fn save(&self, storage: &DemoStorage) { + match serde_json::to_string(self) { + Ok(document) => storage.save_own_data(&document), + Err(error) => log::warn!("the own-data state was not saved: {error}"), + } + } +} + +/// The file an export writes: `profile` as indented JSON. A profile names its keys and never +/// holds their values, so the file holds none. +pub(crate) fn export(profile: &Profile) -> String { + // A profile holds text, numbers and lists only, which always serialise. + serde_json::to_string_pretty(profile).unwrap_or_default() +} + +/// The profile of an exported file. The error says why the file cannot be used: it is not +/// JSON, it does not describe a profile, or it was written by a newer version of the demo. +pub(crate) fn import(text: &str) -> Result { + let file: Value = serde_json::from_str(text).map_err(|error| format!("not JSON: {error}"))?; + // Read first, so that a newer file is named as such whatever else it holds. + let version = file.get("version").and_then(Value::as_u64); + if version.is_some_and(|version| version > u64::from(VERSION)) { + return Err("written by a newer version of the demo".to_owned()); + } + // Every field of a profile has a default, so any object would read as one. + if file.get("name").is_none() { + return Err("not a profile: it has no name".to_owned()); + } + serde_json::from_value(file).map_err(|error| format!("not a profile: {error}")) +} + +/// The ready profiles, in the order the profile list shows them: public sources that need no key. +/// They ship with the demo and are never saved, so a later version of the demo updates them. +pub(crate) fn ready() -> Vec { + const FILES: [&str; 1] = [include_str!("ready/binance-spot.json")]; + // The tests read every shipped file through the feed, so a file that does not read fails + // there. + FILES.iter().filter_map(|file| import(file).ok()).collect() +} + +/// `name` as the stem of a file name: every character that is not an ASCII letter, a digit, +/// `-` or `_` becomes `_`, and an empty name becomes `unnamed`. A profile name or a symbol +/// that was typed or imported can therefore not carry a path to the place a file is written. +pub(crate) fn file_stem(name: &str) -> String { + if name.is_empty() { + return "unnamed".to_owned(); + } + let plain = |letter: char| letter.is_ascii_alphanumeric() || matches!(letter, '-' | '_'); + let stem = name + .chars() + .map(|letter| if plain(letter) { letter } else { '_' }); + stem.collect() +} diff --git a/vendor/egui-charts/examples/demo/owndata/stream.rs b/vendor/egui-charts/examples/demo/owndata/stream.rs new file mode 100644 index 0000000..e92a69b --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/stream.rs @@ -0,0 +1,1179 @@ +//! The stream of one subscription: a socket kept open, the connect and keep-alive messages of +//! the profile, every message split into its records, each record sent to its route, and the +//! connection opened again after it drops. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Duration; + +use chrono::{DateTime, TimeDelta, Utc}; +use serde_json::Value; + +use super::after; +use super::profile::{RouteKind, Stream, at, fill, fill_url, text}; +use super::socket::{Socket, SocketEvent}; + +/// The wait before the first reconnect, and before the one after a connection that settled. +const FIRST_RETRY: Duration = Duration::from_secs(1); +/// The longest wait before a reconnect. +const LONGEST_RETRY: Duration = Duration::from_secs(60); +/// A connection that was open for this long has settled: the waits start again. +const SETTLED_AFTER: TimeDelta = TimeDelta::seconds(10); + +/// What a session reports, in order and one at a time. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum StreamEvent { + /// The socket is open and the connect messages have been sent. `again` is true for every + /// open after the first of this session: records may have been missed since the `Closed` + /// before it, and the feed fills that gap from history. + Open { again: bool }, + /// One message, as received, and its records in the order of the message. + Message { text: String, records: Vec }, + /// A message the session cannot read: binary data that is not UTF-8 text, as a compressed + /// stream sends. `reason` says so with the size. + Unreadable { reason: String }, + /// The connection ended or could not be opened; `reason` is the socket's. The session + /// opens it again after `retry_in`. + Closed { reason: String, retry_in: Duration }, +} + +/// One record of a message and where it goes. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Routed { + /// A record of route `route` of `Stream::routes`, whose kind is bars or trades. + Record { route: usize, record: Value }, + /// A record of route `route`, whose kind is `Ignore`. + Ignored { route: usize }, + /// A record that matched no route. + Unrouted { record: Value }, +} + +/// The records of one message and their routes, in message order: the split and the routing a +/// session applies to every message. The dialog calls it again for the messages of its +/// log when the user edits the routes, so the log always shows what the feed would do. +pub(crate) fn route(stream: &Stream, message: &str) -> Vec { + // A message that is not JSON is one record: its own text. + let root = serde_json::from_str(message).unwrap_or_else(|_| Value::String(message.to_owned())); + let records = match at(&root, &stream.records) { + Some(Value::Array(records)) => records.iter().collect(), + Some(record @ Value::Object(_)) => vec![record], + // Nothing to split at the path, as in a status message: the message is the record. + _ => vec![&root], + }; + let routed = |record: &Value| { + let route = if stream.route_by.is_empty() { + (!stream.routes.is_empty()).then_some(0) + } else { + // The record's own value, then the one the message names once at its root, then + // the record itself when it is a bare value. + at(record, &stream.route_by) + .and_then(text) + .or_else(|| at(&root, &stream.route_by).and_then(text)) + .or_else(|| text(record)) + .and_then(|value| stream.routes.iter().position(|route| route.value == value)) + }; + match route { + Some(route) if matches!(stream.routes[route].kind, RouteKind::Ignore) => { + Routed::Ignored { route } + } + Some(route) => Routed::Record { + route, + record: record.clone(), + }, + None => Routed::Unrouted { + record: record.clone(), + }, + } + }; + records.into_iter().map(routed).collect() +} + +/// The stream of one subscription. Dropping it closes the socket and cancels its timers +/// without waiting; no event is started afterwards. +pub(crate) struct Session { + shared: Arc, +} + +/// What a session, the handler of its socket and its timers share. +struct Shared { + stream: Stream, + values: Vec<(String, String)>, + /// Set by the drop. Read with `on_event` locked, immediately before every call. + closed: AtomicBool, + /// The caller's callback. The drop never locks it. + on_event: Mutex>, + /// Everything that changes. Never locked while `on_event` runs. + core: Mutex, +} + +struct Core { + /// The connection in use or being opened. + socket: Option, + /// True once a socket of this session has opened: the next open is a reconnect. + opened: bool, + /// When the connection in use opened. + open_since: Option>, + /// The wait before the next reconnect. + retry_in: Duration, + /// Cancels the timer in flight: the keep-alive while open, the reconnect while closed. + timer: Arc, +} + +impl Session { + /// Opens the stream described by `stream`. `values` fill its templates: `symbol`, + /// `interval` (the value the service expects) and one pair per key. + /// + /// `on_event` is never called from inside this function or from the drop. Natively it runs + /// on a thread the session owns; in the browser as a task of the page. + pub(crate) fn open( + stream: Stream, + values: Vec<(String, String)>, + on_event: impl FnMut(StreamEvent) + Send + 'static, + ) -> Self { + let shared = Arc::new(Shared { + stream, + values, + closed: AtomicBool::new(false), + on_event: Mutex::new(Box::new(on_event)), + core: Mutex::new(Core { + socket: None, + opened: false, + open_since: None, + retry_in: FIRST_RETRY, + timer: Arc::default(), + }), + }); + shared.connect(); + Self { shared } + } +} + +impl Drop for Session { + fn drop(&mut self) { + self.shared.closed.store(true, Ordering::Release); + let mut core = self.shared.core(); + core.timer.store(true, Ordering::Release); + let socket = core.socket.take(); + drop(core); + drop(socket); + } +} + +impl Shared { + /// The state that changes. A poisoned lock is entered anyway. + fn core(&self) -> MutexGuard<'_, Core> { + self.core.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// The values of the templates, borrowed for `fill` and `fill_url`. + fn values(&self) -> Vec<(&str, &str)> { + self.values + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())) + .collect() + } + + /// Calls the caller, unless the session was dropped. Nothing else touches `on_event`. + fn report(&self, event: StreamEvent) { + let mut on_event = self.on_event.lock().unwrap_or_else(|e| e.into_inner()); + if !self.closed.load(Ordering::Acquire) { + on_event(event); + } + } + + /// Opens the next socket and stores it, unless the session was dropped. `core` stays + /// locked meanwhile: the socket's thread can report the open before `Socket::open` has + /// returned, and its handler must find the socket it sends the connect messages through. + fn connect(self: &Arc) { + let mut core = self.core(); + if self.closed.load(Ordering::Acquire) { + return; + } + let values = self.values(); + let url = fill_url(&self.stream.url, &values); + let offered = |protocol: &String| fill(protocol, &values); + let protocols: Vec = self.stream.protocols.iter().map(offered).collect(); + // Weak: the socket lives in `core`, so a strong capture would be a cycle. + let session = Arc::downgrade(self); + core.socket = Some(Socket::open(&url, &protocols, move |event| { + if let Some(shared) = session.upgrade() { + shared.handle(event); + } + })); + } + + /// What the session does with an event of its socket. + fn handle(self: &Arc, event: SocketEvent) { + match event { + SocketEvent::Open => { + let mut core = self.core(); + if let Some(socket) = &core.socket { + let values = self.values(); + for message in &self.stream.connect { + socket.send(&fill(message, &values)); + } + } + core.open_since = Some(Utc::now()); + if !self.stream.keep_alive.is_empty() { + core.timer = Arc::default(); + self.keep_alive(core.timer.clone()); + } + let again = std::mem::replace(&mut core.opened, true); + drop(core); + self.report(StreamEvent::Open { again }); + } + SocketEvent::Text(text) => { + let records = route(&self.stream, &text); + self.report(StreamEvent::Message { text, records }); + } + SocketEvent::Binary(len) => { + let reason = format!("a binary message of {len} bytes that is not text"); + self.report(StreamEvent::Unreadable { reason }); + } + SocketEvent::Closed { reason } => { + let mut core = self.core(); + // The keep-alive stops, and the timer is now the wait before the reconnect. + core.timer.store(true, Ordering::Release); + core.timer = Arc::default(); + let timer = core.timer.clone(); + let socket = core.socket.take(); + // Wall time: `Instant` is not available in the browser. A clock that was set + // back makes a long connection look short, which only lengthens the wait. + let settled = core + .open_since + .take() + .is_some_and(|since| Utc::now() - since >= SETTLED_AFTER); + let retry_in = if settled { FIRST_RETRY } else { core.retry_in }; + core.retry_in = (retry_in * 2).min(LONGEST_RETRY); + drop(core); + drop(socket); + self.report(StreamEvent::Closed { reason, retry_in }); + let session = Arc::downgrade(self); + after(retry_in, timer, move || { + if let Some(shared) = session.upgrade() { + shared.connect(); + } + }); + } + } + } + + /// Arms the next keep-alive message: after the period it is sent and the one after it is + /// armed, until `timer` is set at the close or at the drop. + fn keep_alive(self: &Arc, timer: Arc) { + let every = Duration::from_secs(self.stream.keep_alive_every.max(1).into()); + let session = Arc::downgrade(self); + after(every, timer.clone(), move || { + let Some(shared) = session.upgrade() else { + return; + }; + let core = shared.core(); + // Read with `core` locked, where the close and the drop set it: the socket of + // `core` is still the one this timer was armed for. + if timer.load(Ordering::Acquire) { + return; + } + if let Some(socket) = &core.socket { + socket.send(&fill(&shared.stream.keep_alive, &shared.values())); + } + drop(core); + shared.keep_alive(timer); + }); + } +} + +#[cfg(test)] +pub(crate) mod tests { + use std::net::{TcpListener, TcpStream}; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex, mpsc}; + use std::time::{Duration, Instant}; + + use eframe::egui; + use egui_charts::data::FeedStatus; + use egui_charts::model::{OrderSide, Tick, Timeframe}; + use egui_charts::widget::{Chart, ChartBuilder, SeriesId}; + use serde_json::json; + use tungstenite::handshake::server::{Callback, ErrorResponse, Request, Response}; + use tungstenite::protocol::CloseFrame; + use tungstenite::{Message, WebSocket}; + + use super::super::feed::MappedFeed; + use super::super::profile::{ + BarFields, ConditionRule, Route, RouteKind, Segment, Stream, TimeSpec, TimeUnit, + TradeFields, + }; + use super::{Routed, Session, StreamEvent, route}; + + /// One step of a scripted connection. + pub(crate) enum Step { + /// Wait for this many text messages and record them. + Receive(usize), + /// Send a text message. + Send(&'static str), + /// Do nothing for this long. + Wait(Duration), + /// Record every further text message until the client closes the connection. + UntilClosed, + /// Close with this code and a close frame. + Close(u16), + /// End the connection without a close frame, as a lost network does. + Drop, + /// Wait until the test calls [`Peer::release`]. A test uses it to send the next message + /// only after it has seen the chart reach a state. + Hold, + } + + /// Notes the target a handshake asks for and accepts the handshake. + struct Asked<'a>(&'a Mutex>); + + impl Callback for Asked<'_> { + fn on_request( + self, + request: &Request, + response: Response, + ) -> Result { + self.0.lock().unwrap().push(request.uri().to_string()); + Ok(response) + } + } + + /// A scripted WebSocket server on a local port. Connection `n` runs `scripts[n]`, one + /// connection at a time; the listener closes after the last script. + pub(crate) struct Peer { + /// `ws://127.0.0.1:PORT`. + pub(crate) url: String, + asked: Arc>>, + received: Arc>>>, + ended: Arc, + held: mpsc::Sender<()>, + } + + impl Peer { + pub(crate) fn start(scripts: Vec>) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let asked = Arc::new(Mutex::new(Vec::new())); + let targets = asked.clone(); + let received = Arc::new(Mutex::new(Vec::new())); + let log = received.clone(); + let ended = Arc::new(AtomicUsize::new(0)); + let over = ended.clone(); + let (held, released) = mpsc::channel(); + std::thread::spawn(move || { + // The scripts come first in the pair, so that no connection is accepted after + // the last one. + for (script, connection) in scripts.into_iter().zip(listener.incoming()) { + let mut socket = + tungstenite::accept_hdr(connection.unwrap(), Asked(&targets)).unwrap(); + log.lock().unwrap().push(Vec::new()); + let record = |socket: &mut WebSocket, mut wanted: usize| { + while wanted > 0 { + match socket.read() { + Ok(Message::Text(text)) => { + log.lock() + .unwrap() + .last_mut() + .unwrap() + .push(text.to_string()); + wanted -= 1; + } + Ok(_) => {} + Err(_) => return, + } + } + }; + for step in script { + match step { + Step::Receive(count) => record(&mut socket, count), + Step::Send(text) => socket.send(Message::text(text)).unwrap(), + Step::Wait(time) => std::thread::sleep(time), + Step::UntilClosed => record(&mut socket, usize::MAX), + Step::Close(code) => { + let frame = CloseFrame { + code: code.into(), + reason: "".into(), + }; + let _ = socket.close(Some(frame)); + record(&mut socket, usize::MAX); + } + Step::Drop => break, + Step::Hold => { + if released.recv().is_err() { + return; + } + } + } + } + // Dropping the socket here ends the connection; without a `Close` step no + // close frame was sent. + drop(socket); + over.fetch_add(1, Ordering::Release); + } + }); + Self { + url, + asked, + received, + ended, + held, + } + } + + /// The target each handshake asked for, such as `/stream?key=k`, one per connection in + /// the order they arrived. + pub(crate) fn asked(&self) -> Vec { + self.asked.lock().unwrap().clone() + } + + /// The text messages received so far, one list per connection in the order they arrived. + pub(crate) fn received(&self) -> Vec> { + self.received.lock().unwrap().clone() + } + + /// How many connections have ended: their scripts are over and their sockets are closed. + pub(crate) fn ended(&self) -> usize { + self.ended.load(Ordering::Acquire) + } + + /// Lets the script pass its next `Hold`. A release that comes first is kept for it. + pub(crate) fn release(&self) { + self.held.send(()).unwrap(); + } + } + + #[test] + fn messages_split_into_routed_records() { + let key = |name: &str| vec![Segment::Key(name.to_owned())]; + let to = |value: &str, kind| Route { + value: value.to_owned(), + kind, + }; + // A status route, a keep-alive answer, trades, and a route whose value is a number. + let stream = Stream { + records: key("data"), + route_by: key("type"), + routes: vec![ + to("status", RouteKind::Ignore), + to("pong", RouteKind::Ignore), + to("trade", RouteKind::Trades(TradeFields::default())), + to("7", RouteKind::Bars(BarFields::default())), + ], + ..Stream::default() + }; + let record = |route, record| Routed::Record { route, record }; + let whole = r#"[{"type":"trade","p":1,"s":1,"t":1},{"type":"status"}]"#; + let rows: Vec<(&str, Vec)> = vec![ + // 1: nothing at `data`, so the message is the record. + ( + r#"{"type":"status","message":"authenticated"}"#, + vec![Routed::Ignored { route: 0 }], + ), + // 2: two records without a `type`, routed by the root's. + ( + r#"{"type":"trade","data":[{"p":"101.5","s":3,"t":1794407400123},{"p":101.25,"s":1,"t":1794407400456}]}"#, + vec![ + record(2, json!({"p": "101.5", "s": 3, "t": 1794407400123_i64})), + record(2, json!({"p": 101.25, "s": 1, "t": 1794407400456_i64})), + ], + ), + // 3: an empty list holds no record. + (r#"{"type":"trade","data":[]}"#, vec![]), + // 4: no route has the value `quote`. + ( + r#"{"type":"quote","data":[{"b":101.0}]}"#, + vec![Routed::Unrouted { + record: json!({"b": 101.0}), + }], + ), + // 5 and 6: text that is not JSON, and a bare JSON string, are routed by their own text. + ("pong", vec![Routed::Ignored { route: 1 }]), + (r#""pong""#, vec![Routed::Ignored { route: 1 }]), + // 7: an object at the path is one record, with a `type` of its own. + ( + r#"{"data":{"type":"trade","p":101.5,"s":2,"t":1794407400789}}"#, + vec![record( + 2, + json!({"type": "trade", "p": 101.5, "s": 2, "t": 1794407400789_i64}), + )], + ), + // 8: a number is compared as JSON prints it. + ( + r#"{"type":7,"data":[{"o":1}]}"#, + vec![record(3, json!({"o": 1}))], + ), + // 9: the root is a list, so `data` leads nowhere and a list has no `type`. + ( + whole, + vec![Routed::Unrouted { + record: serde_json::from_str(whole).unwrap(), + }], + ), + ]; + for (message, expected) in rows { + assert_eq!(route(&stream, message), expected, "{message}"); + } + + // With the root as the place of the records, the list of row 9 is split. + let rooted = Stream { + records: vec![], + ..stream.clone() + }; + assert_eq!( + route(&rooted, whole), + vec![ + record(2, json!({"type": "trade", "p": 1, "s": 1, "t": 1})), + Routed::Ignored { route: 0 }, + ], + ); + // Without a routing field every record goes to the first route, and without a route + // nowhere. + let unrouted = Stream { + route_by: vec![], + ..stream.clone() + }; + assert_eq!( + route(&unrouted, r#"{"data":[{"x":1}]}"#), + vec![Routed::Ignored { route: 0 }], + ); + let bare = Stream { + routes: vec![], + ..unrouted + }; + assert_eq!( + route(&bare, r#"{"data":[{"x":1}]}"#), + vec![Routed::Unrouted { + record: json!({"x": 1}), + }], + ); + } + + #[test] + fn a_session_logs_in_keeps_alive_and_reconnects() { + const LOGIN: &str = r#"{"action":"auth","key":"s3cret-7f3a"}"#; + const SUBSCRIBE: &str = r#"{"action":"subscribe","symbol":"ABC","interval":"1m"}"#; + const PING: &str = r#"{"action":"ping","symbol":"ABC"}"#; + const STATUS: &str = r#"{"type":"status","message":"authenticated"}"#; + const TRADES: &str = r#"{"type":"trade","data":[{"p":101.75,"s":3,"t":1794407710000},{"p":99.75,"s":2,"t":1794407715000}]}"#; + let peer = Peer::start(vec![ + vec![ + Step::Receive(2), + Step::Send(STATUS), + // Longer than two idle ticks of the native client. The message after it must + // still arrive, and no close may be reported in between. + Step::Wait(Duration::from_millis(600)), + Step::Send(TRADES), + // The first keep-alive, one second after the open. + Step::Receive(1), + Step::Close(1008), + ], + vec![Step::Receive(2), Step::Drop], + ]); + let key = |name: &str| vec![Segment::Key(name.to_owned())]; + let stream = Stream { + // No path: the handshake must ask for `/`, as a browser does for this address. + url: format!("{}?key={{key}}", peer.url), + connect: vec![ + r#"{"action":"auth","key":"{key}"}"#.to_owned(), + r#"{"action":"subscribe","symbol":"{symbol}","interval":"{interval}"}"#.to_owned(), + ], + keep_alive: r#"{"action":"ping","symbol":"{symbol}"}"#.to_owned(), + keep_alive_every: 1, + records: key("data"), + route_by: key("type"), + routes: vec![ + Route { + value: "status".to_owned(), + kind: RouteKind::Ignore, + }, + Route { + value: "trade".to_owned(), + kind: RouteKind::Trades(TradeFields::default()), + }, + ], + ..Stream::default() + }; + let values = [ + ("symbol", "ABC"), + ("interval", "1m"), + ("key", "s3cret-7f3a"), + ] + .map(|(name, value)| (name.to_owned(), value.to_owned())) + .to_vec(); + + // Every event with the moment it arrived. + let events = Arc::new(Mutex::new(Vec::new())); + let log = events.clone(); + let session = Session::open(stream, values, move |event| { + log.lock().unwrap().push((Instant::now(), event)); + }); + let start = Instant::now(); + while events.lock().unwrap().len() < 6 { + assert!( + start.elapsed() < Duration::from_secs(30), + "{:?}", + events.lock().unwrap() + ); + std::thread::sleep(Duration::from_millis(5)); + } + // The session would open a third socket two seconds from now. Dropping it cancels that. + drop(session); + + let events = events.lock().unwrap().clone(); + let trade = |price: f64, size: u64, time: i64| Routed::Record { + route: 1, + record: json!({"p": price, "s": size, "t": time}), + }; + assert_eq!(events[0].1, StreamEvent::Open { again: false }); + assert_eq!( + events[1].1, + StreamEvent::Message { + text: STATUS.to_owned(), + records: vec![Routed::Ignored { route: 0 }], + }, + ); + assert_eq!( + events[2].1, + StreamEvent::Message { + text: TRADES.to_owned(), + records: vec![ + trade(101.75, 3, 1794407710000), + trade(99.75, 2, 1794407715000), + ], + }, + ); + assert_eq!( + events[3].1, + StreamEvent::Closed { + reason: "closed by the server (code 1008)".to_owned(), + retry_in: Duration::from_secs(1), + }, + ); + // The keep-alive leaves on time although nothing arrives after the trades, so the close + // that answers it comes long before the ten seconds a read waits during the handshake. + let answered = events[3].0 - events[0].0; + assert!(answered < Duration::from_secs(5), "{answered:?}"); + assert_eq!(events[4].1, StreamEvent::Open { again: true }); + let StreamEvent::Closed { reason, retry_in } = &events[5].1 else { + panic!("{:?}", events[5].1); + }; + assert!(reason.starts_with("connection lost"), "{reason}"); + assert_eq!(*retry_in, Duration::from_secs(2)); + // The wait is kept, not only reported: the socket is not opened again before it has passed. + assert!(events[4].0 - events[3].0 >= Duration::from_secs(1)); + + assert_eq!(peer.asked(), ["/?key=s3cret-7f3a", "/?key=s3cret-7f3a"]); + let received = peer.received(); + assert_eq!(received[0][..3], [LOGIN, SUBSCRIBE, PING]); + assert!(received[0][3..].iter().all(|text| text == PING)); + assert_eq!(received[1], [LOGIN, SUBSCRIBE]); + } + + /// A chart on the mapped feed, with history from the scripted server and trades from the + /// scripted peer. A trade that arrives while a page is being fetched is dropped by rule, so + /// every message of the peer waits behind a `Hold`, which the test releases only once the + /// chart shows the state the message builds on. Each trade folded into a bar also reaches the + /// chart's trades and the tape of time and sales, once. The fixture is one-minute bars of + /// 11 November 2026: 14:35 UTC is second 1,794,407,700, and a trade gives its time in + /// milliseconds. + #[test] + fn a_stream_updates_the_last_bar_and_fills_the_gap() { + use super::super::feed::tests::{Server, Shown, pages, profile, shown, until}; + // History rows as the service sends them: its newest three at the start, what it holds + // later, and two of another symbol in the slots of 14:37 and 14:38. + const J3: &str = r#"{"t":1794407580,"o":100.75,"h":103.0,"l":100.5,"c":102.5,"v":1500}"#; + const J4: &str = r#"{"t":1794407640,"o":102.5,"h":102.75,"l":101.0,"c":101.25,"v":800}"#; + const J5: &str = r#"{"t":1794407700,"o":101.25,"h":101.5,"l":100.0,"c":100.25,"v":700}"#; + const G6: &str = r#"{"t":1794407760,"o":100.5,"h":101.0,"l":100.25,"c":100.75,"v":40}"#; + const G7: &str = r#"{"t":1794407820,"o":100.75,"h":101.25,"l":100.5,"c":101.0,"v":25}"#; + const G7F: &str = r#"{"t":1794407820,"o":100.75,"h":101.5,"l":100.5,"c":101.25,"v":60}"#; + const G8: &str = r#"{"t":1794407880,"o":101.25,"h":101.5,"l":101.0,"c":101.25,"v":10}"#; + const X0: &str = r#"{"t":1794407820,"o":50.0,"h":50.5,"l":49.75,"c":50.25,"v":100}"#; + const X1: &str = r#"{"t":1794407880,"o":50.25,"h":50.75,"l":50.0,"c":50.5,"v":80}"#; + // The messages of the stream. + const LOGIN: &str = r#"{"action":"auth","key":"s3cret-7f3a"}"#; + const ABC: &str = r#"{"action":"subscribe","symbol":"ABC","interval":"1m"}"#; + const XYZ: &str = r#"{"action":"subscribe","symbol":"XYZ","interval":"1m"}"#; + const STATUS: &str = r#"{"type":"status","message":"authenticated"}"#; + const IN_LAST_BAR: &str = r#"{"type":"trade","data":[{"p":"101.75","s":3,"t":1794407710000,"side":"buy"},{"p":99.75,"s":2,"t":1794407715000,"side":"sell"},{"p":120.0,"s":50,"t":1794407716000,"c":"X"},{"p":98.0,"s":4,"t":1794407717000,"c":"T"}]}"#; + const NEW_SLOT: &str = r#"{"type":"trade","data":[{"p":100.5,"s":4,"t":1794407765000}]}"#; + const AFTER_FILL: &str = r#"{"type":"trade","data":[{"p":101.5,"s":5,"t":1794407850000}]}"#; + const AFTER_RESUME: &str = + r#"{"type":"trade","data":[{"p":101.75,"s":2,"t":1794407900000}]}"#; + const OTHER_SYMBOL: &str = + r#"{"type":"trade","data":[{"p":51.0,"s":5,"t":1794407920000}]}"#; + // The bars the chart shows. + const B3: Shown = (1794407580, Some([100.75, 103.0, 100.5, 102.5, 1500.0])); + const B4: Shown = (1794407640, Some([102.5, 102.75, 101.0, 101.25, 800.0])); + const B5: Shown = (1794407700, Some([101.25, 101.5, 100.0, 100.25, 700.0])); + const B5A: Shown = (1794407700, Some([101.25, 101.75, 99.75, 99.75, 709.0])); + const T6: Shown = (1794407760, Some([100.5, 100.5, 100.5, 100.5, 4.0])); + const F6: Shown = (1794407760, Some([100.5, 101.0, 100.25, 100.75, 40.0])); + const F7: Shown = (1794407820, Some([100.75, 101.25, 100.5, 101.0, 25.0])); + const F7C: Shown = (1794407820, Some([100.75, 101.5, 100.5, 101.5, 30.0])); + const R7: Shown = (1794407820, Some([100.75, 101.5, 100.5, 101.25, 60.0])); + const R8: Shown = (1794407880, Some([101.25, 101.5, 101.0, 101.25, 10.0])); + const R8D: Shown = (1794407880, Some([101.25, 101.75, 101.0, 101.75, 12.0])); + const Y0: Shown = (1794407820, Some([50.0, 50.5, 49.75, 50.25, 100.0])); + const Y1: Shown = (1794407880, Some([50.25, 50.75, 50.0, 50.5, 80.0])); + const Y1E: Shown = (1794407880, Some([50.25, 51.0, 50.0, 51.0, 85.0])); + // The trades the chart and time and sales receive: time in milliseconds, price, size and + // side. The ignored trade at 120.0 is in neither. + type Fed = (i64, f64, f64, Option); + const P1: Fed = (1794407710000, 101.75, 3.0, Some(OrderSide::Buy)); + const P2: Fed = (1794407715000, 99.75, 2.0, Some(OrderSide::Sell)); + const P4: Fed = (1794407717000, 98.0, 4.0, None); + const P6: Fed = (1794407765000, 100.5, 4.0, None); + const P8: Fed = (1794407850000, 101.5, 5.0, None); + const P9: Fed = (1794407920000, 51.0, 5.0, None); + let fed = |trades: Vec| -> Vec { + let row = |t: &Tick| (t.ts.timestamp_millis(), t.price, t.size, t.side); + trades.iter().map(row).collect() + }; + + let list = |rows: &[&str]| format!("[{}]", rows.join(",")); + let server = Server::start(pages(vec![ + list(&[J3, J4, J5]), + "[]".to_owned(), + list(&[G6, G7]), + list(&[G6, G7F, G8]), + "[]".to_owned(), + list(&[X0, X1]), + "[]".to_owned(), + ])); + let peer = Peer::start(vec![ + vec![ + Step::Receive(2), + Step::Hold, + Step::Send(STATUS), + Step::Send(IN_LAST_BAR), + Step::Hold, + Step::Send(NEW_SLOT), + Step::Hold, + Step::Drop, + ], + vec![ + Step::Receive(2), + Step::Hold, + Step::Send(AFTER_FILL), + Step::UntilClosed, + ], + vec![ + Step::Receive(2), + Step::Hold, + Step::Send(AFTER_RESUME), + Step::UntilClosed, + ], + vec![ + Step::Receive(2), + Step::Hold, + Step::Send(OTHER_SYMBOL), + Step::UntilClosed, + ], + ]); + + let key = |name: &str| vec![Segment::Key(name.to_owned())]; + let mut profile = profile(&server.origin); + profile.keys = vec!["key".to_owned()]; + profile.stream = Some(Stream { + url: format!("{}/{{key}}/stream?key={{key}}", peer.url), + connect: vec![ + r#"{"action":"auth","key":"{key}"}"#.to_owned(), + r#"{"action":"subscribe","symbol":"{symbol}","interval":"{interval}"}"#.to_owned(), + ], + records: key("data"), + route_by: key("type"), + routes: vec![ + Route { + value: "status".to_owned(), + kind: RouteKind::Ignore, + }, + Route { + value: "trade".to_owned(), + kind: RouteKind::Trades(TradeFields { + time: TimeSpec::Instant { + field: key("t"), + unit: TimeUnit::Milliseconds, + }, + price: key("p"), + size: key("s"), + condition: key("c"), + conditions: vec![ + ("T".to_owned(), ConditionRule::VolumeOnly), + ("X".to_owned(), ConditionRule::Ignore), + ], + side: key("side"), + buy: "buy".to_owned(), + sell: "sell".to_owned(), + ..TradeFields::default() + }), + }, + ], + ..Stream::default() + }); + profile.tick_size = Some(0.25); + let secrets = vec![("key".to_owned(), "s3cret-7f3a".to_owned())]; + let feed = Arc::new(MappedFeed::new(profile, secrets)); + let mut chart = ChartBuilder::new() + .with_feed(feed.clone()) + .with_symbol("ABC") + .with_timeframe(Timeframe::Min1) + .with_initial_bars(3) + .build(); + let ctx = egui::Context::default(); + let state = |chart: &Chart| { + let state = chart.feed_state(SeriesId::MAIN); + state.cloned().unwrap_or_default() + }; + // Waits until history has ended and the chart shows exactly `bars`. + let see = |chart: &mut Chart, what: &str, bars: &[Shown]| { + until(&ctx, chart, what, |chart| { + state(chart).history_complete && shown(chart) == bars + }); + }; + + // 1. History. The instrument carries the profile's price step. + see(&mut chart, "history", &[B3, B4, B5]); + assert_eq!(chart.instrument().and_then(|i| i.tick_size), Some(0.25)); + // 2. Trades in the slot of the newest bar continue that bar. Its open stays the one of + // history, 101.75, sent as text, is the high, 99.75 is the low and the close, and the + // volume is 700 + 3 + 2 + 4: the ignored trade counts nothing, and the volume only + // trade at 98.0 counts its size without moving a price. + peer.release(); + see(&mut chart, "trades in the last bar", &[B3, B4, B5A]); + // 3. The first trade of the next slot opens the next bar, at its price and with its size. + peer.release(); + see(&mut chart, "a new slot", &[B3, B4, B5A, T6]); + let trades = fed(chart.trades(SeriesId::MAIN).cloned().collect()); + assert_eq!(trades, [P1, P2, P4, P6]); + let tape = feed.drain_tape("ABC", Some(Timeframe::Min1)); + assert_eq!(fed(tape), [P1, P2, P4, P6]); + + // 4. The connection is lost. The chart says so with the endpoint, and without the key + // that travels in the address: in its path the key is shown by its name. + peer.release(); + until(&ctx, &mut chart, "the drop", |chart| { + state(chart).last_error.is_some() + }); + assert_eq!(state(&chart).status, Some(FeedStatus::Disconnected)); + let error = state(&chart).last_error.unwrap().to_string(); + let lost = format!( + "network error: {}/{{key}}/stream: connection lost", + peer.url + ); + assert!(error.starts_with(&lost), "{error}"); + // The session connects again after a second and the feed loads what was missed, from the + // slot of the newest bar it knows: the final state of the bar that was forming takes the + // place of the bar the one trade built, and the bar after it is new. + see(&mut chart, "the gap filled", &[B3, B4, B5A, F6, F7]); + assert_eq!(state(&chart).status, Some(FeedStatus::Live)); + // 5. The next trade continues the newest bar of the fill: 101.5 is its high and its + // close, and the volume is 25 + 5. + peer.release(); + see( + &mut chart, + "a trade after the fill", + &[B3, B4, B5A, F6, F7C], + ); + // The bars the fill loaded, from 14:36:05 to 14:37:30, bring no trades. + let trades = fed(chart.trades(SeriesId::MAIN).cloned().collect()); + assert_eq!(trades, [P1, P2, P4, P6, P8]); + + // 6. A paused chart has no socket: the peer sees the connection end during the pause. + chart.set_feed_paused(true); + until(&ctx, &mut chart, "the pause to close the socket", |_| { + peer.ended() == 2 + }); + // Resuming loads the latest page and subscribes again. The chart drops its last bar and + // keeps the others: the row of 14:37 takes the place of the dropped bar and the row of + // 14:38 is new. + chart.set_feed_paused(false); + see(&mut chart, "the resume", &[B3, B4, B5A, F6, R7, R8]); + // 7. The next trade continues the newest bar of that page: 101.75 is its high and its + // close, and the volume is 10 + 2. + peer.release(); + see( + &mut chart, + "a trade after the resume", + &[B3, B4, B5A, F6, R7, R8D], + ); + + // 8. Another symbol: its own history and its own subscription, nothing of the old. + chart.set_symbol("XYZ"); + see(&mut chart, "the other symbol", &[Y0, Y1]); + // 9. Its trade continues its newest bar, in the slot the old symbol's newest bar had: + // 51.0 is the high and the close, and the volume is 80 + 5. + peer.release(); + see(&mut chart, "its trade", &[Y0, Y1E]); + // The chart keeps the trades of the shown symbol only, and so does time and sales: the + // trades of steps 5 and 7, still in the tape, are of the old symbol. + assert_eq!(fed(chart.trades(SeriesId::MAIN).cloned().collect()), [P9]); + assert_eq!(fed(feed.drain_tape("XYZ", Some(Timeframe::Min1))), [P9]); + + let lines: Vec = server.seen().iter().map(|seen| seen.line.clone()).collect(); + assert_eq!(lines.len(), 7, "{lines:?}"); + // The first load, the gap fill and the load after the resume end at the system clock. + for latest in [0, 2, 3] { + assert!( + lines[latest].starts_with("GET /bars?symbol=ABC&interval=1m&to="), + "{lines:?}" + ); + assert!(lines[latest].ends_with("&limit=3"), "{lines:?}"); + } + // Scroll-back asks before the oldest bar held, also after the resume. + assert_eq!( + lines[1], + "GET /bars?symbol=ABC&interval=1m&to=1794407580&limit=3" + ); + assert_eq!(lines[4], lines[1]); + assert!( + lines[5].starts_with("GET /bars?symbol=XYZ&interval=1m&to="), + "{lines:?}" + ); + assert_eq!( + lines[6], + "GET /bars?symbol=XYZ&interval=1m&to=1794407820&limit=3" + ); + // One socket at a time, each opened with the login and the subscription of its symbol. + assert_eq!( + peer.received(), + [[LOGIN, ABC], [LOGIN, ABC], [LOGIN, ABC], [LOGIN, XYZ]] + ); + } + + /// Time and sales lists a trade once while a study reads the chart's symbol on the chart's + /// interval, as Volume Delta does on a one-minute chart: the study's subscription has a + /// socket of its own, which receives the trade again. A second chart on the feed stands for + /// the study. + #[test] + fn a_trade_is_listed_once_while_a_study_streams_the_same_interval() { + use super::super::feed::tests::{Server, profile, shown, until}; + // The bar of midnight on 11 November 2026, which the trade ten seconds later continues. + const BAR: &str = r#"[{"t":1794355200,"o":101.25,"h":101.5,"l":100.0,"c":100.25,"v":700}]"#; + const TRADE: &str = r#"{"type":"trade","data":[{"p":101.75,"s":3,"t":1794355210000}]}"#; + let server = Server::start(|_, seen| { + // A request for bars before the bar held gets none, which ends history. + let older = seen.line.contains("&to=1794355200&"); + let page = if older { "[]" } else { BAR }; + (200, page.to_owned()) + }); + // One socket at a time: the first gets the trade and is closed, then the second gets the + // trade too, and the first one's new socket waits behind it. + let peer = Peer::start(vec![ + vec![ + Step::Receive(1), + Step::Hold, + Step::Send(TRADE), + Step::Close(1000), + ], + vec![Step::Receive(1), Step::Send(TRADE), Step::UntilClosed], + ]); + let key = |name: &str| vec![Segment::Key(name.to_owned())]; + let mut profile = profile(&server.origin); + profile.stream = Some(Stream { + url: peer.url.clone(), + connect: vec![r#"{"symbol":"{symbol}"}"#.to_owned()], + records: key("data"), + route_by: key("type"), + routes: vec![Route { + value: "trade".to_owned(), + kind: RouteKind::Trades(TradeFields { + time: TimeSpec::Instant { + field: key("t"), + unit: TimeUnit::Milliseconds, + }, + price: key("p"), + size: key("s"), + ..TradeFields::default() + }), + }], + ..Stream::default() + }); + let feed = Arc::new(MappedFeed::new(profile, Vec::new())); + let open = || { + ChartBuilder::new() + .with_feed(feed.clone()) + .with_symbol("ABC") + .with_timeframe(Timeframe::Min1) + .with_initial_bars(3) + .build() + }; + let (mut chart, mut study) = (open(), open()); + let ctx = egui::Context::default(); + // Whether the newest bar of a chart holds this volume. + let holds = |volume: f64| { + move |chart: &Chart| { + let newest = shown(chart).last().and_then(|(_, bar)| *bar); + newest.is_some_and(|bar| bar[4] == volume) + } + }; + until(&ctx, &mut chart, "the chart's bar", holds(700.0)); + until(&ctx, &mut study, "the study's bar", holds(700.0)); + peer.release(); + // Both subscriptions fold the trade: 700 + 3. + until(&ctx, &mut chart, "the chart's trade", holds(703.0)); + until(&ctx, &mut study, "the study's trade", holds(703.0)); + let row = |t: &Tick| (t.ts.timestamp_millis(), t.price); + let tape = feed.drain_tape("ABC", Some(Timeframe::Min1)); + let listed: Vec<_> = tape.iter().map(row).collect(); + assert_eq!(listed, [(1794355210000, 101.75)]); + } + + /// Every ready profile reads its service's history rows, bar messages and trade messages, + /// in the form the service documents them, into the chart's bars and trades. The service's + /// hosts are swapped for local ones, so nothing leaves the machine. The fixture is + /// one-minute bars of 11 November 2026 from 14:33 UTC (second 1,794,407,580); every + /// expected bar and request is worked out by hand. + #[test] + fn ready_profiles_chart_recorded_history_and_stream() { + use super::super::feed::tests::{Server, Shown, pages, shown, until}; + use super::super::profile::Profile; + use super::super::store; + + /// A ready profile on recorded answers. The pages answer the history requests in order; + /// the script runs the peer's one connection, each `Hold` until the bars before it are + /// shown. + struct Ready { + name: &'static str, + symbol: &'static str, + timeframe: Timeframe, + pages: Vec, + script: Vec, + /// The bars once history has ended, then after each release of the peer. + bars: Vec>, + /// What the chart and the tape hold at the end: time in ms, price, size, side. + trades: Vec<(i64, f64, f64, Option)>, + tick_size: f64, + /// The start and the end of the first request line, whose bound comes from the + /// clock. + first: (&'static str, &'static str), + /// Every later request line. + asked: Vec<&'static str>, + /// The handshake's target and the messages the peer received. + target: &'static str, + received: Vec<&'static str>, + } + + // Binance: rows of twelve columns, times in milliseconds, values as text. + const R3: &str = r#"[1794407580000,"100750.00","103000.00","100500.00","102500.00","1.50000000",1794407639999,"153375.00000000",120,"0.75000000","76687.50000000","0"]"#; + const R4: &str = r#"[1794407640000,"102500.00","102750.00","101000.00","101250.00","0.75000000",1794407699999,"76312.50000000",64,"0.25000000","25437.50000000","0"]"#; + const R5: &str = r#"[1794407700000,"101250.00","101500.00","100000.00","100250.00","0.50000000",1794407759999,"50437.50000000",41,"0.25000000","25218.75000000","0"]"#; + const KLINE: &str = r#"{"stream":"btcusdt@kline_1m","data":{"e":"kline","E":1794407711000,"s":"BTCUSDT","k":{"t":1794407700000,"T":1794407759999,"s":"BTCUSDT","i":"1m","f":4100,"L":4180,"o":"101250.00","c":"99750.00","h":"101750.00","l":"99750.00","v":"0.75000000","n":81,"x":false,"q":"75687.50000000","V":"0.25000000","Q":"25312.50000000","B":"0"}}}"#; + // `m` is true when the buyer was the maker: the trade sold into the bid. + const SELL: &str = r#"{"stream":"btcusdt@aggTrade","data":{"e":"aggTrade","E":1794407712001,"s":"BTCUSDT","a":2001,"p":"100000.00","q":"0.12500000","f":4181,"l":4182,"T":1794407712000,"m":true,"M":true}}"#; + const BUY: &str = r#"{"stream":"btcusdt@aggTrade","data":{"e":"aggTrade","E":1794407713001,"s":"BTCUSDT","a":2002,"p":"102000.00","q":"0.25000000","f":4183,"l":4183,"T":1794407713000,"m":false,"M":true}}"#; + const B3: Shown = ( + 1794407580, + Some([100750.0, 103000.0, 100500.0, 102500.0, 1.5]), + ); + const B4: Shown = ( + 1794407640, + Some([102500.0, 102750.0, 101000.0, 101250.0, 0.75]), + ); + const B5: Shown = ( + 1794407700, + Some([101250.0, 101500.0, 100000.0, 100250.0, 0.5]), + ); + // The kline takes the place of the history bar. + const K5: Shown = ( + 1794407700, + Some([101250.0, 101750.0, 99750.0, 99750.0, 0.75]), + ); + // The trades continue the kline's bar: the sell at 100000 is the close, volume 0.875; + // the buy at 102000 is the high and the close, volume 1.125. Continuing the history + // bar would give the low 100000 and the volume 0.875. + const K5T: Shown = ( + 1794407700, + Some([101250.0, 102000.0, 99750.0, 102000.0, 1.125]), + ); + + let rows = [Ready { + name: "Binance spot (public)", + symbol: "BTCUSDT", + timeframe: Timeframe::Min1, + // At or before `endTime`, so the older page holds the row that opens at it. That + // row is the symbol's first: the page ends history. + pages: vec![format!("[{R3},{R4},{R5}]"), format!("[{R3}]")], + script: vec![ + Step::Hold, + Step::Send(KLINE), + Step::Hold, + Step::Send(SELL), + Step::Send(BUY), + Step::UntilClosed, + ], + bars: vec![vec![B3, B4, B5], vec![B3, B4, K5], vec![B3, B4, K5T]], + trades: vec![ + (1794407712000, 100000.0, 0.125, Some(OrderSide::Sell)), + (1794407713000, 102000.0, 0.25, Some(OrderSide::Buy)), + ], + tick_size: 0.01, + first: ( + "GET /api/v3/klines?symbol=BTCUSDT&interval=1m&endTime=", + "&limit=3", + ), + // Before the oldest bar held, in milliseconds; the chart asks 600 bars at a time. + asked: vec![ + "GET /api/v3/klines?symbol=BTCUSDT&interval=1m&endTime=1794407580000&limit=600", + ], + target: "/stream?streams=btcusdt@kline_1m/btcusdt@aggTrade", + received: vec![], + }]; + + for row in rows { + let server = Server::start(pages(row.pages)); + let peer = Peer::start(vec![row.script]); + let named = |ready: &Profile| ready.name == row.name; + let mut profile = store::ready().into_iter().find(named).unwrap(); + // The service's address is kept after its host, which is the local one. + let local = |url: &mut String, origin: &str| { + let rest = url.split_once("://").unwrap().1; + let path = rest.find('/').map_or("", |at| &rest[at..]); + *url = format!("{origin}{path}"); + }; + local(&mut profile.history.as_mut().unwrap().url, &server.origin); + local(&mut profile.stream.as_mut().unwrap().url, &peer.url); + let feed = Arc::new(MappedFeed::new(profile, Vec::new())); + let mut chart = ChartBuilder::new() + .with_feed(feed.clone()) + .with_symbol(row.symbol) + .with_timeframe(row.timeframe) + .with_initial_bars(3) + .build(); + let ctx = egui::Context::default(); + for (step, bars) in row.bars.iter().enumerate() { + if step > 0 { + peer.release(); + } + let what = format!("{}, bars {step}", row.name); + until(&ctx, &mut chart, &what, |chart| { + let state = chart.feed_state(SeriesId::MAIN); + state.is_some_and(|state| state.history_complete) && shown(chart) == *bars + }); + } + let fed = |trades: Vec| -> Vec<(i64, f64, f64, Option)> { + let row = |t: &Tick| (t.ts.timestamp_millis(), t.price, t.size, t.side); + trades.iter().map(row).collect() + }; + let held = fed(chart.trades(SeriesId::MAIN).cloned().collect()); + assert_eq!(held, row.trades, "{}", row.name); + let tape = fed(feed.drain_tape(row.symbol, Some(row.timeframe))); + assert_eq!(tape, row.trades, "{}", row.name); + let step = chart + .instrument() + .and_then(|instrument| instrument.tick_size); + assert_eq!(step, Some(row.tick_size), "{}", row.name); + + let lines: Vec = server.seen().iter().map(|seen| seen.line.clone()).collect(); + let (start, end) = row.first; + let first = lines.first().map(String::as_str).unwrap_or_default(); + assert!( + first.starts_with(start) && first.ends_with(end), + "{lines:?}" + ); + assert_eq!(lines[1..], row.asked, "{}", row.name); + assert_eq!(peer.asked(), [row.target], "{}", row.name); + assert_eq!(peer.received(), [row.received], "{}", row.name); + } + } +} diff --git a/vendor/egui-charts/examples/demo/owndata/time.rs b/vendor/egui-charts/examples/demo/owndata/time.rs new file mode 100644 index 0000000..7d1b412 --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/time.rs @@ -0,0 +1,385 @@ +//! Reading the time of a row or record, and printing the bounds of a request. + +use chrono::{ + DateTime, Datelike as _, NaiveDate, NaiveDateTime, NaiveTime, SecondsFormat, TimeDelta, + TimeZone as _, Timelike as _, Utc, +}; +use egui_charts::model::TimezoneId; +use serde_json::Value; + +use super::profile::{ + ClockUnit, DateFormat, FieldPath, RangeFormat, TimeSpec, TimeUnit, at, number, +}; + +/// When a row or record happened. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Stamp { + /// An instant. + At(DateTime), + /// A calendar date without a time of day: a bar dated on that day. + On(NaiveDate), +} + +/// The time of `record` as `spec` describes it. `zone` is the profile's time zone; it applies +/// to a date with a time of day and to ISO 8601 text without an offset. `None` when a field is +/// missing, is `null`, or does not read as the form `spec` names. +pub(crate) fn stamp(record: &Value, spec: &TimeSpec, zone: &TimezoneId) -> Option { + match spec { + TimeSpec::Instant { field, unit } => { + let value = at(record, field)?; + let per_second = match unit { + TimeUnit::Seconds => 1, + TimeUnit::Milliseconds => 1_000, + TimeUnit::Microseconds => 1_000_000, + TimeUnit::Nanoseconds => 1_000_000_000, + TimeUnit::Iso8601 => return iso(value.as_str()?, zone), + }; + unix(value, per_second).map(Stamp::At) + } + TimeSpec::Wall { + date, + format, + clock, + } => { + let date = date_of(at(record, date)?, format)?; + let Some(clock) = clock else { + return Some(Stamp::On(date)); + }; + let time = time_of_day(at(record, &clock.field)?, &clock.unit)?; + wall(date.and_time(time), zone).map(Stamp::At) + } + } +} + +/// The instant `value` names in a Unix unit of which `per_second` make a second. +fn unix(value: &Value, per_second: i64) -> Option> { + let whole = match value { + Value::Number(number) => number.as_i64(), + Value::String(text) => text.trim().parse().ok(), + _ => None, + }; + // An integer is read exactly: nanoseconds have 19 digits and a float holds 15 to 17. + if let Some(whole) = whole { + let nanos = whole.rem_euclid(per_second) * (1_000_000_000 / per_second); + return DateTime::from_timestamp(whole.div_euclid(per_second), u32::try_from(nanos).ok()?); + } + let micros = number(value)? * 1e6 / per_second as f64; + // The cast saturates, and a saturated value lies outside the range of `DateTime`. + DateTime::from_timestamp_micros(micros.round() as i64) +} + +/// The time ISO 8601 `text` names. `YYYY-MM-DD` alone is a date. Followed by `T` or a space and +/// a time of day it is a wall time in `zone`, or an instant when `Z` or an offset written +/// `+HH:MM` or `+HHMM` ends it. +fn iso(text: &str, zone: &TimezoneId) -> Option { + let text = text.trim(); + // Every form is ASCII, so a byte position below is a character position. + if !text.is_ascii() || text.len() < 10 { + return None; + } + let (date, rest) = text.split_at(10); + let date = dashed(date)?; + if rest.is_empty() { + return Some(Stamp::On(date)); + } + let rest = rest.strip_prefix(['T', ' '])?; + let (time, offset) = rest.split_at(rest.find(['Z', '+', '-']).unwrap_or(rest.len())); + let local = date.and_time(clock_text(time)?); + let east = match offset { + "" => return wall(local, zone).map(Stamp::At), + "Z" => 0, + offset => { + let (hours, minutes) = match offset.len() { + 6 if offset.as_bytes()[3] == b':' => (&offset[1..3], &offset[4..]), + 5 => (&offset[1..3], &offset[3..]), + _ => return None, + }; + let (hours, minutes) = (digits(hours, 2)?, digits(minutes, 2)?); + if hours > 23 || minutes > 59 { + return None; + } + let seconds = i64::from(hours * 3600 + minutes * 60); + if offset.starts_with('-') { + -seconds + } else { + seconds + } + } + }; + let instant = local + .and_utc() + .checked_sub_signed(TimeDelta::seconds(east))?; + Some(Stamp::At(instant)) +} + +/// The number `text` holds when it is `width` digits and nothing else. +fn digits(text: &str, width: usize) -> Option { + if text.len() != width || !text.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + text.parse().ok() +} + +/// The calendar day `YYYY-MM-DD` names, when it is one. +fn dashed(text: &str) -> Option { + let mut parts = text.split('-'); + let (year, month, day) = (parts.next()?, parts.next()?, parts.next()?); + if parts.next().is_some() { + return None; + } + let year = i32::try_from(digits(year, 4)?).ok()?; + NaiveDate::from_ymd_opt(year, digits(month, 2)?, digits(day, 2)?) +} + +/// The calendar day the eight digits of `YYYYMMDD` name, when they name one. +fn compact(number: u64) -> Option { + let number = u32::try_from(number).ok()?; + if !(10_000_000..100_000_000).contains(&number) { + return None; + } + let year = i32::try_from(number / 10_000).ok()?; + NaiveDate::from_ymd_opt(year, number / 100 % 100, number % 100) +} + +/// The calendar day a date field holds in `format`. +fn date_of(value: &Value, format: &DateFormat) -> Option { + match (format, value) { + (DateFormat::Compact, Value::Number(number)) => compact(number.as_u64()?), + (DateFormat::Compact, Value::String(text)) => compact(digits(text.trim(), 8)?.into()), + (DateFormat::Dashed, Value::String(text)) => dashed(text.trim()), + _ => None, + } +} + +/// The reading of the wall clock a time-of-day field holds in `unit`. +fn time_of_day(value: &Value, unit: &ClockUnit) -> Option { + let per_second = match unit { + ClockUnit::Milliseconds => 1e3, + ClockUnit::Seconds => 1.0, + ClockUnit::Text => return clock_text(value.as_str()?.trim()), + }; + let micros = (number(value)? * 1e6 / per_second).round(); + if !(0.0..86_400e6).contains(µs) { + return None; + } + let micros = micros as u64; + let (seconds, nanos) = (micros / 1_000_000, micros % 1_000_000 * 1_000); + NaiveTime::from_num_seconds_from_midnight_opt( + u32::try_from(seconds).ok()?, + u32::try_from(nanos).ok()?, + ) +} + +/// The time of day `HH:MM`, `HH:MM:SS` or `HH:MM:SS.fff` names. +fn clock_text(text: &str) -> Option { + NaiveTime::parse_from_str(text, "%H:%M:%S%.f") + .or_else(|_| NaiveTime::parse_from_str(text, "%H:%M")) + .ok() +} + +/// The instant of the wall time `local` in `zone`: the first of two when clocks go back, the +/// instant of the change when clocks go forward over it. +pub(crate) fn wall(local: NaiveDateTime, zone: &TimezoneId) -> Option> { + let instant = |local: &NaiveDateTime| { + let first = zone.from_local_datetime(local).earliest()?; + Some(first.to_utc()) + }; + if let Some(instant) = instant(&local) { + return Some(instant); + } + // The wall time does not occur. The first second after it that does is the change. + let mut local = local.with_nanosecond(0)?; + for _ in 0..=24 * 60 * 60 { + local = local.checked_add_signed(TimeDelta::seconds(1))?; + if let Some(instant) = instant(&local) { + return Some(instant); + } + } + None +} + +/// The reading of the time field at `field` that fits `value` best: ISO 8601 for text that +/// reads as it, a date for eight digits that are a calendar day between 1900 and 2100, and +/// otherwise the Unix unit whose magnitude fits (below 1e11 seconds, below 1e14 milliseconds, +/// below 1e17 microseconds, else nanoseconds). The dialog offers it and the user can change it. +pub(crate) fn guess(field: FieldPath, value: &Value) -> TimeSpec { + let text = value.as_str(); + let format = match text.and_then(|text| iso(text, &TimezoneId::utc())) { + Some(Stamp::At(_)) => { + let unit = TimeUnit::Iso8601; + return TimeSpec::Instant { field, unit }; + } + Some(Stamp::On(_)) => Some(DateFormat::Dashed), + None => { + let day = date_of(value, &DateFormat::Compact); + let recent = day.is_some_and(|day| (1900..=2100).contains(&day.year())); + recent.then_some(DateFormat::Compact) + } + }; + if let Some(format) = format { + return TimeSpec::Wall { + date: field, + format, + clock: None, + }; + } + let unit = match number(value).map_or(0.0, f64::abs) { + size if size < 1e11 => TimeUnit::Seconds, + size if size < 1e14 => TimeUnit::Milliseconds, + size if size < 1e17 => TimeUnit::Microseconds, + _ => TimeUnit::Nanoseconds, + }; + TimeSpec::Instant { field, unit } +} + +/// The reading of a time-of-day field that reads `value`: text such as `09:30:00`, else seconds +/// since midnight, else milliseconds since midnight. `held` when none of them reads it. A +/// number below 86,400 is therefore read as seconds; as milliseconds it would fall in the first +/// minute and a half of the day. The dialog offers it and the user can change it. +pub(crate) fn clock_unit(value: &Value, held: ClockUnit) -> ClockUnit { + [ClockUnit::Text, ClockUnit::Seconds, ClockUnit::Milliseconds] + .into_iter() + .find(|unit| time_of_day(value, unit).is_some()) + .unwrap_or(held) +} + +/// `instant` as the text of `{from}` or `{to}`. The two date forms print the calendar day of +/// `instant` in `zone`. +pub(crate) fn print(instant: DateTime, format: &RangeFormat, zone: &TimezoneId) -> String { + match format { + RangeFormat::Seconds => instant.timestamp().to_string(), + RangeFormat::Milliseconds => instant.timestamp_millis().to_string(), + RangeFormat::Microseconds => instant.timestamp_micros().to_string(), + RangeFormat::Nanoseconds => { + let seconds = i128::from(instant.timestamp()) * 1_000_000_000; + (seconds + i128::from(instant.timestamp_subsec_nanos())).to_string() + } + RangeFormat::Iso8601 => instant.to_rfc3339_opts(SecondsFormat::AutoSi, true), + RangeFormat::Date | RangeFormat::CompactDate => { + print_day(instant.with_timezone(zone).date_naive(), format) + } + } +} + +/// `day` as a date form of `{from}` and `{to}` prints it: `20261111` in the compact form and +/// `2026-11-11` in every other. +pub(crate) fn print_day(day: NaiveDate, format: &RangeFormat) -> String { + let form = match format { + RangeFormat::CompactDate => "%Y%m%d", + _ => "%Y-%m-%d", + }; + day.format(form).to_string() +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::super::profile::{Clock, Segment}; + use super::*; + + #[test] + fn every_time_form_reads_as_the_table_says() { + use {ClockUnit as C, DateFormat as D, TimeUnit as U}; + let key = |name: &str| vec![Segment::Key(name.to_owned())]; + let instant = |unit| TimeSpec::Instant { + field: key("t"), + unit, + }; + let wall = |format, unit| TimeSpec::Wall { + date: key("d"), + format, + clock: Some(Clock { + field: key("c"), + unit, + }), + }; + let day = |format| TimeSpec::Wall { + date: key("d"), + format, + clock: None, + }; + let at = |text: &str| Some(Stamp::At(text.parse().unwrap())); + let on = |day: u32| Some(Stamp::On(NaiveDate::from_ymd_opt(2026, 11, day).unwrap())); + const NY: &str = "America/New_York"; + + // One row per form of time, numbered: the mapping, the record, the profile zone and the + // result. Every result was calculated by hand. 2026-11-11 is day 20,768 after + // 1970-01-01, so 14:30 UTC on it is second 20,768 * 86,400 + 52,200 = 1,794,407,400. + // New York is five hours behind UTC on that day and four on 10 July. Its clocks go + // forward on 8 March 2026 at 07:00 UTC, over 02:30, and back on 1 November at 06:00 UTC, + // so 01:30 occurs at 05:30 UTC and again at 06:30 UTC. + #[rustfmt::skip] + let rows = [ + (1, instant(U::Seconds), json!({"t": 1794407400}), "UTC", at("2026-11-11T14:30:00Z")), + (2, instant(U::Seconds), json!({"t": "1794407400"}), "UTC", at("2026-11-11T14:30:00Z")), + (3, instant(U::Seconds), json!({"t": 1794407400.5}), "UTC", at("2026-11-11T14:30:00.5Z")), + (4, instant(U::Milliseconds), json!({"t": 1794407400123_i64}), "UTC", at("2026-11-11T14:30:00.123Z")), + (5, instant(U::Microseconds), json!({"t": 1794407400123456_i64}), "UTC", at("2026-11-11T14:30:00.123456Z")), + (6, instant(U::Nanoseconds), json!({"t": 1794407400123456789_i64}), "UTC", at("2026-11-11T14:30:00.123456789Z")), + (7, instant(U::Seconds), json!({"t": -2208988800_i64}), "UTC", at("1900-01-01T00:00:00Z")), + (8, instant(U::Iso8601), json!({"t": "2026-11-11T14:30:00Z"}), NY, at("2026-11-11T14:30:00Z")), + (9, instant(U::Iso8601), json!({"t": "2026-11-11T14:30:00.250Z"}), "UTC", at("2026-11-11T14:30:00.25Z")), + (10, instant(U::Iso8601), json!({"t": "2026-11-11T09:30:00-05:00"}), "UTC", at("2026-11-11T14:30:00Z")), + (11, instant(U::Iso8601), json!({"t": "2026-11-11T14:30:00+0000"}), "UTC", at("2026-11-11T14:30:00Z")), + (12, instant(U::Iso8601), json!({"t": "2026-11-11 09:30:00"}), NY, at("2026-11-11T14:30:00Z")), + (13, instant(U::Iso8601), json!({"t": "2026-11-11T09:30"}), NY, at("2026-11-11T14:30:00Z")), + (14, instant(U::Iso8601), json!({"t": "2026-11-11"}), NY, on(11)), + (15, wall(D::Compact, C::Milliseconds), json!({"d": 20261111, "c": 34200000}), NY, at("2026-11-11T14:30:00Z")), + (16, wall(D::Compact, C::Milliseconds), json!({"d": 20260710, "c": 34200000}), NY, at("2026-07-10T13:30:00Z")), + (17, wall(D::Compact, C::Milliseconds), json!({"d": 20260308, "c": 9000000}), NY, at("2026-03-08T07:00:00Z")), + (18, wall(D::Compact, C::Milliseconds), json!({"d": 20261101, "c": 5400000}), NY, at("2026-11-01T05:30:00Z")), + (19, wall(D::Compact, C::Milliseconds), json!({"d": 20261111, "c": 32400000}), "Asia/Tokyo", at("2026-11-11T00:00:00Z")), + (20, wall(D::Dashed, C::Seconds), json!({"d": "2026-11-11", "c": 33300}), "+05:30", at("2026-11-11T03:45:00Z")), + (21, wall(D::Compact, C::Text), json!({"d": "20261111", "c": "09:30:00"}), NY, at("2026-11-11T14:30:00Z")), + (22, day(D::Compact), json!({"d": 20261111}), NY, on(11)), + (23, wall(D::Compact, C::Milliseconds), json!({"d": 20261111, "c": 86400000}), "UTC", None), + (24, wall(D::Compact, C::Milliseconds), json!({"d": 20261341, "c": 0}), "UTC", None), + (25, instant(U::Seconds), json!({"t": "soon"}), "UTC", None), + (25, instant(U::Seconds), json!({"t": null}), "UTC", None), + (25, instant(U::Seconds), json!({"t": true}), "UTC", None), + (25, instant(U::Seconds), json!({}), "UTC", None), + ]; + for (row, spec, record, zone, expected) in rows { + let zone: TimezoneId = zone.parse().unwrap(); + assert_eq!( + stamp(&record, &spec, &zone), + expected, + "row {row}: {record}" + ); + } + + // The bounds of a request, as each form prints them. 03:00 UTC on 11 November is still + // the 10th in New York and already noon of the 11th in Tokyo. + let afternoon: DateTime = "2026-11-11T14:30:00Z".parse().unwrap(); + let night: DateTime = "2026-11-11T03:00:00Z".parse().unwrap(); + for (format, instant, name, expected) in [ + (RangeFormat::Seconds, afternoon, "UTC", "1794407400"), + (RangeFormat::Milliseconds, afternoon, "UTC", "1794407400000"), + ( + RangeFormat::Microseconds, + afternoon, + "UTC", + "1794407400000000", + ), + ( + RangeFormat::Nanoseconds, + afternoon, + "UTC", + "1794407400000000000", + ), + (RangeFormat::Iso8601, afternoon, NY, "2026-11-11T14:30:00Z"), + (RangeFormat::Date, afternoon, NY, "2026-11-11"), + (RangeFormat::Date, night, NY, "2026-11-10"), + (RangeFormat::CompactDate, night, NY, "20261110"), + (RangeFormat::CompactDate, night, "Asia/Tokyo", "20261111"), + ] { + let zone: TimezoneId = name.parse().unwrap(); + assert_eq!( + print(instant, &format, &zone), + expected, + "{format:?} in {name}" + ); + } + } +} diff --git a/vendor/egui-charts/examples/demo/owndata/tree.rs b/vendor/egui-charts/examples/demo/owndata/tree.rs new file mode 100644 index 0000000..ec90243 --- /dev/null +++ b/vendor/egui-charts/examples/demo/owndata/tree.rs @@ -0,0 +1,132 @@ +//! A JSON value drawn as a collapsible tree whose nodes can be clicked. + +use egui::collapsing_header::CollapsingState; +use egui_charts::theme::ThemeExt as _; +use serde_json::Value; + +use super::profile::{FieldPath, Segment}; + +/// The elements of a list that are drawn. The rest is counted. +const LISTED: usize = 50; +/// The characters of a text that are drawn. The rest is cut. +const SHOWN: usize = 80; + +/// Draws `value` and returns the path of the node the user clicked in this frame, from `value` +/// to the node. `marks` names the nodes already in use, such as `rows` or `open`; each name is +/// drawn after its node. `id` keeps the open and closed state apart from other trees. +/// +/// A scalar is drawn as `key: value` and a container as `key` with its size. The tree is open +/// down to the second level and along the first element of every list; text over 80 characters +/// is cut with an ellipsis; a list shows its first 50 elements and then how many more it has. +pub(crate) fn show( + ui: &mut egui::Ui, + id: egui::Id, + value: &Value, + marks: &[(FieldPath, &str)], +) -> Option { + let mut walk = Walk { + marks, + accent: ui.active_theme().ui.accent, + path: FieldPath::new(), + clicked: None, + }; + walk.node(ui, id, "root", value, false); + walk.clicked +} + +/// The drawing of one tree. +struct Walk<'a> { + marks: &'a [(FieldPath, &'a str)], + /// The colour of a node that a slot uses. + accent: egui::Color32, + /// The way from the root to the node being drawn. + path: FieldPath, + clicked: Option, +} + +impl Walk<'_> { + /// Draws the node called `name` and everything below it. `first` says that it is the + /// first element of a list, which is drawn open. + fn node(&mut self, ui: &mut egui::Ui, id: egui::Id, name: &str, value: &Value, first: bool) { + match value { + Value::Array(list) => { + let text = format!("{name} [{}]", list.len()); + self.container(ui, id, &text, first, |walk, ui| { + for (index, element) in list.iter().take(LISTED).enumerate() { + walk.path.push(Segment::Index(index)); + let name = format!("[{index}]"); + walk.node(ui, id.with(index), &name, element, index == 0); + walk.path.pop(); + } + if list.len() > LISTED { + ui.weak(format!("{} more", list.len() - LISTED)); + } + }); + } + Value::Object(members) => { + let text = format!("{name} {{{}}}", members.len()); + self.container(ui, id, &text, first, |walk, ui| { + for (key, member) in members { + walk.path.push(Segment::Key(key.clone())); + walk.node(ui, id.with(key.as_str()), key, member, false); + walk.path.pop(); + } + }); + } + scalar => { + ui.horizontal(|ui| { + // The width of the arrow of a container, so that the names line up. + ui.add_space(ui.spacing().indent); + self.label(ui, &format!("{name}: {}", shown(scalar))); + }); + } + } + } + + /// Draws a list or an object: a row with an arrow that opens and closes it and a label + /// that selects it, then its `children` when it is open. + fn container( + &mut self, + ui: &mut egui::Ui, + id: egui::Id, + text: &str, + first: bool, + children: impl FnOnce(&mut Self, &mut egui::Ui), + ) { + let open = self.path.len() < 2 || first; + let state = CollapsingState::load_with_default_open(ui.ctx(), id, open); + let header = state.show_header(ui, |ui| self.label(ui, text)); + header.body(|ui| children(self, ui)); + } + + /// Draws the label of the node at `self.path`, which a click selects, and after it the + /// names of the slots that use the node. + fn label(&mut self, ui: &mut egui::Ui, text: &str) { + let slots = self.marks.iter().filter(|(path, _)| *path == self.path); + let slots: Vec<&str> = slots.map(|(_, slot)| *slot).collect(); + let mut shown = egui::RichText::new(text).monospace(); + if !slots.is_empty() { + shown = shown.color(self.accent); + } + if ui.add(egui::Button::new(shown).frame(false)).clicked() { + self.clicked = Some(self.path.clone()); + } + if !slots.is_empty() { + ui.label(egui::RichText::new(slots.join(", ")).color(self.accent)); + } + } +} + +/// A scalar as JSON prints it, a long text cut. +fn shown(value: &Value) -> String { + match value { + Value::String(text) if text.chars().count() > SHOWN => { + let cut: String = text.chars().take(SHOWN).collect(); + let mut shown = Value::String(cut).to_string(); + // Before the closing quote. + shown.insert(shown.len() - 1, '…'); + shown + } + other => other.to_string(), + } +} diff --git a/vendor/egui-charts/examples/demo/replay.rs b/vendor/egui-charts/examples/demo/replay.rs index 48c3f80..b6603cf 100644 --- a/vendor/egui-charts/examples/demo/replay.rs +++ b/vendor/egui-charts/examples/demo/replay.rs @@ -433,6 +433,10 @@ impl DemoApp { } fn open_recording(&mut self, loaded: LoadedRecording) -> Result<(), String> { + // A file picked before own data was entered can arrive after it. + if self.synthetic_only("Replay") { + return Ok(()); + } if loaded.instrument.symbol != self.chart.symbol() { return Err(format!( "Open the {} chart before importing this recording", @@ -684,6 +688,9 @@ impl DemoApp { } pub(super) fn toggle_replay(&mut self) { + if self.synthetic_only("Replay") { + return; + } if self.replay.is_some() && self.replay_control.is_user_dismissed() { self.replay_control.show_control(); } else if self.replay.is_some() || self.replay_selecting { diff --git a/vendor/egui-charts/examples/demo/sampledata.rs b/vendor/egui-charts/examples/demo/sampledata.rs index c2d997c..2785c38 100644 --- a/vendor/egui-charts/examples/demo/sampledata.rs +++ b/vendor/egui-charts/examples/demo/sampledata.rs @@ -382,10 +382,9 @@ pub fn calendar_history( to = DateTime::from_timestamp_millis(hi).unwrap(); } if from == start && to == end { - push(Bar { - time: slot, - ..bar.clone() - }); + let mut whole = bar.clone(); + whole.time = slot; + push(whole); } else { let a = (from - start).num_milliseconds(); let b = (to - start).num_milliseconds(); diff --git a/vendor/egui-charts/examples/demo/storage.rs b/vendor/egui-charts/examples/demo/storage.rs index 349f9ff..8f00f7b 100644 --- a/vendor/egui-charts/examples/demo/storage.rs +++ b/vendor/egui-charts/examples/demo/storage.rs @@ -13,6 +13,8 @@ use std::sync::atomic::{AtomicBool, Ordering}; const KEY: &str = "templates"; /// The key of the document that holds the unnamed workspace between sessions. const WORKSPACE: &str = "workspace"; +/// The key of the document that holds the own-data choice, the profiles and the kept keys. +const OWN_DATA: &str = "own-data"; /// Progress of the unnamed workspace checkpoints. #[derive(Default)] @@ -156,7 +158,8 @@ impl super::DemoApp { /// Stores the unnamed workspace when it changed. A saved layout owns its tab, and an unreadable /// document is never replaced. pub(super) fn checkpoint_workspace(&mut self) { - if self.workspace_recovery.unreadable + if self.own_data.is_some() + || self.workspace_recovery.unreadable || self.layout_is_saved(&self.layout_tabs[self.layout_tab].name) { return; @@ -322,6 +325,20 @@ impl DemoStorage { names } + /// The own-data document, when one is stored. + pub(super) fn own_data(&self) -> Option { + self.documents.lock().unwrap().get(OWN_DATA).cloned() + } + + /// Stores the own-data document. + pub(super) fn save_own_data(&self, document: &str) { + self.documents + .lock() + .unwrap() + .insert(OWN_DATA.to_owned(), document.to_owned()); + self.changed.store(true, Ordering::Relaxed); + } + pub(super) fn save_layout_groups( &self, name: &str, @@ -705,6 +722,86 @@ mod tests { assert!(app.layout.sync == Default::default()); } + /// The first-visit choice is on screen at the first start, each way of answering it is + /// remembered across a restart, an application without storage is not asked, and own data + /// that was connected is on again at the next start. + #[test] + fn the_first_visit_choice_is_asked_once() { + use super::super::owndata::feed::tests::{Server, pages, profile}; + use super::super::owndata::store::Saved; + use super::super::tests::{ui_click, ui_frame}; + const SIZE: egui::Vec2 = egui::vec2(1440.0, 900.0); + /// Three whole frames of the application, and the texts of the last one. + fn frames(app: &mut DemoApp, ctx: &egui::Context) -> Vec<(String, egui::Rect)> { + let mut texts = Vec::new(); + for _ in 0..3 { + texts = ui_frame(ctx, SIZE, vec![], |ui| { + app.ui(ui, &mut eframe::Frame::_new_kittest()); + }); + } + texts + } + fn offered(texts: &[(String, egui::Rect)]) -> bool { + texts.iter().any(|(text, _)| text == "Connect my own data") + } + + for answer in ["Use synthetic data", "Connect my own data", "Escape"] { + let ctx = egui::Context::default(); + let mut storage = AppStorage::default(); + let mut app = restart(&ctx, &storage); + let texts = frames(&mut app, &ctx); + assert!(offered(&texts), "{answer}"); + if answer == "Escape" { + let escape = egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + ui_frame(&ctx, SIZE, vec![escape], |ui| { + app.ui(ui, &mut eframe::Frame::_new_kittest()); + }); + } else { + let button = texts.iter().find(|(text, _)| text == answer); + let at = button.unwrap().1.center(); + ui_click(&ctx, SIZE, at, |ui| { + app.ui(ui, &mut eframe::Frame::_new_kittest()); + }); + } + app.save(&mut storage); + let mut app = restart(&ctx, &storage); + assert!(!offered(&frames(&mut app, &ctx)), "{answer}"); + assert!(app.own_data.is_none(), "{answer}"); + } + + // Without storage the answer could not be remembered, so the choice is not offered. + let ctx = egui::Context::default(); + let mut app = DemoApp::new(&eframe::CreationContext::_new_kittest(ctx.clone())); + app.live.set_paused(true); + assert!(!offered(&frames(&mut app, &ctx))); + + // Own data that was connected is on again at the next start, without a dialog. + let server = Server::start(pages(vec!["[]".to_owned()])); + let ctx = egui::Context::default(); + let mut storage = AppStorage::default(); + let mut app = restart(&ctx, &storage); + let connected = Saved { + asked: true, + own: true, + current: Some("Local".to_owned()), + profiles: vec![profile(&server.origin)], + ..Saved::default() + }; + connected.save(&app.storage); + app.save(&mut storage); + let mut app = restart(&ctx, &storage); + assert!(!offered(&frames(&mut app, &ctx))); + let on_chart = app.own_data.as_ref().map(|own| own.profile.name.as_str()); + assert_eq!(on_chart, Some("Local")); + assert_eq!(app.chart.symbol(), "ABC"); + } + #[test] fn unreadable_workspace_opens_a_default_chart_without_overwriting_the_document() { let ctx = egui::Context::default(); diff --git a/vendor/egui-charts/examples/demo/strategy.rs b/vendor/egui-charts/examples/demo/strategy.rs index 2dffdfa..b898288 100644 --- a/vendor/egui-charts/examples/demo/strategy.rs +++ b/vendor/egui-charts/examples/demo/strategy.rs @@ -148,6 +148,9 @@ impl DemoApp { } pub(super) fn run_sample_backtest(&mut self) { + if self.synthetic_only("Strategy tester") { + return; + } self.stop_live_strategy(); let bars = self.chart.bars(SeriesId::MAIN); // The newest bar can still change. Bound this synchronous demonstration to 121 opens. @@ -228,7 +231,7 @@ impl DemoApp { self.state.chart_type = kind; self.top_toolbar.chart_type_selector.current = kind; self.chart.set_chart_type(kind); - self.size_price_based_charts(); + self.size_range_interval(); } if clear { self.stop_live_strategy(); @@ -326,6 +329,9 @@ impl DemoApp { /// Keep the existing live analytics when a finished report also supplies fill markers. pub(super) fn refresh_strategy_signals(&mut self) { + if self.own_data.is_some() { + return; + } for (chart, live) in std::iter::once((&mut self.chart, &self.live)).chain( self.extra_charts .iter_mut() diff --git a/vendor/egui-charts/examples/demo/study_editor.rs b/vendor/egui-charts/examples/demo/study_editor.rs index 4bdd6c4..3a0fb8c 100644 --- a/vendor/egui-charts/examples/demo/study_editor.rs +++ b/vendor/egui-charts/examples/demo/study_editor.rs @@ -374,6 +374,12 @@ mod tests { .iter() .any(|(text, _)| text == "close - close[2]") ); + // The restarted application has storage: its first-visit choice is already answered. + let answered = super::super::owndata::store::Saved { + asked: true, + ..Default::default() + }; + answered.save(&app.storage); let mut saved = Memory::default(); app.save(&mut saved); let mut cc = eframe::CreationContext::_new_kittest(ctx.clone()); diff --git a/vendor/egui-charts/examples/docs/Cargo.toml b/vendor/egui-charts/examples/docs/Cargo.toml index bea6a67..892bf07 100644 --- a/vendor/egui-charts/examples/docs/Cargo.toml +++ b/vendor/egui-charts/examples/docs/Cargo.toml @@ -21,7 +21,7 @@ eframe = { version = "0.37.0", default-features = false, features = ["x11", "way [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen = "0.2.108" wasm-bindgen-futures = "0.4.58" -web-sys = { version = "0.3.85", features = ["Window", "Document", "Element", "HtmlCanvasElement"] } +web-sys = { version = "0.3.85", features = ["Window", "Document", "Element", "HtmlCanvasElement", "MutationObserver", "MutationObserverInit"] } [profile.wasm-release] inherits = "release" diff --git a/vendor/egui-charts/examples/docs/main.rs b/vendor/egui-charts/examples/docs/main.rs index db9eb1a..292d7aa 100644 --- a/vendor/egui-charts/examples/docs/main.rs +++ b/vendor/egui-charts/examples/docs/main.rs @@ -134,6 +134,19 @@ impl eframe::App for ExampleApp { let window = web_sys::window().unwrap(); let document = window.document().unwrap(); let root = document.document_element().unwrap(); + if self.dark.is_none() { + // Wake when the guide switches the theme, instead of polling for it. + let ctx = ui.ctx().clone(); + let wake = wasm_bindgen::closure::Closure::::new(move || { + ctx.request_repaint(); + }); + let options = web_sys::MutationObserverInit::new(); + options.set_attribute_filter(&vec![String::from("data-theme")].into()); + web_sys::MutationObserver::new(wake.as_ref().unchecked_ref()) + .and_then(|observer| observer.observe_with_options(&root, &options)) + .unwrap(); + wake.forget(); + } let dark = root.get_attribute("data-theme").as_deref() != Some("light"); if self.dark != Some(dark) { self.dark = Some(dark); @@ -157,9 +170,8 @@ impl eframe::App for ExampleApp { if canvas.width() != width || canvas.height() != height { canvas.set_width(width); canvas.set_height(height); + ui.ctx().request_repaint(); } - ui.ctx() - .request_repaint_after(std::time::Duration::from_millis(250)); } egui::CentralPanel::default().show(ui, |ui| { match &mut self.scene { diff --git a/vendor/egui-charts/examples/docs/scenes/order_flow.rs b/vendor/egui-charts/examples/docs/scenes/order_flow.rs index 555a19c..6310fdb 100644 --- a/vendor/egui-charts/examples/docs/scenes/order_flow.rs +++ b/vendor/egui-charts/examples/docs/scenes/order_flow.rs @@ -130,10 +130,8 @@ impl ExecutionDepth { } else { ui.label("Latest depth unavailable until a synchronized snapshot arrives."); } - let config = FootprintConfig { - text_color: ui.active_theme().chart.axis_text, - ..Default::default() - }; + let mut config = FootprintConfig::default(); + config.text_color = ui.active_theme().chart.axis_text; chart.show_footprint(ui, &self.flow, &config); } } diff --git a/vendor/egui-charts/src/chart/coords/mod.rs b/vendor/egui-charts/src/chart/coords/mod.rs index 6b329c3..3ccec2c 100644 --- a/vendor/egui-charts/src/chart/coords/mod.rs +++ b/vendor/egui-charts/src/chart/coords/mod.rs @@ -14,6 +14,7 @@ use egui::{Pos2, Rect}; /// /// Share the mapping with overlays and hit tests to keep them aligned with the pane. #[derive(Clone, Debug)] +#[non_exhaustive] pub struct ChartMapping { /// Numeric row positions shared with the time scale; `None` keeps ordinal spacing. pub numeric_positions: Option, @@ -39,7 +40,7 @@ impl ChartMapping { .as_ref() .map_or(self.bar_spacing, |positions| { let right = self.base_idx as f64 + self.right_offset + 0.5; - let left = right - f64::from(self.rect.width()) / f64::from(self.bar_spacing); + let left = right - f64::from(self.rect.width() - 1.0) / f64::from(self.bar_spacing); self.bar_spacing * positions.min_gap(left, right) as f32 }) } diff --git a/vendor/egui-charts/src/chart/overlays/footprint.rs b/vendor/egui-charts/src/chart/overlays/footprint.rs index 0c10eac..7f24bff 100644 --- a/vendor/egui-charts/src/chart/overlays/footprint.rs +++ b/vendor/egui-charts/src/chart/overlays/footprint.rs @@ -3,7 +3,8 @@ use crate::chart::coords::ChartMapping; use crate::chart::rendering::draw_dashed_line; use crate::data::{Footprint, FootprintBar, FootprintLevel, NodeSensitivity}; -use crate::model::{Bar, ChartTypeParams, FootprintStatistic}; +use crate::localization as l10n; +use crate::model::{Bar, ChartTypeParams, FootprintStatistic, SessionProvider}; use crate::theme::ThemeExt; use egui::epaint::{Galley, Mesh, Shape}; use egui::{Align2, Color32, FontId, Painter, Rect, Stroke, StrokeKind, pos2, vec2}; @@ -25,6 +26,7 @@ pub use crate::model::{FootprintColor, FootprintMode}; /// it with its chart settings; fields missing from older documents take their defaults. #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(default)] +#[non_exhaustive] pub struct FootprintConfig { /// One to four columns per bar; only the first four entries are drawn. pub modes: Vec, @@ -36,6 +38,12 @@ pub struct FootprintConfig { pub ask_color: Color32, /// Sell colour. pub bid_color: Color32, + /// Buy colour of imbalance strips, imbalance colouring and stacked imbalance zones, or + /// `None`, the default, for `ask_color`. + pub imbalance_ask_color: Option, + /// Sell colour of imbalance strips, imbalance colouring and stacked imbalance zones, or + /// `None`, the default, for `bid_color`. + pub imbalance_bid_color: Option, /// Text colour and POC outline, or POC fill under [`FootprintColor::VolumeSteps`], which /// picks black or white numbers for each cell, or each half of a split cell, instead. The /// default suits a dark chart; set the theme's text colour on a light one, or the fill, lines @@ -66,8 +74,8 @@ pub struct FootprintConfig { /// Compare to the opposite side one price away instead of at the same price. pub diagonal: bool, /// Put a strip along the outer edge of a side that dominates under the imbalance settings, - /// under [`FootprintColor::VolumeSteps`]: in the side's colour, or its strongest shade next to - /// a cell of that colour. + /// under [`FootprintColor::VolumeSteps`]: in the side's imbalance colour, or its strongest + /// shade next to a cell of that colour. pub show_imbalance: bool, /// Outline the highest-volume row when its cells are large enough for the stroke, or fill it /// under [`FootprintColor::VolumeSteps`]. @@ -105,6 +113,11 @@ pub struct FootprintConfig { pub statistics: bool, /// Statistics rows in display order. An empty list hides the table. pub statistics_rows: Vec, + /// Restart the cumulative delta row of the statistics at the first bar of each trading day, + /// or of each session of the chart's session provider, rather than summing every complete + /// bar. A bar of a day or longer then shows its own delta. Used by the footprint chart type + /// and [`crate::widget::Chart::show_footprint`]. + pub session_cumulative_delta: bool, /// Annotations calculated from the displayed rows after executions or grouping change. /// `None` hides them. Used by the footprint chart type and [`crate::widget::Chart::show_footprint`]. #[cfg(feature = "studies")] @@ -119,6 +132,8 @@ impl Default for FootprintConfig { color_by: FootprintColor::VolumeSteps, ask_color: crate::tokens::DESIGN_TOKENS.semantic.chart.bullish, bid_color: crate::tokens::DESIGN_TOKENS.semantic.chart.bearish, + imbalance_ask_color: None, + imbalance_bid_color: None, text_color: Color32::WHITE, neutral_color: Color32::GRAY, background: None, @@ -143,6 +158,7 @@ impl Default for FootprintConfig { statistics: false, // Keep the existing volume statistics selected; execution metrics are opt-in. statistics_rows: FootprintStatistic::ALL[..9].to_vec(), + session_cumulative_delta: false, #[cfg(feature = "studies")] studies: None, } @@ -159,6 +175,8 @@ impl FootprintConfig { color_by: params.footprint_color_by, ask_color, bid_color, + imbalance_ask_color: params.footprint_imbalance_colors[0], + imbalance_bid_color: params.footprint_imbalance_colors[1], text_color, neutral_color, auto_row_height: (params.footprint_row_ticks == 0).then_some(16.0), @@ -177,6 +195,7 @@ impl FootprintConfig { info_box: params.footprint_info_box, statistics: params.footprint_statistics, statistics_rows: params.footprint_statistics_rows.clone(), + session_cumulative_delta: params.footprint_session_cumulative_delta, #[cfg(feature = "studies")] studies: (params.footprint_stacked_imbalances || params.footprint_naked_poc @@ -204,6 +223,14 @@ impl FootprintConfig { ..Default::default() } } + + /// The sell and buy colours of imbalance marks: their own, or else the side's. + fn imbalance_colors(&self) -> [Color32; 2] { + [ + self.imbalance_bid_color.unwrap_or(self.bid_color), + self.imbalance_ask_color.unwrap_or(self.ask_color), + ] + } } /// The rows of a bar between its close and the extreme it reached beyond the close: from the @@ -283,6 +310,7 @@ pub fn render_footprint( .unwrap_or_else(|| painter.ctx().active_theme().chart.bg) .to_opaque(); let steps = config.color_by == FootprintColor::VolumeSteps; + let imbalance_colors = config.imbalance_colors(); let spine_drawn = !has_ladder(config); // Use the existing half-gap so price markers do not shrink execution columns. let gutter = (mapping.bar_spacing * 0.04).min(2.5); @@ -458,14 +486,14 @@ pub fn render_footprint( imbalances.0 && column == 0, rect.left(), -1.0, - config.bid_color, + imbalance_colors[0], shades[0], ), ( imbalances.1 && column + 1 == columns, rect.right(), 1.0, - config.ask_color, + imbalance_colors[1], shades[1], ), ] { @@ -539,12 +567,11 @@ pub fn render_footprint( ) == (true, true) { if ladder { - let color = [config.bid_color, config.ask_color][side]; - fills[1] = Some((fill, color.gamma_multiply(0.5))); + fills[1] = Some((fill, imbalance_colors[side].gamma_multiply(0.5))); } else { let (bid, ask) = fill.split_left_right_at_x(fill.center().x); - fills[1] = Some((bid, config.bid_color.gamma_multiply(0.5))); - fills[2] = Some((ask, config.ask_color.gamma_multiply(0.5))); + fills[1] = Some((bid, imbalance_colors[0].gamma_multiply(0.5))); + fills[2] = Some((ask, imbalance_colors[1].gamma_multiply(0.5))); } } let inks = if !steps { @@ -747,11 +774,15 @@ pub fn render_footprint( let edge = mapping .price_to_y((level + i64::from(high)) as f64 * step - flow.tick_size() * 0.5); let text = row.ratio().map_or_else( - || "A/B n/a".to_owned(), + || l10n::text(painter.ctx(), "A/B n/a"), |ratio| { - format!( - "A/B {}", - egui::emath::format_with_decimals_in_range(ratio, 0..=2) + l10n::format_text( + painter.ctx(), + "A/B {ratio}", + &[( + "ratio", + egui::emath::format_with_decimals_in_range(ratio, 0..=2), + )], ) }, ); @@ -1238,8 +1269,8 @@ fn cell_color( config.diagonal, config.imbalance_min_volume, ) { - (true, false) => config.bid_color, - (false, true) => config.ask_color, + (true, false) => config.imbalance_colors()[0], + (false, true) => config.imbalance_colors()[1], _ => config.neutral_color, } } @@ -1248,9 +1279,9 @@ fn cell_color( /// Draws a compact per-bar statistics table under the footprint at the same x coordinates. /// Rows show total, bid, ask, delta, minimum and maximum intrabar delta, cumulative delta, -/// delta percentage and ask/bid ratio (undefined without a denominator). Select execution -/// counts and average size with [`render_footprint_statistics_rows`] or -/// [`FootprintConfig::statistics_rows`] in [`crate::widget::Chart::show_footprint`]. Bars before +/// delta percentage and ask/bid ratio (undefined without a denominator). Select other rows with +/// [`render_footprint_statistics_rows`] or [`FootprintConfig::statistics_rows`] in +/// [`crate::widget::Chart::show_footprint`]. Bars before /// [`Footprint::complete_from`] get no column and no share of the cumulative delta. /// Shared labels occupy the left margin. Numeric columns stay aligned with their bars and /// use unabbreviated volume values when they fit, then compact units. Percentages have one @@ -1266,27 +1297,34 @@ pub fn render_footprint_statistics( flow: &Footprint, text_color: Color32, ) { - render_footprint_statistics_rows( - painter, - mapping, - bars, - flow, + let config = FootprintConfig { text_color, - &FootprintStatistic::ALL[..9], - ); + ..Default::default() + }; + render_footprint_statistics_rows(painter, mapping, bars, flow, &config, None); } -/// Draws the selected statistics in their supplied order, including execution counts and average -/// size. An empty selection draws nothing. Uses the same fitting and clipping rules as -/// [`render_footprint_statistics`]; an undefined average is shown as `n/a`. +/// Draws the rows of [`FootprintConfig::statistics_rows`] in their order and in +/// [`FootprintConfig::text_color`]. An empty selection draws nothing. Uses the same fitting and +/// clipping rules as [`render_footprint_statistics`]; an undefined value is shown as `n/a`. +/// +/// The cumulative delta sums every complete bar. With `sessions` it restarts at the first bar of +/// each session, so a bar's value no longer depends on how much earlier history is loaded. +/// Buy and sell percentages are shares of the bar's total volume, and the volume change is +/// relative to the previous bar with executions and blank for the first; all percentages have +/// one decimal. The range is the bar's high minus its low. The point of control is the lowest +/// price of the highest-volume row among the rows [`render_footprint`] groups for `config` under +/// the price mapping of `mapping`, so it names the row marked in the bar. Range and point of +/// control are written at the decimals of the instrument's tick. pub fn render_footprint_statistics_rows( painter: &Painter, mapping: &ChartMapping, bars: &[Bar], flow: &Footprint, - text_color: Color32, - rows: &[FootprintStatistic], + config: &FootprintConfig, + sessions: Option<&dyn SessionProvider>, ) { + let (rows, text_color) = (config.statistics_rows.as_slice(), config.text_color); if rows.is_empty() { return; } @@ -1304,11 +1342,43 @@ pub fn render_footprint_statistics_rows( .map(|label| label.size().x) .fold(0.0, f32::max) + 8.0; + // The first bar of each session in view, from the session the first bar in view belongs to: + // sessions before it end before any column. + let mut restarts = Vec::new(); + if let (Some(sessions), Some(last)) = ( + sessions.filter(|_| rows.contains(&FootprintStatistic::CumulativeDelta)), + bars.len().checked_sub(1), + ) { + let shown = mapping + .x_to_idx(mapping.rect.left()) + .saturating_sub(1) + .min(last); + let end = mapping + .x_to_idx(mapping.rect.right()) + .saturating_add(2) + .clamp(shown + 1, bars.len()); + let first = bars[..shown].partition_point(|bar| { + sessions + .session_break_between(&bar.time, &bars[shown].time) + .is_some() + }); + restarts.push(first); + restarts.extend( + sessions + .session_breaks(&bars[first..end]) + .into_iter() + .map(|(i, _)| first + i), + ); + } let mut cumulative = 0.0; + let mut last_volume = None; let complete = flow.complete_from(); let mut has_data = false; let mut columns = Vec::new(); for (i, bar) in bars.iter().enumerate() { + if restarts.binary_search(&i).is_ok() { + cumulative = 0.0; + } let Some(row) = flow .bar_at(bar.time) .filter(|_| complete.is_some_and(|from| bar.time >= from)) @@ -1316,6 +1386,8 @@ pub fn render_footprint_statistics_rows( continue; }; cumulative += row.delta(); + let volume = row.volume(); + let previous = last_volume.replace(volume); let x = mapping.idx_to_x(i); if !mapping.is_x_visible(x) { continue; @@ -1326,8 +1398,17 @@ pub fn render_footprint_statistics_rows( { continue; } + let share = |side: f64| (volume > 0.0).then(|| side / volume * 100.0); + let poc = rows + .contains(&FootprintStatistic::PointOfControl) + .then(|| { + let group = row_group(mapping, bar, flow, config); + let step = flow.price_step() * group as f64; + group_bar(row, group).poc().map(|level| level as f64 * step) + }) + .flatten(); let values = [ - Some(row.volume()), + Some(volume), Some(row.bid), Some(row.ask), Some(row.delta()), @@ -1338,10 +1419,18 @@ pub fn render_footprint_statistics_rows( (row.bid > 0.0).then(|| row.ask / row.bid), Some(row.trades() as f64), row.average_size(), + share(row.bid), + share(row.ask), + Some(bar.high - bar.low), + poc, + previous + .filter(|previous| *previous > 0.0) + .map(|previous| (volume - previous) / previous * 100.0), ]; let values: Vec<_> = rows.iter().map(|row| values[*row as usize]).collect(); - columns.push((x, values)); + columns.push((x, previous.is_none(), values)); } + let decimals = crate::scales::decimals(flow.tick_size()); let mut size = 10.0; let mut fitted = Vec::new(); if mapping.bar_spacing >= 22.0 && rows_fit { @@ -1350,7 +1439,7 @@ pub fn render_footprint_statistics_rows( size = font_size; fitted = columns .iter() - .map(|(x, values)| { + .map(|(x, first, values)| { ( *x, values @@ -1358,18 +1447,29 @@ pub fn render_footprint_statistics_rows( .copied() .enumerate() .map(|(line, value)| { - let text = value.map_or_else( - || "n/a".to_owned(), - |value| match rows[line] { - FootprintStatistic::DeltaPercent => { - format!("{value:.1}%") - } - FootprintStatistic::AskBidRatio => { - format!("{value:.2}:1") - } - _ => volume_text(value, abbreviate), - }, - ); + let text = match (rows[line], value) { + // The first bar has no bar to change from. + (FootprintStatistic::VolumeChange, None) if *first => { + String::new() + } + (_, None) => "n/a".to_owned(), + ( + FootprintStatistic::DeltaPercent + | FootprintStatistic::BidPercent + | FootprintStatistic::AskPercent + | FootprintStatistic::VolumeChange, + Some(value), + ) => format!("{value:.1}%"), + (FootprintStatistic::AskBidRatio, Some(value)) => { + format!("{value:.2}:1") + } + ( + FootprintStatistic::Range + | FootprintStatistic::PointOfControl, + Some(value), + ) => format!("{value:.decimals$}"), + (_, Some(value)) => volume_text(value, abbreviate), + }; painter.layout_no_wrap( text, FontId::monospace(size), @@ -1504,6 +1604,7 @@ pub(crate) fn render_footprint_annotations( /// Paints footprint study levels and zones. Compute `studies` only after executions change. /// Stacks, naked POCs and unfinished levels extend to their first revisit, their expiry or the /// last displayed bar, in full colour while unvisited and dimmed once revisited or expired; +/// stacks take the imbalance colour of their side; /// local annotations stay anchored to their originating bar. Delta percentage and ratio markers /// are triangles outside the bar: buy markers above it, sell markers below, the delta marker /// nearest and the ratio marker beyond it. Captions avoid every footprint and its marker rows; details are @@ -1581,12 +1682,10 @@ pub fn render_footprint_studies( continue; } let color = match study.kind { - FootprintStudyKind::StackedBid - | FootprintStudyKind::DeltaBid - | FootprintStudyKind::RatioBid => config.bid_color, - FootprintStudyKind::StackedAsk - | FootprintStudyKind::DeltaAsk - | FootprintStudyKind::RatioAsk => config.ask_color, + FootprintStudyKind::StackedBid => config.imbalance_colors()[0], + FootprintStudyKind::StackedAsk => config.imbalance_colors()[1], + FootprintStudyKind::DeltaBid | FootprintStudyKind::RatioBid => config.bid_color, + FootprintStudyKind::DeltaAsk | FootprintStudyKind::RatioAsk => config.ask_color, _ => config.text_color, }; let color = match study.state { @@ -1656,21 +1755,32 @@ pub fn render_footprint_studies( (opposite > 0.0).then(|| format!("{:.2}:1", side / opposite)) }), }; - hovered.push(format!("{label}: {}", value.as_deref().unwrap_or("n/a"))); + let ctx = painter.ctx(); + let value = value.unwrap_or_else(|| l10n::text(ctx, "n/a")); + hovered.push(l10n::format_text( + ctx, + "{label}: {value}", + &[("label", l10n::text(ctx, label)), ("value", value)], + )); } continue; } if pointer.is_some_and(|p| rect.expand(2.0).contains(p)) { - let state = match study.state { - FootprintStudyState::Unvisited => "unvisited", - FootprintStudyState::Revisited => "revisited", - FootprintStudyState::Expired => "expired", - FootprintStudyState::Local => "this bar", + let key = match study.state { + FootprintStudyState::Unvisited => "{label}: {low} to {high} (unvisited)", + FootprintStudyState::Revisited => "{label}: {low} to {high} (revisited)", + FootprintStudyState::Expired => "{label}: {low} to {high} (expired)", + FootprintStudyState::Local => "{label}: {low} to {high} (this bar)", }; - hovered.push(format!( - "{label}: {} to {} ({state})", - study.low as f64 * flow.price_step(), - study.high as f64 * flow.price_step(), + let ctx = painter.ctx(); + hovered.push(l10n::format_text( + ctx, + key, + &[ + ("label", l10n::text(ctx, label)), + ("low", (study.low as f64 * flow.price_step()).to_string()), + ("high", (study.high as f64 * flow.price_step()).to_string()), + ], )); } if !detail { @@ -2663,11 +2773,13 @@ mod tests { } } } - for (minimum, middle, zone) in [ - (0.0, true, true), - (9.0, true, true), - (10.0, false, false), - (0.0, true, true), + for (minimum, middle, zone, own) in [ + (0.0, true, true, None), + (9.0, true, true, None), + (10.0, false, false, None), + (0.0, true, true, None), + // An imbalance colour of its own replaces the buy colour in cells and zones. + (0.0, true, true, Some(Color32::from_rgb(255, 0, 255))), ] { let config = FootprintConfig { color_by: FootprintColor::Imbalance, @@ -2676,6 +2788,7 @@ mod tests { show_poc: false, auto_row_height: (ticks == 1).then_some(20.0), imbalance_min_volume: minimum, + imbalance_ask_color: own, studies: Some(crate::studies::FootprintStudyConfig { naked_poc: false, delta_poc: false, @@ -2702,14 +2815,10 @@ mod tests { }, ); output.textures_delta.clear(); + let buy = own.unwrap_or(config.ask_color); for (price, active) in [(102.0, true), (104.0, middle), (106.0, true)] { let top = map.price_to_y(price + 1.5); - let color = if active { - config.ask_color - } else { - config.neutral_color - } - .gamma_multiply(0.5); + let color = if active { buy } else { config.neutral_color }.gamma_multiply(0.5); let filled = output.shapes.iter().any(|s| match &s.shape { Shape::Mesh(mesh) => mesh .vertices @@ -2719,9 +2828,10 @@ mod tests { }); assert!(filled, "ticks {ticks}, minimum {minimum}, price {price}"); } - let has_zone = output.shapes.iter().any( - |s| matches!(&s.shape, Shape::Rect(r) if r.stroke.color == config.ask_color), - ); + let has_zone = output + .shapes + .iter() + .any(|s| matches!(&s.shape, Shape::Rect(r) if r.stroke.color == buy)); assert_eq!(has_zone, zone, "ticks {ticks}, minimum {minimum}"); } } @@ -2730,6 +2840,13 @@ mod tests { /// Shared row labels and complete numeric columns survive narrow detail widths; a short pane /// reports unavailable detail instead of clipping a row. The first bar has 13 buys and 3 sells: /// delta 10, 62.5%, ask/bid 4.33:1, three executions averaging 16/3; the second adds 2500 sells. + /// + /// The tallest pane holds every row. Of the first bar's volume of 16, 3 sold are 18.75% and + /// 13 bought 81.25%, written to the even digit as 18.8% and 81.2%; it ranges from 100.00 to + /// 100.25, and has no bar to change from. Rows of 0.25 are 11.3 points tall here, so the + /// footprint draws them in pairs and both bars have their point of control in the row at + /// 100.00, where the busiest price of the first is 100.25. The second bar trades 2500 after + /// 16, a change of 2484 / 16 = 15525%, all of it sold, at one price. #[test] fn statistics_keep_shared_rows_and_aligned_values_or_explain_the_overview() { let time = "2026-01-05T10:00:00Z".parse().unwrap(); @@ -2757,9 +2874,16 @@ mod tests { (40.0, true, true, 136.0), (60.0, true, false, 90.0), (60.0, true, false, 112.0), + (60.0, true, false, 196.0), ] { // The default renderer keeps its nine rows, which fit the panes hosts already reserve. - let count = if height == 112.0 { 9 } else { 11 }; + let count = if height == 112.0 { + 9 + } else if height == 196.0 { + 16 + } else { + 11 + }; let rect = Rect::from_min_size(rect.min, vec2(rect.width(), height)); let mut shown = flow.clone(); let mut bars = bars.clone(); @@ -2798,13 +2922,18 @@ mod tests { if count == 9 { render_footprint_statistics(ui.painter(), &map, &bars, flow, Color32::WHITE) } else { + let config = FootprintConfig { + text_color: Color32::WHITE, + statistics_rows: FootprintStatistic::ALL[..count].to_vec(), + ..Default::default() + }; render_footprint_statistics_rows( ui.painter(), &map, &bars, flow, - Color32::WHITE, - &FootprintStatistic::ALL, + &config, + None, ) } }, @@ -2855,16 +2984,17 @@ mod tests { for (column, expected) in [ [ "16", "3", "13", "10", "-3", "10", "10", "62.5%", "4.33:1", "3", "5.333", + "18.8%", "81.2%", "0.25", "100.00", "", ], if large { [ "123.5M", "123.5M", "0", "-123.5M", "-123.5M", "0", "-123.5M", "-100.0%", - "0.00:1", "2", "61.7M", + "0.00:1", "2", "61.7M", "", "", "", "", "", ] } else { [ "2500", "2500", "0", "-2500", "-2500", "0", "-2490", "-100.0%", "0.00:1", - "1", "2500", + "1", "2500", "100.0%", "0.0%", "0.00", "100.00", "15525.0%", ] }, ] @@ -2883,6 +3013,72 @@ mod tests { } } + /// A delta of 5 in the last bar of a UTC day and 2 in the first bar of the next: summed over + /// every bar the row reads 5 and then 7, restarted with the day 5 and then 2. + #[test] + fn cumulative_delta_restarts_with_the_session_when_given_sessions() { + let last: chrono::DateTime = "2026-01-05T23:59:00Z".parse().unwrap(); + let first = last + chrono::TimeDelta::minutes(1); + let mut flow = Footprint::new(BarClock::new(Timeframe::Min1), 1.0, 1).unwrap(); + for (at, size) in [(last, 5.0), (first, 2.0)] { + flow.push(&Tick::new(at, 100.0, size, Some(OrderSide::Buy))) + .unwrap(); + } + let bars = [last, first].map(|time| Bar::new(time, 100.0, 100.0, 100.0, 100.0, 1.0)); + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(240.0, 16.0)); + let map = ChartMapping::new( + rect, + 60.0, + 0, + 1, + 0.0, + PriceMap::new( + PriceTransform::default(), + PriceRange::new(99.0, 102.0), + 0.0, + 16.0, + false, + ), + ); + let config = FootprintConfig { + statistics_rows: vec![FootprintStatistic::CumulativeDelta], + ..Default::default() + }; + let days = + crate::model::ExchangeSessionProvider::new(crate::model::TimezoneId::utc(), None); + for (sessions, expected) in [ + (None, ["CVD", "5", "7"]), + (Some(&days as &dyn SessionProvider), ["CVD", "5", "2"]), + ] { + let mut output = egui::Context::default().run_ui( + egui::RawInput { + screen_rect: Some(rect), + ..Default::default() + }, + |ui| { + render_footprint_statistics_rows( + ui.painter(), + &map, + &bars, + &flow, + &config, + sessions, + ); + }, + ); + output.textures_delta.clear(); + let texts: Vec<_> = output + .shapes + .iter() + .filter_map(|s| match &s.shape { + Shape::Text(t) => Some(t.galley.text()), + _ => None, + }) + .collect(); + assert_eq!(texts, expected, "restarting: {}", sessions.is_some()); + } + } + /// OHLC ticks use exact prices even inside grouped rows and on inverted mappings. /// Identical execution delta must not hide opposite price directions. #[test] @@ -3539,6 +3735,36 @@ mod tests { ); } + /// A buy imbalance colour of its own paints the strip and leaves the cell it marks in the + /// buy colour's shade. Rows as above: 40 bought at 103 is the bar's only imbalance. + #[test] + fn imbalance_strip_takes_its_own_colour() { + let rows = [ + (104.0, 10.0, 10.0), + (103.0, 20.0, 40.0), + (102.0, 10.0, 90.0), + (101.0, 60.0, 20.0), + (100.0, 30.0, 10.0), + ]; + let own = Color32::from_rgb(255, 0, 255); + let config = FootprintConfig { + auto_row_height: None, + text_color: Color32::BLACK, + imbalance_ask_color: Some(own), + ..Default::default() + }; + let (shapes, map) = paint_themed(&rows, 120.0, &crate::theme::Theme::light(), &config); + let quads = quads(&shapes); + let y = map.price_to_y(103.0); + // The buy cell ends at the outer edge of the bar's only column. + let edge = map.idx_to_x(0) - 120.0 * 0.46 + 120.0 * 0.92 - 0.5; + let strip = quads.iter().find(|(rect, _)| { + rect.width() <= 3.01 && rect.left() >= edge - 0.01 && rect.y_range().contains(y) + }); + assert_eq!(strip.map(|strip| strip.1), Some(own)); + assert_ne!(color_at(&quads, pos2(edge - 1.0, y)), Some(own)); + } + /// Under the volume step colouring a sell × buy cell is split into a sell half and a buy half. /// On a light chart a half in the weakest quarter needs black text and a half above it white. /// Rows (sell, buy) 104: 10, 50; 103: 10, 20; 102: 50, 50 (POC); 101: 20, 10; 100: 30, 10. Both diff --git a/vendor/egui-charts/src/chart/overlays/liquidity_heatmap.rs b/vendor/egui-charts/src/chart/overlays/liquidity_heatmap.rs index 25636fe..8e8d71c 100644 --- a/vendor/egui-charts/src/chart/overlays/liquidity_heatmap.rs +++ b/vendor/egui-charts/src/chart/overlays/liquidity_heatmap.rs @@ -123,6 +123,14 @@ pub struct LiquidityHeatmap { marks: Option<([u64; 2], [Color32; 2])>, } +impl std::fmt::Debug for LiquidityHeatmap { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("LiquidityHeatmap") + .field("size", &self.size) + .finish_non_exhaustive() + } +} + impl LiquidityHeatmap { /// Draws the history using the pane's price mapping and the host's time-to-x conversion. /// `step` is the instrument tick size times the history's ticks per row. `view` gives the size diff --git a/vendor/egui-charts/src/chart/primitives.rs b/vendor/egui-charts/src/chart/primitives.rs index bbe2c38..5338ee5 100644 --- a/vendor/egui-charts/src/chart/primitives.rs +++ b/vendor/egui-charts/src/chart/primitives.rs @@ -103,6 +103,17 @@ pub struct PanePrimitiveView<'a> { mapping: &'a ChartMapping, } +impl std::fmt::Debug for PanePrimitiveView<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PanePrimitiveView") + .field("pane", &self.pane) + .field("rect", &self.rect) + .field("visible", &self.visible) + .field("bars", &self.bars.len()) + .finish_non_exhaustive() + } +} + impl<'a> PanePrimitiveView<'a> { pub(crate) fn new(pane: PaneId, view: &'a PrimitiveView<'_>) -> Self { Self { @@ -311,6 +322,17 @@ pub struct PrimitiveView<'a> { pub(crate) custom: Option>, } +impl std::fmt::Debug for PrimitiveView<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PrimitiveView") + .field("series", &self.series) + .field("mapping", &self.mapping) + .field("visible", &self.visible) + .field("bars", &self.bars.len()) + .finish_non_exhaustive() + } +} + impl PrimitiveView<'_> { /// The points of a series added with /// [`Chart::add_custom_data_series`](crate::widget::Chart::add_custom_data_series), in key diff --git a/vendor/egui-charts/src/chart/rendering/axes/labels.rs b/vendor/egui-charts/src/chart/rendering/axes/labels.rs index 4f59382..833a2f6 100644 --- a/vendor/egui-charts/src/chart/rendering/axes/labels.rs +++ b/vendor/egui-charts/src/chart/rendering/axes/labels.rs @@ -248,14 +248,15 @@ pub(crate) fn time_axis_marks( // The logical indices at the right and left edges of the plot; the left one is negative // when the view reaches before the first bar. let right = coords.base_idx as f64 + coords.right_offset; - let left = right + 1.0 - f64::from(context.rect.width() / coords.bar_spacing); + let left = right + 1.0 - f64::from((context.rect.width() - 1.0) / coords.bar_spacing); let (left, right) = coords .numeric_positions .as_ref() .map_or((left.floor(), right), |positions| { let right = right + 0.5; - let left = right - f64::from(context.rect.width()) / f64::from(coords.bar_spacing); + let left = + right - f64::from(context.rect.width() - 1.0) / f64::from(coords.bar_spacing); ( (positions.index(left) + 0.5).floor(), positions.index(right) - 0.5, @@ -1603,6 +1604,37 @@ mod tests { } } + /// The whitespace left of the shortest maturity extrapolates keys below zero, which are + /// no maturities: the axis labels none of them. + #[test] + fn maturity_axis_labels_no_key_below_zero() { + use crate::scales::{MaturityScale, key_time}; + let bars = [3.0, 12.0, 36.0] + .iter() + .map(|&key| Bar::from_value(key_time(key).unwrap(), 4.0)) + .collect(); + let mut chart = Chart::new(BarData::from_bars(bars)); + chart.set_horizontal_scale(Some(std::sync::Arc::new(MaturityScale::default()))); + let ctx = Context::default(); + frame(&ctx, &mut chart, 0.0, vec![]); + let painted = shapes(&ctx, &mut chart, 0.1, vec![]); + let plot = chart.get_rendered_price_rect(); + let labels: Vec = painted + .iter() + .filter_map(|shape| match shape { + Shape::Text(text) if text.pos.y >= plot.bottom() && text.pos.x < plot.right() => { + Some(text.galley.text().to_owned()) + } + _ => None, + }) + .collect(); + assert!(labels.iter().any(|label| label == "3Y"), "{labels:?}"); + assert!( + labels.iter().all(|label| !label.starts_with('-')), + "{labels:?}" + ); + } + /// Whitespace keys stop at chrono's date limits and stay bounded at a host's tiny minimum /// bar spacing, so the chart renders a frame at either limit. #[test] diff --git a/vendor/egui-charts/src/chart/rendering/axes/mod.rs b/vendor/egui-charts/src/chart/rendering/axes/mod.rs index 12c7dd3..cd090e8 100644 --- a/vendor/egui-charts/src/chart/rendering/axes/mod.rs +++ b/vendor/egui-charts/src/chart/rendering/axes/mod.rs @@ -341,12 +341,31 @@ pub(crate) fn render_primitive_time_label( Some(tag.intersect(axis)) } -/// Last-bar values of visible study lines, in the same units and colours as their plot. +/// The last bar `coords` shows, partly or whole, as in the chart's visible range, or `None` when +/// the view ends before the first bar. A view past the newest bar gives an index past the data. +pub(crate) fn last_bar_in_view(coords: &crate::chart::coords::ChartMapping) -> Option { + // The slot of bar `i` spans `i - 0.5..i + 0.5`; the plot's last pixel ends the view. + let last = (coords.x_to_idx_f64(coords.rect.right() - 1.0) - 0.5).ceil(); + (last >= 0.0).then_some(last as usize) +} + +/// The bar a study's value tags read: `last_in_view`, the last bar in view, or the study's last +/// bar when the view reaches past it. `None` without values or without bars in view. +pub(crate) fn study_tag_bar( + study: &dyn crate::studies::Indicator, + last_in_view: Option, +) -> Option { + Some(study.values().len().checked_sub(1)?.min(last_in_view?)) +} + +/// Values of visible study lines at the bar [`study_tag_bar`] gives for `last_in_view`, in the +/// same units and colours as their plot. pub(crate) fn render_study_tags( painter: &Painter, plot: Rect, map: &PriceMap, study: &dyn crate::studies::Indicator, + last_in_view: Option, axis_right: f32, occupied: &mut Vec>, formatter: Option<&dyn crate::scales::PriceFormatter>, @@ -358,8 +377,7 @@ pub(crate) fn render_study_tags( { return; } - let values = study.values(); - let Some(bar) = values.len().checked_sub(1) else { + let Some(bar) = study_tag_bar(study, last_in_view) else { return; }; let transform = map.transform(); @@ -565,6 +583,15 @@ pub fn price_axis_width( price_axis_width_with_edges(painter, price_map, tag_labels, formatter, None) } +/// Width of an axis column that holds each of `tags` whole, with the plot gap and right +/// clearance of the labels. +pub(crate) fn axis_tags_width<'a>(tags: impl IntoIterator>) -> f32 { + tags.into_iter() + .flatten() + .map(|tag| tag.width() + 5.0 + 6.0) + .fold(0.0, f32::max) +} + /// Measures the list painted by an axis, including edge ticks when `pane` is present. pub(crate) fn price_axis_width_with_edges( painter: &Painter, @@ -1533,6 +1560,7 @@ mod tests { plot, &map, &study, + Some(usize::MAX), 120.0, &mut Vec::new(), None, diff --git a/vendor/egui-charts/src/chart/rendering/axes/study_scale.rs b/vendor/egui-charts/src/chart/rendering/axes/study_scale.rs index e757048..95dbd98 100644 --- a/vendor/egui-charts/src/chart/rendering/axes/study_scale.rs +++ b/vendor/egui-charts/src/chart/rendering/axes/study_scale.rs @@ -3,7 +3,6 @@ use super::super::ChartMapping; use crate::scales::{PriceMap, PriceRange, PriceTransform}; use crate::studies::{Indicator, PlotType, StudyScale}; -use crate::theme::ThemeExt; use egui::{Align2, Painter, Pos2, Rect}; /// Keep independent study units out of the main price map, including hidden scales. @@ -106,7 +105,9 @@ pub(crate) fn fit_study_mapping( } } -/// Paint an independent study axis in its reserved gutter beside the plot. +/// Paint an independent study axis in its reserved gutter beside the plot. Each label is in +/// `text`, or in the colour that reads on its tag, on a plate in the colour `background` gives +/// for the chart background behind it. pub(crate) fn render_study_axis( painter: &Painter, studies: &[&dyn Indicator], @@ -114,12 +115,13 @@ pub(crate) fn render_study_axis( axis: Rect, axis_options: &crate::config::PriceAxisOptions, relative_formatter: Option<&dyn crate::scales::PriceFormatter>, + text: egui::Color32, + background: &dyn Fn(Pos2) -> egui::Color32, ) -> f32 { let Some(&study) = studies.first() else { return 0.0; }; let painter = painter.with_clip_rect(axis); - let theme = painter.ctx().active_theme(); let font = crate::chart::rendering::axes::axis_font(painter.ctx()); let (x, align) = if axis.left() >= coords.rect.right() { (axis.left() + 8.0, Align2::LEFT_CENTER) @@ -128,11 +130,12 @@ pub(crate) fn render_study_axis( }; let mut width = 0.0_f32; let mut labels = Vec::new(); + let last_in_view = super::last_bar_in_view(coords); for &member in studies { if !axis_options.show_study_values { continue; } - let Some(bar) = member.values().len().checked_sub(1) else { + let Some(bar) = super::study_tag_bar(member, last_in_view) else { continue; }; for line in 0..member.line_count() { @@ -189,9 +192,7 @@ pub(crate) fn render_study_axis( let galley = painter.layout_no_wrap( label, font.clone(), - color.map_or(theme.chart.axis_text, |color| { - crate::chart::rendering::axes::tag_text_color(color) - }), + color.map_or(text, crate::chart::rendering::axes::tag_text_color), ); let rect = align .anchor_size(Pos2::new(x, y), galley.size()) @@ -203,12 +204,12 @@ pub(crate) fn render_study_axis( { continue; } - painter.rect_filled(rect, 0.0, color.unwrap_or(theme.chart.bg)); - painter.galley( - rect.min + egui::vec2(2.0, 2.0), - galley, - theme.chart.axis_text, + painter.rect_filled( + rect, + 0.0, + color.unwrap_or_else(|| background(rect.center())), ); + painter.galley(rect.min + egui::vec2(2.0, 2.0), galley, text); occupied.push(rect); } width @@ -287,6 +288,8 @@ mod tests { axis, &Default::default(), None, + egui::Color32::WHITE, + &|_| egui::Color32::BLACK, ); } }); diff --git a/vendor/egui-charts/src/chart/rendering/candles/area.rs b/vendor/egui-charts/src/chart/rendering/candles/area.rs index 90c1774..ee5e414 100644 --- a/vendor/egui-charts/src/chart/rendering/candles/area.rs +++ b/vendor/egui-charts/src/chart/rendering/candles/area.rs @@ -76,7 +76,8 @@ pub(super) fn render_area( } } -/// HLC Area: fills high to close and close to low, with the high, low and close lines on top +/// HLC Area: fills high to close and close to low, with the high, low and close lines on top. +/// The close line is at the bar closes whatever price source the single-value types plot. pub(super) fn render_hlc_area( painter: &Painter, volume_ctx: &RenderContext, @@ -89,7 +90,6 @@ pub(super) fn render_hlc_area( chart_rect_min_x: f32, idx_to_coord: impl Fn(usize, f32) -> f32, style: &HlcAreaStyle, - price_source: PriceSource, ) { if visible_data.is_empty() { return; @@ -102,7 +102,6 @@ pub(super) fn render_hlc_area( &coords, chart_rect_min_x, &idx_to_coord, - price_source, ); draw_hlc_fill(painter, visible_data, &points, style); @@ -227,18 +226,14 @@ fn collect_hlc_points( coords: &PriceMap, chart_rect_min_x: f32, idx_to_coord: impl Fn(usize, f32) -> f32, - price_source: PriceSource, ) -> Vec { data.iter() .enumerate() - .map(|(i, bar)| { - let value = price_source.compute(bar.open, bar.high, bar.low, bar.close); - HlcPoint { - x: idx_to_coord(start_idx + i, chart_rect_min_x), - y_high: coords.price_to_y(bar.high), - y_low: coords.price_to_y(bar.low), - y_close: coords.price_to_y(value), - } + .map(|(i, bar)| HlcPoint { + x: idx_to_coord(start_idx + i, chart_rect_min_x), + y_high: coords.price_to_y(bar.high), + y_low: coords.price_to_y(bar.low), + y_close: coords.price_to_y(bar.close), }) .collect() } @@ -876,9 +871,15 @@ mod tests { } /// Every line and fill paints its own price band of an asymmetric bar from its own setting, - /// and each can go without the others. + /// and each can go without the others. The close line stays at the closes when the chart's + /// price source, which the single-value chart types plot, is another price. #[test] fn hlc_area_paints_each_line_and_fill_from_its_own_setting() { + use super::super::{ + BarDimensions, CandleDataContext, ChartTypeParams, CoordMapping, HeikinAshiCache, + TradingColors, VolumeSettings, render_chart_type, + }; + use crate::model::{BarClock, ChartType, ChartTypeStyles, Timeframe}; use crate::scales::{PriceRange, PriceTransform}; let rect = Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)); let map = PriceMap::new( @@ -925,9 +926,16 @@ mod tests { let close = (30, 3.0, 40.0); let upper_band = (upper, 30.0, 40.0); let lower_band = (lower, 40.0, 80.0); - for (style, fills, lines) in [ + for (style, source, fills, lines) in [ ( style.clone(), + PriceSource::Close, + vec![upper_band, lower_band], + vec![high, low, close], + ), + ( + style.clone(), + PriceSource::High, vec![upper_band, lower_band], vec![high, low, close], ), @@ -936,6 +944,7 @@ mod tests { high_line_visible: false, ..style.clone() }, + PriceSource::Close, vec![upper_band, lower_band], vec![low, close], ), @@ -944,6 +953,7 @@ mod tests { low_line_visible: false, ..style.clone() }, + PriceSource::Close, vec![upper_band, lower_band], vec![high, close], ), @@ -952,6 +962,7 @@ mod tests { high_to_close_fill_visible: false, ..style.clone() }, + PriceSource::Close, vec![lower_band], vec![high, low, close], ), @@ -960,6 +971,7 @@ mod tests { close_to_low_fill_visible: false, ..style.clone() }, + PriceSource::Close, vec![upper_band], vec![high, low, close], ), @@ -968,27 +980,48 @@ mod tests { close_line: line(30, 0.0), ..style.clone() }, + PriceSource::Close, vec![upper_band, lower_band], vec![high, low], ), ] { + let type_params = crate::model::ChartTypeParams { + styles: ChartTypeStyles { + hlc_area: style, + ..Default::default() + }, + ..Default::default() + }; let ctx = Context::default(); let output = ctx.run_ui(RawInput::default(), |_| { let painter = Painter::new(ctx.clone(), LayerId::background(), rect); let context = RenderContext::new(&painter, rect); - render_hlc_area( - &painter, - &context, - &bars, - 0, - false, - 0.0, - &colors, - &map, - 0.0, + render_chart_type( + ChartType::HlcArea, + &CandleDataContext { + price_ctx: &context, + volume_ctx: &context, + price_scale: &map, + colors: &colors, + visible_data: &bars, + full_data: &bars, + revision: 0, + heikin_ashi: &HeikinAshiCache::default(), + shows_elements: false, + start_idx: 0, + clock: &BarClock::new(Timeframe::Min1), + tick_size: None, + price_formatter: None, + }, + &ChartTypeParams::new( + BarDimensions::new(1.0, 1.0), + VolumeSettings::new(false, 0.0), + &type_params, + TradingColors::new(colors.bullish, colors.bearish), + CoordMapping::new(0.0), + source, + ), |i, _| 10.0 + i as f32 * 50.0, - &style, - PriceSource::Close, ); }); let mut painted_fills = Vec::new(); @@ -1016,8 +1049,8 @@ mod tests { } } output.drop_without_applying_deltas(); - assert_eq!(painted_fills, fills); - assert_eq!(painted_lines, lines); + assert_eq!(painted_fills, fills, "{source:?}"); + assert_eq!(painted_lines, lines, "{source:?}"); } } } diff --git a/vendor/egui-charts/src/chart/rendering/candles/japanese.rs b/vendor/egui-charts/src/chart/rendering/candles/japanese.rs index 02df7ac..0ec2c6c 100644 --- a/vendor/egui-charts/src/chart/rendering/candles/japanese.rs +++ b/vendor/egui-charts/src/chart/rendering/candles/japanese.rs @@ -7,7 +7,7 @@ use crate::model::KagiStyle; use crate::model::kagi::{KagiLine, KagiThickness}; use crate::model::line_break::LineBreakLine; use crate::model::point_figure::PnfColumn; -use crate::model::{Bar, ColumnDirection, RenkoBrick}; +use crate::model::{ColumnDirection, RenkoBrick}; use crate::scales::PriceMap; use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke}; @@ -40,7 +40,7 @@ pub(super) fn render_renko( Stroke::new(1.0, color), ); } - let rect = calc_brick_rect(x, &bar, &coords, bar_width); + let rect = calc_brick_rect(x, bar.open, bar.close, &coords, bar_width); draw_brick(painter, rect, color, 1.0); } } @@ -153,11 +153,18 @@ pub(super) fn render_point_and_figure( // === Helper Functions === -pub(super) fn calc_brick_rect(x: f32, bar: &Bar, coords: &PriceMap, bar_width: f32) -> Rect { - let y_open = coords.price_to_y(bar.open); - let y_close = coords.price_to_y(bar.close); - let top = y_open.min(y_close); - let bottom = y_open.max(y_close); +/// The rectangle of an element between two of its prices, at least 2 points tall and 3 wide. +pub(super) fn calc_brick_rect( + x: f32, + from: f64, + to: f64, + coords: &PriceMap, + bar_width: f32, +) -> Rect { + let y_from = coords.price_to_y(from); + let y_to = coords.price_to_y(to); + let top = y_from.min(y_to); + let bottom = y_from.max(y_to); let height = (bottom - top).max(2.0); let width = bar_width.max(3.0); diff --git a/vendor/egui-charts/src/chart/rendering/candles/mod.rs b/vendor/egui-charts/src/chart/rendering/candles/mod.rs index f384487..500aee6 100644 --- a/vendor/egui-charts/src/chart/rendering/candles/mod.rs +++ b/vendor/egui-charts/src/chart/rendering/candles/mod.rs @@ -96,7 +96,28 @@ pub fn render_chart_type( let price_rect = ctx.price_ctx.rect; let painter = ctx.price_ctx.painter; - if let Some(message) = params.type_params.invalid(chart_type) { + use crate::localization::{format_text, text}; + let egui_ctx = painter.ctx(); + let message = match params.type_params.invalid(chart_type) { + Some(reason) => Some(text(egui_ctx, reason)), + // A size derived from history waits for it, or the loaded bars give it no positive value. + None => params.type_params.bars_needed(chart_type).map(|count| { + let loaded = ctx.full_data.iter().filter(|bar| !bar.is_whitespace()); + match count { + _ if loaded.take(count).count() >= count => text( + egui_ctx, + "The size cannot be calculated from the loaded bars", + ), + 1 => text(egui_ctx, "Waiting for 1 bar of history to size the chart"), + _ => format_text( + egui_ctx, + "Waiting for {count} bars of history to size the chart", + &[("count", count.to_string())], + ), + } + }), + }; + if let Some(message) = message { painter.text( price_rect.center(), egui::Align2::CENTER_CENTER, @@ -269,7 +290,6 @@ pub fn render_chart_type( params.chart_rect_min_x(), &idx_to_coord, ¶ms.type_params.styles.hlc_area, - params.price_source(), ); } ChartType::Columns => { diff --git a/vendor/egui-charts/src/chart/rendering/candles/price_based.rs b/vendor/egui-charts/src/chart/rendering/candles/price_based.rs index 14fdfbe..4f18658 100644 --- a/vendor/egui-charts/src/chart/rendering/candles/price_based.rs +++ b/vendor/egui-charts/src/chart/rendering/candles/price_based.rs @@ -280,53 +280,109 @@ pub(super) fn range_bars( ) } -/// Range bars built from executions, kept until the executions, the range size or the replay -/// cutoff change. +/// Range bars built from executions, after the range bars the chart's bars approximate before +/// the first held trade. The executions are built again when they, the range size or the replay +/// cutoff change, and joined again when the approximated part changes. #[derive(Default)] pub(crate) struct ExecutionRanges { key: Option<(f64, u64, Option>)>, + /// The range bars of the held trades, and the time of the first one. + executions: Option<(Vec, chrono::DateTime)>, + /// The approximated range bars before the bar holding the first held trade, as the cache built + /// them: a new build gives a new `Arc`. Held instead of the build, whose `Rc` is not `Send`. + approximated: Option>, built: Option<(Arc<[Bar]>, bool)>, + /// Whether `built` starts with approximated range bars. + mixed: bool, } impl ExecutionRanges { - /// One bar per range bar of the trades before `cutoff` (all of them without one), and whether - /// older range bars were left out by the bar limit; `trades_revision` identifies `trades`. - /// `None` for an invalid range size or without a trade, when the range bars come from the - /// chart's OHLC bars. + /// One bar per range bar, and whether older range bars were left out by the bar limit. The + /// range bars come from the trades before `cutoff` (all of them without one), after the + /// closed range bars approximated from the bars of `history` that open before the bar of + /// `clock` holding the first such trade; `trades_revision` identifies `trades` and + /// `history_revision` `history`. `None` for an invalid range size, one that waits for + /// history or without a trade, when the range bars come from the chart's OHLC bars alone. pub(crate) fn bars<'a>( &mut self, params: &ChartTypeParams, + history: &[Bar], + history_revision: u64, + clock: &crate::model::BarClock, trades_revision: u64, trades: impl Iterator, cutoff: Option>, ) -> Option<(Arc<[Bar]>, bool)> { - if params.invalid(ChartType::Range).is_some() { + if params.invalid(ChartType::Range).is_some() + || params.bars_needed(ChartType::Range).is_some() + { *self = Self::default(); return None; } let key = (params.range_size, trades_revision, cutoff); if self.key != Some(key) { let mut builder = RangeBarBuilder::new(params.range_size); + let mut first = None; for trade in trades.filter(|t| cutoff.is_none_or(|c| t.ts < c)) { + first.get_or_insert(trade.ts); builder.push_tick(trade); } - let bars: Arc<[Bar]> = builder - .elements() - .iter() + let bars: Vec<_> = (builder.elements().iter()) .map(range_bar::RangeBar::to_bar) .collect(); - self.built = (!bars.is_empty()).then(|| { - let trimmed = bars.len() >= range_bar::MAX_BARS; - (bars, trimmed) - }); + self.executions = first.map(|first| (bars, first)); self.key = Some(key); + self.built = None; + } + let Some((executions, first)) = &self.executions else { + (self.built, self.approximated, self.mixed) = (None, None, false); + return None; + }; + // The bar holding the first trade is left out: the trades from it on replace its OHLC. A + // trade-based bar opens at its first trade, so the last one open by then holds it. + let before = if clock.timeframe().is_some_and(|tf| tf.is_trade_based()) { + history + .partition_point(|bar| bar.time <= *first) + .saturating_sub(1) + } else { + let open = clock.bar_open(*first); + history.partition_point(|bar| clock.bar_open(bar.time) < open) + }; + let approximated = + (before > 0).then(|| range_bars(&history[..before], history_revision, params)); + let unchanged = match (&approximated, &self.approximated) { + (Some(new), Some(old)) => Arc::ptr_eq(&new.bars, old), + (new, old) => new.is_none() && old.is_none(), + }; + if self.built.is_none() || !unchanged { + // The range in progress at the first trade is dropped: the trades open the next one. + let (closed, late_start) = approximated.as_deref().map_or((&[][..], false), |built| { + let open = usize::from(built.builder.has_open_bar()); + (&built.bars[..built.bars.len() - open], built.late_start) + }); + let all = closed.len() + executions.len(); + let skipped = all.saturating_sub(range_bar::MAX_BARS); + let bars: Arc<[Bar]> = closed + .iter() + .chain(executions) + .skip(skipped) + .cloned() + .collect(); + self.built = Some((bars, late_start || all >= range_bar::MAX_BARS)); + self.mixed = closed.len() > skipped; + self.approximated = approximated.map(|built| built.bars.clone()); } self.built.clone() } - /// Whether the last bars came from executions. - pub(crate) fn in_use(&self) -> bool { - self.built.is_some() + /// What the last bars were built from. + pub(crate) fn source(&self) -> crate::model::RangeBarSource { + use crate::model::RangeBarSource::{Executions, OhlcApproximation, OhlcThenExecutions}; + match (&self.built, self.mixed) { + (None, _) => OhlcApproximation, + (Some(_), false) => Executions, + (Some(_), true) => OhlcThenExecutions, + } } } @@ -388,14 +444,15 @@ pub(crate) fn markers<'a>( } /// One bar per kept element, and whether older elements were left out by the element or work limit. -/// Time-based types, invalid parameters and empty builds keep the source bars' axes. +/// Time-based types, invalid parameters, sizes waiting for history and empty builds keep the +/// source bars' axes. pub(crate) fn elements( chart_type: ChartType, params: &ChartTypeParams, bars: &[Bar], revision: u64, ) -> Option<(Arc<[Bar]>, bool)> { - if params.invalid(chart_type).is_some() { + if params.invalid(chart_type).is_some() || params.bars_needed(chart_type).is_some() { return None; } let built = match chart_type { @@ -679,6 +736,62 @@ mod tests { } } + /// A range bar is drawn over its whole range, wherever in it the bar opened. + #[test] + fn range_bars_are_painted_over_their_whole_range() { + use crate::model::BarData; + use crate::widget::{ + Chart, + test_frames::{frame, shapes}, + }; + // With a range of 2, the fall from 100 to 99 and the rise to 101 complete a bar that + // opened at 100, in the middle of its range from 99 to 101. + let start = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(); + let source = [ + (100.0, 100.0, 100.0, 100.0), + (100.0, 100.0, 99.0, 99.0), + (99.0, 101.0, 99.0, 101.0), + ] + .into_iter() + .enumerate() + .map(|(i, (open, high, low, close))| { + let time = start + Duration::minutes(i as i64); + Bar::new(time, open, high, low, close, 1.0) + }) + .collect(); + let mut chart = Chart::new(BarData::from_bars(source)); + chart.set_chart_type_params(ChartTypeParams { + range_size: 2.0, + ..Default::default() + }); + chart.set_chart_type(ChartType::Range); + let ctx = egui::Context::default(); + frame(&ctx, &mut chart, 0.0, vec![]); + frame(&ctx, &mut chart, 0.1, vec![]); + let painted = shapes(&ctx, &mut chart, 0.2, vec![]); + let map = chart.get_chart_mapping(); + let colors = [chart.config().bullish_color, chart.config().bearish_color]; + let first = painted + .iter() + .find_map(|shape| match shape { + egui::Shape::Rect(rect) + if colors.contains(&rect.fill) + && (rect.rect.center().x - map.idx_to_x(0)).abs() < 0.5 => + { + Some(rect.rect) + } + _ => None, + }) + .expect("the first range bar"); + let (top, bottom) = (map.price_to_y(101.0), map.price_to_y(99.0)); + assert!( + (first.top() - top).abs() < 0.01 && (first.bottom() - bottom).abs() < 0.01, + "painted {} to {}, want {top} to {bottom}", + first.top(), + first.bottom() + ); + } + #[test] fn box_sizes_freeze_through_streaming_and_wait_for_history() { use crate::model::{BarData, BoxSizeMethod}; @@ -917,6 +1030,38 @@ mod tests { } } + /// A bar of a trade-based interval opens at its first trade, so the held trades can start + /// inside a bar that opens before them, as after the oldest held trades are dropped. That bar + /// is left out of the approximation: its rise to 104 after the first held trade is drawn once, + /// from the trades. + #[test] + fn range_bars_leave_the_trade_based_bar_of_the_first_trade_to_the_trades() { + let start = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(); + let at = |second| start + Duration::seconds(second); + // Bars of three trades: 99, 99, 100; 100, 100, 101; 101, 101, 104; then 104, 105. + let history = [ + (0, 99.0, 100.0, 99.0, 100.0), + (3, 100.0, 101.0, 100.0, 101.0), + (6, 101.0, 104.0, 101.0, 104.0), + (9, 104.0, 105.0, 104.0, 105.0), + ] + .map(|(second, open, high, low, close)| Bar::new(at(second), open, high, low, close, 3.0)); + // The trades from the second one of the third bar on. + let trades = [(7, 101.0), (8, 104.0), (9, 104.0), (10, 105.0)] + .map(|(second, price)| crate::model::Tick::new(at(second), price, 1.0, None)); + let params = ChartTypeParams { + range_size: 1.0, + ..Default::default() + }; + let clock = crate::model::BarClock::new("3t".parse().unwrap()); + let (bars, _) = ExecutionRanges::default() + .bars(¶ms, &history, 0, &clock, 0, trades.iter(), None) + .unwrap(); + // The first two bars close range bars at 100 and 101, and the trades at 102 to 105. + let closes: Vec<_> = bars.iter().map(|bar| bar.close).collect(); + assert_eq!(closes, [100.0, 101.0, 102.0, 103.0, 104.0, 105.0]); + } + #[test] fn price_based_charts_are_built_over_the_whole_history() { // (name, chart type, params, calls as (bars, revision), expected OHLC ends and minutes) @@ -1041,4 +1186,109 @@ mod tests { .collect(); assert!(failures.is_empty(), "{failures:#?}"); } + + /// The newest close adds no element and lies beyond the elements in view, further than the + /// scale margins of a tenth of the pane reach: the fit holds the last price line and its + /// label all the same. + #[test] + fn last_price_line_stays_in_view_on_price_based_charts() { + use crate::model::{BarData, LineStyle}; + use crate::widget::test_frames::{frame, shapes}; + use crate::widget::{Chart, SeriesId}; + use egui::{Color32, Shape}; + // (chart type, parameters, first open, closes, label of the newest close) + type Row<'a> = (ChartType, ChartTypeParams, Option, &'a [f64], &'a str); + // Lines of 10 from 100 to 340, then 241: above 240, the low of the last ten lines. Any + // close that adds no line lies within those, so this chart is read with fewer in view. + let stairs = Vec::from_iter((1..=24).map(|i| 100.0 + 10.0 * f64::from(i)).chain([241.0])); + let rows: [Row; 4] = [ + // Bricks of 1 from 100 to 103, fitted up to 103.375. + ( + ChartType::Renko, + ChartTypeParams::default(), + None, + &[100.0, 101.2, 102.4, 103.1, 103.4], + "103.40", + ), + // One line from 100 to 102, fitted down to 99.75; 97.5 is short of a reversal of 5. + ( + ChartType::Kagi, + ChartTypeParams { + kagi_reversal: 5.0, + ..Default::default() + }, + None, + &[100.0, 102.0, 97.5], + "97.50", + ), + ( + ChartType::LineBreak, + ChartTypeParams { + line_break_count: 10, + ..Default::default() + }, + Some(100.0), + &stairs, + "241.00", + ), + // One column of boxes of 1 from 100 to 102, fitted up to 102.25. + ( + ChartType::PointAndFigure, + ChartTypeParams::default(), + None, + &[100.0, 102.0, 102.9], + "102.90", + ), + ]; + let mut failures = Vec::new(); + for (kind, params, first_open, closes, label) in rows { + let ctx = egui::Context::default(); + let mut chart = Chart::new(BarData::from_bars(bars(0, closes, first_open))); + chart.set_chart_type_params(params); + chart.set_chart_type(kind); + let style = chart.series_style_mut(SeriesId::MAIN).unwrap(); + style.price_line_color = Some(Color32::GOLD); + style.price_line_style = LineStyle::Solid; + frame(&ctx, &mut chart, 0.0, vec![]); + // About five slots across the plot, the newest element one slot from its right edge. + chart.apply_synced_time_scale(150.0, 1.0); + frame(&ctx, &mut chart, 0.1, vec![]); + let painted = shapes(&ctx, &mut chart, 0.2, vec![]); + let plot = chart.get_rendered_price_rect(); + let y = chart + .get_chart_mapping() + .price_to_y(closes[closes.len() - 1]); + if !painted.iter().any(|shape| { + matches!(shape, + Shape::LineSegment { points, stroke } + if stroke.color == Color32::GOLD + && (points[0].y - y).abs() < 0.1 + && plot.y_range().contains(y) + ) + }) { + let view = chart.state.visible_range(); + failures.push(format!( + "{kind:?}: no last price line at y {y}, {view:?} in view" + )); + } + let tag = painted.iter().find_map(|shape| match shape { + Shape::Rect(rect) + if rect.fill == Color32::GOLD && rect.rect.center().x > plot.right() => + { + Some(rect.rect) + } + _ => None, + }); + if !tag.is_some_and(|tag| { + painted.iter().any(|shape| { + matches!(shape, + Shape::Text(text) if text.galley.text() == label && tag.contains(text.pos) + ) + }) + }) { + failures.push(format!("{kind:?}: no last price label {label}")); + } + } + assert!(failures.is_empty(), "{failures:#?}"); + } } diff --git a/vendor/egui-charts/src/chart/rendering/candles/range.rs b/vendor/egui-charts/src/chart/rendering/candles/range.rs index 0117f6b..33d53a5 100644 --- a/vendor/egui-charts/src/chart/rendering/candles/range.rs +++ b/vendor/egui-charts/src/chart/rendering/candles/range.rs @@ -142,7 +142,7 @@ fn render_high_low_labels( } } -/// Range bars at their element slots. +/// Range bars at their element slots, each over its whole range from its low to its high. pub(super) fn render_range_bars( painter: &Painter, range_bars: &[Bar], @@ -159,7 +159,7 @@ pub(super) fn render_range_bars( } else { bearish_color }; - let rect = calc_brick_rect(x, range_bar, price_scale, bar_width); + let rect = calc_brick_rect(x, range_bar.low, range_bar.high, price_scale, bar_width); painter.add(Shape::rect_filled(rect, 0.0, color)); } } diff --git a/vendor/egui-charts/src/chart/rendering/context.rs b/vendor/egui-charts/src/chart/rendering/context.rs index ee1147d..22dff64 100644 --- a/vendor/egui-charts/src/chart/rendering/context.rs +++ b/vendor/egui-charts/src/chart/rendering/context.rs @@ -11,6 +11,14 @@ pub struct RenderContext<'a> { pub rect: Rect, } +impl std::fmt::Debug for RenderContext<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RenderContext") + .field("rect", &self.rect) + .finish_non_exhaustive() + } +} + impl<'a> RenderContext<'a> { /// Bind a painter to the rectangle available for rendering. pub fn new(painter: &'a Painter, rect: Rect) -> Self { diff --git a/vendor/egui-charts/src/chart/rendering/legend/mod.rs b/vendor/egui-charts/src/chart/rendering/legend/mod.rs index 3ddd4c3..d862b26 100644 --- a/vendor/egui-charts/src/chart/rendering/legend/mod.rs +++ b/vendor/egui-charts/src/chart/rendering/legend/mod.rs @@ -20,6 +20,7 @@ use egui::{Color32, FontId, ImageSource, Pos2, Rect, Sense, Stroke, Ui, Vec2}; use std::sync::Arc; /// A host-supplied status mark. Its text and colours carry no built-in market meaning. +#[derive(Debug)] pub struct LegendStatus<'a> { /// Short text shown beside the instrument title. pub text: &'a str, @@ -146,6 +147,19 @@ pub struct Legend<'a> { /// The rects the chart shades as extended hours under the legend, left to right, and their /// shading. The chart sets it. pub(crate) extended_hours: (&'a [Rect], Color32), + /// The colour of the chart background at a point under the legend, which the backdrops take. + /// The chart sets it; a legend shown on its own has the theme's chart background. + pub(crate) background: Option<&'a dyn Fn(Pos2) -> Color32>, +} + +impl std::fmt::Debug for Legend<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Legend") + .field("symbol", &self.symbol) + .field("timeframe", &self.timeframe) + .field("bar", &self.bar) + .finish_non_exhaustive() + } } impl<'a> Legend<'a> { @@ -183,6 +197,7 @@ impl<'a> Legend<'a> { quantity: None, thousands_sep: None, extended_hours: (&[], Color32::TRANSPARENT), + background: None, } } @@ -241,15 +256,14 @@ impl<'a> Legend<'a> { let id = ui.next_auto_id().with(("series_legend", self.symbol)); ui.skip_ahead_auto_ids(1); let painter = ui.painter().with_clip_rect(plot); + let theme_background = |_: Pos2| theme.chart.bg; let mut layout = Layout::new( &painter, bounds, colors, (first_row_end - theme.spacing.lg).min(bounds.right()), - ( - self.extended_hours.0, - theme.chart.bg.blend(self.extended_hours.1), - ), + self.background.unwrap_or(&theme_background), + self.extended_hours, ); #[cfg(feature = "icons")] let (title_start, title_end) = (layout.pos, layout.row_end); @@ -500,7 +514,7 @@ impl<'a> Legend<'a> { Stroke::new(1.0, theme.ui.accent), egui::StrokeKind::Inside, ); - painter.add(layout.fill(controls, theme.chart.bg)); + painter.add(layout.fill(controls, 1.0)); let flag_response = ui.interact(flag, id.with("flag"), Sense::click()); crate::icons::icons::FLAG_MARK .as_image_tinted( @@ -634,10 +648,7 @@ impl<'a> Legend<'a> { action }); - layout.backdrop = theme - .chart - .bg - .gamma_multiply(self.study_backdrop.clamp(0.0, 1.0)); + layout.backdrop = self.study_backdrop.clamp(0.0, 1.0); let mut study_settings = None; let collapsed = ui .ctx() @@ -809,7 +820,7 @@ impl<'a> Legend<'a> { ui, row, controls, - false, + None, id.with(("study", index)), study.as_ref(), ); @@ -842,7 +853,7 @@ impl<'a> Legend<'a> { painter.rect( rect, 3.0, - painter.ctx().active_theme().chart.bg, + (layout.chart_background)(rect.center()), Stroke::new( 1.0, if theme.dark { @@ -984,9 +995,11 @@ struct Layout<'a> { row_end: f32, height: f32, background: egui::layers::ShapeIdx, - /// Fill of the current row's background. - backdrop: Color32, - /// The rects shaded as extended hours and the background as shaded there. + /// The colour of the chart background at a point. + chart_background: &'a dyn Fn(Pos2) -> Color32, + /// Opacity of the current row's background. + backdrop: f32, + /// The rects shaded as extended hours and their shading. tint: (&'a [Rect], Color32), colors: &'a StyleColors, } @@ -997,6 +1010,7 @@ impl<'a> Layout<'a> { bounds: Rect, colors: &'a StyleColors, first_row_end: f32, + chart_background: &'a dyn Fn(Pos2) -> Color32, tint: (&'a [Rect], Color32), ) -> Self { Self { @@ -1006,45 +1020,52 @@ impl<'a> Layout<'a> { row_end: first_row_end, height: 24.0, background: painter.add(egui::Shape::Noop), - backdrop: painter.ctx().active_theme().chart.bg, + chart_background, + backdrop: 1.0, tint, colors, } } - /// `rect` in `fill`, the chart background at some opacity, and over the extended hours shading + /// `rect` in the chart background behind it at `opacity`, and over the extended hours shading /// in the shaded background at the same opacity, so each part matches the plot beneath. - fn fill(&self, rect: Rect, fill: Color32) -> egui::Shape { - let (shaded, color) = self.tint; - let color = color.gamma_multiply_u8(fill.a()); + fn fill(&self, rect: Rect, opacity: f32) -> egui::Shape { + let (shaded, shade) = self.tint; + let part = |part: Rect, shaded: bool| { + // shortcut: one colour per part, so a steep horizontal gradient shows a step at the + // ends of a wide row; paint the part as a slice of the gradient if that is seen. + let color = (self.chart_background)(part.center()); + let color = if shaded { color.blend(shade) } else { color }; + egui::Shape::rect_filled(part, 0.0, color.gamma_multiply(opacity)) + }; let mut parts = Vec::new(); let mut left = rect.left(); // The parts are disjoint: a shaded part laid over a translucent fill would apply the // opacity twice. - for part in shaded + for shaded in shaded .iter() .map(|shaded| rect.intersect(*shaded)) .filter(Rect::is_positive) { parts.push(( - Rect::from_x_y_ranges(left..=part.left(), rect.y_range()), - fill, + Rect::from_x_y_ranges(left..=shaded.left(), rect.y_range()), + false, )); - parts.push((part, color)); - left = part.right(); + parts.push((shaded, true)); + left = shaded.right(); } if parts.is_empty() { - return egui::Shape::rect_filled(rect, 0.0, fill); + return part(rect, false); } parts.push(( Rect::from_x_y_ranges(left..=rect.right(), rect.y_range()), - fill, + false, )); egui::Shape::Vec( parts .into_iter() - .filter(|(part, _)| part.is_positive()) - .map(|(part, fill)| egui::Shape::rect_filled(part, 0.0, fill)) + .filter(|(rect, _)| rect.is_positive()) + .map(|(rect, shaded)| part(rect, shaded)) .collect(), ) } @@ -1085,13 +1106,11 @@ impl<'a> Layout<'a> { self.backdrop, ), ); - let background = self.painter.ctx().active_theme().chart.bg; - if self.backdrop != background { + let background = (self.chart_background)(rect.center()); + if background.gamma_multiply(self.backdrop) != background { // Profiles can be opaque or contain letters; protect the full content bounds. - self.painter.add(self.fill( - rect.expand(2.0).intersect(self.bounds.expand(2.0)), - background, - )); + self.painter + .add(self.fill(rect.expand(2.0).intersect(self.bounds.expand(2.0)), 1.0)); } rect } diff --git a/vendor/egui-charts/src/chart/rendering/legend/quotes.rs b/vendor/egui-charts/src/chart/rendering/legend/quotes.rs index e6d2980..5d31259 100644 --- a/vendor/egui-charts/src/chart/rendering/legend/quotes.rs +++ b/vendor/egui-charts/src/chart/rendering/legend/quotes.rs @@ -66,7 +66,7 @@ pub(super) fn paint_quotes( Pos2::new(sell_rect.right(), sell_rect.top()), Vec2::new(gap, 34.0), ); - layout.painter.add(layout.fill(spread_rect, theme.chart.bg)); + layout.painter.add(layout.fill(spread_rect, 1.0)); let quantity = quantity.map(|quantity| { let text = layout.painter.layout_no_wrap( compact_quantity(quantity), diff --git a/vendor/egui-charts/src/chart/rendering/legend/study_controls.rs b/vendor/egui-charts/src/chart/rendering/legend/study_controls.rs index ec4ff5b..9145364 100644 --- a/vendor/egui-charts/src/chart/rendering/legend/study_controls.rs +++ b/vendor/egui-charts/src/chart/rendering/legend/study_controls.rs @@ -16,13 +16,13 @@ pub(crate) fn controls_width(study: &dyn crate::studies::Indicator) -> f32 { /// The row outline and its hide, settings, remove, more-actions and help buttons. Returns the first /// three buttons and, when the more-actions button is clicked or the row secondary-clicked, the -/// corner of the study menu. `backdrop` fills the revealed controls with the chart background, for -/// a caller that paints nothing under them. +/// corner of the study menu. `backdrop`, the chart background behind the controls, fills them +/// when they are revealed, for a caller that paints nothing under them. pub(crate) fn study_controls( ui: &mut Ui, row: Rect, controls: Rect, - backdrop: bool, + backdrop: Option, id: egui::Id, study: &dyn crate::studies::Indicator, ) -> ([Response; 3], Option) { @@ -90,9 +90,9 @@ pub(crate) fn study_controls( && ui.rect_contains_pointer(row); let revealed = selected || focused || hovered; if revealed { - if backdrop { + if let Some(backdrop) = backdrop { ui.painter() - .rect_filled(controls, theme.radius.sm, theme.chart.bg); + .rect_filled(controls, theme.radius.sm, backdrop); } ui.painter().rect_stroke( row.union(controls.expand2(Vec2::new(0.0, 2.0))), @@ -213,7 +213,7 @@ mod tests { ui, row, controls, - true, + Some(theme.chart.bg), egui::Id::unique("study"), &crate::studies::CustomIndicator::new("Plain", |_| Vec::new()), ); @@ -366,7 +366,7 @@ mod tests { ui, row, controls, - true, + Some(theme.chart.bg), egui::Id::unique("locked"), &study, ); @@ -441,7 +441,14 @@ mod tests { ..Default::default() }, |ui| { - study_controls(ui, row, controls, true, egui::Id::unique("locked"), &study); + study_controls( + ui, + row, + controls, + Some(theme.chart.bg), + egui::Id::unique("locked"), + &study, + ); }, ); for command in &output.platform_output.commands { diff --git a/vendor/egui-charts/src/chart/rendering/overlays/tooltip.rs b/vendor/egui-charts/src/chart/rendering/overlays/tooltip.rs index fc929c2..6e2e73e 100644 --- a/vendor/egui-charts/src/chart/rendering/overlays/tooltip.rs +++ b/vendor/egui-charts/src/chart/rendering/overlays/tooltip.rs @@ -33,6 +33,12 @@ pub struct ValueFormatters<'a> { pub percentage: Option<&'a dyn PriceFormatter>, } +impl std::fmt::Debug for ValueFormatters<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ValueFormatters").finish_non_exhaustive() + } +} + /// One visible study plot's value at the selected bar. Missing or warming-up values stay absent. #[derive(Clone, Debug, PartialEq)] pub struct StudyValue { diff --git a/vendor/egui-charts/src/chart/rendering/trading_lines/mod.rs b/vendor/egui-charts/src/chart/rendering/trading_lines/mod.rs index ae2fadb..b7eacde 100644 --- a/vendor/egui-charts/src/chart/rendering/trading_lines/mod.rs +++ b/vendor/egui-charts/src/chart/rendering/trading_lines/mod.rs @@ -90,6 +90,7 @@ impl TradingLabelAlignment { } /// What [`render_trading_lines`] drew, and what the user asked for. +#[derive(Debug)] pub struct TradingLines { /// What the user asked for on a line in this frame. pub action: Option, @@ -104,7 +105,7 @@ pub struct TradingLines { } /// What [`render_trading_lines`] draws and offers. -#[derive(Clone)] +#[derive(Debug, Clone)] pub struct TradingLineOptions<'a> { /// Draw orders and their brackets. Hidden orders still identify existing position exits. pub show_orders: bool, diff --git a/vendor/egui-charts/src/chart/selection/mod.rs b/vendor/egui-charts/src/chart/selection/mod.rs index 6909b64..d0a1da6 100644 --- a/vendor/egui-charts/src/chart/selection/mod.rs +++ b/vendor/egui-charts/src/chart/selection/mod.rs @@ -37,6 +37,7 @@ impl SeriesId { /// Read the chart's current selection with [`Chart::selected_element`](crate::Chart::selected_element). /// Series and studies can be selected in the main pane or an additional pane. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] pub enum ChartElementId { /// A bar or volume series. Series(SeriesId), diff --git a/vendor/egui-charts/src/chart/series/hit_test.rs b/vendor/egui-charts/src/chart/series/hit_test.rs index e9ecf26..76a551e 100644 --- a/vendor/egui-charts/src/chart/series/hit_test.rs +++ b/vendor/egui-charts/src/chart/series/hit_test.rs @@ -13,6 +13,7 @@ use super::selection::{SeriesHitResult, SeriesId}; pub const BODY_WIDTH_RATIO: f32 = 0.6; /// Configuration for series hit testing (tolerance, wick inclusion). +#[derive(Debug)] pub struct HitTestConfig { /// Tolerance in pixels for line/wick hits pub line_tolerance: f32, diff --git a/vendor/egui-charts/src/chart/series/settings.rs b/vendor/egui-charts/src/chart/series/settings.rs index 023b0b7..4107a7e 100644 --- a/vendor/egui-charts/src/chart/series/settings.rs +++ b/vendor/egui-charts/src/chart/series/settings.rs @@ -9,6 +9,7 @@ use egui::Color32; /// Settings for chart series appearance #[derive(Clone, Debug)] +#[non_exhaustive] pub struct SeriesSettings { /// Active chart type, used by the dialog to choose the controls to show and by /// [`Chart::apply_series_settings`](crate::widget::Chart::apply_series_settings) to keep diff --git a/vendor/egui-charts/src/config/chart.rs b/vendor/egui-charts/src/config/chart.rs index 3fe59b2..86413f6 100644 --- a/vendor/egui-charts/src/config/chart.rs +++ b/vendor/egui-charts/src/config/chart.rs @@ -81,7 +81,10 @@ fn pixel_conflation_threshold() -> Option { pub struct PriceAxisOptions { /// Allow value tags to overlap instead of moving them to free vertical slots. pub allow_label_overlap: bool, - /// Display study value tags on price axes, independently of the status line values. + /// Display study value tags on price axes, independently of the status line values. Each tag + /// reads its plot at the last bar in view, or at its last value when the view reaches past + /// it, so it stays where the plot leaves the pane while the chart scrolls; the main series' + /// last price tag follows its own price line source. pub show_study_values: bool, /// Study value tag colour; `None` follows each plot's colour. pub study_value_color: Option, diff --git a/vendor/egui-charts/src/config/crosshair.rs b/vendor/egui-charts/src/config/crosshair.rs index 43b9800..f1a9a65 100644 --- a/vendor/egui-charts/src/config/crosshair.rs +++ b/vendor/egui-charts/src/config/crosshair.rs @@ -9,6 +9,7 @@ use egui::Color32; /// Crosshair mode #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] pub enum CrosshairMode { /// Normal crosshair (snaps x to the bar center and follows the pointer value) #[default] @@ -30,6 +31,7 @@ impl CrosshairMode { /// Crosshair visual style #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] pub enum CrosshairStyle { /// Full crosshair with vertical and horizontal lines (default) #[default] diff --git a/vendor/egui-charts/src/config/drawing_tool/interaction_mode.rs b/vendor/egui-charts/src/config/drawing_tool/interaction_mode.rs index 1006e07..409af8f 100644 --- a/vendor/egui-charts/src/config/drawing_tool/interaction_mode.rs +++ b/vendor/egui-charts/src/config/drawing_tool/interaction_mode.rs @@ -28,6 +28,7 @@ /// ); /// ``` #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[non_exhaustive] pub enum DrawingInteractionMode { /// Click once to place (e.g., `HorizontalLine`, `TextLabel`, arrow markers). /// diff --git a/vendor/egui-charts/src/config/drawing_tool/mod.rs b/vendor/egui-charts/src/config/drawing_tool/mod.rs index 810a8c7..cef06e5 100644 --- a/vendor/egui-charts/src/config/drawing_tool/mod.rs +++ b/vendor/egui-charts/src/config/drawing_tool/mod.rs @@ -273,12 +273,15 @@ pub enum DrawingToolType { /// Flag/mark note at a specific chart location. FlagNote, - // ============ CONTENT (3 tools - placeholders) ============ - /// Image embed identifier; built-in rendering draws a frame without loading an image. + // ============ CONTENT (3 tools) ============ + /// Picture from the address in the drawing's text, loaded by the egui image loaders the + /// host installs, or the picture the host supplies with `Chart::set_drawing_image`. Image, - /// Social post embed identifier; built-in rendering draws a card without fetching content. + /// Social post card showing the post its link resolves to through the host's + /// [`Posts`](crate::services::Posts) service, or the text typed on it. Tweet, - /// Idea embed identifier; built-in rendering draws a badge without fetching content. + /// Idea card showing the idea its link resolves to through the host's + /// [`Posts`](crate::services::Posts) service, or the text typed on it. Idea, // ============ ICONS (2 tools) ============ diff --git a/vendor/egui-charts/src/config/kinetic.rs b/vendor/egui-charts/src/config/kinetic.rs index 4d4b0ae..2d7e0bf 100644 --- a/vendor/egui-charts/src/config/kinetic.rs +++ b/vendor/egui-charts/src/config/kinetic.rs @@ -3,9 +3,13 @@ //! When enabled, releasing a scroll/drag gesture causes the chart to continue //! scrolling with decaying velocity, giving a "momentum" feel similar to //! mobile OS list scrolling. +//! +//! Speeds are in points per frame and the damping is per frame, both at 60 frames per +//! second whatever the display's refresh rate: one point per frame is 60 points per second. /// Kinetic scroll animation parameters. #[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] pub struct KineticScrollOptions { /// Continue scrolling after a horizontal touch drag is released /// Default: false (chart stops immediately on release) @@ -16,21 +20,24 @@ pub struct KineticScrollOptions { #[serde(default)] pub mouse: bool, - /// Min scroll speed (pixels/frame) - /// Default: 0.2 + /// Speed below which a release does not start scrolling and the scrolling ends, in + /// points per frame at 60 frames per second + /// Default: 0.2 (12 points per second) pub min_scroll_speed: f32, - /// Max scroll speed (pixels/frame) - /// Default: 7.0 + /// Highest speed the scrolling starts at, in points per frame at 60 frames per second; + /// a faster release is limited to it + /// Default: 50.0 (3000 points per second) pub max_scroll_speed: f32, - /// Damping coefficient: the share of scroll velocity kept per frame. + /// Damping coefficient: the share of scroll velocity kept per frame at 60 frames per second. /// Accepts finite values in `0.0..1.0` (zero stops immediately, one is excluded). /// Invalid values are replaced by the default when chart options are applied. - /// Default: 0.997 (~99.7% of speed retained each frame) + /// Default: 0.95 (a release at 2000 points per second scrolls on for 100 frames, 1.7 seconds) pub damping_coeff: f32, - /// Min pixels moved to trigger kinetic scroll + /// Horizontal distance a drag must end from its start for its release to start + /// scrolling, in points /// Default: 15.0 pub scroll_min_move: f32, } @@ -41,8 +48,8 @@ impl Default for KineticScrollOptions { enabled: false, // Disabled by default (no inertial scrolling) mouse: false, min_scroll_speed: 0.2, - max_scroll_speed: 7.0, - damping_coeff: 0.997, + max_scroll_speed: 50.0, + damping_coeff: 0.95, scroll_min_move: 15.0, } } diff --git a/vendor/egui-charts/src/config/timescale.rs b/vendor/egui-charts/src/config/timescale.rs index 2156efb..e2b4ac0 100644 --- a/vendor/egui-charts/src/config/timescale.rs +++ b/vendor/egui-charts/src/config/timescale.rs @@ -10,6 +10,7 @@ use egui::Color32; /// Time Scale Options. /// Controls bar spacing, scrolling constraints, and time display. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] pub struct TimeScaleOptions { /// The margin space in bars from the right side of the chart, kept /// whenever the view returns to the live edge. @@ -117,7 +118,8 @@ pub struct TimeScaleOptions { /// Default: None pub border_color: Option, - /// Timezone mode for displaying ts + /// Timezone mode for displaying ts. Behind UTC, bars of a day or longer given without a feed + /// read their date in UTC unless they sit at this zone's midnight. /// Default: UTC pub timezone: TimezoneMode, } diff --git a/vendor/egui-charts/src/data/financials.rs b/vendor/egui-charts/src/data/financials.rs new file mode 100644 index 0000000..34df519 --- /dev/null +++ b/vendor/egui-charts/src/data/financials.rs @@ -0,0 +1,62 @@ +//! Reported company figures supplied by the host. + +/// A company's reported figures, as the host supplies them. +#[derive(Clone, Debug, Default, PartialEq)] +#[non_exhaustive] +pub struct CompanyFinancials { + /// The currency of the amounts, shown above the tables. + pub currency: Option, + /// The pages, such as the income statement, the balance sheet and the statistics, each + /// chosen with its own pill. + pub pages: Vec, +} + +/// One page of [`CompanyFinancials`]: rows of figures by period. +#[derive(Clone, Debug, Default, PartialEq)] +#[non_exhaustive] +pub struct FinancialPage { + /// The page's name, such as "Income statement". + pub name: String, + /// The periods, oldest first, such as "FY 2024" or "Q3 '25": the table's columns. + pub periods: Vec, + /// The rows of the table. + pub rows: Vec, +} + +/// One row of a [`FinancialPage`]. +#[derive(Clone, Debug, Default, PartialEq)] +#[non_exhaustive] +pub struct FinancialRow { + /// The row's name, such as "Total revenue". + pub name: String, + /// One value per period of the page; `None` where the company reported none. Non-finite + /// values are shown as unavailable. + pub values: Vec>, +} + +impl FinancialPage { + /// A page named `name` with columns `periods` and no rows. + pub fn new(name: impl Into, periods: Vec) -> Self { + Self { + name: name.into(), + periods, + rows: Vec::new(), + } + } + + /// Adds a row named `name` with one value per period. + pub fn with_row(mut self, name: impl Into, values: Vec>) -> Self { + self.rows.push(FinancialRow { + name: name.into(), + values, + }); + self + } +} + +impl CompanyFinancials { + /// Financials made of `pages`, with amounts in `currency`. + pub fn new(currency: Option, pages: Vec) -> Self { + Self { currency, pages } + } +} diff --git a/vendor/egui-charts/src/data/footprint.rs b/vendor/egui-charts/src/data/footprint.rs index f40543a..d0749f1 100644 --- a/vendor/egui-charts/src/data/footprint.rs +++ b/vendor/egui-charts/src/data/footprint.rs @@ -72,6 +72,7 @@ pub use crate::model::NodeSensitivity; /// One bar's executed volume and intrabar delta path, starting at zero. #[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] pub struct FootprintBar { /// Bar open from the supplied clock or trade-bar allocation. pub time: DateTime, @@ -779,13 +780,20 @@ impl Footprint { /// the bar before closes at another price than every execution at the start's time, and the /// page's end only when it ends with the last of `history`. The newest proven run is kept, so /// its bars have no gap. Older bars get no cells and draw candles. With `before`, adds only - /// the executions strictly before it. + /// the executions strictly before it. Unless `ended`, executions after the last one may be + /// missing: the page does not end there, and that end proves nothing. Bars that open at or + /// after `stream_from`, the time of the oldest live execution the store kept apart at an + /// instant the page covers, get no cells: the sink opened them, and the page's executions + /// there may include some the stream never sent. They still count in the matching, so the + /// bars before keep their proof. #[cfg(feature = "widget")] pub(crate) fn push_history( &mut self, trades: &[&Tick], history: &[crate::model::Bar], before: Option>, + ended: bool, + stream_from: Option>, ) { let Some(timeframe) = self.clock.timeframe().filter(|tf| tf.is_trade_based()) else { return; @@ -826,6 +834,7 @@ impl Footprint { &history[first..], trades[start].size, None, + ended, ); // The page's end pins the split only with the last bar: an earlier one has executions // after the page, and when they sum to the part a grouping moved, it matches as well. @@ -839,7 +848,9 @@ impl Footprint { } } for (trade, open, size) in newest { - if before.is_none_or(|before| trade.ts < before) { + if before.is_none_or(|before| trade.ts < before) + && stream_from.is_none_or(|from| open < from) + { let _ = self.push_part(trade, open, size); } } @@ -991,7 +1002,8 @@ fn near(a: f64, b: f64) -> bool { } /// Groups `trades` from their first execution along `history`, the bars from the one it opens. -/// `first` is the part of that execution in this bar, and `previous` the open of the bar before. +/// `first` is the part of that execution in this bar, `previous` the open of the bar before, and +/// `ended` whether the page ends with the last of `trades`. #[cfg(feature = "widget")] fn history_run<'a>( timeframe: crate::model::Timeframe, @@ -1000,6 +1012,7 @@ fn history_run<'a>( history: &[crate::model::Bar], first: f64, previous: Option>, + ended: bool, ) -> HistoryRun<'a> { use crate::model::Bar; let same = |grouped: &Bar, bar: Option<&Bar>| { @@ -1043,7 +1056,7 @@ fn history_run<'a>( } } // The page ends here, so a last bar that sums as grouped closes no earlier than it should. - if forming.is_some_and(|grouped| same(&grouped, history.get(matched))) { + if ended && forming.is_some_and(|grouped| same(&grouped, history.get(matched))) { return HistoryRun { parts, proven: true, @@ -1063,14 +1076,16 @@ fn history_run<'a>( /// Groups `trades`, the held executions the sink allocated, in time order, along `history`, the /// chart's bars, from the oldest bar whose parts are all held: the executions are the newest part /// of the sink's stream and the chart's bars hold exactly its parts, so the volume held counts -/// them from the newest. Returns the parts and the grouping after them, or `None` unless they -/// rebuild every bar through the newest. +/// them from the newest. `before` is the open of the bar before `history`'s first when the chart +/// dropped it. Returns the parts and the grouping after them, or `None` unless they rebuild every +/// bar through the newest. #[cfg(feature = "widget")] pub(crate) fn live_run<'a>( timeframe: crate::model::Timeframe, tick_size: Option, trades: &[&'a Tick], history: &[crate::model::Bar], + before: Option>, ) -> Option<(Parts<'a>, super::inbox::TradeBars)> { let mut left: f64 = trades.iter().map(|trade| trade.size).sum(); let mut first = history.len(); @@ -1088,7 +1103,10 @@ pub(crate) fn live_run<'a>( through - left > 1e-9 * trade.size })?; let rest = (through - left).min(trades[start].size); - let previous = first.checked_sub(1).map(|index| history[index].time); + let previous = first + .checked_sub(1) + .map(|index| history[index].time) + .or(before); let run = history_run( timeframe, tick_size, @@ -1096,6 +1114,7 @@ pub(crate) fn live_run<'a>( &history[first..], rest, previous, + true, ); let end = run.end?; (run.parts.last()?.1 == history.last()?.time).then_some((run.parts, end)) @@ -1481,9 +1500,9 @@ mod tests { let references: Vec<_> = trades.iter().collect(); let mut flow = fresh(); let empty = flow.revision(); - flow.push_history(&references, &history, Some(time)); + flow.push_history(&references, &history, Some(time), true, None); assert_eq!(flow.revision(), empty); - flow.push_history(&references, &history, None); + flow.push_history(&references, &history, None, true, None); assert_ne!(flow.revision(), empty); assert_eq!(flow.bars().len(), 2); let mut copied = fresh(); diff --git a/vendor/egui-charts/src/data/http/mod.rs b/vendor/egui-charts/src/data/http/mod.rs index 98e3559..57ea4cd 100644 --- a/vendor/egui-charts/src/data/http/mod.rs +++ b/vendor/egui-charts/src/data/http/mod.rs @@ -47,6 +47,14 @@ pub struct HttpDatafeed { subscriptions: Mutex>>, } +impl std::fmt::Debug for HttpDatafeed { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("HttpDatafeed") + .field("base", &self.base) + .finish_non_exhaustive() + } +} + impl HttpDatafeed { /// Connects to the endpoint root at `address`, which may include a path prefix. /// A trailing slash is optional. Browser servers must allow the application's origin. diff --git a/vendor/egui-charts/src/data/inbox/mod.rs b/vendor/egui-charts/src/data/inbox/mod.rs index 9530d50..43fb613 100644 --- a/vendor/egui-charts/src/data/inbox/mod.rs +++ b/vendor/egui-charts/src/data/inbox/mod.rs @@ -313,6 +313,15 @@ pub struct Reply { answer: PhantomData, } +impl std::fmt::Debug for Reply { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Reply") + .field("request", &self.request) + .field("sent", &self.sent) + .finish_non_exhaustive() + } +} + impl Reply { /// Delivers `result` to the chart. pub fn send(mut self, result: Result) { diff --git a/vendor/egui-charts/src/data/inbox/sink.rs b/vendor/egui-charts/src/data/inbox/sink.rs index 96f32c1..a82dacd 100644 --- a/vendor/egui-charts/src/data/inbox/sink.rs +++ b/vendor/egui-charts/src/data/inbox/sink.rs @@ -187,6 +187,14 @@ pub struct Sink { pub(crate) id: SubscriptionId, } +impl std::fmt::Debug for Sink { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Sink") + .field("id", &self.id) + .finish_non_exhaustive() + } +} + impl Sink { /// Starts a new replay position on this subscription. The next chart drain clears prior /// bars, trades, depth, quote and sampled history before applying subsequent pushes. Resets diff --git a/vendor/egui-charts/src/data/metrics.rs b/vendor/egui-charts/src/data/metrics.rs index 879cf68..d7a4a1b 100644 --- a/vendor/egui-charts/src/data/metrics.rs +++ b/vendor/egui-charts/src/data/metrics.rs @@ -67,7 +67,7 @@ pub struct MetricPage { /// A live metric stream, stopped through [`super::Datafeed::unsubscribe`]. /// Push with [`Sink::push_metric`]; timestamps are retained without price-bar aggregation. -#[derive(Clone)] +#[derive(Debug, Clone)] pub struct MetricSubscription { /// Identifier used to unsubscribe this metric stream. pub id: SubscriptionId, diff --git a/vendor/egui-charts/src/data/mod.rs b/vendor/egui-charts/src/data/mod.rs index 76e0047..351918a 100644 --- a/vendor/egui-charts/src/data/mod.rs +++ b/vendor/egui-charts/src/data/mod.rs @@ -39,6 +39,7 @@ use std::time::Duration; pub(crate) mod depth; mod depth_history; +mod financials; mod footprint; #[cfg(feature = "http")] pub mod http; @@ -66,6 +67,7 @@ mod study; mod targets; mod volume_profile; pub use depth_history::{DepthColumn, DepthHistory, DepthHistoryConfig}; +pub use financials::{CompanyFinancials, FinancialPage, FinancialRow}; #[cfg(any(feature = "studies", feature = "detectors"))] pub(crate) use footprint::meets_threshold; pub use footprint::{Footprint, FootprintBar, FootprintLevel, NodeSensitivity}; @@ -325,6 +327,16 @@ pub trait Datafeed: MaybeSend + 'static { reply.send(Err(FeedError::NotSupported)); } + /// Reported company figures for `symbol`, with periods oldest first and missing figures + /// left as `None`. The host supplies the statements and their currency; no analytics or + /// currency conversion run in the library. The default answers [`FeedError::NotSupported`], + /// which keeps Financials out of the symbol details' More menu in the terminal. Declared by + /// [`FeedService::Financials`]. + fn financials(&self, symbol: &str, reply: Reply) { + let _ = symbol; + reply.send(Err(FeedError::NotSupported)); + } + /// Key statistics and the company or contract profile of `symbol`, for the symbol details /// panel. The default answers [`FeedError::NotSupported`], and the panel then shows neither. fn symbol_details(&self, symbol: &str, reply: Reply) { @@ -705,6 +717,7 @@ impl SymbolDetails { } /// A live subscription: push its updates into `sink` until [`Datafeed::unsubscribe`] gets `id`. +#[derive(Debug)] #[non_exhaustive] pub struct Subscription { /// Identifier passed back to the feed when unsubscribing. diff --git a/vendor/egui-charts/src/data/option_chain.rs b/vendor/egui-charts/src/data/option_chain.rs index 36a80e2..d03cff3 100644 --- a/vendor/egui-charts/src/data/option_chain.rs +++ b/vendor/egui-charts/src/data/option_chain.rs @@ -161,7 +161,7 @@ struct ChainState { /// A feed's destination for complete chain snapshots. Cheap to clone. /// Only the latest accepted rows and error are retained; updates never queue. -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct OptionChainSink(Weak>); impl OptionChainSink { @@ -231,6 +231,12 @@ impl OptionChainSink { #[derive(Clone)] pub struct OptionChain(Arc>); +impl std::fmt::Debug for OptionChain { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("OptionChain").finish_non_exhaustive() + } +} + impl OptionChain { /// Subscribe through `feed`, outside egui closures, and wake the host on each snapshot or /// error. Returns `None` for an empty underlying symbol or reversed expiry range. @@ -534,7 +540,7 @@ struct ExposureState { /// A feed's destination for complete exposure snapshots. Cheap to clone. /// Updates replace the latest snapshot without queuing or adding to computed gamma. -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct OptionExposureSink(Weak>); impl OptionExposureSink { @@ -596,6 +602,13 @@ impl OptionExposureSink { #[derive(Clone)] pub struct OptionExposureHandle(Arc>); +impl std::fmt::Debug for OptionExposureHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("OptionExposureHandle") + .finish_non_exhaustive() + } +} + impl OptionExposureHandle { /// Subscribe outside egui closures, waking the host on every snapshot or error. /// Returns `None` for an empty symbol or reversed expiry range. Unsupported feeds report diff --git a/vendor/egui-charts/src/data/options_volume.rs b/vendor/egui-charts/src/data/options_volume.rs index 2409fb7..2c86305 100644 --- a/vendor/egui-charts/src/data/options_volume.rs +++ b/vendor/egui-charts/src/data/options_volume.rs @@ -53,7 +53,7 @@ impl Snapshot { /// A feed's options snapshots for one underlying and expiry query. Cheap to clone. /// Only the latest snapshot is retained, so updates cannot accumulate between frames. -#[derive(Clone)] +#[derive(Debug, Clone)] pub struct OptionsVolumeSink(Weak>>); impl OptionsVolumeSink { diff --git a/vendor/egui-charts/src/data/order_flow.rs b/vendor/egui-charts/src/data/order_flow.rs index 74998d2..fab3739 100644 --- a/vendor/egui-charts/src/data/order_flow.rs +++ b/vendor/egui-charts/src/data/order_flow.rs @@ -390,6 +390,12 @@ struct State { #[derive(Clone)] pub struct OrderFlowInput(Arc>); +impl std::fmt::Debug for OrderFlowInput { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("OrderFlowInput").finish_non_exhaustive() + } +} + impl OrderFlowInput { /// An empty source for this fixed aggregation. pub fn new(kind: OrderFlowKind) -> Self { @@ -826,7 +832,7 @@ impl OrderFlowInput { self.clear(); let lost = trades.lost_until(); let tick_size = self.state().tick_size; - let chart_run = || Self::chart_run(clock, tick_size, trades, history, None); + let chart_run = || Self::chart_run(clock, tick_size, trades, history, None, None); if footprint { // Without the original live anchor, wait for allocations from the sink. if trade_based && lost.is_some() { @@ -902,15 +908,23 @@ impl OrderFlowInput { /// Groups the executions the sink allocated along `history`, the chart's bars, on a /// trade-based interval: the live ones, after a loss only those after it. Without a loss a /// page's copy stands in for a live execution the store dropped as a repeat, so paged ones - /// from the open of the chart bar holding the oldest live one join them, or from `anchor`, - /// the open of an older bar known to hold the sink's allocations. A bar the sink opened a - /// nanosecond after the one before starts with an execution no later than that one's open, - /// so a run of such bars counts from the open of its first. Older paged ones belong to - /// history bars, which the chart did not fold from them. At the first instant, as the page - /// stamps it, where the store left a live execution to a page, the page may hold executions - /// the stream never sent, so the live ones the store kept apart count in place of the page's - /// executions of that instant. Returns the parts and the grouping after them, or `None` - /// unless they rebuild every bar through the newest. + /// from the open of the chart bar holding the oldest live one, held or kept apart as below, + /// join them, or from `anchor`, the open of an older bar known to hold the sink's + /// allocations. A bar the sink opened a nanosecond after the one before starts with an + /// execution no later than that one's open, so a run of such bars counts from the open of its + /// first. Older paged ones belong to history bars, which the chart did not fold from them. At + /// the first instant, as the page stamps it, where the store left a live execution to a page, + /// the page may hold executions the stream never sent, so the live ones the store kept apart + /// count in place of the page's executions of that instant. They are live executions too: + /// when the chart holds a bar at or before the oldest of them, the run starts at that bar, + /// unless the executions from there fail to rebuild the chart's bars or, from a bar that + /// opens at the oldest of them, leave part of their volume to an older bar. A paged execution + /// the sink never allocated, such as one the stream sent late, does either, and the run then + /// starts as it would without them. `before` is the open of a bar the chart dropped when the + /// sink opened the chart's oldest bar a nanosecond after it: the run then opens the oldest bar + /// after it, and the copies count from `anchor` though no chart bar is at or before it. Returns + /// the parts and the grouping after them, or `None` unless they rebuild every bar through the + /// newest. #[cfg(feature = "widget")] fn chart_run<'a>( clock: &BarClock, @@ -918,30 +932,50 @@ impl OrderFlowInput { trades: &'a super::trades::Trades, history: &[crate::model::Bar], anchor: Option>, + before: Option>, ) -> Option> { let timeframe = clock.timeframe().filter(|tf| tf.is_trade_based())?; let lost = trades.lost_until(); let paged = trades.iter().count() - trades.live().count(); - let oldest = trades.live().map(|trade| trade.ts).chain(anchor).min(); - let from = oldest.filter(|_| lost.is_none()).and_then(|oldest| { - let bars = &history[..history.partition_point(|bar| bar.time <= oldest)]; - let chained = (bars.windows(2).rev()) - .take_while(|pair| pair[1].time - pair[0].time == TimeDelta::nanoseconds(1)) - .count(); - Some(bars[..bars.len() - chained].last()?.time) - }); - let live = trades - .live() - .filter(|trade| lost.is_none_or(|lost| trade.ts > lost)); let (unheld_at, unheld) = trades.unheld_live().unzip(); - let mut held: Vec<_> = (trades.iter().take(paged)) - .filter(|trade| Some(trade.ts) != unheld_at) - .chain(unheld.into_iter().flatten()) - .filter(|trade| from.is_some_and(|from| trade.ts >= from)) - .chain(live) - .collect(); - held.sort_by_key(|trade| trade.ts); - super::footprint::live_run(timeframe, tick_size, &held, history) + let streamed = (trades.live().map(|trade| trade.ts)).chain(anchor).min(); + // The live executions the store kept apart are the stream's too, so the oldest of them + // opens a bar the sink allocated, unless the chart starts after it. + let kept_from = (unheld.and_then(|kept| kept.first())) + .map(|trade| trade.ts) + .filter(|at| history.first().is_some_and(|bar| bar.time <= *at)) + .filter(|at| streamed.is_none_or(|oldest| *at < oldest)); + let run = |oldest: Option>| { + let from = oldest.filter(|_| lost.is_none()).and_then(|oldest| { + let bars = &history[..history.partition_point(|bar| bar.time <= oldest)]; + let chained = (bars.windows(2).rev()) + .take_while(|pair| pair[1].time - pair[0].time == TimeDelta::nanoseconds(1)) + .count(); + (bars[..bars.len() - chained].last().map(|bar| bar.time)) + .or(anchor.filter(|_| before.is_some())) + }); + let live = trades + .live() + .filter(|trade| lost.is_none_or(|lost| trade.ts > lost)); + let mut held: Vec<_> = (trades.iter().take(paged)) + .filter(|trade| Some(trade.ts) != unheld_at) + .chain(unheld.into_iter().flatten()) + .filter(|trade| from.is_some_and(|from| trade.ts >= from)) + .chain(live) + .collect(); + held.sort_by_key(|trade| trade.ts); + let grouped = super::footprint::live_run(timeframe, tick_size, &held, history, before)?; + // Whether the run holds all of the held volume, none of it left to older bars. + let parted: f64 = grouped.0.iter().map(|part| part.2).sum(); + let total: f64 = held.iter().map(|trade| trade.size).sum(); + Some((grouped, from, total - parted <= 1e-9 * total)) + }; + // From a bar that opens at the oldest kept execution, every held one is an execution the + // sink allocated there or later, so none of them belongs to an older bar. + (kept_from.and_then(|kept| run(Some(kept)))) + .filter(|(_, from, whole)| *whole || *from != kept_from) + .or_else(|| run(streamed)) + .map(|(grouped, ..)| grouped) } /// Applies a chart replay cutoff, exclusive, or removes it with `None`. Readers then stop at @@ -971,17 +1005,33 @@ impl OrderFlowInput { let tick_size = state.tick_size; let mut part = State::new(state.source); part.tick_size = tick_size; + // A row a nanosecond before the chart's oldest bar is a bar the chart dropped and + // the sink opened the oldest one right after it, so a fill at one instant may run + // from that bar into the oldest one. + let before = (history.first()) + .and_then(|first| first.time.checked_sub_signed(TimeDelta::nanoseconds(1))) + .filter(|before| { + state.bars.contains_key(before) + || (state.footprint.as_ref()) + .is_some_and(|flow| flow.bars().contains_key(before)) + }); // The sink allocated the oldest bar this source holds and every bar after it, so // a page's copies count from there, or from the chart's oldest bar once the chart - // no longer holds that one, or from the oldest live execution's bar when the page - // lacks one of them. + // no longer holds that one and does not continue such a fill, or from the oldest + // live execution's bar when the page lacks one of them. let anchor = (state.footprint.as_ref()) .and_then(|flow| flow.bars().keys().next()) .or(state.bars.keys().next()) .zip(history.first()) - .map(|(anchor, first)| first.time.max(*anchor)); - let run = Self::chart_run(clock, tick_size, trades, history, anchor) - .or_else(|| Self::chart_run(clock, tick_size, trades, history, None)); + .map(|(anchor, first)| { + if before.is_some() { + *anchor + } else { + first.time.max(*anchor) + } + }); + let run = Self::chart_run(clock, tick_size, trades, history, anchor, before) + .or_else(|| Self::chart_run(clock, tick_size, trades, history, None, None)); let parts = run.map_or_else( || { // Executions that do not match the chart's bars are grouped from the diff --git a/vendor/egui-charts/src/data/recording.rs b/vendor/egui-charts/src/data/recording.rs index 2fa0932..00731c7 100644 --- a/vendor/egui-charts/src/data/recording.rs +++ b/vendor/egui-charts/src/data/recording.rs @@ -12,6 +12,7 @@ const MAX_RECORD: usize = 16 * 1024 * 1024; /// little-endian numbers, optional-id flags and UTF-8 symbols. Version 2 retains resting order /// participant and placement metadata. No runtime or filesystem policy /// is imposed; a host can use a buffered file on native targets or bytes in a browser. +#[derive(Debug)] pub struct RecordingWriter { writer: W, } @@ -149,6 +150,7 @@ impl RecordingWriter { /// Reads version 1 or 2 binary events, including order placement and participant metadata in /// version 2. Limits allocation to 16 MiB per record, rejects unknown /// versions, malformed values and truncated records, and distinguishes clean EOF from truncation. +#[derive(Debug)] pub struct RecordingReader { reader: R, order_metadata: bool, diff --git a/vendor/egui-charts/src/data/replay.rs b/vendor/egui-charts/src/data/replay.rs index c683cd5..aca739d 100644 --- a/vendor/egui-charts/src/data/replay.rs +++ b/vendor/egui-charts/src/data/replay.rs @@ -302,6 +302,12 @@ pub struct ReplayDriver { dispatch: Mutex<()>, } +impl std::fmt::Debug for ReplayDriver { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ReplayDriver").finish_non_exhaustive() + } +} + struct Playback { clock: ReplayClock, instruments: HashMap, diff --git a/vendor/egui-charts/src/data/study.rs b/vendor/egui-charts/src/data/study.rs index d024be4..a53c547 100644 --- a/vendor/egui-charts/src/data/study.rs +++ b/vendor/egui-charts/src/data/study.rs @@ -41,6 +41,7 @@ impl StudyDataRequest { /// A requested series available during calculation, sorted by time with unique bars. /// Metric points use their value for OHLC and zero volume, without interval aggregation. /// An unavailable history has no bars; it is never substituted with the chart's prices. +#[derive(Debug)] pub struct StudyData<'a> { /// The declaration this series answers, before resolving chart defaults. pub request: StudyDataRequest, diff --git a/vendor/egui-charts/src/data/trades.rs b/vendor/egui-charts/src/data/trades.rs index 75a633a..6c2379b 100644 --- a/vendor/egui-charts/src/data/trades.rs +++ b/vendor/egui-charts/src/data/trades.rs @@ -7,9 +7,10 @@ //! dropped if a page added a trade at or after it and the two do not both carry ids. Trades //! sharing the boundary instant may be lost but are never counted twice. The first page after a //! new subscription on a retained tape also fills the time between the tape and the live stream, -//! through the instant of the oldest live trade under the same rule. A page's trades at the -//! stream's first instant may have traded before the subscription, so the live trades left to a -//! page there are kept apart: they, not the page's, are what the stream sent at that instant. +//! from the instant of the newest retained trade through that of the oldest live trade, each under +//! the same rule. A page's trades at the stream's first instant may have traded before the +//! subscription, so the live trades left to a page there are kept apart: they, not the page's, are +//! what the stream sent at that instant. use crate::model::{OrderSide, Tick, next_revision}; use chrono::{DateTime, Utc}; @@ -197,6 +198,16 @@ impl Trades { self.lost_until } + /// Time of the newest retained trade, until a page fills the time after it: trades from that + /// instant on, before the live ones, may be missing. + #[cfg_attr( + not(feature = "widget"), + expect(dead_code, reason = "only the chart widget consumes a feed") + )] + pub(crate) fn retained_until(&self) -> Option> { + self.retained_until + } + /// Time of the oldest live trades, while a page left out its trades at that time because ids /// did not tell them from the live ones. #[cfg_attr( @@ -229,7 +240,10 @@ impl Trades { } /// Starts a new subscription anchor while retaining executions, ids and loss evidence. - #[cfg(feature = "widget")] + #[cfg_attr( + not(any(feature = "widget", test)), + expect(dead_code, reason = "only the chart widget consumes a feed") + )] pub(crate) fn reanchor(&mut self) { self.paged = self.trades.len(); self.paged_until = self.trades.iter().map(|trade| trade.ts).max(); @@ -420,29 +434,35 @@ impl Trades { } /// Moves the trades of `page` after the retained tape and before the live stream between - /// them: nothing streamed while the subscription changed. A trade at the instant of the oldest - /// live trade follows them when it and every held trade at that instant carry ids and its id - /// is not held; one that ids do not tell from the held ones is left out and the instant - /// recorded. The oldest go beyond capacity. + /// them: nothing streamed while the subscription changed. One whose id is held stays out. A + /// trade at the instant of the newest retained trade or of the oldest live trade follows them + /// when it and every held trade at that instant carry ids; one that ids do not tell from the + /// held ones is left out, and the instant of the oldest live trade recorded. The oldest go + /// beyond capacity. fn fill_gap(&mut self, page: &mut Vec, changed: &mut impl FnMut(&Tick, bool)) { let Some(until) = self.retained_until.take() else { return; }; let live_from = self.trades.iter().skip(self.paged).map(|t| t.ts).min(); - let ids_at_live = (self.trades.iter()) - .filter(|held| Some(held.ts) == live_from) - .all(|held| held.id.is_some()); + let ids_at = |at: Option>| { + (self.trades.iter()) + .filter(|held| Some(held.ts) == at) + .all(|held| held.id.is_some()) + }; + let (ids_at_tape, ids_at_live) = (ids_at(Some(until)), ids_at(live_from)); + // The tape's last instant is a boundary of its own while the stream starts after it. + let after_tape = live_from.is_none_or(|from| until < from); let mut left_out = false; let (gap, older): (Vec<_>, Vec<_>) = std::mem::take(page).into_iter().partition(|t| { + let unheld = t.id.is_none_or(|id| !self.ids.contains_key(&id)); // A live trade stamped inside the retained tape marks no boundary. - if Some(t.ts) != live_from || t.ts < until { - return t.ts > until && live_from.is_none_or(|from| t.ts < from); + let at_live = Some(t.ts) == live_from && t.ts >= until; + if !at_live && (t.ts != until || !after_tape) { + return unheld && t.ts > until && live_from.is_none_or(|from| t.ts < from); } - let Some(id) = t.id.filter(|_| ids_at_live) else { - left_out = true; - return false; - }; - !self.ids.contains_key(&id) + let told_apart = t.id.is_some() && if at_live { ids_at_live } else { ids_at_tape }; + left_out |= at_live && !told_apart; + told_apart && unheld }); *page = older; if left_out { @@ -493,8 +513,10 @@ mod tests { /// Trades pushed between two drains. Live(Vec), Page(Vec), + /// An interval change that retains the held trades. + Reanchor, } - use Step::{Live, Page}; + use Step::{Live, Page, Reanchor}; /// Group only explicit aggressor ids, across pages and drains, without moving price volume. #[test] @@ -550,6 +572,7 @@ mod tests { Page(page) => { store.prepend(page, &mut |_, _| ()); } + Reanchor => store.reanchor(), } } let combined = combine_trades(store.iter()); @@ -709,27 +732,55 @@ mod tests { vec![Live(vec![trade(10, 10.0), trade(11, 11.0)]), Page(vec![trade(8, 8.0), trade(9, 9.0)]), Live(vec![trade(12, 12.0)])], vec![9.0, 10.0, 11.0, 12.0], 0, vec![10.0, 11.0, 12.0]), + // The old stream stopped between two trades of 10:00:02: ids 1 and 2 are held, 3 is not. + ("after an interval change, with ids, a page trade at the tape's last instant joins", 10, + vec![Live(vec![id(trade(1, 1.0), 1), id(trade(2, 2.0), 2)]), Reanchor, + Live(vec![id(trade(3, 5.0), 5)]), + Page(vec![id(trade(1, 1.0), 1), id(trade(2, 2.0), 2), id(trade(2, 3.0), 3), + id(trade(3, 5.0), 5)])], + vec![1.0, 2.0, 3.0, 5.0], 0, vec![5.0]), + ("after an interval change, with ids, a page trade stamped earlier than the live copy \ + is dropped", 10, + vec![Live(vec![id(trade(1, 1.0), 1), id(trade(2, 2.0), 2)]), Reanchor, + Live(vec![id(later(trade(3, 5.0), 400), 5)]), + Page(vec![id(trade(1, 1.0), 1), id(trade(2, 2.0), 2), id(trade(3, 5.0), 5)])], + vec![1.0, 2.0, 5.0], 0, vec![5.0]), ]; for (name, capacity, steps, prices, rejected, live_prices) in cases { let mut store = Trades::new(capacity); let mut dropped = 0; + // The prices `changed` reports added and not evicted since. + let mut reported = Vec::new(); + let mut changed = |trade: &Tick, added| { + if added { + reported.push(trade.price); + } else { + let evicted = reported.iter().position(|price| *price == trade.price); + reported.remove(evicted.expect(name)); + } + }; for step in steps { match step { Live(trades) => { let mut pending = store.empty(); trades.into_iter().for_each(|trade| pending.push(trade)); - store.append(pending, &mut |_, _| ()); + store.append(pending, &mut changed); } - Page(page) => dropped += store.prepend(page, &mut |_, _| ()), + Page(page) => dropped += store.prepend(page, &mut changed), + Reanchor => store.reanchor(), } } let held = Vec::from_iter(store.iter().map(|trade| trade.price)); let live = Vec::from_iter(store.live().map(|trade| trade.price)); + reported.sort_by(f64::total_cmp); + let mut sorted = held.clone(); + sorted.sort_by(f64::total_cmp); assert_eq!( (held, dropped, live), (prices, rejected, live_prices), "{name}" ); + assert_eq!(reported, sorted, "{name}: reported by `changed`"); let ids = store.iter().filter(|trade| trade.id.is_some()).count(); assert_eq!(store.ids.len(), ids, "{name}: held ids"); let repeats: Vec<_> = store.iter().filter(|t| t.id.is_some()).cloned().collect(); diff --git a/vendor/egui-charts/src/drawings/domain/alert_levels.rs b/vendor/egui-charts/src/drawings/domain/alert_levels.rs index ffda60f..d5add61 100644 --- a/vendor/egui-charts/src/drawings/domain/alert_levels.rs +++ b/vendor/egui-charts/src/drawings/domain/alert_levels.rs @@ -142,6 +142,43 @@ impl Drawing { } levels } + + /// The alert source name template of fork level `level` of [`Self::alert_levels`] and the + /// value of its setting, which fills `{value}`; `None` for a median and other drawings. With + /// `{tool}` and `{id}` filled, its English is the drawing's name and the level's name, as + /// alerts and presets saved before names kept their parts hold it. + pub(crate) fn fork_line(&self, level: usize) -> Option<(&'static str, String)> { + if !is_fork(self.tool_type) { + return None; + } + let config = self + .pitchfork + .clone() + .unwrap_or_else(PitchforkConfig::legacy); + let value = config.levels.get(level / 2)?.value; + (value != 0.0).then(|| { + ( + [ + "{tool} {id}: {value}: first line", + "{tool} {id}: {value}: second line", + ][level % 2], + value.to_string(), + ) + }) + } +} + +/// Whether [`Drawing::fork_alert_levels`] gives the alert levels of `tool`. +pub(super) fn is_fork(tool: DrawingToolType) -> bool { + use DrawingToolType as T; + matches!( + tool, + T::Pitchfork + | T::SchiffPitchfork + | T::ModifiedSchiffPitchfork + | T::InsidePitchfork + | T::Pitchfan + ) } /// A straight painted segment in axis coordinates, extended to the requested bar. diff --git a/vendor/egui-charts/src/drawings/domain/drawing.rs b/vendor/egui-charts/src/drawings/domain/drawing.rs index dcd6f44..df53c90 100644 --- a/vendor/egui-charts/src/drawings/domain/drawing.rs +++ b/vendor/egui-charts/src/drawings/domain/drawing.rs @@ -177,11 +177,11 @@ pub struct Drawing { /// drawings have it on. #[serde(default = "enabled")] pub background: bool, - /// Whether an annotation's box has a 1 px border. Older drawings have it on. + /// Whether an annotation's box has a 1 px border. Older drawings have it on, except price + /// labels saved before they had a border. #[serde(default = "enabled")] pub border: bool, - /// Border colour of annotation boxes; `None` uses the drawing colour, except on a price label, - /// which then has no border, as price labels saved before they had one. + /// Border colour of annotation boxes; `None` uses the drawing colour. #[serde(default)] pub border_color: Option<[u8; 4]>, /// Whether a Text, Anchored text or Callout breaks its text into lines no wider than @@ -568,12 +568,7 @@ impl Drawing { }, background: !plain_text, border: !plain_text, - border_color: match tool_type { - _ if plain_text => Some([112, 112, 112, 255]), - // Its own colour, which the badge keeps when its background changes. - DrawingToolType::PriceLabel => Some(style.color), - _ => None, - }, + border_color: plain_text.then_some([112, 112, 112, 255]), text_wrap: false, text_wrap_width: default_text_wrap_width(), text_follows_zoom: false, @@ -872,14 +867,7 @@ impl Drawing { ], ) } - ( - T::Pitchfork - | T::SchiffPitchfork - | T::ModifiedSchiffPitchfork - | T::InsidePitchfork - | T::Pitchfan, - _, - ) => self.fork_alert_levels(bar, scale), + (tool, _) if super::alert_levels::is_fork(tool) => self.fork_alert_levels(bar, scale), (T::Rect, [a, b, ..]) => named( &["Top", "Bottom"], &[a.price.max(b.price), a.price.min(b.price)], diff --git a/vendor/egui-charts/src/drawings/domain/ghost_feed.rs b/vendor/egui-charts/src/drawings/domain/ghost_feed.rs index e1bf0ce..3ffceb5 100644 --- a/vendor/egui-charts/src/drawings/domain/ghost_feed.rs +++ b/vendor/egui-charts/src/drawings/domain/ghost_feed.rs @@ -10,6 +10,7 @@ pub const MAX_GHOST_CANDLES: usize = 1000; /// Older saved `spacing` and `wick` settings are ignored and use these defaults. #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] #[serde(default)] +#[non_exhaustive] pub struct GhostFeedConfig { /// Target average high-low range in ticks, before widening to contain the body and path. /// Must be positive and finite. @@ -31,6 +32,7 @@ impl Default for GhostFeedConfig { /// One projected candle, with its body following the noisy path and wicks widened to the /// configured range when the body and intervening anchors fit inside it. #[derive(Debug, Clone, Copy, PartialEq)] +#[non_exhaustive] pub struct GhostCandle { /// Bar index where the candle opens. pub bar_idx: f32, diff --git a/vendor/egui-charts/src/drawings/domain/mod.rs b/vendor/egui-charts/src/drawings/domain/mod.rs index a7e4c89..bfc84aa 100644 --- a/vendor/egui-charts/src/drawings/domain/mod.rs +++ b/vendor/egui-charts/src/drawings/domain/mod.rs @@ -34,4 +34,4 @@ pub use options::{ }; pub use pitchfork::{PitchforkConfig, PitchforkLevel}; pub use template::DrawingTemplate; -pub use vwap::{VwapBand, VwapConfig}; +pub use vwap::{VwapBand, VwapBandMode, VwapConfig, VwapFill, VwapPlotType}; diff --git a/vendor/egui-charts/src/drawings/domain/options.rs b/vendor/egui-charts/src/drawings/domain/options.rs index 28bdf5e..d75c2c4 100644 --- a/vendor/egui-charts/src/drawings/domain/options.rs +++ b/vendor/egui-charts/src/drawings/domain/options.rs @@ -20,6 +20,7 @@ use std::ops::RangeInclusive; /// `Start` and `End`; rectangles use four corner and four edge handles; /// multi-point tools use indexed `Point(i)` handles. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[non_exhaustive] pub enum HandlePos { /// First anchor point of the drawing. Start, @@ -50,6 +51,7 @@ pub enum HandlePos { /// Arrow/arrowhead style for line drawings #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash, Serialize, Deserialize)] +#[non_exhaustive] pub enum ArrowStyle { /// No arrowhead None, @@ -108,6 +110,7 @@ pub use crate::config::FontWeight; /// value are those of its label, as [`Timeframe::as_str`](crate::model::Timeframe::as_str) writes /// it: `90min` is 90 minutes, and a 24 hour interval, labelled `1D`, is 1 day. #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[non_exhaustive] pub struct TimeframeVisibility { /// Show on every interval. pub show_on_all: bool, @@ -283,6 +286,7 @@ impl TimeframeVisibility { /// Drawing interaction options #[derive(Debug, Clone)] +#[non_exhaustive] pub struct DrawingOptions { /// Enable snap to OHLC prices pub snap_to_price: bool, @@ -322,6 +326,7 @@ impl Default for DrawingOptions { /// Configuration for a single Fibonacci level #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] pub struct FibonacciLevel { /// The ratio value (e.g., 0.236, 0.382, 0.618) pub value: f32, @@ -907,6 +912,7 @@ impl Default for RegressionTrendConfig { /// without rounding. #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] #[serde(default)] +#[non_exhaustive] pub struct PositionSizing { /// Account-currency value of one price point per underlying unit. pub point_value: f64, @@ -991,6 +997,8 @@ impl PositionReadout { /// Resolve account economics from a host-supplied rate. Matching currencies need no rate; /// a missing rate for a different currency returns `None`, rather than a mislabeled result. + /// A code that mixes cases, such as `GBp` for pence, matches only itself; other codes match + /// regardless of case. pub fn account_sizing( &self, mut sizing: PositionSizing, @@ -1000,7 +1008,7 @@ impl PositionReadout { return None; } if let Some(currency) = &self.account_currency - && !instrument_currency.is_some_and(|base| base.eq_ignore_ascii_case(currency)) + && !instrument_currency.is_some_and(|base| crate::model::same_currency(base, currency)) { sizing.point_value *= self.conversion_rate?; } @@ -1289,6 +1297,7 @@ impl LineMeasurements { /// How a long or short position drawing sizes its quantity. #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] pub enum PositionSize { /// A fixed quantity, interpreted as lots by [`Self::quantity_with_sizing`]. Quantity(f64), @@ -1882,4 +1891,61 @@ mod tests { } } } + + /// A code that mixes cases names a minor unit (`GBp` pence, `ZAr` South African cents) and + /// matches only itself; codes in a single case match regardless of case. The instrument's + /// point is worth one unit of its currency, times the rate when the codes differ. + #[test] + fn minor_unit_instrument_converts_into_the_account_currency() { + let sizing = PositionSizing::default(); + for (instrument, account, rate, point_value) in [ + // One pence is 1 x 0.01 = 0.01 pounds. + ("GBp", "GBP", Some(0.01), Some(0.01)), + ("GBp", "gbp", Some(0.01), Some(0.01)), + ("ZAr", "ZAR", Some(0.01), Some(0.01)), + // One pound is 1 x 100 = 100 pence. + ("GBP", "GBp", Some(100.0), Some(100.0)), + // Pence without a rate have no pound value, rather than a mislabeled one. + ("GBp", "GBP", None, None), + // The same currency takes no rate: the point stays 1. + ("GBp", "GBp", Some(0.01), Some(1.0)), + ("gbp", "GBP", Some(0.01), Some(1.0)), + ("GBP", "GBP", None, Some(1.0)), + // Different letters are different currencies in any case. + ("GBX", "GBP", Some(0.01), Some(0.01)), + ] { + let readout = PositionReadout { + account_currency: Some(account.into()), + conversion_rate: rate, + ..Default::default() + }; + assert_eq!( + readout + .account_sizing(sizing, Some(instrument)) + .map(|sizing| sizing.point_value), + point_value, + "{instrument} in {account}" + ); + } + // Risking 10 pounds with the stop 10 pence away: 10 / (10 x 0.01) = 100 units. Quoted in + // pounds, the stop is 10 pounds away: 10 / (10 x 1) = 1 unit. + let readout = PositionReadout { + account_currency: Some("GBP".into()), + conversion_rate: Some(0.01), + ..Default::default() + }; + for (instrument, expected) in [("GBp", 100.0), ("gbp", 1.0)] { + let quantity = readout.quantity( + PositionSize::RiskAmount(10.0), + 250.0, + 240.0, + sizing, + Some(instrument), + ); + assert!( + quantity.is_some_and(|quantity| (quantity - expected).abs() < 1e-9), + "{instrument}: {quantity:?}" + ); + } + } } diff --git a/vendor/egui-charts/src/drawings/domain/template.rs b/vendor/egui-charts/src/drawings/domain/template.rs index 6cd48ee..51b4bdd 100644 --- a/vendor/egui-charts/src/drawings/domain/template.rs +++ b/vendor/egui-charts/src/drawings/domain/template.rs @@ -4,6 +4,7 @@ /// same type; its coordinates, closed outline, name, notes, layer, post link and persistence identity /// stay intact. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] pub struct DrawingTemplate { /// Tool and reusable properties. Serialization omits anchors and record identity. pub settings: crate::drawings::Drawing, diff --git a/vendor/egui-charts/src/drawings/domain/vwap.rs b/vendor/egui-charts/src/drawings/domain/vwap.rs index 37ea6d8..145dd3e 100644 --- a/vendor/egui-charts/src/drawings/domain/vwap.rs +++ b/vendor/egui-charts/src/drawings/domain/vwap.rs @@ -1,19 +1,20 @@ -//! Bands of the anchored VWAP drawing. +//! Source, bands, fills and base line of the anchored VWAP drawing. -use serde::{Deserialize, Serialize}; +use crate::model::PriceSource; +use serde::{Deserialize, Deserializer, Serialize}; /// Colours of the three bands: green, olive and teal. const BAND_COLORS: [[u8; 4]; 3] = [[76, 175, 80, 255], [128, 128, 0, 255], [0, 137, 123, 255]]; -/// A line above and a line below an anchored VWAP, a multiple of the volume-weighted standard -/// deviation of the typical price away from it. +/// A line above and a line below an anchored VWAP, a multiple of the +/// [band unit](VwapBandMode) away from it. #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] #[serde(try_from = "VwapBandFields")] pub struct VwapBand { /// Whether the band is drawn. pub enabled: bool, multiplier: f64, - /// Colour of the band's lines and, on the first band, of its fill at 5%. + /// Colour of the band's lines and, on the first band, of its fill unless the fill has its own. pub color: [u8; 4], } @@ -43,8 +44,8 @@ impl TryFrom for VwapBand { } impl VwapBand { - /// A green band `multiplier` standard deviations either side of the VWAP (above 0, at most - /// 10); `None` when out of bounds. + /// A green band `multiplier` band units either side of the VWAP (above 0, at most 10); + /// `None` when out of bounds. pub fn new(enabled: bool, multiplier: f64) -> Option { (multiplier > 0.0 && multiplier <= 10.0).then_some(Self { enabled, @@ -53,23 +54,175 @@ impl VwapBand { }) } - /// Distance of the band's lines from the VWAP, in standard deviations. + /// Distance of the band's lines from the VWAP, in band units. pub fn multiplier(&self) -> f64 { self.multiplier } } -/// The bands of an anchored VWAP drawing; a drawing without one uses the default. +/// What a band multiplier counts: the unit of an anchored VWAP band's distance from the VWAP. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum VwapBandMode { + /// Volume-weighted standard deviations of the source price. + #[default] + Deviation, + /// Percent of the VWAP. + Percentage, +} + +/// How the line of an anchored VWAP drawing is drawn, at the drawing's colour and width. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum VwapPlotType { + /// Connected values. + #[default] + Line, + /// Horizontal segments followed by a vertical change at the next bar. + StepLine, + /// Bars of the line's width from zero to each value. + Histogram, + /// Columns from zero to each value, at 80% of the bar pitch. + Columns, + /// Filled area between the values and zero. + Area, + /// A circle at each value. + Circles, + /// A plus at each value. + Crosses, +} + +impl VwapPlotType { + /// Every plot type, in the order the Inputs tab lists them. + pub const ALL: [Self; 7] = [ + Self::Line, + Self::StepLine, + Self::Histogram, + Self::Columns, + Self::Area, + Self::Circles, + Self::Crosses, + ]; + + /// User-facing name. + pub fn name(self) -> &'static str { + match self { + Self::Line => "Line", + Self::StepLine => "Step line", + Self::Histogram => "Histogram", + Self::Columns => "Columns", + Self::Area => "Area", + Self::Circles => "Circles", + Self::Crosses => "Crosses", + } + } +} + +/// A fill of an anchored VWAP drawing: whether it is painted, its colour and opacity. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[serde(try_from = "VwapFillFields")] +pub struct VwapFill { + /// Whether the fill is painted. + pub visible: bool, + /// Colour; `None` follows the first band's colour in the band fill and the line colour in + /// the background. + pub color: Option<[u8; 4]>, + opacity: f32, +} + +/// Stored settings of a fill, checked by [`VwapFill::new`] on load. +#[derive(Deserialize)] +struct VwapFillFields { + visible: bool, + color: Option<[u8; 4]>, + opacity: f32, +} + +impl TryFrom for VwapFill { + type Error = &'static str; + + fn try_from(fields: VwapFillFields) -> Result { + Self::new(fields.visible, fields.color, fields.opacity) + .ok_or("anchored VWAP fill opacity out of bounds") + } +} + +impl VwapFill { + /// A fill at `opacity`, from 0 (clear) through 1 (opaque); `None` when out of bounds. + pub fn new(visible: bool, color: Option<[u8; 4]>, opacity: f32) -> Option { + (0.0..=1.0).contains(&opacity).then_some(Self { + visible, + color, + opacity, + }) + } + + /// The band fill of a drawing saved before the fill had its own colour: on, in the first + /// band's colour at 5%. + fn following_band() -> Self { + Self { + visible: true, + color: None, + opacity: 0.05, + } + } + + /// Opacity from 0 (clear) through 1 (opaque), which scales the colour's own alpha. + pub fn opacity(&self) -> f32 { + self.opacity + } +} + +/// The settings of an anchored VWAP drawing; a drawing without them uses the default, and a +/// saved one restores missing settings from it. #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[serde(default)] #[non_exhaustive] pub struct VwapConfig { - /// The bands, each drawn when enabled; the first one is also filled. + /// The bands, each drawn when enabled. pub bands: [VwapBand; 3], + /// Bar price the VWAP and its deviation average. + pub source: PriceSource, + /// Unit of the band multipliers. + pub band_mode: VwapBandMode, + /// Whether the VWAP line is drawn; the bands and fills keep their own switches. + pub show_line: bool, + /// How the VWAP line is drawn. + pub plot_type: VwapPlotType, + /// Whether a dotted line across the pane and a price axis tag mark the latest VWAP. + pub track_price: bool, + /// Decimal places of the latest VWAP's price axis tag, from 0 through 8; `None` follows + /// the price scale. + #[serde(deserialize_with = "precision")] + pub precision: Option, + /// Fill between the first band's lines, drawn while that band is enabled. A drawing saved + /// without one fills in the first band's colour, as it was drawn. + #[serde(default = "VwapFill::following_band")] + pub band_fill: VwapFill, + /// Wash over the pane's height from the anchor bar to the last bar, under the bands. + pub background: VwapFill, +} + +fn precision<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + let places = Option::::deserialize(deserializer)?; + if places.is_some_and(|p| p > 8) { + return Err(serde::de::Error::custom( + "anchored VWAP precision above 8 decimals", + )); + } + Ok(places) +} + +impl VwapConfig { + /// Whether the precision is at most 8 decimals. + pub fn is_valid(&self) -> bool { + self.precision.is_none_or(|places| places <= 8) + } } impl Default for VwapConfig { - /// The green band one standard deviation away is on; the olive and teal bands two and three - /// away are off. + /// The VWAP of the typical price as a line, with the green band one standard deviation away + /// filled green at 5%; the olive and teal bands two and three away, the green background at + /// 5% and the latest-value line are off. fn default() -> Self { let band = |index: usize, enabled| VwapBand { enabled, @@ -78,6 +231,45 @@ impl Default for VwapConfig { }; Self { bands: [band(0, true), band(1, false), band(2, false)], + source: PriceSource::HLC3, + band_mode: VwapBandMode::Deviation, + show_line: true, + plot_type: VwapPlotType::Line, + track_price: false, + precision: None, + band_fill: VwapFill { + color: Some(BAND_COLORS[0]), + ..VwapFill::following_band() + }, + background: VwapFill { + visible: false, + color: Some(BAND_COLORS[0]), + opacity: 0.05, + }, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A drawing saved with bands only restores every later setting at its default, except its + /// band fill, which keeps following the first band's colour, so it paints as before; + /// out-of-range settings are refused. + #[test] + fn saved_settings_restore_and_are_checked() { + let saved = r#"{"bands":[{"enabled":true,"multiplier":1.0,"color":[76,175,80,255]},{"enabled":false,"multiplier":2.0,"color":[128,128,0,255]},{"enabled":false,"multiplier":3.0,"color":[0,137,123,255]}]}"#; + let config: VwapConfig = serde_json::from_str(saved).unwrap(); + let mut legacy = VwapConfig::default(); + legacy.band_fill.color = None; + assert_eq!(config, legacy); + for bad in [ + r#"{"precision":9}"#, + r#"{"band_fill":{"visible":true,"color":null,"opacity":1.5}}"#, + r#"{"background":{"visible":true,"color":null,"opacity":-0.1}}"#, + ] { + assert!(serde_json::from_str::(bad).is_err(), "{bad}"); } } } diff --git a/vendor/egui-charts/src/drawings/manager/edit.rs b/vendor/egui-charts/src/drawings/manager/edit.rs index 8a46040..e0a8137 100644 --- a/vendor/egui-charts/src/drawings/manager/edit.rs +++ b/vendor/egui-charts/src/drawings/manager/edit.rs @@ -278,6 +278,7 @@ impl DrawingManager { /// Applies `edit` to the drawing with the given ID, records it for undo and queues it to /// be saved. Edit a drawing through this rather than [`Self::drawings`] so the change is /// saved. A locked drawing accepts only visibility, name and folder changes, or an edit that unlocks it. + /// An edit that hides the drawing deselects it. /// Does nothing if there is no such drawing. pub fn edit_drawing(&mut self, id: usize, edit: impl FnOnce(&mut Drawing)) { if let Some(drawing) = self.drawings.iter_mut().find(|d| d.id == id) { @@ -304,7 +305,7 @@ impl DrawingManager { drawing.folder = folder; drawing.folder_sync = folder_sync; } - if !drawing.selectable { + if !drawing.selectable || (old.visible && !drawing.visible) { self.selection.deselect(id); } self.queue_edit(&old); @@ -343,6 +344,7 @@ impl DrawingManager { /// Edits live drawing ids as one undo step and queues their saved changes. /// Locked drawings accept visibility, name and folder changes, or an edit that unlocks them. + /// The drawings the edit hides are deselected. pub fn edit_drawings(&mut self, ids: &[usize], mut edit: impl FnMut(&mut Drawing)) { if ids.is_empty() { return; @@ -380,7 +382,7 @@ impl DrawingManager { drawing.folder = folder; drawing.folder_sync = folder_sync; } - if !drawing.selectable { + if !drawing.selectable || (old.visible && !drawing.visible) { self.selection.deselect(old.id); } before.push((index, old)); @@ -529,14 +531,15 @@ impl DrawingManager { // === Visibility === - /// Toggles the visibility of all drawings. If all are visible, hides them - /// all; otherwise shows them all. + /// Hides every drawing unless all of them are already hidden, in which case shows them all, + /// as the Hide drawings toolbar entry does. Does nothing without drawings. pub fn toggle_visibility_all(&mut self) { - let visible = !self.drawings.iter().all(|drawing| drawing.visible); + let visible = self.drawings.iter().all(|drawing| !drawing.visible); self.set_visibility_all(visible); } - /// Set every drawing's visibility as one undoable edit. + /// Set every drawing's visibility as one undoable edit. Hiding deselects the drawings it hides; + /// undo restores their visibility, not the selection. pub fn set_visibility_all(&mut self, visible: bool) { let mut before = Vec::new(); for (index, drawing) in self @@ -560,6 +563,9 @@ impl DrawingManager { } for (_, drawing) in &before { self.stamp(drawing.id); + if !visible { + self.selection.deselect(drawing.id); + } } self.history.push_snapshot(before); } @@ -901,4 +907,29 @@ mod tests { assert!(manager.undo()); assert_eq!(folders(&manager), before); } + + /// Redo restores an added drawing as it was when the add was undone, with the bar spacing + /// its text was first displayed at, which the drawing adopts after its undo step is recorded. + #[test] + fn redo_keeps_the_spacing_added_text_was_first_shown_at() { + let mut manager = DrawingManager::new(); + let mut text = Drawing::new(0, DrawingToolType::TextLabel); + text.text = Some("Note".into()); + text.text_follows_zoom = true; + text.chart_points = vec![ChartPoint::new(10.0, 100.0)]; + let id = manager.add_drawing(text).unwrap(); + // First shown at 6 points a bar, then zoomed in to 12. + manager.update_all_screen_coords(|bar: f32| bar * 6.0, |price: f64| price as f32); + let at_12 = |bar: f32| bar * 12.0; + manager.update_all_screen_coords(at_12, |price: f64| price as f32); + let zoom = |manager: &DrawingManager| { + let text = manager.drawings.iter().find(|d| d.id == id).unwrap(); + text.text_zoom(at_12, at_12(10.0)) + }; + // Sized at 6 points a bar and shown at 12, the text is drawn at 12 / 6 = 2 times its size. + assert_eq!(zoom(&manager), 2.0, "before the undo"); + assert!(manager.undo() && manager.redo()); + manager.update_all_screen_coords(at_12, |price: f64| price as f32); + assert_eq!(zoom(&manager), 2.0, "after the redo"); + } } diff --git a/vendor/egui-charts/src/drawings/manager/interaction.rs b/vendor/egui-charts/src/drawings/manager/interaction.rs index 4497190..88848e4 100644 --- a/vendor/egui-charts/src/drawings/manager/interaction.rs +++ b/vendor/egui-charts/src/drawings/manager/interaction.rs @@ -620,6 +620,12 @@ impl DrawingManager { self.dragging_handle } + /// Whether a drag or a continuous edit is in progress, which [`Self::end_drag_handle`] records + /// as one step from the state it started in. + pub(crate) fn drag_in_progress(&self) -> bool { + self.drag_old_state.is_some() + } + /// Starts a registered tool's multi-click construction. One-anchor tools complete on the /// first click. The host picker uses `registry.custom_tools()` for its ids and names. pub fn set_custom_tool(&mut self, id: &str) -> Result<(), &'static str> { diff --git a/vendor/egui-charts/src/drawings/manager/mod.rs b/vendor/egui-charts/src/drawings/manager/mod.rs index b98bfd4..f4f6fa2 100644 --- a/vendor/egui-charts/src/drawings/manager/mod.rs +++ b/vendor/egui-charts/src/drawings/manager/mod.rs @@ -51,6 +51,7 @@ pub enum DrawingSyncAction { /// of each frame to ensure the manager stays in sync with toolbar selections, /// keyboard shortcuts, and other UI actions that modify drawing state. #[derive(Debug, Clone, Default)] +#[non_exhaustive] pub struct DrawingState { /// Currently selected drawing tool. `None` means selection/pointer mode. pub active_tool: Option, @@ -72,6 +73,7 @@ pub struct DrawingState { /// Controls default colors, snapping behavior, magnet mode thresholds, and /// selection handle appearance. #[derive(Clone, Debug)] +#[non_exhaustive] pub struct DrawingManagerOptions { /// Line colour every new drawing takes instead of its tool's own, as RGBA bytes. `None` /// (the default) keeps each tool's colour; a default saved for a tool wins over both. @@ -288,6 +290,15 @@ pub struct DrawingManager { pub(crate) sync_enabled: bool, } +impl std::fmt::Debug for DrawingManager { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DrawingManager") + .field("active_tool", &self.active_tool) + .field("drawings", &self.drawings.len()) + .finish_non_exhaustive() + } +} + impl Default for DrawingManager { fn default() -> Self { Self::new() @@ -505,7 +516,7 @@ impl DrawingManager { (None, false) => {} } } - // A redone addition comes back as it was recorded, before its first edit time. + // A state recorded before the drawing's first edit comes back without an edit time. let now = chrono::Utc::now().timestamp_millis(); let affected = self.history.affected_ids().to_vec(); for drawing in self @@ -515,8 +526,15 @@ impl DrawingManager { { drawing.modified_at.get_or_insert(now); } - self.selection - .prune(&self.drawings.iter().map(|d| d.id).collect()); + // A step that hides a selected drawing deselects it, as hiding it by an edit does. + self.selection.prune( + &self + .drawings + .iter() + .filter(|d| d.visible) + .map(|d| d.id) + .collect(), + ); true } diff --git a/vendor/egui-charts/src/drawings/manager/paint.rs b/vendor/egui-charts/src/drawings/manager/paint.rs index fb1f735..d5f6737 100644 --- a/vendor/egui-charts/src/drawings/manager/paint.rs +++ b/vendor/egui-charts/src/drawings/manager/paint.rs @@ -362,8 +362,12 @@ impl DrawingManager { /// A tag a drawing puts on an axis of its pane. #[derive(Clone, Copy)] pub(crate) enum DrawingAxisTag { - /// `price` on the price axis, on a `color` tag. - Price { price: f64, color: Color32 }, + /// `price` on the price axis, on a `color` tag, at `decimals` places or the scale's. + Price { + price: f64, + color: Color32, + decimals: Option, + }, /// The time of `anchor` on the time axis at screen `x`, on an opaque `color` tag. Time { x: f32, @@ -375,14 +379,17 @@ pub(crate) enum DrawingAxisTag { impl DrawingManager { /// The axis tags of visible drawings of the pane last handled, in drawing order: enabled /// price and time labels of horizontal, vertical and cross lines reaching `plot`, position - /// levels, whose entry takes `entry_color`, and the time of a vertical line reaching that pane - /// from another. Call after the pane handles input so tags follow a drag in the same frame. - /// Line tags use opaque RGB so their text stays legible. - pub(crate) fn axis_tags( - &self, + /// levels, whose entry takes `entry_color`, the latest value of an anchored VWAP that tracks + /// it over the pane's `bars` at `revision`, and the time of a vertical line reaching that + /// pane from another. Call after the pane handles input so tags follow a drag in the same + /// frame. Line tags use opaque RGB so their text stays legible. + pub(crate) fn axis_tags<'a>( + &'a self, plot: Rect, entry_color: Color32, - ) -> impl Iterator + '_ { + bars: &'a [crate::model::Bar], + revision: u64, + ) -> impl Iterator + 'a { self.drawings .iter() .filter(|drawing| { @@ -413,7 +420,16 @@ impl DrawingManager { .map(|(anchor, _)| DrawingAxisTag::Price { price: anchor.price, color, + decimals: None, }); + let vwap = + drawing + .anchored_vwap_last(bars, revision) + .map(|price| DrawingAxisTag::Price { + price, + color, + decimals: drawing.vwap.and_then(|config| config.precision), + }); let time = at .filter(|(_, point)| time && plot.x_range().contains(point.x)) .map(|(anchor, point)| DrawingAxisTag::Time { @@ -424,8 +440,12 @@ impl DrawingManager { drawing .position_price_tags(entry_color) .into_iter() - .map(|(price, color)| DrawingAxisTag::Price { price, color }) - .chain([price, time].into_iter().flatten()) + .map(|(price, color)| DrawingAxisTag::Price { + price, + color, + decimals: None, + }) + .chain([price, vwap, time].into_iter().flatten()) }) } } diff --git a/vendor/egui-charts/src/drawings/mod.rs b/vendor/egui-charts/src/drawings/mod.rs index ee168d5..fc9273e 100644 --- a/vendor/egui-charts/src/drawings/mod.rs +++ b/vendor/egui-charts/src/drawings/mod.rs @@ -42,7 +42,7 @@ pub use domain::{ LineTextHorizontalAlign, LineTextOrientation, LineTextVerticalAlign, NoteTextStyle, ParseToolTypeError, PitchforkConfig, PitchforkLevel, PositionReadout, PositionSize, PositionSizing, PositionStyle, RegressionTrendConfig, TimeframeVisibility, VwapBand, - VwapConfig, + VwapBandMode, VwapConfig, VwapFill, VwapPlotType, }; // Re-export manager types diff --git a/vendor/egui-charts/src/drawings/persistence.rs b/vendor/egui-charts/src/drawings/persistence.rs index c4b142b..1d7e99a 100644 --- a/vendor/egui-charts/src/drawings/persistence.rs +++ b/vendor/egui-charts/src/drawings/persistence.rs @@ -49,6 +49,7 @@ use std::fmt; /// these values are independent of chart pan/zoom and of the loaded history, /// making them suitable for long-term storage and cross-device synchronization. #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct StoredCoord { /// Timestamp in Unix epoch milliseconds. pub ts_ms: i64, @@ -97,6 +98,7 @@ fn is_zero(value: &u32) -> bool { /// type and every setting. Convert between the two with [`drawing_to_stored`] /// and [`stored_to_drawing`]. #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct StoredDrawing { /// Unique identifier (string for backend compatibility). pub id: String, @@ -317,6 +319,7 @@ impl StoredDrawing { /// It is read only through [`Self::from_json`], which checks the version, /// migrates older files and loads each drawing on its own. #[derive(Debug, Clone, Serialize)] +#[non_exhaustive] pub struct DrawingStorage { /// Format version, [`Self::CURRENT_VERSION`] once loaded pub version: u32, @@ -332,6 +335,7 @@ pub struct DrawingStorage { /// Storage metadata #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct StorageMetadata { /// When the storage was created pub created_at: i64, @@ -353,8 +357,10 @@ impl Default for StorageMetadata { } impl DrawingStorage { - /// Current storage format version. Version 9 draws a callout's border at its stored width; - /// those saved before that change load with the 1 px border they were drawn with. Version 8 + /// Current storage format version. Version 10 draws a price label without a border colour + /// with a border in its own colour; those saved before that change load with the border off, + /// as drawn. Version 9 draws a callout's border at its stored width; those saved before that + /// change load with the 1 px border they were drawn with. Version 8 /// extends a trend line past the anchor its Left or Right names; those saved before that /// change load with the reach they were drawn with. /// Version 7 does the same for rays, extended lines, info lines and trend angles. @@ -366,7 +372,7 @@ impl DrawingStorage { /// versions load at the width and opacity their strokes were drawn at. Version 3 preserves /// editable ray and extended-line extensions; versions 1 and 2 migrate to their former /// rendered reach when loaded. - pub const CURRENT_VERSION: u32 = 9; + pub const CURRENT_VERSION: u32 = 10; /// Create new storage for a symbol pub fn new(symbol: impl Into) -> Self { @@ -631,6 +637,14 @@ impl DrawingStorage { // width. drawing.drawing.stroke_width = 1.0; } + if version < 10 + && tool == T::PriceLabel + && drawing.drawing.border_color.is_none() + { + // Earlier renderers drew no border on a price label without a border + // colour, which now follows the label's colour. + drawing.drawing.border = false; + } if ((version < 7 && matches!(tool, T::InfoLine | T::TrendAngle) && !has_price_labels) @@ -754,6 +768,7 @@ impl DrawingStorage { /// Why [`DrawingStorage::to_json`] did not save. #[derive(Debug)] +#[non_exhaustive] pub enum SaveError { /// A drawing holds NaN or an infinity, which JSON cannot store, or a size or pitchfork /// level out of the range drawings are drawn at, and loading skips it. @@ -836,6 +851,7 @@ impl std::error::Error for SaveError { /// A drawing [`DrawingStorage::from_json`] left out because it could not be /// read or its id was already taken. #[derive(Debug)] +#[non_exhaustive] pub struct SkippedDrawing { /// The position of the entry in the file's list of drawings, counted from 0. pub index: usize, @@ -2193,10 +2209,10 @@ mod tests { assert!(visibility.is_visible_on("2h") && !visibility.is_visible_on("1D")); let error = - DrawingStorage::from_json(¤t.replace("\"version\": 9", "\"version\": 10")) + DrawingStorage::from_json(¤t.replace("\"version\": 10", "\"version\": 11")) .unwrap_err(); assert!( - matches!(&error, LoadError::UnsupportedVersion { found: 10, supported } if *supported == (1..=9)), + matches!(&error, LoadError::UnsupportedVersion { found: 11, supported } if *supported == (1..=10)), "{error}" ); } @@ -2299,7 +2315,9 @@ mod tests { } assert_eq!(drawing.font_weight, FontWeight::Normal, "{tool:?}"); assert_eq!(drawing.text_color, None, "{tool:?}"); - assert!(drawing.background && drawing.border, "{tool:?}"); + // A price label drew no border then, which one without a colour now has. + assert!(drawing.background, "{tool:?}"); + assert_eq!(drawing.border, tool != T::PriceLabel, "{tool:?}"); assert_eq!(drawing.border_color, None, "{tool:?}"); assert!(!drawing.channel_midline, "{tool:?}"); if tool == T::Measure { @@ -2492,25 +2510,51 @@ mod tests { } /// The fixture is a price label and a price note as the release before their badge and text - /// settings saved them: the label stored no border colour and drew a plain badge, and the - /// note drew its typed text as its price. A new label has a border colour of its own. + /// settings saved them: the label stored no border colour and drew a plain badge, also once + /// saved again, and the note drew its typed text as its price. A version 9 label with a border + /// colour keeps it, and a new label's border takes the colour it is given, also once saved. #[test] fn price_label_and_note_saved_before_their_settings_keep_their_look() { + use egui::{Color32, Stroke}; let saved = include_str!("fixtures/storage_v9_price_label_note.json"); let (storage, skipped) = DrawingStorage::from_json(saved).unwrap(); assert!(skipped.is_empty(), "{skipped:?}"); - let blue = egui::Color32::from_rgb(41, 98, 255); - let label = restore(&storage.drawings[0], 1); - let colors = label.price_label_colors(); - assert_eq!( - (colors.text, colors.fill, colors.border), - (egui::Color32::WHITE, blue, egui::Stroke::NONE) - ); + let blue = Color32::from_rgb(41, 98, 255); + let red = Color32::from_rgb(242, 54, 69); + let (again, _) = DrawingStorage::from_json(&storage.to_json().unwrap()).unwrap(); + for storage in [&storage, &again] { + let colors = restore(&storage.drawings[0], 1).price_label_colors(); + assert_eq!( + (colors.text, colors.fill, colors.border), + (Color32::WHITE, blue, Stroke::NONE) + ); + } + // A red label with the default blue border, as version 9 saved one recoloured through + // `Drawing::color` or given that border in its settings: it was drawn so. + let mut recoloured: serde_json::Value = serde_json::from_str(saved).unwrap(); + let settings = &mut recoloured["drawings"][0]["drawing"]; + settings["color"] = serde_json::json!([242, 54, 69, 255]); + settings["border_color"] = serde_json::json!([41, 98, 255, 255]); + let (old, skipped) = DrawingStorage::from_json(&recoloured.to_string()).unwrap(); + assert!(skipped.is_empty(), "{skipped:?}"); + let colors = restore(&old.drawings[0], 1).price_label_colors(); + assert_eq!((colors.fill, colors.border), (red, Stroke::new(1.0, blue))); + let mut placed = Drawing::new(1, DrawingToolType::PriceLabel); + placed.chart_points = vec![ChartPoint::new(1.0, 108.0)]; + placed.color = [242, 54, 69, 255]; + let mut fresh = DrawingStorage::new("AAPL"); + fresh.add_drawing(drawing_to_stored(&placed, bar_to_time)); + let (loaded, skipped) = DrawingStorage::from_json(&fresh.to_json().unwrap()).unwrap(); + assert!(skipped.is_empty(), "{skipped:?}"); + for label in [&placed, &restore(&loaded.drawings[0], 1)] { + let colors = label.price_label_colors(); + assert_eq!((colors.fill, colors.border), (red, Stroke::new(1.0, red))); + } let note = restore(&storage.drawings[1], 2); assert_eq!(note.text.as_deref(), Some("Entry")); assert_eq!(note.note_text_style, None); let colors = note.text_box_colors(&egui::Context::default()); - assert_eq!((colors.text, colors.fill), (egui::Color32::WHITE, blue)); + assert_eq!((colors.text, colors.fill), (Color32::WHITE, blue)); } /// Builds that wrote versions 3 to 6 carried a sloping ray's Left and Right towards the diff --git a/vendor/egui-charts/src/drawings/registry.rs b/vendor/egui-charts/src/drawings/registry.rs index c7ec576..6154e55 100644 --- a/vendor/egui-charts/src/drawings/registry.rs +++ b/vendor/egui-charts/src/drawings/registry.rs @@ -25,6 +25,7 @@ pub trait DrawingRenderer: Send + Sync { /// Whether a built-in tool appears in a picker and can create new drawings. Existing drawings /// remain visible and editable, so hiding a tool never makes a saved annotation disappear. #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub struct ToolAvailability { /// Include the tool in picker lists. pub visible: bool, @@ -52,10 +53,19 @@ pub struct RegisteredDrawingTool { pub implementation: Arc, } +impl std::fmt::Debug for RegisteredDrawingTool { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RegisteredDrawingTool") + .field("name", &self.name) + .field("anchors", &self.anchors) + .finish_non_exhaustive() + } +} + /// Per-manager catalogue. Register stable host-owned string ids before loading drawings. /// Unknown custom ids stay in storage but are not rendered or hit until registered. /// Clone the catalogue into a host picker to share implementations and availability. -#[derive(Clone, Default)] +#[derive(Debug, Clone, Default)] pub struct DrawingToolRegistry { custom: BTreeMap, builtins: HashMap, diff --git a/vendor/egui-charts/src/drawings/rendering/annotations/labels.rs b/vendor/egui-charts/src/drawings/rendering/annotations/labels.rs index 78c4b61..15a85cc 100644 --- a/vendor/egui-charts/src/drawings/rendering/annotations/labels.rs +++ b/vendor/egui-charts/src/drawings/rendering/annotations/labels.rs @@ -115,16 +115,19 @@ impl Drawing { } /// Colours of a price label's badge. Unset text is white or black, whichever reads on the - /// fill, and a label without a border colour, as saved before it had one, has no border. + /// fill, and an unset border takes the label's colour, which it keeps when its background + /// changes. pub(crate) fn price_label_colors(&self) -> TextBoxColors { let rgba = |[r, g, b, a]: [u8; 4]| Color32::from_rgba_unmultiplied(r, g, b, a); let fill = self.fill_color32().unwrap_or(self.color32()); TextBoxColors { text: self.text_color.map_or_else(|| label_text_color(fill), rgba), fill, - border: match self.border_color { - Some(color) if self.border => Stroke::new(stroke::HAIRLINE, rgba(color)), - _ => Stroke::NONE, + border: if self.border { + let color = self.border_color.map_or_else(|| self.color32(), rgba); + Stroke::new(stroke::HAIRLINE, color) + } else { + Stroke::NONE }, } } @@ -411,14 +414,16 @@ mod tests { shapes } - /// A price label's badge takes its text and border colours with their opacity. A label saved - /// before it had a border colour stored none and keeps its plain badge. + /// A price label's badge takes its text and border colours with their opacity. A border never + /// chosen takes the label's colour however that is set, and a chosen one stays when the colour + /// changes. A label without a border, as one saved before it had a border loads, keeps its + /// plain badge. #[test] fn price_label_badge_takes_its_text_and_border_colours() { const BLUE: Color32 = Color32::from_rgb(41, 98, 255); const RED: Color32 = Color32::from_rgb(242, 54, 69); type Row = (fn(&mut Drawing), Color32, Stroke); - let rows: [Row; 4] = [ + let rows: [Row; 5] = [ (|_| {}, Color32::WHITE, Stroke::new(1.0, BLUE)), // A border that shares the label's colour follows it. ( @@ -426,12 +431,19 @@ mod tests { Color32::WHITE, Stroke::new(1.0, RED), ), - (|d| d.border_color = None, Color32::WHITE, Stroke::NONE), + // The public field, as the `Drawing` example and `edit_drawing` closures set it. + ( + |d| d.color = [242, 54, 69, 255], + Color32::WHITE, + Stroke::new(1.0, RED), + ), + (|d| d.border = false, Color32::WHITE, Stroke::NONE), ( |d| { d.fill_color = Some([255, 235, 59, 255]); d.text_color = Some([1, 2, 3, 128]); d.border_color = Some([0, 128, 0, 64]); + d.set_line_color([242, 54, 69, 255]); }, Color32::from_rgba_unmultiplied(1, 2, 3, 128), Stroke::new(1.0, Color32::from_rgba_unmultiplied(0, 128, 0, 64)), diff --git a/vendor/egui-charts/src/drawings/rendering/annotations/text.rs b/vendor/egui-charts/src/drawings/rendering/annotations/text.rs index 8a550e9..3a51cf2 100644 --- a/vendor/egui-charts/src/drawings/rendering/annotations/text.rs +++ b/vendor/egui-charts/src/drawings/rendering/annotations/text.rs @@ -6,6 +6,21 @@ use crate::styles::typography::font_size; use crate::tokens::DESIGN_TOKENS; use egui::epaint::StrokeKind; +fn pine_label_origin(style: &str, pos: egui::Pos2, size: egui::Vec2) -> egui::Pos2 { + let anchor = match style { + "style_label_up" => egui::Align2::CENTER_TOP, + "style_label_down" => egui::Align2::CENTER_BOTTOM, + "style_label_left" => egui::Align2::LEFT_CENTER, + "style_label_right" => egui::Align2::RIGHT_CENTER, + "style_label_upper_left" => egui::Align2::LEFT_TOP, + "style_label_upper_right" => egui::Align2::RIGHT_TOP, + "style_label_lower_left" => egui::Align2::LEFT_BOTTOM, + "style_label_lower_right" => egui::Align2::RIGHT_BOTTOM, + _ => egui::Align2::CENTER_CENTER, + }; + anchor.align_size_within_rect(size, egui::Rect::from_min_max(pos, pos)).min +} + impl Drawing { /// Renders Text and Anchored text with the text's top-left corner on the first anchor, /// surrounded by a background and border when enabled. Anchored text differs only in @@ -33,6 +48,10 @@ impl Drawing { } galley = painter.layout_job(job); } + let pos = match self.custom_settings.get("pine_label_style").and_then(|value| value.as_str()) { + Some(style) => pine_label_origin(style, pos, galley.size()), + None => pos, + }; if colors.fill.a() > 0 || !colors.border.is_empty() { let padding = egui::vec2( DESIGN_TOKENS.sizing.annotation.label_padding_x, @@ -50,3 +69,18 @@ impl Drawing { painter.galley(pos, galley, colors.text); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pine_labels_are_placed_on_the_requested_side() { + let point = egui::pos2(100.0, 100.0); + let size = egui::vec2(40.0, 20.0); + assert_eq!(pine_label_origin("style_label_down", point, size), egui::pos2(80.0, 80.0)); + assert_eq!(pine_label_origin("style_label_up", point, size), egui::pos2(80.0, 100.0)); + assert_eq!(pine_label_origin("style_label_left", point, size), egui::pos2(100.0, 90.0)); + assert_eq!(pine_label_origin("style_label_right", point, size), egui::pos2(60.0, 90.0)); + } +} diff --git a/vendor/egui-charts/src/drawings/rendering/gann.rs b/vendor/egui-charts/src/drawings/rendering/gann.rs index 5fd310a..c459a3f 100644 --- a/vendor/egui-charts/src/drawings/rendering/gann.rs +++ b/vendor/egui-charts/src/drawings/rendering/gann.rs @@ -7,6 +7,7 @@ use crate::drawings::domain::{ Drawing, DrawingToolType, GANN_MAX_ARC, GANN_SQUARE_UNITS, GannConfig, GannFanDirection, GannLevel, }; +use crate::localization as l10n; use crate::styles::typography; use crate::theme::ThemeExt; use crate::tokens::DESIGN_TOKENS; @@ -438,10 +439,21 @@ impl Drawing { || format!("{range:.decimals$}"), |formatter| formatter.format(range), ); - let mut label = format!("{range_text}\n{} bars", bars.round() as i64); + let mut label = range_text; + label.push('\n'); + label.push_str(&l10n::format_text( + painter.ctx(), + "{count} bars", + &[("count", (bars.round() as i64).to_string())], + )); if bars > 0.0 { let ratio_decimals = decimals + 2; - label.push_str(&format!("\n{:.ratio_decimals$}/bar", range / bars)); + label.push('\n'); + label.push_str(&l10n::format_text( + painter.ctx(), + "{ratio}/bar", + &[("ratio", format!("{:.ratio_decimals$}", range / bars))], + )); } let chart = painter.ctx().active_theme().chart; super::measurements::boxed_label( diff --git a/vendor/egui-charts/src/drawings/rendering/lines.rs b/vendor/egui-charts/src/drawings/rendering/lines.rs index 1282131..bdb6908 100644 --- a/vendor/egui-charts/src/drawings/rendering/lines.rs +++ b/vendor/egui-charts/src/drawings/rendering/lines.rs @@ -524,7 +524,8 @@ impl Drawing { let height = rect.height(); let width = rect.width(); let [width_label, height_label] = - <[String; 2]>::try_from(self.size_labels(price_formatter)).unwrap_or_default(); + <[String; 2]>::try_from(self.size_labels(painter.ctx(), price_formatter)) + .unwrap_or_default(); let chart = painter.ctx().active_theme().chart; let label_bg = chart.bg_axis; diff --git a/vendor/egui-charts/src/drawings/rendering/measurements.rs b/vendor/egui-charts/src/drawings/rendering/measurements.rs index 39030cb..124617b 100644 --- a/vendor/egui-charts/src/drawings/rendering/measurements.rs +++ b/vendor/egui-charts/src/drawings/rendering/measurements.rs @@ -5,6 +5,7 @@ use super::{ChartView, bars_between}; use crate::drawings::LineTextVerticalAlign; use crate::drawings::domain::{Drawing, DrawingToolType}; +use crate::localization as l10n; use crate::model::{Bar, percent_change}; use crate::scales::price_decimals; use crate::scales::{DefaultPriceFormatter, PriceFormatter, VolumeFormatter}; @@ -161,7 +162,7 @@ impl Drawing { return None; } let settings = self.line_measurements; - let text = self.line_measurement_label(view); + let text = self.line_measurement_label(painter.ctx(), view); if text.is_empty() { return None; } @@ -301,7 +302,7 @@ impl Drawing { /// displayed geometry; length is measured in horizontal bar spacings, not price units. /// Up to three lines, each present only with a readout: the price change and its percentage /// and pips, then the bars, elapsed time and length, then the inclination. - fn line_measurement_label(&self, view: &ChartView) -> String { + fn line_measurement_label(&self, ctx: &egui::Context, view: &ChartView) -> String { let ([a, b, ..], [start, end, ..]) = (self.chart_points.as_slice(), self.points.as_slice()) else { return String::new(); @@ -319,13 +320,15 @@ impl Drawing { (price, percent) => price.or(percent), }); if settings.pip_change { - prices.extend(unit_change_text(change, view.instrument, false)); + prices.extend(unit_change_text(ctx, change, view.instrument, false)); } let mut spans = Vec::new(); if settings.bar_count { - spans.push(format!( - "{} bars", - (b.bar_idx.round() - a.bar_idx.round()).abs() as i64 + let count = (b.bar_idx.round() - a.bar_idx.round()).abs() as i64; + spans.push(l10n::format_text( + ctx, + "{count} bars", + &[("count", count.to_string())], )); } if settings.elapsed_time && view.time_axis { @@ -348,7 +351,11 @@ impl Drawing { let spacing = ((view.bar_to_x)(a.bar_idx + 1.0) - (view.bar_to_x)(a.bar_idx)).abs(); let length = delta.length() / spacing; if spacing > 0.0 && length.is_finite() { - spans.push(format!("{length:.2} periods")); + spans.push(l10n::format_text( + ctx, + "{length} periods", + &[("length", format!("{length:.2}"))], + )); } } let mut lines = vec![prices.join(" "), spans.join(", ")]; @@ -371,6 +378,7 @@ impl Drawing { /// span N bars of time and the volume of the N + 1 bars from one to the other, both included. pub(crate) fn measurement_label( &self, + ctx: &egui::Context, bars: &[Bar], instrument: Option<&crate::model::Instrument>, time_axis: bool, @@ -385,14 +393,15 @@ impl Drawing { "{} ({pct:+.2}%)", change_text(a.price, change, instrument, price_formatter) ); - if let Some(text) = unit_change_text(b.price - a.price, instrument, true) { + if let Some(text) = unit_change_text(ctx, b.price - a.price, instrument, true) { change.push_str(&format!(" {text}")); } if self.tool_type == DrawingToolType::PriceRange { return Some(change); } let (from, to) = (a.bar_idx.round(), b.bar_idx.round()); - let mut span = format!("{} bars", (to - from).abs() as i64); + let count = (to - from).abs() as i64; + let mut span = l10n::format_text(ctx, "{count} bars", &[("count", count.to_string())]); if let Some(ms) = elapsed_ms(bars, from, to).filter(|_| time_axis) { span = format!("{span}, {}", format_duration(ms)); } @@ -408,7 +417,13 @@ impl Drawing { let unit = &text[digits.len()..]; // Precision 2 writes a point, so trimming zeros never eats an integer digit. let digits = digits.trim_end_matches('0').trim_end_matches('.'); - format!("\nVol {digits}{unit}") + let mut volume = String::from("\n"); + volume.push_str(&l10n::format_text( + ctx, + "Vol {volume}", + &[("volume", format!("{digits}{unit}"))], + )); + volume }) .unwrap_or_default(); Some(match self.tool_type { @@ -421,7 +436,11 @@ impl Drawing { } /// The rectangle's width in bars and height in price, from its stored anchors. - pub(crate) fn size_labels(&self, price_formatter: Option<&dyn PriceFormatter>) -> Vec { + pub(crate) fn size_labels( + &self, + ctx: &egui::Context, + price_formatter: Option<&dyn PriceFormatter>, + ) -> Vec { let gap = |a: f64, b: f64| { let (low, gap) = (a.min(b), (a - b).abs()); let pct = percent_change(low, low + gap); @@ -435,7 +454,11 @@ impl Drawing { }; match (self.tool_type, &self.chart_points[..]) { (DrawingToolType::Rect, [a, b, ..]) => vec![ - format!("{} bars", (b.bar_idx - a.bar_idx).abs() as i64), + l10n::format_text( + ctx, + "{count} bars", + &[("count", ((b.bar_idx - a.bar_idx).abs() as i64).to_string())], + ), gap(a.price, b.price), ], _ => Vec::new(), @@ -463,6 +486,7 @@ fn change_text( /// Pips when supplied by the instrument, otherwise ticks; omit unavailable or inexact counts. fn unit_change_text( + ctx: &egui::Context, change: f64, instrument: Option<&crate::model::Instrument>, whole: bool, @@ -495,8 +519,13 @@ fn unit_change_text( &text }; let text = if text == "-0" { "+0" } else { text }; - let plural = if matches!(text, "+1" | "-1") { "" } else { "s" }; - Some(format!("{text} {unit}{plural}")) + let key = match (unit, matches!(text, "+1" | "-1")) { + ("pip", true) => "{0} pip", + ("pip", false) => "{0} pips", + (_, true) => "{0} tick", + (_, false) => "{0} ticks", + }; + Some(l10n::format_text(ctx, key, &[("0", text)])) } /// Decimals of a price change from `price`, as the chart writes prices: the instrument's price @@ -527,6 +556,7 @@ impl Drawing { fn range_card(&self, painter: &egui::Painter, rect: Rect, view: &ChartView) { let (Some(text), [first, second, ..]) = ( self.measurement_label( + painter.ctx(), view.bars, view.instrument, view.time_axis, @@ -738,17 +768,28 @@ mod tests { let mut drawing = Drawing::new(1, tool); drawing.chart_points = vec![ChartPoint::new(b1, p1), ChartPoint::new(b2, p2)]; drawing.update_screen_coords(|bar| bar * 10.0, |price| 500.0 - price as f32); - let got = drawing.measurement_label(&bars, None, true, None); + let got = drawing.measurement_label(&egui::Context::default(), &bars, None, true, None); if got.as_deref() != Some(want) { wrong.push(format!("{tool:?}: got {got:?}, want {want:?}")); } } + // The bar count and the volume reach the host's lookup as templates. + let marked = egui::Context::default(); + crate::localization::mark_keys(&marked); + let mut drawing = Drawing::new(1, DrawingToolType::Measure); + drawing.chart_points = vec![ChartPoint::new(1.0, 100.0), ChartPoint::new(4.0, 95.0)]; + assert_eq!( + drawing + .measurement_label(&marked, &bars, None, true, None) + .as_deref(), + Some("-5.00 (-5.00%)\n~3~, 3h\n~900~") + ); let mut drawing = Drawing::new(0, DrawingToolType::Measure); drawing.chart_points = vec![ChartPoint::new(1.0, 1.1000), ChartPoint::new(4.0, 1.0995)]; // On a horizontal scale other than time the bar times are keys, not times. assert_eq!( drawing - .measurement_label(&bars, None, false, None) + .measurement_label(&egui::Context::default(), &bars, None, false, None) .as_deref(), Some("-0.0005 (-0.05%)\n3 bars\nVol 900") ); @@ -789,7 +830,13 @@ mod tests { instrument.pip_size = pip; instrument.price_decimals = precision; let label = drawing - .measurement_label(&bars, Some(&instrument), true, None) + .measurement_label( + &egui::Context::default(), + &bars, + Some(&instrument), + true, + None, + ) .unwrap(); assert_eq!( label.lines().next(), @@ -800,7 +847,13 @@ mod tests { // Counts beyond the exactly representable integers, including overflow, are omitted. let instrument = crate::model::Instrument::new("PAIR").with_tick_size(1e-300); let label = drawing - .measurement_label(&bars, Some(&instrument), true, None) + .measurement_label( + &egui::Context::default(), + &bars, + Some(&instrument), + true, + None, + ) .unwrap(); assert!( !label.contains("ticks") && !label.contains("pips"), @@ -809,6 +862,28 @@ mod tests { assert!(wrong.is_empty(), "{}", wrong.join("\n")); } + /// A pip count takes the decimals one tick has in pips: a 0.01 tick is a tenth of a 0.1 pip, + /// so 2345.67 to 2357.89 is +122.2 pips, although 0.01 / 0.1 is 0.09999999999999999 in binary. + /// A 0.00001 tick is a tenth of a 0.0001 pip: 0.00123 is +12.3 pips and 0.0012 is +12 pips. + #[test] + fn pip_readout_keeps_the_tick_precision_of_a_pip() { + let ctx = egui::Context::default(); + for (tick, pip, change, want) in [ + (0.01, 0.1, 2357.89 - 2345.67, "+122.2 pips"), + (0.00001, 0.0001, 0.00123, "+12.3 pips"), + (0.00001, 0.0001, 0.0012, "+12 pips"), + ] { + let instrument = crate::model::Instrument::new("TEST") + .with_tick_size(tick) + .with_pip_size(pip); + assert_eq!( + unit_change_text(&ctx, change, Some(&instrument), false).as_deref(), + Some(want), + "{tick}, {pip}, {change}" + ); + } + } + /// A 30-by-40 screen segment is 50 points, or five 10-point periods, at atan(4/3). /// Raw 100 to 200 is +100 (+100%), 400 quarter-point ticks or 200 half-point pips. /// A logarithmic midpoint is sqrt(100*200), not the arithmetic price midpoint. @@ -889,9 +964,16 @@ mod tests { drawing.chart_points.reverse(); } drawing.update_screen_coords(x, y); - assert!(drawing.line_measurement_label(&view).is_empty()); + assert!( + drawing + .line_measurement_label(&egui::Context::default(), &view) + .is_empty() + ); drawing.line_measurements = options; - assert_eq!(drawing.line_measurement_label(&view), want); + assert_eq!( + drawing.line_measurement_label(&egui::Context::default(), &view), + want + ); // Each switch independently removes exactly its own readout. for (index, label) in want .split(['\n', ',']) @@ -914,7 +996,7 @@ mod tests { } drawing.line_measurements = only; assert_eq!( - drawing.line_measurement_label(&view), + drawing.line_measurement_label(&egui::Context::default(), &view), label, "readout {index}" ); @@ -1018,7 +1100,7 @@ mod tests { }; drawing.chart_points = vec![ChartPoint::new(0.0, 100.0), ChartPoint::new(3.0, 101.25)]; assert_eq!( - drawing.line_measurement_label(&view), + drawing.line_measurement_label(&egui::Context::default(), &view), if pip.is_some() { "+2.5 pips" } else { @@ -1043,7 +1125,10 @@ mod tests { if reverse { drawing.chart_points.reverse(); } - assert_eq!(drawing.line_measurement_label(&view), "3h 15m"); + assert_eq!( + drawing.line_measurement_label(&egui::Context::default(), &view), + "3h 15m" + ); } drawing.line_measurements = Default::default(); } @@ -1166,7 +1251,10 @@ mod tests { fn size_labels_are_in_price_and_bars() { let mut drawing = Drawing::new(1, DrawingToolType::Rect); drawing.chart_points = vec![ChartPoint::new(0.0, 100.0), ChartPoint::new(20.0, 110.0)]; - assert_eq!(drawing.size_labels(None), ["20 bars", "10.00 (10.00%)"]); + assert_eq!( + drawing.size_labels(&egui::Context::default(), None), + ["20 bars", "10.00 (10.00%)"] + ); } /// In a 500 x 400 pane, info lines near its top and bottom edges and steep ones in either @@ -1516,7 +1604,11 @@ mod tests { drawing.chart_points = vec![ChartPoint::new(from, 100.0), ChartPoint::new(to, 100.0)]; drawing.update_screen_coords(|bar| 10.0 * bar, |price| 300.0 - price as f32); - assert_eq!(drawing.line_measurement_label(&view), want, "{tool:?}"); + assert_eq!( + drawing.line_measurement_label(&egui::Context::default(), &view), + want, + "{tool:?}" + ); } } let (_, shapes) = paint_trend_angle( diff --git a/vendor/egui-charts/src/drawings/rendering/mod.rs b/vendor/egui-charts/src/drawings/rendering/mod.rs index 66f2252..4660acb 100644 --- a/vendor/egui-charts/src/drawings/rendering/mod.rs +++ b/vendor/egui-charts/src/drawings/rendering/mod.rs @@ -89,6 +89,16 @@ pub struct ChartView<'a> { pub finer: &'a [crate::data::StudyData<'a>], } +impl std::fmt::Debug for ChartView<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ChartView") + .field("revision", &self.revision) + .field("time_axis", &self.time_axis) + .field("bars", &self.bars.len()) + .finish_non_exhaustive() + } +} + /// Index of the first bar and the bars from anchor `a` to anchor `b` /// (inclusive, either order), clamped to the series; `None` when no bar lies /// between them. diff --git a/vendor/egui-charts/src/drawings/rendering/trading/forecast.rs b/vendor/egui-charts/src/drawings/rendering/trading/forecast.rs index cf624cf..af03253 100644 --- a/vendor/egui-charts/src/drawings/rendering/trading/forecast.rs +++ b/vendor/egui-charts/src/drawings/rendering/trading/forecast.rs @@ -3,6 +3,7 @@ use crate::drawings::domain::{ChartPoint, Drawing}; use crate::drawings::rendering::measurements::{boxed_label, elapsed_ms, format_duration}; use crate::drawings::rendering::{ChartView, bars_between}; +use crate::localization as l10n; use crate::model::{Bar, percent_change}; use crate::scales::{DefaultPriceFormatter, instrument_price_precision, price_decimals}; use crate::theme::ThemeExt; @@ -54,15 +55,21 @@ impl Drawing { } else { "+" }; - let mut target = format!( + let moved = format!( "{sign}{change_text} ({:+.2}%)", percent_change(from.price, to.price) ); - if let Some(ms) = elapsed_ms(view.bars, from.bar_idx, to.bar_idx).filter(|_| view.time_axis) - { - target.push_str(&format!(" in {}", format_duration(ms))); - } - target.push_str(&format!("\n{}", anchor_label(to))); + let mut target = + match elapsed_ms(view.bars, from.bar_idx, to.bar_idx).filter(|_| view.time_axis) { + Some(ms) => l10n::format_text( + painter.ctx(), + "{change} in {duration}", + &[("change", moved), ("duration", format_duration(ms))], + ), + None => moved, + }; + target.push('\n'); + target.push_str(&anchor_label(to)); let up = change >= 0.0; let gap = DESIGN_TOKENS.spacing.md; diff --git a/vendor/egui-charts/src/drawings/rendering/trading/projection.rs b/vendor/egui-charts/src/drawings/rendering/trading/projection.rs index 099f99e..c890be2 100644 --- a/vendor/egui-charts/src/drawings/rendering/trading/projection.rs +++ b/vendor/egui-charts/src/drawings/rendering/trading/projection.rs @@ -4,6 +4,7 @@ use crate::drawings::domain::Drawing; use crate::drawings::rendering::ChartView; use crate::drawings::rendering::measurements::boxed_label; use crate::drawings::rendering::utils::draw_dashed_line; +use crate::localization as l10n; use crate::styles::stroke; use crate::theme::ThemeExt; use crate::tokens::DESIGN_TOKENS; @@ -186,13 +187,14 @@ impl Drawing { // Projection target label let zone_height = (dy.abs() * 0.2).max(20.0); let target_label = self.chart_points.get(2).map_or_else( - || "Target: n/a".to_owned(), + || l10n::text(painter.ctx(), "Target: n/a"), |c| { let target = c.price + self.chart_points[1].price - self.chart_points[0].price; - match price_formatter { - Some(formatter) => format!("Target: {}", formatter.format(target)), - None => format!("Target: {target:.2}"), - } + let price = match price_formatter { + Some(formatter) => formatter.format(target), + None => format!("{target:.2}"), + }; + l10n::format_text(painter.ctx(), "Target: {price}", &[("price", price)]) }, ); boxed_label( diff --git a/vendor/egui-charts/src/drawings/rendering/trading/volume_profile.rs b/vendor/egui-charts/src/drawings/rendering/trading/volume_profile.rs index bbb4408..c649934 100644 --- a/vendor/egui-charts/src/drawings/rendering/trading/volume_profile.rs +++ b/vendor/egui-charts/src/drawings/rendering/trading/volume_profile.rs @@ -3,8 +3,9 @@ use crate::data::{StudyDataRequest, VolumeProfile}; use crate::drawings::domain::Drawing; use crate::drawings::domain::DrawingToolType; +use crate::drawings::domain::{VwapBandMode, VwapConfig, VwapPlotType}; use crate::drawings::rendering::{ChartView, MAX_CACHED_SPANS, bars_between}; -use crate::model::{Bar, ProfileResolution, Timeframe}; +use crate::model::{Bar, PriceSource, ProfileResolution, Timeframe}; use crate::painting::span_cache::{SpanCache, SpanFingerprint}; use crate::painting::volume_profile::ProfileStyle; use crate::styles::stroke; @@ -23,7 +24,8 @@ type ProfileCache = SpanCache, (usize, Option)>; type FinerCache = SpanCache, (usize, Option, SpanFingerprint, usize)>; thread_local! { - static VWAP_CHECKPOINTS: RefCell>> = + /// Checkpoints by the price they average. + static VWAP_CHECKPOINTS: RefCell, PriceSource>> = const { RefCell::new(SpanCache::new(MAX_CACHED_SPANS)) }; /// Profiles by their number of rows. static PROFILES: RefCell = @@ -34,9 +36,10 @@ thread_local! { } impl Drawing { - /// Renders the anchored VWAP from the anchor bar to the last bar at the drawing's width, - /// with the enabled bands of its [`VwapConfig`](crate::drawings::VwapConfig) in their colours, - /// the first one filled at 5%. + /// Renders the anchored VWAP from the anchor bar to the last bar as its + /// [`VwapConfig`](crate::drawings::VwapConfig) sets: the background, the first band's fill, + /// the enabled bands in their colours, the line at the drawing's colour and width, and the + /// latest value across the pane. pub(crate) fn render_anchored_vwap(&self, painter: &egui::Painter, view: &ChartView) { let Some(anchor_at) = self.chart_points.first() else { return; @@ -61,50 +64,96 @@ impl Drawing { return; } - // The checkpoints only cover whole blocks before the last bar, so the - // forming bar's updates reuse them. - let covered = (bars.len() - 1) / VWAP_CHECKPOINT * VWAP_CHECKPOINT; - let checkpoints = VWAP_CHECKPOINTS.with_borrow_mut(|cache| { - cache.get((), first, &bars[..covered], view.revision, vwap_checkpoints) - }); - // The VWAP, then the upper and lower line of every enabled band, in standard deviations - // from it. let config = self.vwap.unwrap_or_default(); + let checkpoints = cached_checkpoints(config.source, first, bars, view.revision); + // The VWAP, then the upper and lower line of every enabled band, in band units from it. let mut offsets = vec![0.0]; let mut colors = Vec::new(); for band in config.bands.iter().filter(|b| b.enabled) { offsets.extend([band.multiplier(), -band.multiplier()]); - let [r, g, b, a] = band.color; - colors.extend([Color32::from_rgba_unmultiplied(r, g, b, a); 2]); + colors.extend([rgba(band.color); 2]); } let mut lines = vec![Vec::with_capacity(to - from); offsets.len()]; - for (i, value) in (from..to).zip(anchored_vwap(bars, &checkpoints, from..to)) { - let Some((vwap, sigma)) = value else { continue }; + for (i, value) in (from..to).zip(anchored_vwap(bars, &checkpoints, &config, from..to)) { + let Some((vwap, unit)) = value else { continue }; let x = (view.bar_to_x)((first + i) as f32); for (line, k) in lines.iter_mut().zip(&offsets) { - line.push(Pos2::new(x, (view.price_to_y)(vwap + k * sigma))); + line.push(Pos2::new(x, (view.price_to_y)(vwap + k * unit))); } } if lines[0].is_empty() { return; } - if config.bands[0].enabled { + let line_color = self.color32(); + if config.background.visible { + let color = config.background.color.map_or(line_color, rgba); + let anchor = (view.bar_to_x)(first as f32); + let last = (view.bar_to_x)((first + bars.len() - 1) as f32); + painter.rect_filled( + egui::Rect::from_x_y_ranges(anchor..=last, clip.y_range()), + 0.0, + color.gamma_multiply(config.background.opacity()), + ); + } + if config.bands[0].enabled && config.band_fill.visible { + let color = config.band_fill.color.map_or(colors[0], rgba); super::super::fibonacci::paint_band( painter, &lines[1], &lines[2], - colors[0].gamma_multiply(0.05), + color.gamma_multiply(config.band_fill.opacity()), ); } let vwap_line = lines.remove(0); for (line, color) in lines.into_iter().zip(colors) { painter.add(Shape::line(line, Stroke::new(stroke::HAIRLINE, color))); } - painter.add(Shape::line( + if !config.show_line { + return; + } + paint_vwap_line( + painter, vwap_line, - Stroke::new(self.stroke_width, self.color32()), - )); + config.plot_type, + Stroke::new(self.stroke_width, line_color), + (view.price_to_y)(0.0), + step, + ); + let last = bars.len() - 1; + if config.track_price + && let Some(Some((vwap, _))) = + anchored_vwap(bars, &checkpoints, &config, last..bars.len()).next() + { + let y = (view.price_to_y)(vwap); + if clip.y_range().contains(y) { + crate::painting::dashed_line::draw_dashed_line( + painter, + Pos2::new(clip.left(), y), + Pos2::new(clip.right(), y), + Stroke::new(1.0, line_color), + 1.0, + 3.0, + ); + } + } + } + + /// The anchored VWAP at the last of `bars`, the pane's bars at `revision`, when its latest + /// value is tracked; `None` for other drawings, before volume trades or with the line hidden. + pub(crate) fn anchored_vwap_last(&self, bars: &[Bar], revision: u64) -> Option { + if self.tool_type != DrawingToolType::AnchoredVWAP { + return None; + } + let config = self.vwap.unwrap_or_default(); + if !(config.track_price && config.show_line) { + return None; + } + let (first, bars) = bars_between(bars, self.chart_points.first()?.bar_idx, f32::INFINITY)?; + let checkpoints = cached_checkpoints(config.source, first, bars, revision); + let last = bars.len() - 1; + let value = anchored_vwap(bars, &checkpoints, &config, last..bars.len()).next()??; + Some(value.0) } /// Whether a visible profile drawing reads the chart's executions and finer bars. @@ -205,9 +254,10 @@ impl Drawing { if self.tool_type == DrawingToolType::AnchoredVWAP { let anchor = self.chart_points.first()?.bar_idx; let (first, bars) = bars_between(view.bars, anchor, f32::INFINITY)?; + let source = self.vwap.unwrap_or_default().source; let mut sums = VwapSums::default(); let (i, (vwap, _)) = bars.iter().enumerate().find_map(|(i, bar)| { - sums.add(bar); + sums.add(bar, source); sums.value().map(|value| (i, value)) })?; let x = (view.bar_to_x)((first + i) as f32); @@ -303,7 +353,7 @@ impl Drawing { } } -/// Running sums of volume, typical price times volume, and squared typical +/// Running sums of volume, source price times volume, and squared source /// price times volume. #[derive(Clone, Copy, Default)] struct VwapSums { @@ -313,8 +363,8 @@ struct VwapSums { } impl VwapSums { - fn add(&mut self, bar: &Bar) { - let price = bar.typical_price(); + fn add(&mut self, bar: &Bar, source: PriceSource) { + let price = source.compute(bar.open, bar.high, bar.low, bar.close); self.volume += bar.volume; self.price_volume += price * bar.volume; self.square_volume += price * price * bar.volume; @@ -334,34 +384,129 @@ impl VwapSums { /// The running sums at the start of the span and after every block of /// `VWAP_CHECKPOINT` bars of `prefix`, the span's leading whole blocks, so the /// VWAP at any bar takes fewer than `VWAP_CHECKPOINT` further additions. -fn vwap_checkpoints(prefix: &[Bar]) -> Vec { +fn vwap_checkpoints(prefix: &[Bar], source: PriceSource) -> Vec { let mut sums = VwapSums::default(); let mut checkpoints = vec![sums]; for block in prefix.chunks(VWAP_CHECKPOINT) { - block.iter().for_each(|bar| sums.add(bar)); + block.iter().for_each(|bar| sums.add(bar, source)); checkpoints.push(sums); } checkpoints } -/// VWAP from the first bar of the span, with its standard deviation, at each -/// bar of the non-empty `range`, resuming from the checkpoint before it. +/// The checkpoints of the span of `bars` that starts at bar `first`, averaging `source`. They +/// only cover whole blocks before the last bar, so the forming bar's updates reuse them. +fn cached_checkpoints( + source: PriceSource, + first: usize, + bars: &[Bar], + revision: u64, +) -> Rc> { + let covered = (bars.len() - 1) / VWAP_CHECKPOINT * VWAP_CHECKPOINT; + VWAP_CHECKPOINTS.with_borrow_mut(|cache| { + cache.get(source, first, &bars[..covered], revision, |prefix| { + vwap_checkpoints(prefix, source) + }) + }) +} + +/// VWAP of `config`'s source from the first bar of the span, with its band unit, at each bar of +/// the non-empty `range`, resuming from the checkpoint before it. fn anchored_vwap<'a>( bars: &'a [Bar], checkpoints: &[VwapSums], + config: &VwapConfig, range: Range, ) -> impl Iterator> + 'a { + let (source, mode) = (config.source, config.band_mode); let checkpoint = range.start / VWAP_CHECKPOINT; let mut sums = checkpoints[checkpoint]; bars[checkpoint * VWAP_CHECKPOINT..range.start] .iter() - .for_each(|bar| sums.add(bar)); + .for_each(|bar| sums.add(bar, source)); bars[range].iter().map(move |bar| { - sums.add(bar); - sums.value() + sums.add(bar, source); + let (vwap, sigma) = sums.value()?; + Some(match mode { + VwapBandMode::Deviation => (vwap, sigma), + VwapBandMode::Percentage => (vwap, vwap.abs() / 100.0), + }) }) } +/// Draws the VWAP at `points` as `plot` in `stroke`, the plots that start from price zero from +/// `zero`, at bars `pitch` apart. The area fills in the stroke's colour, as a study's area does. +fn paint_vwap_line( + painter: &egui::Painter, + points: Vec, + plot: VwapPlotType, + stroke: Stroke, + zero: f32, + pitch: f32, +) { + let clip = painter.clip_rect(); + // Zero is usually far off the pane: plots from it start at the pane's edge. + let zero = if zero.is_finite() { + zero.clamp(clip.top(), clip.bottom()) + } else { + clip.bottom() + }; + let color = stroke.color; + match plot { + VwapPlotType::Line => { + painter.add(Shape::line(points, stroke)); + } + VwapPlotType::StepLine => { + let mut steps = Vec::with_capacity(points.len() * 2); + for (i, &point) in points.iter().enumerate() { + if i > 0 { + steps.push(Pos2::new(point.x, points[i - 1].y)); + } + steps.push(point); + } + painter.add(Shape::line(steps, stroke)); + } + VwapPlotType::Histogram | VwapPlotType::Columns => { + let half = if plot == VwapPlotType::Columns { + pitch * 0.4 + } else { + stroke.width * 0.5 + }; + for point in points { + painter.rect_filled( + egui::Rect::from_two_pos( + Pos2::new(point.x - half, zero), + Pos2::new(point.x + half, point.y), + ), + 0.0, + color, + ); + } + } + VwapPlotType::Area => { + let base: Vec<_> = points.iter().map(|p| Pos2::new(p.x, zero)).collect(); + super::super::fibonacci::paint_band(painter, &points, &base, color); + } + VwapPlotType::Circles => { + for point in points { + painter.circle_filled(point, stroke.width, color); + } + } + VwapPlotType::Crosses => { + let arm = stroke.width + 1.0; + for point in points { + for delta in [egui::vec2(arm, 0.0), egui::vec2(0.0, arm)] { + painter.line_segment([point - delta, point + delta], Stroke::new(1.0, color)); + } + } + } + } +} + +fn rgba([r, g, b, a]: [u8; 4]) -> Color32 { + Color32::from_rgba_unmultiplied(r, g, b, a) +} + /// Profile of `bars`, the span that starts at bar `first`, with `rows` rows. /// While the last bar, which may be forming, trades inside the range of the /// bars before it, their profile is reused, so a tick or a new bar costs one @@ -460,9 +605,11 @@ mod tests { } /// The line keeps the drawing's width and only the enabled bands are drawn, band 1 filled. + /// The line, its plot, the fill, the background and the latest-value line each follow their + /// own setting. #[test] fn anchored_vwap_draws_its_line_and_enabled_bands_only() { - use crate::drawings::{ChartPoint, VwapBand, VwapConfig}; + use crate::drawings::{VwapBand, VwapConfig, VwapFill}; // From bar 1: V = 1, 2, 8; PV = 10, 22, 88; P²V = 100, 244, 970. // VWAP = 10, 11, 11; deviation = 0, 1, 0.5. let bars: Vec<_> = [(50.0, 0.0), (10.0, 1.0), (12.0, 1.0), (11.0, 6.0)] @@ -486,6 +633,7 @@ mod tests { other_bands.bands[2].color = teal_band; let mut no_bands = VwapConfig::default(); no_bands.bands[0].enabled = false; + let render = |anchor, width, config| render_vwap(&bars, anchor, width, config); for (name, anchor, config, width, fill, expected) in [ ( "default", @@ -523,39 +671,10 @@ mod tests { ), ("past last bar", 4.0, None, 1.0, false, vec![]), ] { - let mut drawing = Drawing::new(1, DrawingToolType::AnchoredVWAP); - drawing.color = [41, 98, 255, 255]; - drawing.stroke_width = width; - drawing.vwap = config; - drawing.chart_points = vec![ChartPoint::new(anchor, 50.0)]; - let view = ChartView { - instrument: None, - price_formatter: None, - time_formatter: None, - bar_seconds: 0, - bars: &bars, - revision: 0, - bar_to_x: &|b| 100.0 + 10.0 * b, - price_to_y: &|p| ((20.0 - p) * 10.0) as f32, - y_to_price: &|y| 20.0 - f64::from(y) / 10.0, - time_axis: true, - executions: None, - timeframe: None, - finer: &[], - }; - let mut output = egui::Context::default().run_ui(egui::RawInput::default(), |ui| { - let painter = egui::Painter::new( - ui.ctx().clone(), - egui::LayerId::background(), - Rect::from_min_max(Pos2::ZERO, Pos2::new(800.0, 600.0)), - ); - drawing.render_anchored_vwap(&painter, &view); - }); - let shapes = std::mem::take(&mut output.shapes); - output.drop_without_applying_deltas(); + let shapes = render(anchor, width, config); assert_eq!(shapes.len(), expected.len() + usize::from(fill), "{name}"); if fill { - let Shape::Mesh(mesh) = &shapes[0].shape else { + let Shape::Mesh(mesh) = &shapes[0] else { panic!("{name}: band fill") }; assert!( @@ -566,7 +685,7 @@ mod tests { ); } for (shape, (ys, color, width)) in shapes[usize::from(fill)..].iter().zip(expected) { - let Shape::Path(line) = &shape.shape else { + let Shape::Path(line) = shape else { panic!("{name}: unexpected shape") }; assert_eq!(line.stroke, Stroke::new(width, color).into(), "{name}"); @@ -578,12 +697,132 @@ mod tests { assert_eq!(line.points, points, "{name}"); } } + + let edited = |edit: fn(&mut VwapConfig)| { + let mut config = VwapConfig::default(); + edit(&mut config); + render(0.0, 1.0, Some(config)) + }; + let strokes = |shapes: &[Shape]| -> Vec { + shapes + .iter() + .filter_map(|shape| match shape { + Shape::Path(line) => match line.stroke.color { + egui::epaint::ColorMode::Solid(color) => Some(color), + _ => None, + }, + _ => None, + }) + .collect() + }; + // Hidden line: the fill and band 1 stay. + let shapes = edited(|c| c.show_line = false); + assert!(matches!(shapes[0], Shape::Mesh(_))); + assert_eq!(strokes(&shapes), [green, green]); + assert_eq!(shapes.len(), 3); + // Columns: one column per value, from price zero up to the VWAP. + let shapes = edited(|c| c.plot_type = crate::drawings::VwapPlotType::Columns); + assert_eq!(strokes(&shapes), [green, green]); + let columns: Vec<_> = shapes[3..] + .iter() + .map(|shape| match shape { + Shape::Rect(rect) if rect.fill == blue => (rect.rect.center().x, rect.rect.top()), + other => panic!("column: {other:?}"), + }) + .collect(); + assert_eq!(columns, [(110.0, 100.0), (120.0, 90.0), (130.0, 90.0)]); + // Fill off: no mesh under the band. + let shapes = edited(|c| c.band_fill.visible = false); + assert_eq!(strokes(&shapes), [green, green, blue]); + assert_eq!(shapes.len(), 3); + // Fill in its own colour and opacity. + let shapes = + edited(|c| c.band_fill = VwapFill::new(true, Some([200, 0, 0, 255]), 0.5).unwrap()); + let Shape::Mesh(mesh) = &shapes[0] else { + panic!("band fill") + }; + let red = Color32::from_rgb(200, 0, 0).gamma_multiply(0.5); + assert!(mesh.vertices.iter().all(|v| v.color == red)); + // Background: green at 5% from the anchor bar to the last bar, full height, under the + // fill. + let shapes = edited(|c| c.background.visible = true); + let Shape::Rect(wash) = &shapes[0] else { + panic!("background") + }; + assert_eq!( + (wash.rect, wash.fill), + ( + Rect::from_min_max(Pos2::new(100.0, 0.0), Pos2::new(130.0, 600.0)), + green.gamma_multiply(0.05) + ) + ); + assert!(matches!(shapes[1], Shape::Mesh(_))); + assert_eq!(shapes.len(), 5); + // Latest value: a dotted line in the line colour across the pane at VWAP 11, y = 90. + let shapes = edited(|c| c.track_price = true); + assert_eq!(shapes.len(), 5); + let Shape::Mesh(dashes) = &shapes[4] else { + panic!("price line") + }; + assert!( + dashes + .vertices + .iter() + .all(|v| (v.pos.y - 90.0).abs() <= 1.0) + ); + let xs = dashes.vertices.iter().map(|v| v.pos.x); + assert!(xs.clone().fold(f32::MAX, f32::min) < 5.0); + assert!(xs.fold(f32::MIN, f32::max) > 795.0); + } + + /// Paints an anchored VWAP of a blue drawing over `bars` from `anchor`, 10 px a bar from + /// x = 100 and 10 px a price from 20 at the top of an 800 by 600 pane. + fn render_vwap( + bars: &[Bar], + anchor: f32, + width: f32, + config: Option, + ) -> Vec { + let mut drawing = Drawing::new(1, DrawingToolType::AnchoredVWAP); + drawing.color = [41, 98, 255, 255]; + drawing.stroke_width = width; + drawing.vwap = config; + drawing.chart_points = vec![crate::drawings::ChartPoint::new(anchor, 50.0)]; + let view = ChartView { + instrument: None, + price_formatter: None, + time_formatter: None, + bar_seconds: 0, + bars, + revision: 0, + bar_to_x: &|b| 100.0 + 10.0 * b, + price_to_y: &|p| ((20.0 - p) * 10.0) as f32, + y_to_price: &|y| 20.0 - f64::from(y) / 10.0, + time_axis: true, + executions: None, + timeframe: None, + finer: &[], + }; + let mut output = egui::Context::default().run_ui(egui::RawInput::default(), |ui| { + let painter = egui::Painter::new( + ui.ctx().clone(), + egui::LayerId::background(), + Rect::from_min_max(Pos2::ZERO, Pos2::new(800.0, 600.0)), + ); + drawing.render_anchored_vwap(&painter, &view); + }); + let shapes = std::mem::take(&mut output.shapes); + output.drop_without_applying_deltas(); + shapes.into_iter().map(|shape| shape.shape).collect() } /// Reference: VWAP of (h + l + c) / 3 from bar 1, and the standard - /// deviation from its definition, sqrt(sum v (tp - vwap)^2 / sum v). + /// deviation from its definition, sqrt(sum v (tp - vwap)^2 / sum v). Every source and band + /// unit follows the same definition from the bar's own prices, and each source gives its own + /// VWAP on bars whose open, high, low and close differ. #[test] fn anchored_vwap_matches_reference() { + use crate::drawings::{VwapBandMode, VwapConfig}; let want = [ (11.666666666666664, 0.0), (11.595238095238095, 0.08247860988423196), @@ -593,7 +832,14 @@ mod tests { (12.78395061728395, 0.8112060000493586), ]; let bars = &sample_bars()[1..]; - let got: Vec<_> = anchored_vwap(bars, &vwap_checkpoints(&[]), 0..bars.len()).collect(); + let typical = VwapConfig::default(); + let got: Vec<_> = anchored_vwap( + bars, + &vwap_checkpoints(&[], typical.source), + &typical, + 0..bars.len(), + ) + .collect(); assert_eq!(got.len(), want.len()); for (got, (vwap, sigma)) in got.into_iter().zip(want) { let (got_vwap, got_sigma) = got.unwrap(); @@ -607,46 +853,74 @@ mod tests { // Windows that start inside a block or on a block boundary resume // from a checkpoint: compare with the definition over a series three - // blocks long, the forming bar in the third block. + // blocks long, the forming bar in the third block, for every source + // and unit. The checkpoints of one source are never reused for another. let long: Vec = (0..3 * VWAP_CHECKPOINT) .map(|i| { let close = 100.0 + (i * 37 % 101) as f64 / 10.0; let time = chrono::DateTime::from_timestamp(i as i64 * 60, 0).unwrap(); let volume = (1 + i % 7) as f64; - Bar::new(time, close, close + 1.0, close - 1.5, close, volume) + Bar::new(time, close - 0.4, close + 1.0, close - 1.5, close, volume) }) .collect(); - let checkpoints = vwap_checkpoints(&long[..2 * VWAP_CHECKPOINT]); - for window in [ - VWAP_CHECKPOINT + 5..VWAP_CHECKPOINT + 9, - 2 * VWAP_CHECKPOINT..2 * VWAP_CHECKPOINT + 4, - ] { - let got = anchored_vwap(&long, &checkpoints, window.clone()); - for (i, got) in window.zip(got) { - let prefix = &long[..=i]; - let volume: f64 = prefix.iter().map(|b| b.volume).sum(); - let vwap = prefix - .iter() - .map(|b| b.typical_price() * b.volume) - .sum::() - / volume; - let variance = prefix - .iter() - .map(|b| b.volume * (b.typical_price() - vwap).powi(2)) - .sum::() - / volume; - let (got_vwap, got_sigma) = got.unwrap(); - assert!( - (got_vwap - vwap).abs() < 1e-9, - "bar {i}: vwap {got_vwap}, want {vwap}" - ); - assert!( - (got_sigma - variance.sqrt()).abs() < 1e-6, - "bar {i}: sigma {got_sigma}, want {}", - variance.sqrt() - ); + type Source = (PriceSource, fn(&Bar) -> f64); + let sources: [Source; 7] = [ + (PriceSource::Open, |b| b.open), + (PriceSource::High, |b| b.high), + (PriceSource::Low, |b| b.low), + (PriceSource::Close, |b| b.close), + (PriceSource::HL2, |b| (b.high + b.low) / 2.0), + (PriceSource::HLC3, |b| (b.high + b.low + b.close) / 3.0), + (PriceSource::OHLC4, |b| { + (b.open + b.high + b.low + b.close) / 4.0 + }), + ]; + let mut finals = Vec::new(); + for (source, price) in sources { + for mode in [VwapBandMode::Deviation, VwapBandMode::Percentage] { + let config = VwapConfig { + source, + band_mode: mode, + ..VwapConfig::default() + }; + let checkpoints = cached_checkpoints(source, 0, &long, 0); + for window in [ + 0..4, + VWAP_CHECKPOINT + 5..VWAP_CHECKPOINT + 9, + 2 * VWAP_CHECKPOINT..2 * VWAP_CHECKPOINT + 4, + long.len() - 1..long.len(), + ] { + let got = anchored_vwap(&long, &checkpoints, &config, window.clone()); + for (i, got) in window.zip(got) { + let prefix = &long[..=i]; + let volume: f64 = prefix.iter().map(|b| b.volume).sum(); + let vwap = prefix.iter().map(|b| price(b) * b.volume).sum::() / volume; + let unit = match mode { + VwapBandMode::Deviation => (prefix + .iter() + .map(|b| b.volume * (price(b) - vwap).powi(2)) + .sum::() + / volume) + .sqrt(), + VwapBandMode::Percentage => vwap / 100.0, + }; + let (got_vwap, got_unit) = got.unwrap(); + let row = format!("{source:?} {mode:?} bar {i}"); + assert!((got_vwap - vwap).abs() < 1e-9, "{row}: {got_vwap} {vwap}"); + assert!((got_unit - unit).abs() < 1e-6, "{row}: {got_unit} {unit}"); + if i == long.len() - 1 && mode == VwapBandMode::Deviation { + finals.push(got_vwap); + } + } + } } } + for (i, a) in finals.iter().enumerate() { + assert!( + finals[i + 1..].iter().all(|b| (a - b).abs() > 1e-3), + "{finals:?}" + ); + } } /// Rows retain their gaps on either scale, leave two thirds of the span clear, diff --git a/vendor/egui-charts/src/drawings/repositories.rs b/vendor/egui-charts/src/drawings/repositories.rs index 08fd13c..d4a348e 100644 --- a/vendor/egui-charts/src/drawings/repositories.rs +++ b/vendor/egui-charts/src/drawings/repositories.rs @@ -30,6 +30,7 @@ pub trait DrawingToolsRepository { } /// Drawing tool lookup backed by [`categories`]. +#[derive(Debug)] pub struct InMemoryToolsRepository; impl InMemoryToolsRepository { diff --git a/vendor/egui-charts/src/drawings/services/handle.rs b/vendor/egui-charts/src/drawings/services/handle.rs index 251b0c9..1a980ce 100644 --- a/vendor/egui-charts/src/drawings/services/handle.rs +++ b/vendor/egui-charts/src/drawings/services/handle.rs @@ -19,6 +19,7 @@ use egui::{Color32, Pos2}; /// Configuration for selection handle appearance and hit testing. #[derive(Clone, Debug)] +#[non_exhaustive] pub struct HandleConfig { /// Handle diameter in pixels. pub size: f32, @@ -48,6 +49,7 @@ impl Default for HandleConfig { /// All methods are static (`&self`-free) since `HandleService` carries no state. /// It computes handle positions, performs hit testing, updates handle positions /// during drags, and renders the handles onto the chart. +#[derive(Debug)] pub struct HandleService; impl HandleService { diff --git a/vendor/egui-charts/src/drawings/services/history.rs b/vendor/egui-charts/src/drawings/services/history.rs index d9b20f6..97e5cf4 100644 --- a/vendor/egui-charts/src/drawings/services/history.rs +++ b/vendor/egui-charts/src/drawings/services/history.rs @@ -309,9 +309,12 @@ impl HistoryService { modified_at, }); } - DrawingCommand::Add(drawing) => { - // Undo add = remove the drawing - drawings.retain(|d| d.id != drawing.id); + DrawingCommand::Add(mut drawing) => { + // Undo add = remove the drawing, keeping it as it is now for redo: it has taken + // on state since it was recorded, such as what its first display adopts. + if let Some(at) = drawings.iter().position(|d| d.id == drawing.id) { + drawing = drawings.remove(at); + } self.redo_stack.push(DrawingCommand::Add(drawing)); } DrawingCommand::Delete { drawing, index } => { diff --git a/vendor/egui-charts/src/drawings/services/interaction.rs b/vendor/egui-charts/src/drawings/services/interaction.rs index 6c76b76..e10bd26 100644 --- a/vendor/egui-charts/src/drawings/services/interaction.rs +++ b/vendor/egui-charts/src/drawings/services/interaction.rs @@ -16,6 +16,7 @@ use egui::{Color32, Pos2, Rect, Stroke, epaint::StrokeKind}; /// Manages selection state, handle dragging, and hit testing. Unlike /// [`DrawingManager`](crate::drawings::DrawingManager) which coordinates all /// services, `DrawingInteraction` focuses purely on pointer-based interaction. +#[derive(Debug)] pub struct DrawingInteraction { /// Currently selected drawing ID, or `None`. pub sel_drawing: Option, diff --git a/vendor/egui-charts/src/drawings/services/snap.rs b/vendor/egui-charts/src/drawings/services/snap.rs index 3d94d46..0e50a96 100644 --- a/vendor/egui-charts/src/drawings/services/snap.rs +++ b/vendor/egui-charts/src/drawings/services/snap.rs @@ -12,6 +12,7 @@ use egui::Pos2; /// Options for snap behavior #[derive(Debug, Clone)] +#[non_exhaustive] pub struct SnapOptions { /// Enable snap to OHLC prices pub snap_to_price: bool, @@ -39,6 +40,7 @@ impl Default for SnapOptions { /// Snap targets - prices and times to snap to #[derive(Debug, Clone, Default)] +#[non_exhaustive] pub struct SnapTargets { /// Y-coordinates of OHLC prices in screen space pub prices: Vec, diff --git a/vendor/egui-charts/src/drawings/services/z_order.rs b/vendor/egui-charts/src/drawings/services/z_order.rs index 2f8ec2f..7e0f231 100644 --- a/vendor/egui-charts/src/drawings/services/z_order.rs +++ b/vendor/egui-charts/src/drawings/services/z_order.rs @@ -6,6 +6,7 @@ use crate::drawings::domain::Drawing; /// Service for managing drawing z-order (render layering) +#[derive(Debug)] pub struct ZOrderService; impl ZOrderService { diff --git a/vendor/egui-charts/src/lib.rs b/vendor/egui-charts/src/lib.rs index 811e13f..d9aa477 100644 --- a/vendor/egui-charts/src/lib.rs +++ b/vendor/egui-charts/src/lib.rs @@ -130,8 +130,19 @@ //! //! Construct extensible options with their constructors or `Default`, then assign //! public fields. Include a fallback arm when matching a `#[non_exhaustive]` enum. +//! +//! A few types stay exhaustive on purpose. `widget::SeriesOptions`, +//! `chart::overlays::VolumeBubblesConfig`, `model::ChartTypeParams`, `theme::Theme` and +//! `drawings::{FibonacciConfig, PitchforkConfig, GannConfig}` are built in one expression +//! that ends in `..Default::default()` or `..Theme::light()`, which keeps compiling when a +//! field is added. The records a custom study returns from `studies::Indicator` methods, +//! such as `studies::PlotStyle` and `studies::StudyZone`, stay exhaustive so that a study +//! can build them directly; studies grow through new default trait methods instead. +//! `widget::MismatchDirection`, `model::PriceLineSource` and `model::LogicalRange` are +//! complete by meaning. // ─── Crate-level lint configuration ────────────────────────────────────────── +#![warn(missing_debug_implementations)] #![warn(unnameable_types)] #![allow(clippy::too_many_arguments)] #![allow(clippy::module_inception)] @@ -205,10 +216,14 @@ pub mod guide {} #[cfg(feature = "ui")] #[cfg_attr(docsrs, doc(cfg(feature = "ui")))] +// Debug for these types remains follow-up work from #1315. +#[allow(missing_debug_implementations)] pub mod ui_kit; #[cfg(feature = "ui")] #[cfg_attr(docsrs, doc(cfg(feature = "ui")))] +// Debug for these types remains follow-up work from #1315. +#[allow(missing_debug_implementations)] pub mod ui; // ─── Convenience re-exports ────────────────────────────────────────────────── diff --git a/vendor/egui-charts/src/localization.rs b/vendor/egui-charts/src/localization.rs index 5772417..1b8c1cd 100644 --- a/vendor/egui-charts/src/localization.rs +++ b/vendor/egui-charts/src/localization.rs @@ -66,6 +66,20 @@ pub fn format_text(ctx: &Context, english: &str, values: &[(&str, impl AsRef, + english: &str, + values: &[(&str, impl AsRef)], +) -> String { + match ctx { + Some(ctx) => format_text(ctx, english, values), + None => substitute(english, values), + } +} + /// The host's translation of `english`, or `None` to keep the English text. pub(crate) fn lookup(ctx: &Context, english: &str) -> Option { let translator = ctx.data(|data| data.get_temp::(translator_id())); diff --git a/vendor/egui-charts/src/model/alert.rs b/vendor/egui-charts/src/model/alert.rs index b13b559..a859273 100644 --- a/vendor/egui-charts/src/model/alert.rs +++ b/vendor/egui-charts/src/model/alert.rs @@ -2,6 +2,7 @@ use chrono::{DateTime, Datelike, NaiveTime, Utc, Weekday}; use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; use super::{Bar, Timeframe, TimezoneId}; @@ -157,7 +158,7 @@ pub struct AlertInputs { /// Exchange calendar of the creation symbol. Other symbols resolve their own calendars. pub calendar: Option, /// Source choices shown when editing, independent of the currently displayed chart. - pub sources: Vec<(AlertSource, String)>, + pub sources: Vec<(AlertSource, AlertSourceName)>, /// Include extended trading sessions. pub extended_hours: bool, /// Host currency or unit conversion. @@ -193,7 +194,9 @@ impl Default for AlertInputs { impl AlertInputs { /// Offer newly available study sources during an explicit edit. Existing identifiers keep - /// their original definitions, including when another chart reuses an identifier. + /// their original definitions, including when another chart reuses an identifier. A saved + /// name whose English text equals the offered name takes the offered one, so a name saved + /// as finished text is translated from then on. pub fn add_sources_from(&mut self, other: &Self) { for study in &other.studies { if !self.studies.iter().any(|saved| saved.id == study.id) { @@ -201,8 +204,10 @@ impl AlertInputs { } } for (source, name) in &other.sources { - if !self.sources.iter().any(|(saved, _)| saved == source) { - self.sources.push((source.clone(), name.clone())); + match self.sources.iter_mut().find(|(saved, _)| saved == source) { + Some((_, saved)) if *saved == *name => *saved = name.clone(), + Some(_) => {} + None => self.sources.push((source.clone(), name.clone())), } } } @@ -335,8 +340,8 @@ impl Alert { /// fired, both in RFC 3339, `{{open}}`, `{{high}}`, `{{low}}`, `{{close}}` and `{{volume}}` of /// `bar`, `{{value}}` the value of the alert's source, `{{output_N}}` the value of output `N` /// of the study the source names (empty if the source is not a study), `{{plot_ID_N}}` the - /// value of output `N` of the study `ID` whatever the source is, and `{{level}}` the label - /// that [`AlertInputs::sources`] gives the drawing level the first condition tests: the source + /// value of output `N` of the study `ID` whatever the source is, and `{{level}}` the English + /// name that [`AlertInputs::sources`] gives the drawing level the first condition tests: the source /// if it is a drawing, otherwise the drawing it compares with or those bounding its channel, /// joined by `, `, and empty if it tests no drawing. `value` gives the value of a source at /// the bar. A value that is missing or not finite becomes `NaN`, a number is written in the @@ -403,7 +408,7 @@ impl Alert { .flatten() .filter(|source| matches!(source, AlertSource::Drawing(_))) .filter_map(|source| saved.iter().find(|(s, _)| s == source)) - .map(|(_, label)| label.as_str()) + .map(|(_, label)| label.to_string()) .collect(); labels.join(", ") } @@ -572,6 +577,120 @@ pub enum AlertSource { Volume, } +/// The name an alert source is shown with: English text, translated only when shown. +/// +/// `Chart::alert_sources` builds each name from an English template such as +/// `"{tool} {id}: {level}"`, whose placeholders take values shown as given, such as a study's +/// name or a drawing's number, and labels translated whole, such as a drawing tool, a level or a +/// study output, and keeps the English text they make. A host's own name converts from a string +/// and is translated whole. A name is stored and compared by its English text, which +/// [`Display`](std::fmt::Display) gives, so names saved as finished text, as alerts and presets +/// stored every name before names kept their parts, still match the chart's names. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(transparent)] +pub struct AlertSourceName(SourceName); + +/// A name with its parts, or finished text: a host's own name, or one that alerts and presets +/// saved before names kept their parts hold. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(untagged)] +enum SourceName { + /// `template` with each `{name}` taken from `values` as given or from `labels` translated, + /// and `text`, the English it makes. + Parts { + text: String, + template: String, + values: BTreeMap, + labels: BTreeMap, + }, + /// Text translated whole. + Text(String), +} + +impl AlertSourceName { + /// A name built from `template`, whose placeholders take `values` as given and `labels` + /// translated when shown. + #[cfg(feature = "drawings")] + pub(crate) fn new(template: &str, values: &[(&str, &str)], labels: &[(&str, &str)]) -> Self { + let owned = |parts: &[(&str, &str)]| { + parts + .iter() + .map(|&(name, part)| (name.to_owned(), part.to_owned())) + .collect() + }; + Self(SourceName::Parts { + text: crate::localization::substitute(template, &[values, labels].concat()), + template: template.to_owned(), + values: owned(values), + labels: owned(labels), + }) + } + + /// The name in the language of `ctx`'s translator: each label looked up whole, then the + /// template looked up and filled with the values and the translated labels, as + /// [`format_text`](crate::localization::format_text) does. A name without parts is looked up + /// whole. Without a translator this is the English text. + #[cfg(feature = "widget")] + #[cfg_attr(docsrs, doc(cfg(feature = "widget")))] + pub fn text(&self, ctx: &egui::Context) -> String { + use crate::localization as l10n; + match &self.0 { + SourceName::Text(text) => l10n::text(ctx, text), + SourceName::Parts { + template, + values, + labels, + .. + } => { + let labels: Vec<_> = labels + .iter() + .map(|(name, label)| (name.as_str(), l10n::text(ctx, label))) + .collect(); + let parts: Vec<(&str, &str)> = values + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())) + .chain(labels.iter().map(|(name, label)| (*name, label.as_str()))) + .collect(); + l10n::format_text(ctx, template, &parts) + } + } + } + + /// The English text. + fn english(&self) -> &str { + match &self.0 { + SourceName::Parts { text, .. } | SourceName::Text(text) => text, + } + } +} + +impl From for AlertSourceName { + fn from(text: String) -> Self { + Self(SourceName::Text(text)) + } +} + +impl From<&str> for AlertSourceName { + fn from(text: &str) -> Self { + text.to_owned().into() + } +} + +impl std::fmt::Display for AlertSourceName { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.english()) + } +} + +/// Names are equal when their English text is, whether or not they keep their parts. +impl PartialEq for AlertSourceName { + fn eq(&self, other: &Self) -> bool { + self.english() == other.english() + } +} + +impl Eq for AlertSourceName {} + /// Comparison of two outputs. Crossings require a strict previous side and include equality now. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum AlertComparison { diff --git a/vendor/egui-charts/src/model/bar/bar.rs b/vendor/egui-charts/src/model/bar/bar.rs index b20e5ff..582f2ad 100644 --- a/vendor/egui-charts/src/model/bar/bar.rs +++ b/vendor/egui-charts/src/model/bar/bar.rs @@ -46,6 +46,7 @@ pub(crate) fn last_with_value(bars: &[Bar]) -> Option<&Bar> { /// assert!(bar.is_bullish()); // close > open /// ``` #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] pub struct Bar { /// Timestamp of the bar. Read from JSON as an RFC 3339 time, or as a date alone /// (`"2024-03-15"`), which is midnight UTC of that day, the open of its day bar. diff --git a/vendor/egui-charts/src/model/bar/bar_data.rs b/vendor/egui-charts/src/model/bar/bar_data.rs index d74ab78..8334cf8 100644 --- a/vendor/egui-charts/src/model/bar/bar_data.rs +++ b/vendor/egui-charts/src/model/bar/bar_data.rs @@ -17,6 +17,7 @@ use super::bar::Bar; /// assert!(data.is_empty()); /// ``` #[derive(Debug, Clone, Default)] +#[non_exhaustive] pub struct BarData { /// Bars in caller-supplied order; construction does not sort or validate them. pub bars: Vec, diff --git a/vendor/egui-charts/src/model/chart_type.rs b/vendor/egui-charts/src/model/chart_type.rs index 4688781..1f283fe 100644 --- a/vendor/egui-charts/src/model/chart_type.rs +++ b/vendor/egui-charts/src/model/chart_type.rs @@ -317,7 +317,8 @@ impl ChartType { } /// Whether this chart type is time-independent, with one time-scale slot per element. - /// Studies, drawings and markers are kept but not drawn, hit or edited on these types. + /// Studies, drawings and markers are drawn at the element that contains their time, and + /// volume is hidden. pub fn is_time_independent(&self) -> bool { matches!( self, @@ -536,11 +537,22 @@ pub enum FootprintStatistic { Trades, /// Total volume divided by execution count; undefined for an empty bar. AverageSize, + /// Sell volume divided by total volume, in percent. + BidPercent, + /// Buy volume divided by total volume, in percent. + AskPercent, + /// The bar's high minus its low. + Range, + /// The lowest price of the bar's highest-volume row, as the footprint groups its rows. + PointOfControl, + /// The change of total volume from the previous bar with executions, in percent; the first + /// such bar has none. + VolumeChange, } impl FootprintStatistic { /// All available rows in their display order. - pub const ALL: [Self; 11] = [ + pub const ALL: [Self; 16] = [ Self::Volume, Self::Bid, Self::Ask, @@ -552,6 +564,11 @@ impl FootprintStatistic { Self::AskBidRatio, Self::Trades, Self::AverageSize, + Self::BidPercent, + Self::AskPercent, + Self::Range, + Self::PointOfControl, + Self::VolumeChange, ]; /// Shared table label. @@ -568,6 +585,11 @@ impl FootprintStatistic { Self::AskBidRatio => "Ask/Bid", Self::Trades => "Trades", Self::AverageSize => "Average size", + Self::BidPercent => "Bid %", + Self::AskPercent => "Ask %", + Self::Range => "Range", + Self::PointOfControl => "POC", + Self::VolumeChange => "Vol change %", } } } @@ -594,6 +616,9 @@ pub struct ChartTypeParams { pub footprint_color_by: FootprintColor, /// Footprint: buy, sell, text and neutral colours. None follows the chart theme. pub footprint_colors: [Option; 4], + /// Footprint: buy and sell colours of imbalance strips, imbalance colouring and stacked + /// imbalance zones. None follows the buy or sell colour. + pub footprint_imbalance_colors: [Option; 2], /// Footprint: instrument ticks per row; zero groups automatically with zoom. pub footprint_row_ticks: u32, /// Footprint: put a strip along the outer edge of a side that dominates under the imbalance @@ -645,6 +670,9 @@ pub struct ChartTypeParams { pub footprint_statistics: bool, /// Footprint: statistics rows in display order; an empty list hides the table. pub footprint_statistics_rows: Vec, + /// Footprint: restart the cumulative delta row at the first bar of each session, rather than + /// summing every complete bar. + pub footprint_session_cumulative_delta: bool, /// Execution-based session profile display settings. pub profile: TradeProfileSettings, /// Independent line, area and baseline styles, retained across chart type changes. @@ -732,6 +760,7 @@ impl Default for ChartTypeParams { footprint_profile: false, footprint_color_by: FootprintColor::VolumeSteps, footprint_colors: [None; 4], + footprint_imbalance_colors: [None; 2], footprint_row_ticks: 0, footprint_imbalance: true, footprint_poc: true, @@ -760,6 +789,7 @@ impl Default for ChartTypeParams { FootprintStatistic::Delta, FootprintStatistic::DeltaPercent, ], + footprint_session_cumulative_delta: false, profile: TradeProfileSettings::default(), styles: super::ChartTypeStyles::default(), renko_size_method: super::BoxSizeMethod::Fixed, @@ -841,24 +871,34 @@ impl ChartTypeParams { ] } - /// Resolve pending sizes only when their history is ready. Each successful calculation is - /// frozen until explicitly armed again; prepending history and live corrections keep it. + /// Sizes in Renko, Kagi, Range, Point and Figure order. #[cfg(feature = "widget")] - pub(crate) fn resolve_sizes(&mut self, bars: &[super::Bar], pending: &mut [bool; 4]) { - let methods = self.size_methods(); - let sizes = [ + pub(crate) fn sizes_mut(&mut self) -> [&mut f64; 4] { + [ &mut self.renko_brick_size, &mut self.kagi_reversal, &mut self.range_size, &mut self.pnf_box_size, - ]; - for ((method, size), pending) in methods.into_iter().zip(sizes).zip(pending) { + ] + } + + /// Resolve pending sizes only when their history is ready. Each successful calculation is + /// frozen until explicitly armed again; prepending history and live corrections keep it. + #[cfg(feature = "widget")] + pub(crate) fn resolve_sizes(&mut self, bars: &[super::Bar], pending: &mut [bool; 4]) { + let methods = self.size_methods(); + // Whitespace bars have no price and do not count, as in `BoxSizeMethod::resolve`. This + // runs every frame, so it reads only as many bars as a pending size needs. + let loaded = bars.iter().filter(|bar| !bar.is_whitespace()); + for ((method, size), pending) in methods.into_iter().zip(self.sizes_mut()).zip(pending) { if !*pending { continue; } let waiting = match method { - super::BoxSizeMethod::Atr { period, .. } => period > bars.len(), - super::BoxSizeMethod::Percentage(_) => bars.is_empty(), + super::BoxSizeMethod::Atr { period, .. } => { + loaded.clone().take(period).count() < period + } + super::BoxSizeMethod::Percentage(_) => loaded.clone().next().is_none(), super::BoxSizeMethod::Fixed => false, }; *size = method.resolve(*size, bars).unwrap_or(0.0); @@ -866,21 +906,30 @@ impl ChartTypeParams { } } - /// Why `chart_type` cannot be drawn with these parameters, if it cannot. + /// Why `chart_type` cannot be drawn with these parameters, if it cannot. A size derived from + /// history is judged by its method, since it is 0 while it waits for history. #[cfg(feature = "widget")] pub(crate) fn invalid(&self, chart_type: ChartType) -> Option<&'static str> { - let usable = |size: f64| size > 0.0 && size.is_finite(); + use super::BoxSizeMethod::{Atr, Fixed, Percentage}; + let positive = |n: f64| n > 0.0 && n.is_finite(); + let usable = |method, size| match method { + Fixed => positive(size), + Atr { period, multiplier } => period > 0 && positive(multiplier), + Percentage(percent) => positive(percent), + }; match chart_type { - ChartType::Renko if !usable(self.renko_brick_size) => { + ChartType::Renko if !usable(self.renko_size_method, self.renko_brick_size) => { Some("Renko brick size must be a positive number") } - ChartType::Kagi if !usable(self.kagi_reversal) => { + ChartType::Kagi if !usable(self.kagi_size_method, self.kagi_reversal) => { Some("Kagi reversal amount must be a positive number") } - ChartType::Range if !usable(self.range_size) => { + ChartType::Range if !usable(self.range_size_method, self.range_size) => { Some("Range size must be a positive number") } - ChartType::PointAndFigure if !usable(self.pnf_box_size) || self.pnf_reversal == 0 => { + ChartType::PointAndFigure + if !usable(self.pnf_size_method, self.pnf_box_size) || self.pnf_reversal == 0 => + { Some( "Point and Figure box size must be a positive number and the reversal at least 1 box", ) @@ -891,6 +940,25 @@ impl ChartTypeParams { _ => None, } } + + /// The bars of history the size of `chart_type` needs, while its method derives it from + /// history and it is not yet a positive size. + #[cfg(feature = "widget")] + pub(crate) fn bars_needed(&self, chart_type: ChartType) -> Option { + let (method, size) = match chart_type { + ChartType::Renko => (self.renko_size_method, self.renko_brick_size), + ChartType::Kagi => (self.kagi_size_method, self.kagi_reversal), + ChartType::Range => (self.range_size_method, self.range_size), + ChartType::PointAndFigure => (self.pnf_size_method, self.pnf_box_size), + _ => return None, + }; + match method { + _ if size > 0.0 && size.is_finite() => None, + super::BoxSizeMethod::Atr { period, .. } => Some(period), + super::BoxSizeMethod::Percentage(_) => Some(1), + super::BoxSizeMethod::Fixed => None, + } + } } #[cfg(test)] @@ -902,8 +970,11 @@ mod tests { let settings = serde_json::json!({ "footprint_modes": ["Delta", "BidAskTrades", "Trades", "AverageSize"], "footprint_row_ticks": 2, "footprint_value_area": 0.010003969988090037, - "footprint_statistics": true, "footprint_statistics_rows": ["Volume", "Delta", "Trades", "AverageSize"], + "footprint_statistics": true, + "footprint_statistics_rows": ["Volume", "Delta", "Trades", "AverageSize", "PointOfControl", "VolumeChange"], + "footprint_session_cumulative_delta": true, "footprint_colors": [[12, 34, 56, 255], null, null, null], + "footprint_imbalance_colors": [[200, 30, 220, 255], null], "tpo_letters": false, "profile": {"mode": "Volume", "value_area": 0.5, "developing_poc": true, "developing_value_area": true, "extend_poc": true, "extend_vah": true, @@ -953,6 +1024,11 @@ mod tests { legacy["footprint_colors"], serde_json::json!([null, null, null, null]) ); + assert_eq!( + legacy["footprint_imbalance_colors"], + serde_json::json!([null, null]) + ); + assert_eq!(legacy["footprint_session_cumulative_delta"], false); for field in [ "footprint_stacked_imbalances", "footprint_naked_poc", diff --git a/vendor/egui-charts/src/model/instrument.rs b/vendor/egui-charts/src/model/instrument.rs index f7ae1ba..03ae06a 100644 --- a/vendor/egui-charts/src/model/instrument.rs +++ b/vendor/egui-charts/src/model/instrument.rs @@ -87,6 +87,8 @@ pub enum FeedService { Metrics, /// [`Datafeed::price_targets`](crate::data::Datafeed::price_targets). PriceTargets, + /// [`Datafeed::financials`](crate::data::Datafeed::financials). + Financials, /// [`Datafeed::symbol_details`](crate::data::Datafeed::symbol_details). SymbolDetails, /// [`Datafeed::news`](crate::data::Datafeed::news). @@ -150,7 +152,9 @@ pub struct Instrument { pub price_decimals: Option, /// Decimals of volume readouts, including abbreviated K/M/B values. pub volume_decimals: Option, - /// Currency of prices, such as "USD". + /// Currency of prices, such as "USD". A code that mixes upper and lower case names a minor + /// unit and matches only itself, such as "GBp" for pence against "GBP"; other codes match + /// regardless of case. pub currency: Option, /// Host-supplied price unit, such as "USD/barrel"; no conversion is performed. pub unit: Option, @@ -378,6 +382,21 @@ impl Instrument { } } +/// Whether two currency codes name the same currency. A code that mixes upper and lower case +/// names a minor unit, such as `GBp` for pence, and matches only itself; other codes match +/// regardless of ASCII case, so `gbp` is `GBP`. +#[cfg(any(feature = "studies", feature = "drawings"))] +pub(crate) fn same_currency(a: &str, b: &str) -> bool { + let mixed = |code: &str| { + code.bytes().any(|c| c.is_ascii_lowercase()) && code.bytes().any(|c| c.is_ascii_uppercase()) + }; + if mixed(a) || mixed(b) { + a == b + } else { + a.eq_ignore_ascii_case(b) + } +} + /// A bar interval a feed suggests for volume profile studies and drawings, for profiles up to a length. /// Report them in [`Instrument::profile_resolutions`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/vendor/egui-charts/src/model/kagi.rs b/vendor/egui-charts/src/model/kagi.rs index fb60e05..8d388b6 100644 --- a/vendor/egui-charts/src/model/kagi.rs +++ b/vendor/egui-charts/src/model/kagi.rs @@ -13,7 +13,9 @@ //! //! A new line segment is created whenever price reverses by at least the //! configured [`reversal_amount`](KagiConfig::reversal_amount). Time is -//! ignored -- only price movement matters. +//! ignored -- only price movement matters. The first line starts at the first +//! close and runs to the first price beyond the reversal amount from it, up or +//! down. //! //! Use [`to_kagi_lines`] to transform a slice of [`Bar`]s. @@ -23,6 +25,7 @@ use chrono::{DateTime, Utc}; /// A single vertical segment in a Kagi chart. #[derive(Debug, Clone)] +#[non_exhaustive] pub struct KagiLine { /// Timestamp when this segment was created (from the source bar). pub ts: DateTime, @@ -73,6 +76,7 @@ impl KagiLine { /// The reversal amount can be set directly, derived from ATR, or /// computed as a percentage of price. #[derive(Debug, Clone)] +#[non_exhaustive] pub struct KagiConfig { /// Reversal amount - price movement needed to create a new line pub reversal_amount: f64, @@ -217,8 +221,18 @@ impl PriceBuilder for KagiBuilder { return; }; st.last_ts = bar.time; + // Only the first line can be unmoved: it has no direction until a price lies beyond the + // reversal amount from the first close. A bar beyond it on both sides counts as a rise. + let first = st.curr_price == st.line_start_price; let price = match self.source { PriceBasedSource::Close => bar.close, + PriceBasedSource::HighLow if first => { + if bar.high > st.curr_price + reversal { + bar.high + } else { + bar.low + } + } PriceBasedSource::HighLow if st.line_direction_up => { if bar.high > st.curr_price { bar.high @@ -235,6 +249,14 @@ impl PriceBuilder for KagiBuilder { } }; + if first { + if price > st.curr_price + reversal || price < st.curr_price - reversal { + st.line_direction_up = price > st.curr_price; + st.curr_price = price; + } + return; + } + let up = st.line_direction_up; if up && price < st.curr_price - reversal || !up && price > st.curr_price + reversal { self.lines.push(st.line()); @@ -285,36 +307,55 @@ mod tests { #[test] fn thickness_changes_where_a_line_crosses_the_prior_shoulder_or_waist() { use KagiThickness::{Thick, Thin}; + type Line = (f64, f64, KagiThickness, Option); + let cases: [(&[f64], &[Line]); 2] = [ + // 100 up to 105, down to 102, up through the 105 shoulder to 107 in one bar, down to + // 103 and on through the 102 waist to 101. + ( + &[100.0, 105.0, 102.0, 107.0, 103.0, 101.0], + &[ + (100.0, 105.0, Thin, None), + (105.0, 102.0, Thin, None), + (102.0, 107.0, Thick, Some(105.0)), + (107.0, 101.0, Thin, Some(102.0)), + ], + ), + // A first move down starts a falling line at the first close: 100 down to 95, up to + // 98 short of the 100 shoulder, down to 94, up through the 98 shoulder to 101, and + // down to 99, above the 94 waist. + ( + &[100.0, 95.0, 98.0, 94.0, 101.0, 99.0], + &[ + (100.0, 95.0, Thin, None), + (95.0, 98.0, Thin, None), + (98.0, 94.0, Thin, None), + (94.0, 101.0, Thick, Some(98.0)), + (101.0, 99.0, Thick, None), + ], + ), + ]; let start = Utc::now(); - // 100 up to 105, down to 102, up through the 105 shoulder to 107 in one bar, down to - // 103 and on through the 102 waist to 101. - let bars: Vec = [100.0, 105.0, 102.0, 107.0, 103.0, 101.0] - .into_iter() - .enumerate() - .map(|(i, close)| Bar { - time: start + Duration::minutes(i as i64), - open: close, - high: close, - low: close, - close, - volume: 0.0, - colors: None, - payload: None, - }) - .collect(); - let lines: Vec<_> = to_kagi_lines(&bars, &KagiConfig::new(1.0)) - .into_iter() - .map(|l| (l.start_price, l.end_price, l.thickness, l.crossing)) - .collect(); - assert_eq!( - lines, - [ - (100.0, 105.0, Thin, None), - (105.0, 102.0, Thin, None), - (102.0, 107.0, Thick, Some(105.0)), - (107.0, 101.0, Thin, Some(102.0)), - ] - ); + for (closes, expected) in cases { + let bars: Vec = closes + .iter() + .enumerate() + .map(|(i, &close)| Bar { + time: start + Duration::minutes(i as i64), + open: close, + high: close, + low: close, + close, + volume: 0.0, + colors: None, + payload: None, + }) + .collect(); + let lines: Vec<_> = to_kagi_lines(&bars, &KagiConfig::new(1.0)) + .into_iter() + .map(|l| (l.start_price, l.end_price, l.thickness, l.crossing)) + .collect(); + assert_eq!(lines, expected, "closes {closes:?}"); + } } #[test] diff --git a/vendor/egui-charts/src/model/line_break.rs b/vendor/egui-charts/src/model/line_break.rs index d5f20fe..fb59690 100644 --- a/vendor/egui-charts/src/model/line_break.rs +++ b/vendor/egui-charts/src/model/line_break.rs @@ -19,6 +19,7 @@ use chrono::{DateTime, Utc}; /// The `line_count` parameter (typically 3) controls how many prior lines /// must be exceeded for a reversal to register. #[derive(Debug, Clone)] +#[non_exhaustive] pub struct LineBreakConfig { /// Number of lines to look back for reversal pub line_count: usize, diff --git a/vendor/egui-charts/src/model/markers.rs b/vendor/egui-charts/src/model/markers.rs index 205b853..548f491 100644 --- a/vendor/egui-charts/src/model/markers.rs +++ b/vendor/egui-charts/src/model/markers.rs @@ -36,6 +36,7 @@ pub enum MarkerShape { /// Marker position relative to the data point #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[non_exhaustive] pub enum MarkerPos { /// Above the high price #[default] @@ -100,6 +101,7 @@ impl Default for MarkerOptions { /// Marker for chart annotations #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct Marker { /// Time of the marker (matches a data point) pub time: DateTime, @@ -250,6 +252,7 @@ impl Default for ChangeMarkers { /// Line style of drawings, series, grid and price lines. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash, Serialize, Deserialize)] +#[non_exhaustive] pub enum LineStyle { /// A continuous line. #[default] diff --git a/vendor/egui-charts/src/model/mod.rs b/vendor/egui-charts/src/model/mod.rs index 43126de..05352e0 100644 --- a/vendor/egui-charts/src/model/mod.rs +++ b/vendor/egui-charts/src/model/mod.rs @@ -57,8 +57,8 @@ mod watchlist; pub use alert::{ Alert, AlertCalendar, AlertChannelComparison, AlertComparison, AlertCondition, AlertDelivery, - AlertFrequency, AlertId, AlertInputs, AlertRule, AlertSource, AlertStatus, AlertStudy, - NotificationSchedule, NotificationWindow, + AlertFrequency, AlertId, AlertInputs, AlertRule, AlertSource, AlertSourceName, AlertStatus, + AlertStudy, NotificationSchedule, NotificationWindow, }; pub use bar::{Bar, BarColors, BarData}; #[cfg(feature = "widget")] @@ -80,6 +80,8 @@ pub use chart_type::{ pub use clock::BarClock; pub use color::ColorType; pub use date_range::DateRange; +#[cfg(any(feature = "studies", feature = "drawings"))] +pub(crate) use instrument::same_currency; pub use instrument::{ DataStatus, FeedService, Instrument, OverrideWindow, ProfileResolution, Session, SessionOverride, SessionWindow, SymbolType, diff --git a/vendor/egui-charts/src/model/range_bar.rs b/vendor/egui-charts/src/model/range_bar.rs index 89b651f..6e3b5b5 100644 --- a/vendor/egui-charts/src/model/range_bar.rs +++ b/vendor/egui-charts/src/model/range_bar.rs @@ -8,6 +8,8 @@ use super::PriceBuilder; use super::Tick; use super::bar::Bar; +use super::renko::reaches; +use super::rounding_tolerance; use chrono::{DateTime, Utc}; /// Configuration for range-bar construction. @@ -116,17 +118,27 @@ impl RangeBar { /// What a chart's range bars are built from. #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] pub enum RangeBarSource { /// The trades the feed supplied, in order, with their timestamps and volume. Executions, /// The open, high, low and close of the chart's bars: an approximation, used while the chart /// holds no trades. OhlcApproximation, + /// The OHLC approximation of the bars before the one holding the first held trade, followed + /// by the range bars of the trades from that trade on. + OhlcThenExecutions, } /// Build range bars from trades (exact construction). A trade's size that would make its bar's /// volume overflow is left out. /// +/// A bar closes one range from its low when a rise completes it and one range from its high when +/// a fall does, and a trade that reaches that price within the rounding of decimal prices and +/// sizes is on it: with a range of 0.1, trades at 1.1, 1.15 and 1.2 close a bar at 1.2. Bars that +/// follow one another in one direction are counted from where the run began, so their prices +/// carry no rounding from bar to bar. +/// /// # Safety Limits /// - At most the newest 5,000 range bars pub fn to_range_bars_from_ticks(ticks: &[Tick], config: &RangeBarConfig) -> Vec { @@ -137,8 +149,10 @@ pub fn to_range_bars_from_ticks(ticks: &[Tick], config: &RangeBarConfig) -> Vec< builder.elements() } -/// Convert OHLC bars to range bars (approximation). A bar's volume that would make its range bar's -/// volume overflow is left out. +/// Convert OHLC bars to range bars (approximation). Each bar is taken to have traded from its +/// open to the extreme nearer the open, on to the other extreme and then to its close; a range +/// bar closes at its high when a rise completes its range and at its low when a fall does. A +/// bar's volume that would make its range bar's volume overflow is left out. /// /// Returns no bars when the range size is not a positive finite number. /// @@ -175,6 +189,13 @@ pub(crate) struct RangeBarBuilder { range_size: f64, /// The range bar in progress; `None` until the first bar. curr_bar: Option, + /// The first OHLC bar while it is the only one: `curr_bar` shows it whole, and its path is + /// walked when the next bar arrives, so a first bar far wider than the range costs nothing. + seed: Option, + /// The bar in progress opened `steps` ranges from `anchor`, a price as it was supplied. + /// Boundaries are counted from it instead of added up from bar to bar. + anchor: f64, + steps: f64, bars: Vec, } @@ -183,14 +204,18 @@ impl RangeBarBuilder { Self { range_size, curr_bar: None, + seed: None, + anchor: 0.0, + steps: 0.0, bars: Vec::new(), } } /// Adds one trade, after the bars or trades already added. A trade that crosses several /// ranges closes one bar per range; a range of 0 or less closes none. A trade closes at most - /// 100 bars, which bounds the work for one bad print; raise it if gaps that large must chart - /// in full. The bar that follows a close holds the trade only when it lies beyond the close. + /// 100 bars, which bounds the work for one bad print, and the rest of its move is dropped; + /// raise it if gaps that large must chart in full. The bar that follows a close holds the + /// trade only when it lies beyond the close. pub(crate) fn push_tick(&mut self, tick: &Tick) { let range_size = self.range_size; let Some(mut curr_bar) = self.curr_bar.take() else { @@ -205,45 +230,113 @@ impl RangeBarBuilder { range_size, tick_cnt: 1, }); + (self.anchor, self.steps) = (tick.price, 0.0); return; }; - curr_bar.high = curr_bar.high.max(tick.price); - curr_bar.low = curr_bar.low.min(tick.price); - curr_bar.close = tick.price; curr_bar.volume = add_volume(curr_bar.volume, tick.size); curr_bar.end_time = tick.ts; curr_bar.tick_cnt += 1; const MAX_CLOSES: usize = 100; + if self.advance(&mut curr_bar, tick.price, tick.ts, MAX_CLOSES) { + curr_bar.tick_cnt = usize::from(curr_bar.close != curr_bar.open); + } + self.curr_bar = Some(curr_bar); + } + + /// Moves the bar in progress to `price`, closing at most `max_closes` bars, one at every + /// boundary the move reaches; a move that would close more stops at the last close. Returns + /// whether a bar closed. + fn advance( + &mut self, + curr_bar: &mut RangeBar, + mut price: f64, + time: DateTime, + max_closes: usize, + ) -> bool { + let range_size = self.range_size; let mut closes = 0; - while curr_bar.range() >= range_size && range_size > 0.0 && closes < MAX_CLOSES { - closes += 1; - if tick.price >= curr_bar.open { - curr_bar.close = curr_bar.low + range_size; - curr_bar.high = curr_bar.close; + loop { + // A price within rounding of the open is on it, as the price that closed the bar + // before is. + if reaches((price - curr_bar.open).abs(), range_size, price) { + price = curr_bar.open; + } + // A rise completes the range one size above the low and a fall one size below the + // high. An extreme the bar opened at is counted from the anchor; any other is a + // price as it was supplied and becomes the anchor. + let from = |extreme: f64| { + if extreme == curr_bar.open { + (self.anchor, self.steps) + } else { + (extreme, 0.0) + } + }; + let ((low, low_steps), (high, high_steps)) = (from(curr_bar.low), from(curr_bar.high)); + let up = low + (low_steps + 1.0) * range_size; + let down = high + (high_steps - 1.0) * range_size; + let (anchor, steps, close, far) = if reaches(up - price, range_size, price) { + (low, low_steps + 1.0, up, curr_bar.low) + } else if reaches(price - down, range_size, price) { + (high, high_steps - 1.0, down, curr_bar.high) } else { - curr_bar.close = curr_bar.high - range_size; - curr_bar.low = curr_bar.close; + break; + }; + // A size below the precision of the price moves nothing, nor does one of 0 or less + if close == far || range_size <= 0.0 { + break; + } + if closes == max_closes { + price = curr_bar.open; + break; } + closes += 1; + curr_bar.close = close; + curr_bar.high = far.max(close); + curr_bar.low = far.min(close); + curr_bar.end_time = time; self.bars.push(curr_bar.clone()); + + // Bound memory by dropping the oldest bars; `curr_bar` never reads them. if self.bars.len() == 2 * MAX_BARS { self.bars.drain(..MAX_BARS); } // Start the next bar where the last one ended - curr_bar = RangeBar { - open: curr_bar.close, - high: tick.price.max(curr_bar.close), - low: tick.price.min(curr_bar.close), - close: tick.price, + (self.anchor, self.steps) = (anchor, steps); + *curr_bar = RangeBar { + open: close, + high: close, + low: close, + close, volume: 0.0, - start_time: tick.ts, - end_time: tick.ts, + start_time: time, + end_time: time, range_size, - tick_cnt: usize::from(tick.price != curr_bar.close), + tick_cnt: 0, }; } - self.curr_bar = Some(curr_bar); + curr_bar.high = curr_bar.high.max(price); + curr_bar.low = curr_bar.low.min(price); + curr_bar.close = price; + closes > 0 + } + + /// Takes the bar in progress along the price path of `bar`, closing a range bar wherever the + /// path completes one. + fn walk(&mut self, curr_bar: &mut RangeBar, bar: &Bar) { + for price in price_path(bar) { + self.advance(curr_bar, price, bar.time, usize::MAX); + } + curr_bar.volume = add_volume(curr_bar.volume, bar.volume); + curr_bar.end_time = bar.time; + curr_bar.tick_cnt += 1; + } + + /// Whether [`elements`](PriceBuilder::elements) ends with the range bar in progress. + #[cfg(feature = "widget")] + pub(crate) fn has_open_bar(&self) -> bool { + self.curr_bar.as_ref().is_some_and(|bar| bar.tick_cnt > 0) } } @@ -264,62 +357,22 @@ impl PriceBuilder for RangeBarBuilder { range_size, tick_cnt: 1, }); + self.seed = Some(bar.clone()); return; }; - - // Simulate processing this bar's range - let prices = [bar.open, bar.high, bar.low, bar.close]; - - for &price in &prices { - curr_bar.high = curr_bar.high.max(price); - curr_bar.low = curr_bar.low.min(price); - - while curr_bar.range() >= range_size { - // Complete the bar - if curr_bar.high - curr_bar.open >= range_size { - // A size below the precision of the price moves nothing - if curr_bar.low + range_size == curr_bar.low { - break; - } - // Closed up - curr_bar.close = curr_bar.low + range_size; - curr_bar.high = curr_bar.close; - } else { - if curr_bar.high - range_size == curr_bar.high { - break; - } - // Closed down - curr_bar.close = curr_bar.high - range_size; - curr_bar.low = curr_bar.close; - } - - curr_bar.end_time = bar.time; - self.bars.push(curr_bar.clone()); - - // Bound memory by dropping the oldest bars; `curr_bar` never reads them. - if self.bars.len() == 2 * MAX_BARS { - self.bars.drain(..MAX_BARS); - } - - // Start new bar - curr_bar = RangeBar { - open: curr_bar.close, - high: price.max(curr_bar.close), - low: price.min(curr_bar.close), - close: price, - volume: 0.0, - start_time: bar.time, - end_time: bar.time, - range_size, - tick_cnt: 0, - }; - } + if let Some(seed) = self.seed.take() { + curr_bar = RangeBar { + high: seed.open, + low: seed.open, + close: seed.open, + volume: 0.0, + tick_cnt: 0, + ..curr_bar + }; + (self.anchor, self.steps) = (seed.open, 0.0); + self.walk(&mut curr_bar, &seed); } - - curr_bar.close = bar.close; - curr_bar.volume = add_volume(curr_bar.volume, bar.volume); - curr_bar.end_time = bar.time; - curr_bar.tick_cnt += 1; + self.walk(&mut curr_bar, bar); self.curr_bar = Some(curr_bar); } @@ -339,9 +392,27 @@ fn add_volume(volume: f64, added: f64) -> f64 { if sum.is_finite() { sum } else { volume } } +/// The order a bar's prices are taken to have traded in: open, the extreme nearer the open, the +/// other extreme, close; the high first when both extremes are as near within a few ulps. The +/// strategy tester fills orders along the same path. +pub(crate) fn price_path(bar: &Bar) -> [f64; 4] { + let tie = rounding_tolerance(bar.high.abs().max(bar.low.abs()), 4.0 * f64::EPSILON); + if (bar.high - bar.open) - (bar.open - bar.low) <= tie { + [bar.open, bar.high, bar.low, bar.close] + } else { + [bar.open, bar.low, bar.high, bar.close] + } +} + +/// The distance a bar's price path covers. +fn travel(bar: &Bar) -> f64 { + let path = price_path(bar); + path.windows(2).map(|leg| (leg[1] - leg[0]).abs()).sum() +} + /// Index of the bar to build from so that the range bars move at most `MAX_WORK` range sizes. -/// Bar `i` costs its path through open, high, low and close in sizes plus 4; the returned bar -/// only seeds the state, and its own range is split at the next bar's first price. +/// Bar `i` costs the move from the close before it and its price path in sizes plus 4; the +/// returned bar only seeds the state, and its own path is walked when the next bar arrives. pub(crate) fn work_start(bars: &[Bar], size: f64) -> usize { let mut total = 0.0; let mut priced = bars @@ -353,14 +424,8 @@ pub(crate) fn work_start(bars: &[Bar], size: f64) -> usize { return 0; }; for (previous_i, prev) in priced { - total += (((b.open - prev.close).abs() - + (b.high - b.open).abs() - + (b.high - b.low) - + (b.close - b.low).abs()) - / size) - .max(0.0) - + 4.0; - if total + (prev.high - prev.low) / size > super::MAX_WORK { + total += (((b.open - prev.close).abs() + travel(b)) / size).max(0.0) + 4.0; + if total + travel(prev) / size > super::MAX_WORK { return i; } (i, b) = (previous_i, prev); @@ -480,6 +545,128 @@ mod tests { ); } + #[test] + fn ohlc_range_bars_follow_the_bar_path() { + // (bars as (open, high, low, close), (open, high, low, close) of each range bar); the + // range is 2 and the last range bar is the one in progress. + type Ohlc = (f64, f64, f64, f64); + let cases: [(&[Ohlc], &[Ohlc]); 4] = [ + // A bar that only rises gives rising range bars, from the first bar on. + ( + &[(100.0, 100.0, 100.0, 100.0), (100.0, 104.0, 100.0, 104.0)], + &[ + (100.0, 102.0, 100.0, 102.0), + (102.0, 104.0, 102.0, 104.0), + (104.0, 104.0, 104.0, 104.0), + ], + ), + // The first bar is walked too: 100 down to 99, up to 104 and back to 103, so the + // bar in progress keeps the high of 104. + ( + &[(100.0, 104.0, 99.0, 103.0), (103.0, 103.0, 103.0, 103.0)], + &[ + (100.0, 101.0, 99.0, 101.0), + (101.0, 103.0, 101.0, 103.0), + (103.0, 104.0, 103.0, 103.0), + ], + ), + // The mirror: a bar that only falls gives falling range bars. + ( + &[(104.0, 104.0, 104.0, 104.0), (104.0, 104.0, 100.0, 100.0)], + &[ + (104.0, 104.0, 102.0, 102.0), + (102.0, 102.0, 100.0, 100.0), + (100.0, 100.0, 100.0, 100.0), + ], + ), + // 100 down to 99 and up to 101, as the trades 100, 99, 101: the rise completes the + // range, so the bar closes at its high. + ( + &[ + (100.0, 100.0, 100.0, 100.0), + (100.0, 100.0, 99.0, 99.0), + (99.0, 101.0, 99.0, 101.0), + ], + &[(100.0, 101.0, 99.0, 101.0), (101.0, 101.0, 101.0, 101.0)], + ), + ]; + for (source, expected) in cases { + let data: Vec = source + .iter() + .enumerate() + .map(|(i, &(open, high, low, close))| { + let time = DateTime::from_timestamp(60 * i as i64, 0).unwrap(); + Bar::new(time, open, high, low, close, 1.0) + }) + .collect(); + let bars: Vec<_> = to_range_bars_from_ohlc(&data, &RangeBarConfig::new(2.0)) + .iter() + .map(|b| (b.open, b.high, b.low, b.close)) + .collect(); + assert_eq!(bars, expected, "{source:?}"); + } + } + + /// Closes and trades one size apart complete one element each, on the bar or trade that + /// reaches the boundary, and element prices are counted in sizes instead of added up. + #[test] + fn decimal_sizes_complete_on_exact_boundaries() { + use crate::model::{RenkoConfig, to_renko_bricks}; + const STEPS: usize = 3000; + let time = |i: usize| DateTime::from_timestamp(60 * i as i64, 0).unwrap(); + // (size, sizes per unit of price, first price in sizes): price `i` is the decimal + // (first + i) / per_unit as a feed quotes it. The last row needs the rounding of the + // price itself: near 100,000 a price is exact to about 1e-11, more than a billionth of + // a size of 0.01. + for (size, per_unit, first) in [ + (0.1, 10.0, 10.0), + (0.05, 20.0, 20.0), + (0.01, 100.0, 100.0), + (0.01, 100.0, 10_000_000.0), + ] { + let prices: Vec = (0..=STEPS).map(|i| (first + i as f64) / per_unit).collect(); + let bars: Vec = (prices.iter().enumerate()) + .map(|(i, &p)| Bar::new(time(i), p, p, p, p, 1.0)) + .collect(); + let ticks: Vec = (prices.iter().enumerate()) + .map(|(i, &p)| Tick::new(time(i), p, 1.0, None)) + .collect(); + // Element `k` completes on price `k`: brick `k` closes `first + k` sizes from zero, + // range bar `k` closes `k` sizes from the first price. + let bricks: Vec<_> = (1..=STEPS) + .map(|k| (time(k), (first + k as f64) * size)) + .collect(); + let ranges: Vec<_> = (1..=STEPS) + .map(|k| (time(k), prices[0] + k as f64 * size)) + .collect(); + let config = RangeBarConfig::new(size); + let renko = to_renko_bricks(&bars, &RenkoConfig::new(size)); + let from_ticks = to_range_bars_from_ticks(&ticks, &config); + // The bar in progress after the last close is left out. + let mut from_ohlc = to_range_bars_from_ohlc(&bars, &config); + from_ohlc.truncate(STEPS); + let closes = + |bars: &[RangeBar]| Vec::from_iter(bars.iter().map(|b| (b.end_time, b.close))); + for (name, got, want) in [ + ( + "renko", + renko.iter().map(|b| (b.ts, b.close)).collect(), + &bricks, + ), + ("ticks", closes(&from_ticks), &ranges), + ("ohlc", closes(&from_ohlc), &ranges), + ] { + let differs = got.iter().zip(want).position(|(got, want)| got != want); + assert!( + differs.is_none() && got.len() == STEPS, + "{name}, size {size} from {}: {} elements, first difference at {differs:?}", + prices[0], + got.len() + ); + } + } + } + /// Guards the volume scale: an infinite first volume, or two valid volumes near `f64::MAX`, /// must not give a range bar an infinite volume, from ticks or from bars. #[test] diff --git a/vendor/egui-charts/src/model/renko.rs b/vendor/egui-charts/src/model/renko.rs index efc8adc..2dfeffa 100644 --- a/vendor/egui-charts/src/model/renko.rs +++ b/vendor/egui-charts/src/model/renko.rs @@ -10,11 +10,13 @@ //! Use [`to_renko_bricks`] to transform OHLCV bars into Renko bricks. use super::PriceBasedSource; +use super::rounding_tolerance; use crate::model::{Bar, PriceBuilder}; use chrono::{DateTime, Utc}; /// A single Renko brick representing a fixed-size price movement. #[derive(Debug, Clone)] +#[non_exhaustive] pub struct RenkoBrick { /// Timestamp of the source bar that completed this brick. pub ts: DateTime, @@ -60,6 +62,7 @@ impl RenkoBrick { /// The brick size can be set directly or derived from ATR via /// [`from_atr`](Self::from_atr). #[derive(Debug, Clone)] +#[non_exhaustive] pub struct RenkoConfig { /// Size of each brick in price units pub brick_size: f64, @@ -104,6 +107,10 @@ impl RenkoConfig { /// brick's close, and reverses it when a close reaches one brick beyond the /// last brick's open, so a reversal needs a two-brick move. /// +/// Brick prices are whole multiples of the brick size, and a close that reaches a multiple within +/// the rounding of decimal prices and sizes is on it: with a brick of 0.1, closes at 1.1, 1.2 and +/// 1.3 complete one brick each. +/// /// Returns no bricks when the brick size is not a positive finite number. /// /// # Safety Limits @@ -127,14 +134,26 @@ pub fn to_renko_bricks(bars: &[Bar], config: &RenkoConfig) -> Vec { pub(crate) const MAX_BRICKS: usize = 10_000; +/// Whether a price that is `short` of a brick or range boundary has reached it. Decimal prices +/// and sizes are not exact in binary, so a price one size beyond the last boundary can lie just +/// under the next: it counts as reached within a billionth of the size, or within a few ulps of +/// the price where those are more, and never from more than half a size away. +pub(super) fn reaches(short: f64, size: f64, price: f64) -> bool { + short + <= (1e-9 * size) + .max(rounding_tolerance(price, 4.0 * f64::EPSILON)) + .min(size / 2.0) +} + /// Builds Renko bricks bar by bar; `size` must be a positive finite number. #[derive(Clone)] pub(crate) struct RenkoBuilder { size: f64, source: PriceBasedSource, extremes: Option<(f64, f64)>, - /// Open and close of the last brick, or the start price before the first brick; `None` - /// until the first bar. + /// Open and close of the last brick, counted in brick sizes from zero, or the start twice + /// before the first brick; `None` until the first bar. Prices are these counts times the + /// size, so no rounding builds up from brick to brick. last: Option<(f64, f64)>, bricks: Vec, } @@ -157,7 +176,10 @@ impl PriceBuilder for RenkoBuilder { fn push(&mut self, bar: &Bar) { let size = self.size; let Some(mut last) = self.last else { - let start = (bar.close / size).floor() * size; + let mut start = (bar.close / size).floor(); + if reaches((start + 1.0) * size - bar.close, size, bar.close) { + start += 1.0; + } self.last = Some((start, start)); self.extremes = Some((bar.close, bar.close)); return; @@ -172,14 +194,14 @@ impl PriceBuilder for RenkoBuilder { let price = match self.source { PriceBasedSource::Close => bar.close, PriceBasedSource::HighLow if close >= open => { - if high >= close + size { + if reaches((close + 1.0) * size - high, size, high) { high } else { low } } PriceBasedSource::HighLow => { - if low <= close - size { + if reaches(low - (close - 1.0) * size, size, low) { low } else { high @@ -190,13 +212,14 @@ impl PriceBuilder for RenkoBuilder { let (open, close) = last; let (low, high) = (open.min(close), open.max(close)); // Before the first brick both ends are the start, so either direction needs one brick. - let (brick_open, brick_close) = if price >= high + size { - (high, high + size) - } else if price <= low - size { - (low, low - size) + let (from, to) = if reaches((high + 1.0) * size - price, size, price) { + (high, high + 1.0) + } else if reaches(price - (low - 1.0) * size, size, price) { + (low, low - 1.0) } else { break; }; + let (brick_open, brick_close) = (from * size, to * size); // A box below the precision of the price moves nothing. if brick_close == brick_open { break; @@ -223,7 +246,7 @@ impl PriceBuilder for RenkoBuilder { RenkoDirection::Down }, }); - last = (brick_open, brick_close); + last = (from, to); wick_low = brick_close; wick_high = brick_close; diff --git a/vendor/egui-charts/src/model/session/mod.rs b/vendor/egui-charts/src/model/session/mod.rs index ad63205..e81ff9a 100644 --- a/vendor/egui-charts/src/model/session/mod.rs +++ b/vendor/egui-charts/src/model/session/mod.rs @@ -115,6 +115,7 @@ pub enum SessionBreakType { /// matching NYSE regular-session close in exchange time, or [`continuous`](Self::continuous) /// for 24/7 markets (midnight UTC). #[derive(Debug, Clone)] +#[non_exhaustive] pub struct DailySessionProvider { /// Hour of day for session break (0-23) pub break_hour: u32, @@ -325,6 +326,14 @@ impl SessionProvider for CompositeSessionProvider { } } +impl std::fmt::Debug for CompositeSessionProvider { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CompositeSessionProvider") + .field("providers", &self.providers.len()) + .finish_non_exhaustive() + } +} + /// Scan a bar slice for session breaks. /// /// Returns a `Vec` of `(bar_index, SessionBreak)` pairs indicating diff --git a/vendor/egui-charts/src/model/signal.rs b/vendor/egui-charts/src/model/signal.rs index c21137d..5a797e1 100644 --- a/vendor/egui-charts/src/model/signal.rs +++ b/vendor/egui-charts/src/model/signal.rs @@ -5,6 +5,7 @@ use chrono::{DateTime, Utc}; /// One finding of the host's analytics: a marker, a level or a zone, for the chart to draw in the /// theme's colours for its direction and category. #[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] pub struct Signal { /// Identifies the signal within its subscription: an upsert with the same id replaces it. pub id: SignalId, @@ -18,6 +19,20 @@ pub struct Signal { pub tooltip: Option, } +impl Signal { + /// A signal without a label or tooltip. Assign [`label`](Self::label) and + /// [`tooltip`](Self::tooltip) to add them. + pub fn new(id: SignalId, shape: SignalShape, category: impl Into) -> Self { + Self { + id, + shape, + category: category.into(), + label: None, + tooltip: None, + } + } +} + /// Identifies a signal. The host chooses it. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct SignalId( diff --git a/vendor/egui-charts/src/model/study.rs b/vendor/egui-charts/src/model/study.rs index f20baaf..a2a809b 100644 --- a/vendor/egui-charts/src/model/study.rs +++ b/vendor/egui-charts/src/model/study.rs @@ -5,6 +5,7 @@ use egui::Color32; /// A price series or an output of another study on the chart. #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] pub enum StudySource { /// A field or average of fields of the input bars. Price(PriceSource), diff --git a/vendor/egui-charts/src/model/timescale.rs b/vendor/egui-charts/src/model/timescale.rs index 0edddc6..20a1c9f 100644 --- a/vendor/egui-charts/src/model/timescale.rs +++ b/vendor/egui-charts/src/model/timescale.rs @@ -334,6 +334,17 @@ impl TimeScale { self.apply_constraints(); } + /// Sets the width and scales the bar spacing so a plot resized from `old_width` to + /// `new_width` shows the same slots. The plot spans `width - 1` pixels of slots, as in + /// [`Self::coord_to_idx`]. + #[cfg(feature = "widget")] + pub(crate) fn keep_slots_on_resize(&mut self, old_width: f32, new_width: f32) { + let ratio = (f64::from(new_width) - 1.0) / (f64::from(old_width) - 1.0); + self.width = new_width; + self.bar_spacing = self.clamp_spacing(self.bar_spacing * ratio); + self.apply_constraints(); + } + /// Update min bar spacing, floored at 0.000001 pixels. Non-finite values are ignored. pub fn set_min_bar_spacing(&mut self, min: f32) { if !min.is_finite() { @@ -419,7 +430,7 @@ impl TimeScale { /// Calculate visible logical range pub fn visible_logical_range(&self) -> LogicalRange { let base_idx = self.base_idx() as f64; - let bars_len = self.width as f64 / self.bar_spacing; + let bars_len = (self.width as f64 - 1.0) / self.bar_spacing; let right_border = base_idx + self.right_offset; let left_border = right_border - bars_len + 1.0; @@ -444,7 +455,10 @@ impl TimeScale { /// Plot boundaries in spacing units, retaining precision across large numeric gaps. pub(crate) fn visible_positions(&self) -> (f64, f64) { let right = self.base_idx() as f64 + self.right_offset + 0.5; - (right - f64::from(self.width) / self.bar_spacing, right) + ( + right - (f64::from(self.width) - 1.0) / self.bar_spacing, + right, + ) } /// Convert logical index to x coord @@ -595,7 +609,8 @@ impl TimeScale { .map_or((0.0, self.live_right_offset), |px| (px, 0.0)) }; self.bar_spacing = self.clamp_spacing( - (self.width as f64 - pixels as f64) / (right - left + 1.0 + bars as f64).max(1.0), + (self.width as f64 - 1.0 - pixels as f64) + / (right - left + 1.0 + bars as f64).max(1.0), ); let margin = if self.fix_right_edge { 0.0 @@ -657,7 +672,7 @@ impl TimeScale { // Keep the first participating slot at the left border. Some( self.content_range().0 - self.base_idx() as f64 - + self.width as f64 / self.bar_spacing + + (self.width as f64 - 1.0) / self.bar_spacing - 1.0, ) } else { @@ -712,9 +727,10 @@ impl TimeScale { } } - /// Get number of visible candles + /// The slots across the plot's `width - 1` pixels, rounded, so the count given to + /// `Chart::set_visible_bars` reads back. pub fn visible_candles(&self) -> usize { - (self.width as f64 / self.bar_spacing).floor() as usize + ((self.width as f64 - 1.0) / self.bar_spacing).round() as usize } } @@ -780,15 +796,16 @@ mod tests { } /// Scrolling far into the past stops with the first bar at the left edge while - /// `fix_left_edge` is set: 100 bars fit 800 px at a spacing of 8, so the right offset stops - /// at 100 - 1,000 bars, and at 100 - 50 bars when every bar fits, leaving the empty space on - /// the right. Unset, the view goes on to 100 bars past the first. + /// `fix_left_edge` is set: the 799 pixels of an 800 px plot hold 99.875 bars at a spacing of 8, + /// so the right offset stops at 99.875 - 1,000 bars, and at 99.875 - 50 bars when every bar + /// fits, leaving the empty space on the right. Unset, the view goes on to 100 bars past the + /// first. #[test] fn fix_left_edge_stops_the_view_at_the_first_bar() { for (fix, bars, expected) in [ - (true, 1000, -900.0), + (true, 1000, -900.125), (false, 1000, -1100.0), - (true, 50, 50.0), + (true, 50, 49.875), (false, 50, -150.0), ] { let mut ts = TimeScale::new(); @@ -838,7 +855,7 @@ mod tests { assert_eq!(ts.bar_spacing(), 50.0, "{name}, {invalid}"); ts.apply_options(8.0, 0.5, 50.0, true, false, invalid, None); assert_eq!(ts.right_offset(), 7.0, "bar offset, {invalid}"); - assert_eq!(ts.visible_logical_range(), LogicalRange::new(7.0, 106.0)); + assert_eq!(ts.visible_logical_range(), LogicalRange::new(7.125, 106.0)); } } } @@ -923,10 +940,10 @@ mod tests { assert!(ts.right_offset_precise().is_finite(), "{name}"); } } - // At the fixed left edge, width / spacing - bar count is the offset. + // At the fixed left edge, (width - 1) / spacing - bar count is the offset. if fix_left { ts.scroll_bars(f32::MAX); - let expected = 800.0 / f64::from(zoomed) - 100.0; + let expected = 799.0 / f64::from(zoomed) - 100.0; assert!( (ts.right_offset_precise() - expected).abs() < 1e-6, "{name}" diff --git a/vendor/egui-charts/src/model/tpo.rs b/vendor/egui-charts/src/model/tpo.rs index fbd56a3..8dd2ba5 100644 --- a/vendor/egui-charts/src/model/tpo.rs +++ b/vendor/egui-charts/src/model/tpo.rs @@ -40,6 +40,7 @@ pub struct TPOLetter { /// Contains all TPO letters, statistical levels (POC, value area, /// initial balance), and structural flags (poor high/low, single prints). #[derive(Debug, Clone)] +#[non_exhaustive] pub struct TPOProfile { /// Session timestamp pub session_date: DateTime, @@ -89,6 +90,7 @@ pub struct TPOProfile { /// Configuration for TPO chart generation and rendering. #[derive(Debug, Clone)] +#[non_exhaustive] pub struct TPOConfig { /// Row height for price grouping, such as 0.25 for one ES tick or 1.0 for four. With /// `instrument_tick` it rounds up to whole ticks. [`to_tpo_profiles`] widens it to bound the diff --git a/vendor/egui-charts/src/scales/horizontal.rs b/vendor/egui-charts/src/scales/horizontal.rs index ea61419..6c00ff7 100644 --- a/vendor/egui-charts/src/scales/horizontal.rs +++ b/vendor/egui-charts/src/scales/horizontal.rs @@ -8,8 +8,7 @@ use super::time_formatter::TimeFormatter; use super::timescale_marks::{ - TickMark, TickMarkGenerator, TickMarkGeneratorConfig, TickMarkType, TickMarkWeight, - keep_spaced_by, + TickMark, TickMarkGenerator, TickMarkGeneratorConfig, TickMarkWeight, keep_spaced_by, }; use crate::model::Bar; use chrono::{DateTime, Duration, Utc}; @@ -50,6 +49,14 @@ pub struct CustomHorizontalScale { format: Box String + Send + Sync>, } +impl std::fmt::Debug for CustomHorizontalScale { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CustomHorizontalScale") + .field("keys", &self.keys.len()) + .finish_non_exhaustive() + } +} + impl CustomHorizontalScale { /// Builds a domain sorted by key, with one entry per distinct key. Formatting never changes /// ordering: distinct keys may have the same label. @@ -108,14 +115,12 @@ impl HorizontalScale for CustomHorizontalScale { let marks = points .iter() .filter_map(|&(time, index)| { - Some(TickMark { + Some(TickMark::new( time, index, - label: (self.format)(self.key(time)?), - mark_type: TickMarkType::Time, - weight: TickMarkWeight::new(1), - bold: false, - }) + TickMarkWeight::new(1), + (self.format)(self.key(time)?), + )) }) .collect(); keep_spaced_by( @@ -298,7 +303,8 @@ impl HorizontalScale for PriceHorizontalScale { /// A horizontal scale of maturities in months, for yield curves, encoded with [`key_time`]. /// -/// Maturities read `3M` below a year and `2Y` or `2Y6M` from a year on. The axis labels +/// Maturities read `3M` below a year and `2Y` or `2Y6M` from a year on, with at most two +/// decimals of a month, such as `2Y9.33M`. Keys below zero get no label. The axis labels /// multiples of 10 years first, then of 5 and 3 years, whole years, half years, quarters and /// months, and draws the longest kind shown in bold. /// @@ -346,14 +352,21 @@ impl MaturityScale { .collect() } + /// Writes `months` to two decimals of a month at most, rounded before the years are split + /// off, so keys derived from days or weeks carry no float noise. fn format(months: f64) -> String { + let months = (months * 100.0).round() / 100.0; let (years, rest) = ((months / 12.0).floor(), months % 12.0); + let short = |value: f64| { + let text = format!("{value:.2}"); + text.trim_end_matches('0').trim_end_matches('.').to_owned() + }; if months < 12.0 { - format!("{months}M") - } else if rest == 0.0 { + format!("{}M", short(months)) + } else if short(rest) == "0" { format!("{years}Y") } else { - format!("{years}Y{rest}M") + format!("{years}Y{}M", short(rest)) } } } @@ -382,7 +395,13 @@ impl HorizontalScale for MaturityScale { .find(|(step, _)| months % step == 0.0) .map_or(0, |(_, weight)| weight) }; - weighted_marks(points, layout, weight, Self::format) + // Keys extrapolated left of zero are no maturities. + let points: Vec<_> = points + .iter() + .copied() + .filter(|(time, _)| time_key(*time) >= 0.0) + .collect(); + weighted_marks(&points, layout, weight, Self::format) } fn format_crosshair(&self, key: DateTime, _bar_seconds: i64) -> String { @@ -401,13 +420,13 @@ fn weighted_marks( ) -> Vec { let marks = points .iter() - .map(|&(time, index)| TickMark { - time, - mark_type: TickMarkType::Time, - weight: TickMarkWeight::new(weight(time_key(time))), - label: String::new(), - index, - bold: false, + .map(|&(time, index)| { + TickMark::new( + time, + index, + TickMarkWeight::new(weight(time_key(time))), + String::new(), + ) }) .collect(); let mut kept = keep_spaced_by( @@ -528,7 +547,16 @@ mod tests { "4512.50" ); let maturity = MaturityScale::default(); - for (months, label) in [(3.0, "3M"), (30.0, "2Y6M"), (360.0, "30Y")] { + // Keys derived from days carry float noise: a third of 100 months and of one month. + for (months, label) in [ + (3.0, "3M"), + (30.0, "2Y6M"), + (360.0, "30Y"), + (100.0 / 3.0, "2Y9.33M"), + (1.0 / 3.0, "0.33M"), + (30.5, "2Y6.5M"), + (0.25, "0.25M"), + ] { assert_eq!(maturity.format_crosshair(at(months), 0), label); } diff --git a/vendor/egui-charts/src/scales/mod.rs b/vendor/egui-charts/src/scales/mod.rs index 87170d7..8780e52 100644 --- a/vendor/egui-charts/src/scales/mod.rs +++ b/vendor/egui-charts/src/scales/mod.rs @@ -27,12 +27,12 @@ pub use price_formatter::{ }; #[cfg(feature = "widget")] pub(crate) use price_formatter::{decimals, group_thousands, price_decimals, to_step}; -#[cfg(feature = "widget")] -pub(crate) use pricescale::auto_scale_span; pub use pricescale::{ PriceMap, PriceRange, PriceScale, PriceScaleId, PriceScaleMargins, PriceScaleMode, PriceScaleOptions, PriceTransform, }; +#[cfg(feature = "widget")] +pub(crate) use pricescale::{auto_scale_span, fit_span}; pub use pricescale_marks::{PriceMark, PriceMarkGenerator, PriceMarkGeneratorConfig}; pub use study_format::StudyFormat; pub use time_formatter::{ diff --git a/vendor/egui-charts/src/scales/price_formatter.rs b/vendor/egui-charts/src/scales/price_formatter.rs index 5e2a61e..f512ed6 100644 --- a/vendor/egui-charts/src/scales/price_formatter.rs +++ b/vendor/egui-charts/src/scales/price_formatter.rs @@ -263,6 +263,7 @@ impl PriceFormatter for PercentageFormatter { /// If the thousands and decimal separators match, grouping is omitted so an amount /// never uses the same character for both separators, including after direct field edits. #[derive(Debug, Clone)] +#[non_exhaustive] pub struct CurrencyFormatter { /// Currency symbol (e.g., "$", "€", "£", "¥") pub symbol: String, @@ -439,6 +440,13 @@ pub struct CustomPriceFormatter { formatter: Arc String + Send + Sync>, } +impl std::fmt::Debug for CustomPriceFormatter { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CustomPriceFormatter") + .finish_non_exhaustive() + } +} + impl CustomPriceFormatter { /// Create a new custom formatter from a closure pub fn new(formatter: F) -> Self @@ -464,6 +472,7 @@ impl PriceFormatter for CustomPriceFormatter { } /// Builder for creating price formatters +#[derive(Debug)] pub struct PriceFormatterBuilder { precision: usize, currency: Option, diff --git a/vendor/egui-charts/src/scales/pricescale.rs b/vendor/egui-charts/src/scales/pricescale.rs index 2bef60a..ccf279f 100644 --- a/vendor/egui-charts/src/scales/pricescale.rs +++ b/vendor/egui-charts/src/scales/pricescale.rs @@ -23,7 +23,10 @@ pub enum PriceScaleMode { /// Prices on a linear axis: equal price differences take equal heights. #[default] Normal, - /// Prices on a logarithmic axis: equal price ratios take equal heights. + /// Prices on a logarithmic axis: equal price ratios take equal heights. The fit uses the + /// positive values in view; while every value in view is at or below zero, the scale shows + /// prices as [`Normal`](PriceScaleMode::Normal) does. A view without any value keeps the + /// units the scale shows. Logarithmic, /// Change from the first visible value, in percent; that value reads 0%. Percentage, @@ -123,6 +126,15 @@ pub(crate) fn auto_scale_span(min: f64, max: f64) -> f64 { } } +/// The span a fit of `min..max` (scale units of `mode`) takes its margins from. +pub(crate) fn fit_span(mode: PriceScaleMode, min: f64, max: f64) -> f64 { + match mode { + // Log units measure ratios: flat data gets 0.01, which is 1% of the price. + PriceScaleMode::Logarithmic if max - min <= 1e-9 => 0.01, + _ => auto_scale_span(min, max), + } +} + /// Identifies one of a pane's price axes. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] pub enum PriceScaleId { @@ -154,6 +166,7 @@ impl fmt::Display for PriceScaleId { /// Configuration options for a [`PriceScale`]. #[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] pub struct PriceScaleOptions { /// Price scale mode pub mode: PriceScaleMode, @@ -389,7 +402,14 @@ impl PriceScale { let old = std::mem::replace(&mut self.transform, transform); if self.manual && old != transform { let rebased = |value| transform.to_scale(old.to_price(value)); - self.range = PriceRange::new(rebased(self.range.min), rebased(self.range.max)); + let (min, max) = (rebased(self.range.min), rebased(self.range.max)); + if min.is_finite() && max.is_finite() && min < max { + self.range = PriceRange::new(min, max); + } else { + // Prices without a value in the new units, such as those at or below zero on a + // logarithmic scale, leave no range to keep: the scale fits the data again. + self.reset(); + } } } @@ -409,11 +429,7 @@ impl PriceScale { if self.manual { return; } - let span = match self.transform.mode { - // Log units measure ratios: flat data gets 0.01, which is 1% of the price. - PriceScaleMode::Logarithmic if max - min <= 1e-9 => 0.01, - _ => auto_scale_span(min, max), - }; + let span = fit_span(self.transform.mode, min, max); let PriceScaleMargins { top, bottom } = self.options.scale_margins; let (top, bottom) = (top.clamp(0.0, 1.0), bottom.clamp(0.0, 1.0)); let (top, bottom) = if top + bottom < 1.0 { diff --git a/vendor/egui-charts/src/scales/pricescale_marks.rs b/vendor/egui-charts/src/scales/pricescale_marks.rs index cd25404..0ce3190 100644 --- a/vendor/egui-charts/src/scales/pricescale_marks.rs +++ b/vendor/egui-charts/src/scales/pricescale_marks.rs @@ -34,9 +34,10 @@ pub struct PriceMarkGeneratorConfig { /// Max number of marks, capped at 1,000 during generation. pub max_marks: usize, - /// Target density (marks per 100 pixels): linear marks take the nice step nearest - /// `100 / target_density` pixels, logarithmic marks stay at least that far apart, and no - /// marks are closer than `min_spacing` + /// Target density (marks per 100 pixels): marks take the nice step nearest + /// `100 / target_density` pixels. On a logarithmic axis the 1, 2 and 5 times powers of ten + /// stay at least that far apart, and each wider gap between them takes round prices at the + /// step that spacing gives at the gap's lower end. No marks are closer than `min_spacing`. pub target_density: f32, /// Minimum price tick size. Normal and logarithmic marks lie on its multiples; @@ -61,6 +62,7 @@ impl Default for PriceMarkGeneratorConfig { /// Smart price axis mark generator /// Implements "nice numbers" algorithm for price ticks +#[derive(Debug)] pub struct PriceMarkGenerator { config: PriceMarkGeneratorConfig, } @@ -81,7 +83,8 @@ impl PriceMarkGenerator { /// Generates marks for the visible range of `map`, positioned through it. /// - /// Logarithmic scales get marks at 1, 2 and 5 times powers of ten; the other + /// Logarithmic scales get marks at 1, 2 and 5 times powers of ten and round prices in the + /// gaps between them that are wider than the target density allows; the other /// modes get evenly stepped marks in scale units, labelled as prices, signed /// percentages or index values. Labels group their thousands with the map's separator. pub fn generate_marks(&self, map: &PriceMap) -> Vec { @@ -99,7 +102,7 @@ impl PriceMarkGenerator { let (min_price, max_price) = (transform.to_price(range.min), transform.to_price(range.max)); let marks = self.generate_log_marks(min_price, max_price, height_pixels, map); if marks.len() >= 3 { - return marks; + return self.fill_log_gaps(marks, min_price, max_price, height_pixels, map); } // A narrow log range holds few multiples of powers of ten: step it in prices instead. self.generate_linear_marks(min_price, max_price, height_pixels, map, true) @@ -182,27 +185,7 @@ impl PriceMarkGenerator { map.scale_to_y(curr_price) }; - // Determine precision based on price value and step - let precision = map.price_precision().unwrap_or_else(|| { - let mut decimals = self.calculate_precision(nice_step); - if min_step.is_some() { - while decimals < 8 { - let scaled = nice_step * 10f64.powi(decimals as i32); - if (scaled - scaled.round()).abs() <= scaled * f64::EPSILON * 4.0 { - break; - } - decimals += 1; - } - } - if matches!( - map.transform().mode, - PriceScaleMode::Normal | PriceScaleMode::Logarithmic - ) { - decimals.max(2) - } else { - decimals - } - }); + let precision = self.step_precision(map, nice_step, min_step.is_some()); let label = if map.price_precision().is_none() && precision > 8 { let mut label = self.format_price(curr_price, precision, true); if map.transform().mode == PriceScaleMode::Percentage { @@ -333,6 +316,107 @@ impl PriceMarkGenerator { ) } + /// Adds round prices to the logarithmic `marks` wherever the gap between two of them, or + /// between one and an end of the axis, is wider than the target spacing. Each gap takes the + /// regular axis's step for that spacing at its lower end, where a price step is tallest, on + /// the minimum price grid. The added marks weigh less than the 1, 2 and 5 marks, which all stay. + fn fill_log_gaps( + &self, + marks: Vec, + min_price: f64, + max_price: f64, + height_pixels: f32, + map: &PriceMap, + ) -> Vec { + let spacing = f64::from( + self.config + .min_spacing + .max(100.0 / self.config.target_density), + ); + // Pixels per unit of the natural logarithm of the price. + let pixels = f64::from(height_pixels) / (max_price.ln() - min_price.ln()); + let min_step = map.volume_step().or(self.min_step()); + let decade = |price: f64| price.log10().floor() as i32; + let mut ends: Vec = marks.iter().map(|mark| mark.price).collect(); + ends.insert(0, min_price); + ends.push(max_price); + let mut filled = marks; + // The finest decimals the added marks of each decade need. + let mut decimals = std::collections::BTreeMap::new(); + let mut budget = self.config.max_marks * 10; + for pair in ends.windows(2) { + let (low, high) = (pair[0], pair[1]); + // A price step of `low * spacing / pixels` is `spacing` pixels tall at `low`. + let mut step = self.calculate_nice_step(low * spacing / pixels); + if let Some(decimals) = map.price_precision() { + step = Self::round_up_to_multiple(step, 10f64.powi(-(decimals as i32))); + } + if let Some(min_step) = min_step { + step = Self::round_up_to_multiple(step, min_step); + } + if !step.is_finite() || step <= 0.0 { + continue; + } + let precision = self.step_precision(map, step, min_step.is_some()); + let mut index = (low / step).floor() + 1.0; + while index * step < high && budget > 0 { + let price = index * step; + index += 1.0; + budget -= 1; + let finest = decimals.entry(decade(price)).or_insert(precision); + *finest = precision.max(*finest); + filled.push(PriceMark { + price, + label: String::new(), + y_coord: map.price_to_y(price), + // Below the 60 of a 2 times power of ten. + weight: self.calculate_weight(price, step) / 2, + }); + } + } + let mut filled = self.apply_spacing_constraints(filled, self.config.min_spacing); + // One decade reads with one count of decimals, that of its finest mark. + for mark in &mut filled { + let order = decade(mark.price); + let precision = map.price_precision().unwrap_or_else(|| { + let base = self.calculate_precision(10f64.powi(order)).max(2); + decimals + .get(&order) + .map_or(base, |finest| base.max(*finest)) + }); + mark.label = super::price_formatter::group_thousands( + self.format_price(mark.price, precision, map.price_precision().is_none()), + map.thousands_sep(), + ); + } + filled + } + + /// Decimals of marks `step` apart: the map's precision, or enough for the step, and for a + /// step on the minimum price grid (`on_grid`) enough to write it exactly. Prices keep two. + fn step_precision(&self, map: &PriceMap, step: f64, on_grid: bool) -> usize { + map.price_precision().unwrap_or_else(|| { + let mut decimals = self.calculate_precision(step); + if on_grid { + while decimals < 8 { + let scaled = step * 10f64.powi(decimals as i32); + if (scaled - scaled.round()).abs() <= scaled * f64::EPSILON * 4.0 { + break; + } + decimals += 1; + } + } + if matches!( + map.transform().mode, + PriceScaleMode::Normal | PriceScaleMode::Logarithmic + ) { + decimals.max(2) + } else { + decimals + } + }) + } + fn round_up_to_multiple(step: f64, unit: f64) -> f64 { let ratio = step / unit; let rounded = ratio.round(); @@ -775,12 +859,53 @@ mod tests { #[test] fn test_log_marks_generation() { let generator = PriceMarkGenerator::new(); - let (lo, hi) = (10f64.ln(), 1000f64.ln()); - let marks = generator.generate_marks(&map(PriceScaleMode::Logarithmic, lo, hi)); - - // Axis endpoints are unlabelled; the interior 1/2/5 decade marks remain. - let prices: Vec<_> = marks.iter().map(|mark| mark.price).collect(); - assert_eq!(prices, [20.0, 50.0, 100.0, 200.0, 500.0]); + // On 849 pixels at 2.5 marks per 100 pixels, neighbouring labels lie between the + // 20-pixel minimum and twice the 40 pixels the density asks for, below a decade, over + // about one and over several, and the 1, 2 and 5 times powers of ten in view stay. + // The labels of one decade have one count of decimals. + for (low, high, decade) in [ + (90.0, 520.0, &[100.0, 200.0, 500.0][..]), + (0.9, 5.5, &[1.0, 2.0, 5.0]), + (9.0, 110.0, &[10.0, 20.0, 50.0, 100.0]), + (10.0, 1_000.0, &[20.0, 50.0, 100.0, 200.0, 500.0]), + (1.0, 100_000.0, &[10.0, 100.0, 1_000.0, 10_000.0]), + ] { + let map = PriceMap::new( + crate::scales::PriceTransform { + mode: PriceScaleMode::Logarithmic, + base: 0.0, + }, + crate::scales::PriceRange::new(f64::ln(low), f64::ln(high)), + 0.0, + 849.0, + false, + ); + let marks = generator.generate_marks(&map); + let labels: Vec<&str> = marks.iter().map(|mark| mark.label.as_str()).collect(); + for price in decade { + assert!( + marks.iter().any(|mark| mark.price == *price), + "{low}..{high}: {price} missing from {labels:?}" + ); + } + let decimals = |label: &str| label.split_once('.').map_or(0, |(_, part)| part.len()); + for pair in marks.windows(2) { + if pair[0].price.log10().floor() == pair[1].price.log10().floor() { + assert_eq!( + decimals(&pair[0].label), + decimals(&pair[1].label), + "{low}..{high}: {labels:?}" + ); + } + let gap = pair[0].y_coord - pair[1].y_coord; + assert!( + (20.0..=80.0).contains(&gap), + "{low}..{high}: {} and {} lie {gap} apart in {labels:?}", + pair[0].label, + pair[1].label + ); + } + } // 18,200..22,800 holds one multiple of a power of ten (20,000), so the marks // fall back to 400-unit price steps. diff --git a/vendor/egui-charts/src/scales/time_formatter.rs b/vendor/egui-charts/src/scales/time_formatter.rs index f945c6e..c7996ea 100644 --- a/vendor/egui-charts/src/scales/time_formatter.rs +++ b/vendor/egui-charts/src/scales/time_formatter.rs @@ -18,8 +18,9 @@ use chrono::Datelike; /// Display time and chart locale for one time-axis tick. #[derive(Debug, Clone, Copy)] pub struct TickMarkContext<'a> { - /// Wall-clock fields in the chart's display zone, carried in a UTC value. - /// This is not a UTC instant and must not be converted to the display zone again. + /// Wall-clock fields in the chart's display zone, carried in a UTC value; behind UTC, bars of + /// a day or longer given to a chart without a feed read in UTC unless they sit at the display + /// zone's midnight. This is not a UTC instant and must not be converted to a time zone again. pub time: DateTime, /// Calendar or clock precision selected for this tick. pub mark_type: TickMarkType, @@ -96,6 +97,7 @@ pub trait TimeFormatter: Send + Sync { /// Default time formatter using standard formats #[derive(Debug, Clone)] +#[non_exhaustive] pub struct DefaultTimeFormatter { /// Whether to use 24-hour format pub use_24_hour: bool, @@ -270,6 +272,7 @@ impl Style<'_> { /// The names need the `locales` cargo feature, on by default; without it they /// are English, as with an unknown locale. #[derive(Debug, Clone)] +#[non_exhaustive] pub struct LocaleTimeFormatter { /// Locale identifier: language and region, such as `"en-US"`, `"ja-JP"` or /// `"de-DE"` (`"de_DE"` also works). Unknown identifiers use English names. @@ -338,6 +341,13 @@ pub struct CustomTimeFormatter { formatter: Arc, TickMarkType) -> String + Send + Sync>, } +impl std::fmt::Debug for CustomTimeFormatter { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CustomTimeFormatter") + .finish_non_exhaustive() + } +} + impl CustomTimeFormatter { /// Create a new custom formatter from a closure pub fn new(formatter: F) -> Self @@ -585,6 +595,19 @@ pub struct TimeFormatterBuilder { time_visible: bool, } +impl std::fmt::Debug for TimeFormatterBuilder { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TimeFormatterBuilder") + .field("use_24_hour", &self.use_24_hour) + .field("show_seconds", &self.show_seconds) + .field("locale", &self.locale) + .field("date_format", &self.date_format) + .field("timezone", &self.timezone) + .field("time_visible", &self.time_visible) + .finish_non_exhaustive() + } +} + impl TimeFormatterBuilder { /// Create a new formatter builder pub fn new() -> Self { diff --git a/vendor/egui-charts/src/scales/timescale_marks.rs b/vendor/egui-charts/src/scales/timescale_marks.rs index 18b5cc0..77836a4 100644 --- a/vendor/egui-charts/src/scales/timescale_marks.rs +++ b/vendor/egui-charts/src/scales/timescale_marks.rs @@ -91,6 +91,7 @@ impl TickMarkWeight { /// A single tick mark on the time axis #[derive(Debug, Clone)] +#[non_exhaustive] pub struct TickMark { /// Time of this tick mark pub time: DateTime, @@ -111,6 +112,28 @@ pub struct TickMark { pub bold: bool, } +impl TickMark { + /// A mark at the bar `index` whose key is `time`, for a + /// [`HorizontalScale`](crate::scales::HorizontalScale) to return. It is of type + /// [`TickMarkType::Time`] and not bold; assign [`mark_type`](Self::mark_type) and + /// [`bold`](Self::bold) to change that. + pub fn new( + time: DateTime, + index: usize, + weight: TickMarkWeight, + label: impl Into, + ) -> Self { + Self { + time, + mark_type: TickMarkType::Time, + weight, + label: label.into(), + index, + bold: false, + } + } +} + /// Configuration for tick mark generation #[derive(Debug, Clone)] pub struct TickMarkGeneratorConfig { @@ -150,6 +173,15 @@ pub struct TickMarkGenerator { uniform_distribution: bool, } +impl std::fmt::Debug for TickMarkGenerator { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TickMarkGenerator") + .field("config", &self.config) + .field("uniform_distribution", &self.uniform_distribution) + .finish_non_exhaustive() + } +} + impl TickMarkGenerator { /// Create a new tick mark generator with default config pub fn new() -> Self { diff --git a/vendor/egui-charts/src/services/alert_engine.rs b/vendor/egui-charts/src/services/alert_engine.rs index 3bce6d3..26eaf81 100644 --- a/vendor/egui-charts/src/services/alert_engine.rs +++ b/vendor/egui-charts/src/services/alert_engine.rs @@ -102,6 +102,12 @@ pub struct AlertEngine { deliver: Option>, } +impl std::fmt::Debug for AlertEngine { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AlertEngine").finish_non_exhaustive() + } +} + /// The host's callback for triggers. trait Deliver: MaybeSend { fn deliver(&self, alert: &Alert, event: &AlertEvent); diff --git a/vendor/egui-charts/src/services/alert_evaluator.rs b/vendor/egui-charts/src/services/alert_evaluator.rs index f017415..c2ba75a 100644 --- a/vendor/egui-charts/src/services/alert_evaluator.rs +++ b/vendor/egui-charts/src/services/alert_evaluator.rs @@ -25,6 +25,15 @@ pub struct AlertEvaluator { storage: Option>, } +impl std::fmt::Debug for AlertEvaluator { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AlertEvaluator") + .field("runs", &self.runs.len()) + .field("feeds", &self.feeds.len()) + .finish_non_exhaustive() + } +} + #[derive(Clone, PartialEq, Eq, Hash)] struct Subject { symbol: String, diff --git a/vendor/egui-charts/src/services/alert_feed.rs b/vendor/egui-charts/src/services/alert_feed.rs index 6bf530f..5a94e84 100644 --- a/vendor/egui-charts/src/services/alert_feed.rs +++ b/vendor/egui-charts/src/services/alert_feed.rs @@ -20,6 +20,16 @@ pub struct AlertData<'a> { pub drawings: &'a [crate::drawings::Drawing], } +impl std::fmt::Debug for AlertData<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AlertData") + .field("request", &self.request) + .field("bars", &self.bars.len()) + .field("history_complete", &self.history_complete) + .finish_non_exhaustive() + } +} + /// Historical and streaming inputs for an alert without a rendered chart. Uses the same /// validation, trade aggregation and history/live merge rules as a chart. Dropping it stops /// its subscription and discards late replies. Available with `alert-engine`. @@ -52,6 +62,17 @@ pub struct AlertFeed { start: Option>, } +impl std::fmt::Debug for AlertFeed { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AlertFeed") + .field("request", &self.request) + .field("bars", &self.bars.len()) + .field("ready", &self.ready) + .field("stopped", &self.stopped) + .finish_non_exhaustive() + } +} + impl AlertFeed { /// A latest-history request for 1,000 bars. Set its public calendar, session, conversion /// and count fields before passing it to [`new`](Self::new) to match the source chart. diff --git a/vendor/egui-charts/src/services/detectors/mod.rs b/vendor/egui-charts/src/services/detectors/mod.rs index 471d3da..0ebe3f7 100644 --- a/vendor/egui-charts/src/services/detectors/mod.rs +++ b/vendor/egui-charts/src/services/detectors/mod.rs @@ -90,6 +90,12 @@ pub struct OrderFlowDetectors { state: Mutex, } +impl std::fmt::Debug for OrderFlowDetectors { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("OrderFlowDetectors").finish_non_exhaustive() + } +} + /// The detections the service makes, each drawn in its own signal category. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] diff --git a/vendor/egui-charts/src/services/events.rs b/vendor/egui-charts/src/services/events.rs index 8431f8b..acd3750 100644 --- a/vendor/egui-charts/src/services/events.rs +++ b/vendor/egui-charts/src/services/events.rs @@ -20,6 +20,15 @@ pub struct Events { event: PhantomData, } +impl std::fmt::Debug for Events { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Events") + .field("key", &self.key) + .field("active", &self.is_active()) + .finish_non_exhaustive() + } +} + impl Events { /// Delivers `event` to the terminal, or nothing once the stream is inactive. pub fn push(&self, event: T) { diff --git a/vendor/egui-charts/src/services/paper.rs b/vendor/egui-charts/src/services/paper.rs index 544cd50..77a296c 100644 --- a/vendor/egui-charts/src/services/paper.rs +++ b/vendor/egui-charts/src/services/paper.rs @@ -56,6 +56,17 @@ pub struct PaperAccount { state: Mutex, } +impl std::fmt::Debug for PaperAccount { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PaperAccount") + .field("currency", &self.currency) + .field("initial", &self.initial) + .field("leverage", &self.leverage) + .field("commission", &self.commission) + .finish_non_exhaustive() + } +} + #[derive(Default)] struct State { events: Option>, diff --git a/vendor/egui-charts/src/services/profile_directory.rs b/vendor/egui-charts/src/services/profile_directory.rs index fcdf290..49ebead 100644 --- a/vendor/egui-charts/src/services/profile_directory.rs +++ b/vendor/egui-charts/src/services/profile_directory.rs @@ -47,6 +47,14 @@ pub struct ProfileDirectory { sent: u64, } +impl std::fmt::Debug for ProfileDirectory { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ProfileDirectory") + .field("profiles", &self.profiles.len()) + .finish_non_exhaustive() + } +} + impl ProfileDirectory { /// A directory without a service. Attach one with [`set_service`](Self::set_service). pub fn new() -> Self { diff --git a/vendor/egui-charts/src/services/settings.rs b/vendor/egui-charts/src/services/settings.rs index f9e5a28..53b4b40 100644 --- a/vendor/egui-charts/src/services/settings.rs +++ b/vendor/egui-charts/src/services/settings.rs @@ -3,8 +3,9 @@ use super::document::{Received, StoredDocument}; use super::{ConflictChoice, Storage, StoreKind}; use crate::config::{CursorType, DrawingSort, DrawingToolType}; -use crate::model::{ReplaySession, Timeframe, Watchlist}; +use crate::model::{ChartType, ReplaySession, Timeframe, Watchlist}; use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned}; +use std::borrow::Cow; use std::collections::BTreeMap; use std::sync::Arc; use std::time::Duration; @@ -39,7 +40,9 @@ pub struct UserSettings { /// Whether the user hid the favourites strip with its close or toggle button. pub drawing_favorites_hidden: bool, /// The top-left corner of the favourites strip, in logical points, where the user left it; - /// `None` until it has been shown, when it starts beside the drawing toolbar. + /// `None` until it has been shown, when it starts beside the drawing toolbar. A non-finite + /// position reads as `None`. + #[serde(deserialize_with = "known_or_unset")] pub drawing_favorites_pos: Option<(f32, f32)>, /// Whether the user dismissed the drawing toolbar's card that explains the magnet; a document /// without it reads as not dismissed. @@ -56,6 +59,18 @@ pub struct UserSettings { /// know is left out when reading. #[serde(deserialize_with = "known_items")] pub interval_favorites: Vec, + /// The intervals the user added to the interval menu, in order. An interval this release does + /// not know is left out when reading. + #[serde(deserialize_with = "known_items")] + pub custom_intervals: Vec, + /// The intervals the user hid from the interval menu. An interval this release does not know + /// is left out when reading. + #[serde(deserialize_with = "known_items")] + pub hidden_intervals: Vec, + /// The chart types starred in the chart type menu, in order. A chart type this release does + /// not know is left out when reading. + #[serde(deserialize_with = "known_items")] + pub chart_type_favorites: Vec, /// The properties each drawing tool starts with, keyed by tool, as the JSON of /// its `DrawingTemplate`. A tool without an entry starts with /// the built-in defaults. @@ -74,8 +89,8 @@ pub struct UserSettings { /// The market heatmap's universe, size metric and colour metric. pub market_heatmap: MarketHeatmapSelection, /// The replay position to resume, with the interval its history was fetched at. A position - /// this release cannot read, such as one at an interval a newer release added, reads as - /// `None`. + /// this release cannot read, such as one at an interval a newer release added or one with a + /// non-finite speed, reads as `None`. #[serde(deserialize_with = "known_or_unset")] pub replay_session: Option<(ReplaySession, Timeframe)>, } @@ -147,9 +162,9 @@ impl UserSettings { /// Reads a document [`to_json`](Self::to_json) wrote, migrating older versions. Fails on /// invalid JSON and on a version this release does not know. A missing field takes its - /// default. A drawing order, tool, cursor mode or interval a newer release added is left out, - /// as each field says, and the rest is read. Values left out when reading are absent from the - /// next save. + /// default. A drawing order, tool, cursor mode, interval or chart type a newer release added + /// is left out, as each field says, and the rest is read. Values left out when reading are + /// absent from the next save. pub fn from_json(json: &str) -> Result { let document: Document = serde_json::from_str(json)?; match document.version { @@ -160,6 +175,30 @@ impl UserSettings { ))), } } + + /// The settings as [`from_json`](Self::from_json) reads back what [`to_json`](Self::to_json) + /// writes: JSON has no non-finite numbers, so a replay position with such a speed and such a + /// favourites position are unset. + fn as_read_back(&self) -> Cow<'_, Self> { + let speed = self + .replay_session + .as_ref() + .is_some_and(|(session, _)| !session.speed.is_finite()); + let pos = self + .drawing_favorites_pos + .is_some_and(|(x, y)| !x.is_finite() || !y.is_finite()); + if !speed && !pos { + return Cow::Borrowed(self); + } + let mut settings = self.clone(); + if speed { + settings.replay_session = None; + } + if pos { + settings.drawing_favorites_pos = None; + } + Cow::Owned(settings) + } } /// Keeps [`UserSettings`] in the host's [`Storage`]: reads them once, then writes them a second @@ -181,6 +220,14 @@ pub struct SettingsStore { error: Option, } +impl std::fmt::Debug for SettingsStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SettingsStore") + .field("error", &self.error) + .finish_non_exhaustive() + } +} + impl SettingsStore { /// How long settings stay the same before they are written. pub const DELAY: Duration = Duration::from_secs(1); @@ -205,6 +252,8 @@ impl SettingsStore { /// `current` once it has stayed the same for [`DELAY`](Self::DELAY), and at once while a /// conflict is unsettled, so that the choice applies to the newest settings. pub fn poll(&mut self, ctx: &egui::Context, current: &UserSettings) -> Option { + // Compared with the settings read back from the last save. + let current = &*current.as_read_back(); self.document.hold( self.written .as_ref() @@ -249,6 +298,7 @@ impl SettingsStore { /// [`poll`](Self::poll) has not returned yet are pending, nor while a conflict is unsettled; /// it returns `false` then, so a host that waits for `true` bounds the wait. pub fn flush(&mut self, current: &UserSettings) -> bool { + let current = &*current.as_read_back(); if self.written.is_none() { return false; } @@ -365,8 +415,10 @@ mod tests { ); } - /// An interval from a newer release is left out of the starred intervals and unsets the last - /// interval and the replay position; the same places keep an interval this release knows. + /// An interval from a newer release is left out of the starred, custom and hidden intervals + /// and unsets the last interval and the replay position; the same places keep an interval + /// this release knows. A chart type from a newer release is left out of the starred chart + /// types. #[test] fn unknown_intervals_keep_the_other_settings() { use chrono::TimeZone; @@ -388,6 +440,8 @@ mod tests { UserSettings { interval: Some(Timeframe::Day1), interval_favorites: vec![Timeframe::Min5, Timeframe::Day1], + custom_intervals: vec![Timeframe::Day1], + hidden_intervals: vec![Timeframe::Day1], replay_session: Some((session, Timeframe::Day1)), ..UserSettings::default() }, @@ -395,8 +449,9 @@ mod tests { ]; for (interval, mut expected) in rows { expected.theme = Some("Dark".into()); + expected.chart_type_favorites = vec![ChartType::Bars]; let json = format!( - r#"{{"version":1,"theme":"Dark","interval":"{interval}","interval_favorites":["Min5","{interval}"],"replay_session":[{{"symbol":"AAA","time":"2026-01-02T00:00:00Z","speed":2.0}},"{interval}"]}}"# + r#"{{"version":1,"theme":"Dark","interval":"{interval}","interval_favorites":["Min5","{interval}"],"custom_intervals":["{interval}"],"hidden_intervals":["{interval}"],"chart_type_favorites":["Bars","FutureChartType"],"replay_session":[{{"symbol":"AAA","time":"2026-01-02T00:00:00Z","speed":2.0}},"{interval}"]}}"# ); assert_eq!( UserSettings::from_json(&json).map_err(|error| error.to_string()), @@ -596,6 +651,89 @@ mod tests { } } + /// Storage that keeps one document and counts its saves. + #[derive(Default)] + struct Counted(Host, std::sync::atomic::AtomicUsize); + + impl Storage for Counted { + fn list(&self, kind: StoreKind, reply: Reply>) { + self.0.list(kind, reply); + } + fn load(&self, kind: StoreKind, name: &str, reply: Reply>) { + self.0.load(kind, name, reply); + } + fn save(&self, kind: StoreKind, name: &str, document: String, reply: Reply<()>) { + self.1.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + self.0.save(kind, name, document, reply); + } + fn delete(&self, kind: StoreKind, name: &str, reply: Reply<()>) { + self.0.delete(kind, name, reply); + } + } + + /// A non-finite replay speed or favourites position is written as unset, so the settings + /// are saved once, a second after they changed, and the document reads back. + #[test] + fn non_finite_settings_are_saved_once_and_read_back() { + use chrono::TimeZone; + let session = |speed| ReplaySession { + symbol: "AAA".into(), + time: chrono::Utc.with_ymd_and_hms(2026, 1, 2, 0, 0, 0).unwrap(), + speed, + }; + let cases = [ + ( + "infinite speed", + UserSettings { + replay_session: Some((session(f32::INFINITY), Timeframe::Day1)), + ..UserSettings::default() + }, + ), + ( + "NaN speed", + UserSettings { + replay_session: Some((session(f32::NAN), Timeframe::Day1)), + ..UserSettings::default() + }, + ), + ( + "infinite position", + UserSettings { + drawing_favorites_pos: Some((f32::INFINITY, 0.0)), + ..UserSettings::default() + }, + ), + ]; + for (case, mut settings) in cases { + settings.theme = Some("Dark".into()); + let ctx = egui::Context::default(); + let host = Arc::new(Counted::default()); + let saves = || host.1.load(std::sync::atomic::Ordering::Relaxed); + let mut store = SettingsStore::new(host.clone()); + poll_at(&ctx, &mut store, 0.0, &UserSettings::default()); + for tenth in 1..=100 { + poll_at(&ctx, &mut store, f64::from(tenth) / 10.0, &settings); + if tenth < 11 { + assert_eq!(saves(), 0, "{case} at {tenth}"); + } + } + assert_eq!(saves(), 1, "{case}"); + assert!(store.flush(&settings), "{case}"); + assert_eq!(saves(), 1, "{case}"); + let expected = UserSettings { + theme: Some("Dark".into()), + ..UserSettings::default() + }; + let mut store = SettingsStore::new(host.clone()); + assert_eq!( + poll_at(&ctx, &mut store, 20.0, &UserSettings::default()), + Some(expected), + "{case}" + ); + assert_eq!(store.take_error(), None, "{case}"); + } + } + #[test] fn settings_restore_once_wait_a_second_and_keep_unreadable_documents() { let ctx = egui::Context::default(); diff --git a/vendor/egui-charts/src/services/signals.rs b/vendor/egui-charts/src/services/signals.rs index 7b92239..813d6a2 100644 --- a/vendor/egui-charts/src/services/signals.rs +++ b/vendor/egui-charts/src/services/signals.rs @@ -27,17 +27,18 @@ use crate::model::{Signal, SignalId, Timeframe}; /// while events.is_active() { /// std::thread::sleep(Duration::from_secs(1)); /// count += 1; -/// events.push(SignalEvent::Upsert(Signal { -/// id: SignalId(format!("{symbol}-breakout-{count}")), -/// shape: SignalShape::Marker { +/// let mut signal = Signal::new( +/// SignalId(format!("{symbol}-breakout-{count}")), +/// SignalShape::Marker { /// time: chrono::Utc::now(), /// price: None, /// direction: Direction::Up, /// }, -/// category: "Breakouts".into(), -/// label: Some("B".into()), -/// tooltip: Some(format!("Breakout {count} on {symbol}")), -/// })); +/// "Breakouts", +/// ); +/// signal.label = Some("B".into()); +/// signal.tooltip = Some(format!("Breakout {count} on {symbol}")); +/// events.push(SignalEvent::Upsert(signal)); /// } /// }); /// } diff --git a/vendor/egui-charts/src/strategies/backtest.rs b/vendor/egui-charts/src/strategies/backtest.rs index 92de6ad..be5479a 100644 --- a/vendor/egui-charts/src/strategies/backtest.rs +++ b/vendor/egui-charts/src/strategies/backtest.rs @@ -9,6 +9,7 @@ use serde::{Deserialize, Serialize}; mod live; pub use live::StrategyFill; +use crate::model::range_bar::price_path; use crate::model::rounding_tolerance; use crate::model::{ Bar, ChartType, OrderSide, OrderType, StrategyExit, StrategyReport, StrategyTrade, Timeframe, @@ -323,6 +324,17 @@ pub struct StrategyContext<'a> { order_delay: u32, } +impl std::fmt::Debug for StrategyContext<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("StrategyContext") + .field("bars", &self.bars.len()) + .field("position", &self.position) + .field("price", &self.price) + .field("equity", &self.equity) + .finish_non_exhaustive() + } +} + impl StrategyContext<'_> { /// Chart bars through this decision, oldest first. Live tick decisions include the forming /// bar. Historical tick decisions and their fill callbacks include a candle containing only @@ -832,22 +844,6 @@ fn sign(side: OrderSide) -> f64 { } } -fn price_path(bar: &Bar) -> [f64; 4] { - let near = if (bar.high - bar.open) - (bar.open - bar.low) - <= rounding_tolerance(bar.high.abs().max(bar.low.abs()), 4.0 * f64::EPSILON) - { - bar.high - } else { - bar.low - }; - [ - bar.open, - near, - if near == bar.high { bar.low } else { bar.high }, - bar.close, - ] -} - struct Run<'a> { orders: Vec, /// Open entries, oldest first, all on one side. diff --git a/vendor/egui-charts/src/strategies/library/mod.rs b/vendor/egui-charts/src/strategies/library/mod.rs index 8a871ee..b9a09c8 100644 --- a/vendor/egui-charts/src/strategies/library/mod.rs +++ b/vendor/egui-charts/src/strategies/library/mod.rs @@ -34,6 +34,14 @@ pub struct StrategyFactory { constructors: HashMap, } +impl std::fmt::Debug for StrategyFactory { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("StrategyFactory") + .field("constructors", &self.constructors.keys()) + .finish_non_exhaustive() + } +} + impl StrategyFactory { /// Creates a catalogue with every built-in enabled by the current features. pub fn new() -> Self { diff --git a/vendor/egui-charts/src/strategies/library/studies.rs b/vendor/egui-charts/src/strategies/library/studies.rs index 31ed5a5..b89ae34 100644 --- a/vendor/egui-charts/src/strategies/library/studies.rs +++ b/vendor/egui-charts/src/strategies/library/studies.rs @@ -116,6 +116,10 @@ impl Strategy for StudyStrategy { let mut inputs = Vec::new(); for (index, study) in self.studies.iter().enumerate() { for mut input in study.inputs() { + // A strategy draws no study table, so its look and rows are not inputs here. + if matches!(self.rule, Rule::Rating) && input.id.starts_with("table_") { + continue; + } if matches!(self.rule, Rule::TwoAverages) { let prefix = if index == 0 { "fast" } else { "slow" }; input.id = format!("{prefix}.{}", input.id); diff --git a/vendor/egui-charts/src/strategies/library/tests.rs b/vendor/egui-charts/src/strategies/library/tests.rs index f756356..2dc306d 100644 --- a/vendor/egui-charts/src/strategies/library/tests.rs +++ b/vendor/egui-charts/src/strategies/library/tests.rs @@ -590,6 +590,8 @@ fn every_default_strategy_is_causal_and_declares_valid_defaults() { for name in StrategyFactory::new().list() { let mut strategy = configured(name, &[]); for input in strategy.study_inputs() { + // A strategy draws no study table. + assert!(!input.id.starts_with("table_"), "{name}: {}", input.id); assert!(input.accepts(&input.value), "{name}: {}", input.id); assert!( input.accepts(&input.default), diff --git a/vendor/egui-charts/src/studies/builtin/auto_drawing.rs b/vendor/egui-charts/src/studies/builtin/auto_drawing.rs index 946ec22..0e5a5c0 100644 --- a/vendor/egui-charts/src/studies/builtin/auto_drawing.rs +++ b/vendor/egui-charts/src/studies/builtin/auto_drawing.rs @@ -36,6 +36,7 @@ fn level_slot(id: &str) -> Option { /// Construction to place on the latest Zig Zag pivots. #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum AutoDrawingKind { /// Last two pivots of the same kind, including the moving last extreme. TrendLine, diff --git a/vendor/egui-charts/src/studies/builtin/chart_patterns.rs b/vendor/egui-charts/src/studies/builtin/chart_patterns.rs index f69ad43..c07679b 100644 --- a/vendor/egui-charts/src/studies/builtin/chart_patterns.rs +++ b/vendor/egui-charts/src/studies/builtin/chart_patterns.rs @@ -30,6 +30,7 @@ const MAX_CONFIRMED: usize = 64; /// The formation a detector looks for. #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum FormationKind { /// A rise, then a falling channel; confirms above it. BullFlag, @@ -187,6 +188,7 @@ pub enum PatternDirection { /// Whether a formation has broken out. #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum FormationStatus { /// All its pivots are known but no close has broken its boundary yet. Developing, @@ -196,6 +198,7 @@ pub enum FormationStatus { /// A detected formation, with bar indices into the calculated bars. #[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] pub struct Formation { /// The formation's shape. pub kind: FormationKind, diff --git a/vendor/egui-charts/src/studies/builtin/close_to_close_vol.rs b/vendor/egui-charts/src/studies/builtin/close_to_close_vol.rs index 883cabd..219b0d0 100644 --- a/vendor/egui-charts/src/studies/builtin/close_to_close_vol.rs +++ b/vendor/egui-charts/src/studies/builtin/close_to_close_vol.rs @@ -6,10 +6,14 @@ use crate::studies::{Indicator, IndicatorValue, IndicatorValues}; use egui::Color32; /// Close-to-Close Volatility -/// Standard deviation of log returns, annualized by sqrt(252) +/// Standard deviation of log returns, annualized by the square root of the bars per year (252 +/// by default) #[derive(Clone)] pub struct CloseToCloseVol { period: usize, + /// Trading days per year the result is annualized over, one bar per day (252 for stocks, 365 + /// for crypto); bars shorter than a day need the bars in a year instead + trading_days: f64, values: IndicatorValues, colors: Vec, visible: bool, @@ -20,11 +24,19 @@ impl CloseToCloseVol { pub fn new(period: usize) -> Self { Self { period: period.max(1), + trading_days: 252.0, values: IndicatorValues::new(), colors: vec![palette::LIGHT_BLUE], // Purple visible: true, } } + + /// Set the bars per year the volatility is annualized over, clamped into 0 to + /// `f64::MAX`, NaN to 0. + pub fn with_trading_days(mut self, days: f64) -> Self { + self.trading_days = super::clamp_param(days, 0.0, f64::MAX); + self + } } impl Default for CloseToCloseVol { @@ -76,8 +88,8 @@ impl CloseToCloseVol { valid.iter().map(|x| (x - mean).powi(2)).sum::() / (valid.len() - 1) as f64; let std_dev = variance.sqrt(); - // Annualize: std_dev * sqrt(252) * 100 (as percentage) - let annualized = std_dev * 252.0_f64.sqrt() * 100.0; + // Annualize: std_dev * sqrt(trading_days) * 100 (as percentage) + let annualized = std_dev * self.trading_days.sqrt() * 100.0; values.push(IndicatorValue::Single(annualized)); } @@ -93,7 +105,8 @@ impl Indicator for CloseToCloseVol { } crate::studies::inputs::study_inputs!(self; - period: length("Period", 1, usize::MAX) + period: length("Period", 1, usize::MAX), + trading_days: number("Trading days per year", 0.0, f64::MAX) ; {}); fn value_format(&self) -> crate::scales::StudyFormat { @@ -162,3 +175,40 @@ impl Indicator for CloseToCloseVol { vec![format!("C2C Vol({})", self.period)] } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::studies::test_support::make_bar; + + /// Closes 100, 110, a bar without a close, 110 and 99 (a tie in the middle of the window), then + /// the second close corrected to 105. Expected values come from the definition over the three + /// returns of the usable bars, evaluated independently, annualized over 252 and 365 bars. + #[test] + fn c2c_annualizes_over_the_bars_per_year_across_gaps_ties_and_corrections() { + let bars = |second: f64| -> Vec { + [100.0, second, f64::NAN, 110.0, 99.0] + .map(make_bar) + .to_vec() + }; + for (days, as_saved, corrected) in [ + (252.0, 159.34400080811727, 140.25269412585286), + (365.0, 191.7705346575994, 168.79414350887444), + ] { + let mut study = CloseToCloseVol::new(3).with_trading_days(days); + let mut data = bars(110.0); + study.calculate(&data); + assert_eq!( + study.values().value(0, 2), + None, + "{days}: bar without a close" + ); + let got = study.values().value(0, 4).unwrap(); + assert!((got - as_saved).abs() < 1e-9, "{days}: {got}"); + data = bars(105.0); + study.update(&data, 1); + let got = study.values().value(0, 4).unwrap(); + assert!((got - corrected).abs() < 1e-9, "{days} corrected: {got}"); + } + } +} diff --git a/vendor/egui-charts/src/studies/builtin/cvd.rs b/vendor/egui-charts/src/studies/builtin/cvd.rs index 0579d64..e2c8ca3 100644 --- a/vendor/egui-charts/src/studies/builtin/cvd.rs +++ b/vendor/egui-charts/src/studies/builtin/cvd.rs @@ -29,6 +29,7 @@ pub struct CVD { /// How [`CVD`] estimates a bar's delta from its prices #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[non_exhaustive] pub enum CVDMode { /// Estimate based on bar close position within range #[default] diff --git a/vendor/egui-charts/src/studies/builtin/elliott_wave.rs b/vendor/egui-charts/src/studies/builtin/elliott_wave.rs index c137672..61e9ff5 100644 --- a/vendor/egui-charts/src/studies/builtin/elliott_wave.rs +++ b/vendor/egui-charts/src/studies/builtin/elliott_wave.rs @@ -117,7 +117,7 @@ impl ElliottWave { .map(String::from) .to_vec(), rows: Vec::new(), - ..StudyTable::default() + ..Default::default() }, colors: [palette::ACCENT, palette::GREEN, palette::RED], visible: true, diff --git a/vendor/egui-charts/src/studies/builtin/footprint_studies.rs b/vendor/egui-charts/src/studies/builtin/footprint_studies.rs index 11cbede..03939d7 100644 --- a/vendor/egui-charts/src/studies/builtin/footprint_studies.rs +++ b/vendor/egui-charts/src/studies/builtin/footprint_studies.rs @@ -6,6 +6,7 @@ use serde::{Deserialize, Serialize}; /// Meaning of a footprint annotation. Sells trade on the bid and buys on the ask. #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum FootprintStudyKind { /// Consecutive sell imbalances. StackedBid, @@ -35,6 +36,7 @@ pub enum FootprintStudyKind { /// Where a level or zone stands against later trading. #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum FootprintStudyState { /// A marker that stays inside its own bar. Local, @@ -48,6 +50,7 @@ pub enum FootprintStudyState { /// A level or zone beginning at one bar and optionally ending at its first revisit. #[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] pub struct FootprintStudy { /// Bar that created the level or zone. pub start: DateTime, @@ -69,6 +72,7 @@ pub struct FootprintStudy { /// imbalances at 300%, unfinished highs and lows, naked and delta POCs, and leaves the rest off. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] +#[non_exhaustive] pub struct FootprintStudyConfig { /// Mark consecutive imbalance zones. pub stacked_imbalances: bool, diff --git a/vendor/egui-charts/src/studies/builtin/guppy_ma.rs b/vendor/egui-charts/src/studies/builtin/guppy_ma.rs index b259282..041b511 100644 --- a/vendor/egui-charts/src/studies/builtin/guppy_ma.rs +++ b/vendor/egui-charts/src/studies/builtin/guppy_ma.rs @@ -3,14 +3,14 @@ use crate::studies::stepper::Stepper; use crate::studies::{Indicator, IndicatorValue, IndicatorValues}; use egui::Color32; -/// Short group periods: 3, 5, 8, 10, 12, 15 -/// Long group periods: 30, 35, 40, 45, 50, 60 -const SHORT_PERIODS: [usize; 6] = [3, 5, 8, 10, 12, 15]; -const LONG_PERIODS: [usize; 6] = [30, 35, 40, 45, 50, 60]; - -/// Guppy Multiple Moving Average (GMMA) +/// Guppy Multiple Moving Average (GMMA): twelve exponential moving averages of one source, six +/// short and six long, each seeded with the first close. +/// +/// The lengths default to 3, 5, 8, 10, 12 and 15 for the short group and 30, 35, 40, 45, 50 and 60 +/// for the long group; each one is an input. #[derive(Clone)] pub struct GuppyMA { + periods: [usize; 12], values: IndicatorValues, stepper: Stepper>, colors: Vec, @@ -21,6 +21,7 @@ impl GuppyMA { /// Create the six short and six long exponential moving averages. pub fn new() -> Self { Self { + periods: [3, 5, 8, 10, 12, 15, 30, 35, 40, 45, 50, 60], values: IndicatorValues::new(), stepper: Stepper::default(), colors: [217, 224, 232, 240, 247, 255] @@ -35,6 +36,12 @@ impl GuppyMA { visible: true, } } + + /// Set the twelve lengths, short group first. A length below 1 is raised to 1. + pub fn with_periods(mut self, periods: [usize; 12]) -> Self { + self.periods = periods.map(|period| period.max(1)); + self + } } impl Default for GuppyMA { @@ -50,6 +57,21 @@ impl Indicator for GuppyMA { )) } + crate::studies::inputs::study_inputs!(self; + periods[0]: length("Short EMA 1", 1, usize::MAX), + periods[1]: length("Short EMA 2", 1, usize::MAX), + periods[2]: length("Short EMA 3", 1, usize::MAX), + periods[3]: length("Short EMA 4", 1, usize::MAX), + periods[4]: length("Short EMA 5", 1, usize::MAX), + periods[5]: length("Short EMA 6", 1, usize::MAX), + periods[6]: length("Long EMA 1", 1, usize::MAX), + periods[7]: length("Long EMA 2", 1, usize::MAX), + periods[8]: length("Long EMA 3", 1, usize::MAX), + periods[9]: length("Long EMA 4", 1, usize::MAX), + periods[10]: length("Long EMA 5", 1, usize::MAX), + periods[11]: length("Long EMA 6", 1, usize::MAX) + ; {}); + fn name(&self) -> &str { "GMMA" } @@ -69,10 +91,7 @@ impl Indicator for GuppyMA { return IndicatorValue::None; } let averages = state.get_or_insert([bar.close; 12]); - for (average, period) in averages - .iter_mut() - .zip(SHORT_PERIODS.into_iter().chain(LONG_PERIODS)) - { + for (average, period) in averages.iter_mut().zip(self.periods) { *average = (bar.close - *average) * (2.0 / (period as f64 + 1.0)) + *average; } IndicatorValue::Multiple(averages.to_vec()) @@ -118,13 +137,83 @@ impl Indicator for GuppyMA { } fn line_names(&self) -> Vec { - let mut names = Vec::with_capacity(12); - for &p in &SHORT_PERIODS { - names.push(format!("EMA({p})")); + self.periods.map(|p| format!("EMA({p})")).to_vec() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::studies::InputValue; + + /// Bars whose open, high and low lie away from the close, so only the close can feed the averages. + fn bars(closes: &[f64]) -> Vec { + closes + .iter() + .enumerate() + .map(|(i, &c)| { + let time = chrono::DateTime::from_timestamp(i as i64 * 60, 0).unwrap(); + Bar::new(time, c - 3.0, c + 5.0, c - 7.0, c, 1.0) + }) + .collect() + } + + fn row(g: &GuppyMA, bar: usize) -> Option> { + match &g.values().to_rows()[bar] { + IndicatorValue::Multiple(v) => Some(v.clone()), + _ => None, } - for &p in &LONG_PERIODS { - names.push(format!("EMA({p})")); + } + + fn assert_close(got: f64, want: f64, what: &str) { + assert!((got - want).abs() < 1e-9, "{what}: {got} != {want}"); + } + + /// Lengths 1 and 2 replace the first two defaults, giving alphas 1 and 2/3; the third stays 8 + /// and the last 60 (alpha 2/61). Closes 10, 12, none, 9, 9, hand-derived: + /// + /// | bar | close | EMA(1) | EMA(2) | EMA(60) | + /// |-----|-------|--------|---------|------------| + /// | 0 | 10 | 10 | 10 | 10 | + /// | 1 | 12 | 12 | 34/3 | 10 + 4/61 | + /// | 2 | none | none | none | none | + /// | 3 | 9 | 9 | 88/9 | | + /// | 4 | 9 | 9 | 250/27 | | + /// + /// EMA(60) is checked at bar 1 only. A corrected close of 8 at bar 3 gives EMA(1) 8 and + /// EMA(2) 82/9. + #[test] + fn periods_drive_the_averages() { + let mut g = GuppyMA::new(); + g.set_input("periods [0]", InputValue::Length(1)).unwrap(); + g.set_input("periods [1]", InputValue::Length(2)).unwrap(); + let mut data = bars(&[10.0, 12.0, f64::NAN, 9.0, 9.0]); + g.calculate(&data); + + assert_eq!(&g.line_names()[..3], ["EMA(1)", "EMA(2)", "EMA(8)"]); + assert_eq!(g.line_names()[11], "EMA(60)"); + assert_eq!(row(&g, 0).unwrap(), vec![10.0; 12]); + let r = row(&g, 1).unwrap(); + assert_close(r[0], 12.0, "bar 1 EMA(1)"); + assert_close(r[1], 34.0 / 3.0, "bar 1 EMA(2)"); + assert_close(r[11], 10.0 + 4.0 / 61.0, "bar 1 EMA(60)"); + assert!(row(&g, 2).is_none()); + let r = row(&g, 3).unwrap(); + assert_close(r[0], 9.0, "bar 3 EMA(1)"); + assert_close(r[1], 88.0 / 9.0, "bar 3 EMA(2)"); + let r = row(&g, 4).unwrap(); + assert_close(r[1], 250.0 / 27.0, "bar 4 EMA(2), equal closes"); + + // A correction to bar 3 recomputes from there and matches a fresh calculation. + data[3] = Bar::new(data[3].time, 5.0, 13.0, 1.0, 8.0, 1.0); + let mut fresh = g.clone(); + fresh.calculate(&data); + g.update(&data, 3); + for bar in 0..data.len() { + assert_eq!(row(&g, bar), row(&fresh, bar), "bar {bar}"); } - names + let r = row(&g, 3).unwrap(); + assert_close(r[0], 8.0, "corrected EMA(1)"); + assert_close(r[1], 82.0 / 9.0, "corrected EMA(2)"); } } diff --git a/vendor/egui-charts/src/studies/builtin/historical_volatility.rs b/vendor/egui-charts/src/studies/builtin/historical_volatility.rs index d85bc31..99b7ae3 100644 --- a/vendor/egui-charts/src/studies/builtin/historical_volatility.rs +++ b/vendor/egui-charts/src/studies/builtin/historical_volatility.rs @@ -131,7 +131,7 @@ impl Indicator for HistoricalVolatility { crate::studies::inputs::study_inputs!(self; period: length("Period", 1, usize::MAX), - trading_days: number("Trading days", 0.0, f64::MAX) + trading_days: number("Trading days per year", 0.0, f64::MAX) ; {}); fn value_format(&self) -> crate::scales::StudyFormat { diff --git a/vendor/egui-charts/src/studies/builtin/key_levels.rs b/vendor/egui-charts/src/studies/builtin/key_levels.rs index 973493c..dae0c3d 100644 --- a/vendor/egui-charts/src/studies/builtin/key_levels.rs +++ b/vendor/egui-charts/src/studies/builtin/key_levels.rs @@ -186,7 +186,7 @@ impl Indicator for KeyLevels { title: "Key levels".to_string(), columns: ["Level", "Touches", "Pivots"].map(String::from).to_vec(), rows, - ..StudyTable::default() + ..Default::default() }; } diff --git a/vendor/egui-charts/src/studies/builtin/lunar_phases.rs b/vendor/egui-charts/src/studies/builtin/lunar_phases.rs index e66156f..32cc0f6 100644 --- a/vendor/egui-charts/src/studies/builtin/lunar_phases.rs +++ b/vendor/egui-charts/src/studies/builtin/lunar_phases.rs @@ -49,6 +49,7 @@ use egui::Color32; /// A phase of the Moon with a published instant. #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum MoonPhase { /// The Moon passes between the Earth and the Sun. New, @@ -58,6 +59,7 @@ pub enum MoonPhase { /// One new or full moon. #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub struct LunarPhase { /// Which phase. pub phase: MoonPhase, diff --git a/vendor/egui-charts/src/studies/builtin/ma_combination.rs b/vendor/egui-charts/src/studies/builtin/ma_combination.rs index 9f81789..f8ec467 100644 --- a/vendor/egui-charts/src/studies/builtin/ma_combination.rs +++ b/vendor/egui-charts/src/studies/builtin/ma_combination.rs @@ -11,6 +11,7 @@ use egui::Color32; /// Average formula used by a line of [`MACombination`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum AverageType { /// Arithmetic mean of a complete window. Simple, @@ -52,6 +53,7 @@ impl AverageType { /// One moving average's formula, length, input price and colour. #[derive(Clone, Debug)] +#[non_exhaustive] pub struct AverageLine { /// Average formula. pub kind: AverageType, diff --git a/vendor/egui-charts/src/studies/builtin/majority_rule.rs b/vendor/egui-charts/src/studies/builtin/majority_rule.rs index 30978b3..7740ace 100644 --- a/vendor/egui-charts/src/studies/builtin/majority_rule.rs +++ b/vendor/egui-charts/src/studies/builtin/majority_rule.rs @@ -4,11 +4,32 @@ use crate::studies::stepper::{update_window, usable_behind}; use crate::studies::{Indicator, IndicatorValue, IndicatorValues}; use egui::Color32; -/// Majority Rule - counts up vs down closes over period. -/// Outputs +1 if majority up, -1 if majority down, 0 if tie. +/// What [`MajorityRule`] reports for each window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MajorityMode { + /// 100 times the share of the window's closes that rose above the close before. Equal and + /// falling closes count against it. + Percentage, + /// +1 when more closes rose than fell, -1 when more fell, 0 when the counts are equal. + Direction, +} + +impl MajorityMode { + const ALL: [Self; 2] = [Self::Percentage, Self::Direction]; +} + +/// Majority Rule: the share of the last `period` bars whose close rose above the close before. +/// +/// In [`MajorityMode::Percentage`] (the default) it outputs the percentage of rising closes; in +/// [`MajorityMode::Direction`] it outputs +1 if the majority rose, -1 if the majority fell and 0 +/// on a tie. A bar without a finite close has no value and does not break the window. The first +/// bar has no close before it and counts as not rising, so the first value is at bar +/// `period - 1`. In percentage mode the pane has a dashed guide at 50, where rising and other +/// closes are evenly split. #[derive(Clone)] pub struct MajorityRule { period: usize, + mode: MajorityMode, values: IndicatorValues, colors: Vec, visible: bool, @@ -19,16 +40,24 @@ impl MajorityRule { pub fn new(period: usize) -> Self { Self { period: period.max(1), + mode: MajorityMode::Percentage, values: IndicatorValues::new(), colors: vec![Color32::from_rgb(255, 82, 82)], visible: true, } } + + /// Choose the percentage of rising closes or the signed direction. + pub fn with_mode(mut self, mode: MajorityMode) -> Self { + self.mode = mode; + self + } } impl Default for MajorityRule { + /// A lookback of 14 bars. fn default() -> Self { - Self::new(10) + Self::new(14) } } @@ -40,11 +69,9 @@ impl MajorityRule { return values; } - // First bar has no previous close to compare - values.push(IndicatorValue::None); - - for i in 1..data.len() { - if i < self.period { + // The first bar has no close before it and counts as not rising. + for i in 0..data.len() { + if i + 1 < self.period { values.push(IndicatorValue::None); continue; } @@ -64,12 +91,9 @@ impl MajorityRule { } } - let result = if up_count > down_count { - 1.0 - } else if down_count > up_count { - -1.0 - } else { - 0.0 + let result = match self.mode { + MajorityMode::Percentage => 100.0 * f64::from(up_count) / self.period as f64, + MajorityMode::Direction => f64::from((up_count - down_count).signum()), }; values.push(IndicatorValue::Single(result)); @@ -87,15 +111,23 @@ impl Indicator for MajorityRule { } crate::studies::inputs::study_inputs!(self; - period: length("Period", 1, usize::MAX) + period: length("Period", 1, usize::MAX), + mode: choice("Output", MajorityMode::ALL) ; {}); + fn value_format(&self) -> crate::scales::StudyFormat { + match self.mode { + MajorityMode::Percentage => crate::scales::StudyFormat::Percent, + MajorityMode::Direction => crate::scales::StudyFormat::Fixed(2), + } + } + fn name(&self) -> &str { "MajRule" } fn desc(&self) -> &str { - "Majority Rule - +1 if majority up closes, -1 if majority down, 0 if tie" + "Majority Rule - percentage of rising closes, or +1 / -1 / 0 for the majority direction" } fn calculate(&mut self, data: &[Bar]) { @@ -136,6 +168,18 @@ impl Indicator for MajorityRule { false } + fn pane(&self) -> crate::studies::StudyPane { + crate::studies::StudyPane { + levels: match self.mode { + MajorityMode::Percentage => { + vec![(50.0, crate::studies::palette::GRAY, "Middle guide")] + } + MajorityMode::Direction => Vec::new(), + }, + ..Default::default() + } + } + fn is_visible(&self) -> bool { self.visible } @@ -149,6 +193,170 @@ impl Indicator for MajorityRule { } fn line_names(&self) -> Vec { - vec![format!("MajRule({})", self.period)] + let mode = match self.mode { + MajorityMode::Percentage => "Percentage", + MajorityMode::Direction => "Direction", + }; + vec![format!("MajRule({}, {mode})", self.period)] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Bars whose open, high and low lie away from the close the rule reads. + fn bars(closes: &[f64]) -> Vec { + closes + .iter() + .enumerate() + .map(|(i, &close)| { + let time = chrono::DateTime::from_timestamp(i as i64 * 60, 0).unwrap(); + Bar::new(time, close - 0.5, close + 2.0, close - 1.0, close, 1.0) + }) + .collect() + } + + /// Both outputs over three changes, by hand. The bar without a close has no value and is + /// skipped, so the closes read 10, 12, 12, 11, 13, 14, 14, 9, 8. Bar 2 sees the first bar, + /// which counts as not rising, up and equal (33.33 %, +1); bar 3 sees up, equal, down + /// (33.33 %, tie); bar 5 sees equal, down, up (33.33 %, tie); bar 6 sees down, up, up + /// (66.67 %, +1); bar 7 sees up, up, equal (66.67 %, +1); bar 8 sees up, equal, down + /// (33.33 %, tie); bar 9 sees equal, down, down (0 %, -1). Correcting the close of bar 6 from + /// 14 to 12 changes bars 6 to 9: bar 6 sees down, up, down (33.33 %, -1); bar 7 up, down, up + /// (66.67 %, +1); bar 8 down, up, down (33.33 %, -1); bar 9 up, down, down (33.33 %, -1). + #[test] + fn both_outputs_follow_the_rising_closes_through_ties_a_gap_and_a_correction() { + let third = 100.0 / 3.0; + let none = f64::NAN; + let mut closes = [10.0, 12.0, 12.0, 11.0, f64::NAN, 13.0, 14.0, 14.0, 9.0, 8.0]; + let saved = [ + ( + MajorityMode::Percentage, + [ + none, + none, + third, + third, + none, + third, + 2.0 * third, + 2.0 * third, + third, + 0.0, + ], + ), + ( + MajorityMode::Direction, + [none, none, 1.0, 0.0, none, 0.0, 1.0, 1.0, 0.0, -1.0], + ), + ]; + let corrected = [ + ( + MajorityMode::Percentage, + [ + none, + none, + third, + third, + none, + third, + third, + 2.0 * third, + third, + third, + ], + ), + ( + MajorityMode::Direction, + [none, none, 1.0, 0.0, none, 0.0, -1.0, 1.0, -1.0, -1.0], + ), + ]; + let fresh = |mode, closes: &[f64]| { + let mut study = MajorityRule::new(3).with_mode(mode); + study.calculate(&bars(closes)); + study + }; + let check = |study: &MajorityRule, want: &[f64; 10]| { + for (bar, want) in want.iter().enumerate() { + let got = study.values().value(0, bar).unwrap_or(f64::NAN); + let equal = (got.is_nan() && want.is_nan()) || (got - want).abs() < 1e-9; + assert!(equal, "bar {bar}: {got}, not {want}"); + } + }; + let studies: Vec<_> = saved + .iter() + .map(|(mode, _)| fresh(*mode, &closes)) + .collect(); + for (study, (_, want)) in studies.iter().zip(&saved) { + check(study, want); + } + closes[6] = 12.0; + for (study, (mode, want)) in studies.iter().zip(&corrected) { + let mut study = study.clone(); + study.update(&bars(&closes), 6); + check(&study, want); + check(&fresh(*mode, &closes), want); + } + } + + /// At length `n` the first value is at bar `n - 1`, the first bar counting as not rising. + /// Length 3 on closes 10, 11, 10, 12: bar 2 sees the first bar, up, down (33.33 %, tie) and + /// bar 3 up, down, up (66.67 %, +1). Length 1: bar 0 is the first bar (0 %, tie), then up, + /// down, up (100 %, +1; 0 %, -1; 100 %, +1). + #[test] + fn the_first_value_is_at_the_bar_before_the_length() { + let third = 100.0 / 3.0; + let none = f64::NAN; + let data = bars(&[10.0, 11.0, 10.0, 12.0]); + for (length, mode, want) in [ + ( + 3, + MajorityMode::Percentage, + [none, none, third, 2.0 * third], + ), + (3, MajorityMode::Direction, [none, none, 0.0, 1.0]), + (1, MajorityMode::Percentage, [0.0, 100.0, 0.0, 100.0]), + (1, MajorityMode::Direction, [0.0, 1.0, -1.0, 1.0]), + ] { + let mut study = MajorityRule::new(length).with_mode(mode); + study.calculate(&data); + for (bar, want) in want.iter().enumerate() { + let got = study.values().value(0, bar).unwrap_or(f64::NAN); + let equal = (got.is_nan() && want.is_nan()) || (got - want).abs() < 1e-9; + assert!( + equal, + "length {length}, {mode:?}, bar {bar}: {got}, not {want}" + ); + } + } + } + + /// A Majority Rule from the catalogue opens at length 14 with a dashed grey guide at 50, and + /// one in direction mode has no guide. + #[test] + fn a_new_study_has_length_14_and_a_middle_guide_for_the_percentage() { + let study = crate::studies::IndicatorFactory::new() + .create("MajRule") + .unwrap(); + let period = study + .inputs() + .into_iter() + .find(|input| input.id == "period") + .map(|input| input.value); + assert_eq!(period, Some(crate::studies::InputValue::Length(14))); + let levels: Vec<_> = study + .pane() + .levels + .into_iter() + .map(|(value, color, _)| (value, color)) + .collect(); + assert_eq!(levels, [(50.0, crate::studies::palette::GRAY)]); + assert_eq!( + study.settings().levels[0].pattern, + crate::model::LineStyle::Dashed + ); + let direction = MajorityRule::default().with_mode(MajorityMode::Direction); + assert!(direction.pane().levels.is_empty()); } } diff --git a/vendor/egui-charts/src/studies/builtin/mod.rs b/vendor/egui-charts/src/studies/builtin/mod.rs index 24ecb6b..2592920 100644 --- a/vendor/egui-charts/src/studies/builtin/mod.rs +++ b/vendor/egui-charts/src/studies/builtin/mod.rs @@ -310,7 +310,7 @@ pub use market_breadth::{ mod special_k; mod woodies_cci; pub use symbol_pair::{Correlation, Ratio, Spread, SymbolPair}; -pub use technical_ratings::TechnicalRatings; +pub use technical_ratings::{RatingBasis, TechnicalRatings}; // Time studies mod lower_interval; mod performance; @@ -495,7 +495,7 @@ pub use ma_presets::{MARibbon, MixedMACross, TripleMA}; pub use smoothed_ma::SmoothedMA; // Re-exports - Tenth batch (Statistics) -pub use majority_rule::MajorityRule; +pub use majority_rule::{MajorityMode, MajorityRule}; pub use rank_correlation::RankCorrelationIndex; pub use standard_error::StandardError; pub use standard_error_bands::StandardErrorBands; diff --git a/vendor/egui-charts/src/studies/builtin/ohlc_volatility.rs b/vendor/egui-charts/src/studies/builtin/ohlc_volatility.rs index 5ababab..68223ab 100644 --- a/vendor/egui-charts/src/studies/builtin/ohlc_volatility.rs +++ b/vendor/egui-charts/src/studies/builtin/ohlc_volatility.rs @@ -10,6 +10,9 @@ use egui::Color32; #[derive(Clone)] pub struct OhlcVolatility { period: usize, + /// Trading days per year the result is annualized over, one bar per day (252 for stocks, 365 + /// for crypto); bars shorter than a day need the bars in a year instead + trading_days: f64, values: IndicatorValues, colors: Vec, visible: bool, @@ -20,11 +23,19 @@ impl OhlcVolatility { pub fn new(period: usize) -> Self { Self { period: period.max(1), + trading_days: 252.0, values: IndicatorValues::new(), colors: vec![Color32::from_rgb(255, 82, 82)], // Violet visible: true, } } + + /// Set the bars per year the volatility is annualized over, clamped into 0 to + /// `f64::MAX`, NaN to 0. + pub fn with_trading_days(mut self, days: f64) -> Self { + self.trading_days = super::clamp_param(days, 0.0, f64::MAX); + self + } } impl Default for OhlcVolatility { @@ -76,7 +87,7 @@ impl OhlcVolatility { let avg = valid.iter().sum::() / valid.len() as f64; // sqrt of average GK, annualized, as percentage let vol = if avg >= 0.0 { - avg.sqrt() * 252.0_f64.sqrt() * 100.0 + avg.sqrt() * self.trading_days.sqrt() * 100.0 } else { 0.0 }; @@ -90,7 +101,8 @@ impl OhlcVolatility { impl Indicator for OhlcVolatility { crate::studies::inputs::study_inputs!(self; - period: length("Period", 1, usize::MAX) + period: length("Period", 1, usize::MAX), + trading_days: number("Trading days per year", 0.0, f64::MAX) ; {}); fn value_format(&self) -> crate::scales::StudyFormat { @@ -172,3 +184,39 @@ impl Indicator for OhlcVolatility { vec![format!("GK Vol({})", self.period)] } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Four usable bars with open, high, low and close apart and a bar that closes at its open, an + /// unusable bar between the second and the third, then the second bar's high and close + /// corrected. Expected values come from the Garman-Klass definition over the last three + /// usable bars, evaluated independently, annualized over 252 and 365 bars. + #[test] + fn ohlc_annualizes_over_the_bars_per_year_across_gaps_ties_and_corrections() { + let bars = |second: (f64, f64, f64, f64)| -> Vec { + let bar = |(o, h, l, c)| Bar::new(chrono::DateTime::UNIX_EPOCH, o, h, l, c, 1.0); + vec![ + bar((100.0, 104.0, 98.0, 103.0)), + bar(second), + bar((f64::NAN, 105.0, 99.0, 102.0)), + bar((102.0, 105.0, 99.0, 102.0)), + bar((102.0, 107.0, 100.0, 106.0)), + ] + }; + for (days, as_saved, corrected) in [ + (252.0, 68.93275599968585, 77.34860413688467), + (365.0, 82.96058468746685, 93.08905948841814), + ] { + let mut study = OhlcVolatility::new(3).with_trading_days(days); + study.calculate(&bars((103.0, 108.0, 101.0, 102.0))); + assert_eq!(study.values().value(0, 2), None, "{days}: unusable bar"); + let got = study.values().value(0, 4).unwrap(); + assert!((got - as_saved).abs() < 1e-9, "{days}: {got}"); + study.update(&bars((103.0, 110.0, 100.0, 108.0)), 1); + let got = study.values().value(0, 4).unwrap(); + assert!((got - corrected).abs() < 1e-9, "{days} corrected: {got}"); + } + } +} diff --git a/vendor/egui-charts/src/studies/builtin/performance.rs b/vendor/egui-charts/src/studies/builtin/performance.rs index 7bbc968..05e86bc 100644 --- a/vendor/egui-charts/src/studies/builtin/performance.rs +++ b/vendor/egui-charts/src/studies/builtin/performance.rs @@ -69,7 +69,7 @@ impl Performance { title: "Performance".into(), columns: vec!["Period".into(), "Change".into()], rows: Vec::new(), - ..StudyTable::default() + ..Default::default() }, colors: [palette::BLUE; 6], visible: true, diff --git a/vendor/egui-charts/src/studies/builtin/price_oscillator.rs b/vendor/egui-charts/src/studies/builtin/price_oscillator.rs index e9fd530..00076d4 100644 --- a/vendor/egui-charts/src/studies/builtin/price_oscillator.rs +++ b/vendor/egui-charts/src/studies/builtin/price_oscillator.rs @@ -9,6 +9,7 @@ use std::collections::VecDeque; /// Average formula of an oscillator's averages and signal line, and of the middle line of /// [`KeltnerChannels`](super::KeltnerChannels). #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum OscillatorAverage { /// Alpha 2/(length+1). The Price and Percentage Volume Oscillators and Keltner's middle line /// seed it with the mean of the first `length` values, MACD with the first value. diff --git a/vendor/egui-charts/src/studies/builtin/relative_volume_at_time.rs b/vendor/egui-charts/src/studies/builtin/relative_volume_at_time.rs index 52552f0..f0b0a35 100644 --- a/vendor/egui-charts/src/studies/builtin/relative_volume_at_time.rs +++ b/vendor/egui-charts/src/studies/builtin/relative_volume_at_time.rs @@ -52,6 +52,7 @@ const DAY_MS: i64 = 86_400_000; /// The period at whose start [`RelativeVolumeAtTime`] restarts its comparison. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] pub enum RelativeVolumeAnchor { /// Each trading day. #[default] diff --git a/vendor/egui-charts/src/studies/builtin/rsi.rs b/vendor/egui-charts/src/studies/builtin/rsi.rs index 946eec1..d51fe31 100644 --- a/vendor/egui-charts/src/studies/builtin/rsi.rs +++ b/vendor/egui-charts/src/studies/builtin/rsi.rs @@ -36,10 +36,20 @@ //! input offers none, SMA, SMA with Bollinger Bands, EMA, SMMA (RMA), WMA and VWMA, with the length //! and the band deviation as inputs of their own. [`RSI::new`] starts without it. //! +//! # Divergences +//! +//! With its divergence input on, the RSI also marks the regular divergences between its swings +//! and the price's, found as [`RsiDivergence`](super::RsiDivergence) finds them with its default +//! pivots: 5 bars on each side of a pivot and 5 to 60 bars between two pivots. A pivot low of the +//! RSI above the previous one, on a bar whose low is below that pivot's, is bullish; a pivot high +//! below the previous one, on a bar whose high is above, is bearish. Each is a segment of the RSI +//! between the two pivots and a "Bull" or "Bear" mark on the second. A source other than the +//! close changes the RSI and leaves the highs and lows compared. The input is off by default. +//! //! # Default colour //! //! Purple (#7E57C2), with a one-pixel line, the average yellow (#FDD835) and its bands green -//! (#4CAF50). +//! (#4CAF50). Bullish divergences are green (#4CAF50) and bearish ones red (#F23645). //! //! # Example //! @@ -54,6 +64,7 @@ //! assert!(matches!(rsi.values().to_rows()[14], IndicatorValue::Single(_))); //! ``` +use super::rsi_divergence::{Confirmed, MARKS, Pivots, Search}; use super::smoothing::{SMOOTHING_COLORS, Smoothed, SmoothingType}; use crate::model::Bar; use crate::studies::palette; @@ -71,19 +82,26 @@ pub struct RSI { smoothing: SmoothingType, smoothing_length: usize, smoothing_deviation: f64, + divergence: bool, values: IndicatorValues, stepper: Stepper, + confirmed: Confirmed, color: Color32, smoothing_colors: [Color32; 3], fill_color: Color32, + /// The colours of the four divergence plots: the bullish and the bearish segment, then the + /// bullish and the bearish mark. + divergence_colors: [Color32; 4], visible: bool, } -/// The RSI and the average of its values. +/// The RSI, the average of its values and the pivots its divergences compare. #[derive(Clone, Default)] struct Averaged { rsi: State, smoothed: Smoothed, + bar: usize, + pivots: Pivots, } #[derive(Clone)] @@ -156,15 +174,31 @@ impl RSI { smoothing: SmoothingType::None, smoothing_length: 14, smoothing_deviation: 2.0, + divergence: false, values: IndicatorValues::new(), stepper: Stepper::default(), + confirmed: Confirmed::default(), color: palette::PURPLE, smoothing_colors: SMOOTHING_COLORS, fill_color: palette::PURPLE.gamma_multiply_u8(26), + divergence_colors: [palette::GREEN, palette::RED, palette::GREEN, palette::RED], visible: true, } } + /// Whether to mark the regular divergences between the RSI and price (builder pattern). + pub fn with_divergence(mut self, divergence: bool) -> Self { + self.divergence = divergence; + self + } + + /// Which of the four divergence outputs `line` is: the bullish segment, the bearish segment, + /// the bullish mark or the bearish mark. + fn divergence_output(&self, line: usize) -> Option { + line.checked_sub(1 + self.smoothing.lines()) + .filter(|&output| self.divergence && output < 4) + } + /// Set a custom line colour (builder pattern). pub fn with_color(mut self, color: Color32) -> Self { self.set_colors(vec![color]); @@ -193,13 +227,28 @@ impl Indicator for RSI { )) } + /// A source stands in for the close and leaves each bar's high and low, which the + /// divergences compare. + fn update_source(&mut self, data: &[Bar], from: usize, source: &[f64]) { + let bars: Vec<_> = data + .iter() + .enumerate() + .map(|(at, bar)| Bar { + close: source.get(at).copied().unwrap_or(f64::NAN), + ..bar.clone() + }) + .collect(); + self.update(&bars, from); + } + crate::studies::inputs::study_inputs!(self; period: length("Period", 1, usize::MAX), smoothing: choice("Smoothing", SmoothingType::ALL), smoothing_length: length("Smoothing length", 1, usize::MAX) if smoothing in SmoothingType::WITH_LENGTH, smoothing_deviation: number("Band deviation", 0.0, f64::MAX) - if smoothing in SmoothingType::WITH_BANDS + if smoothing in SmoothingType::WITH_BANDS, + divergence: toggle("Calculate divergence") ; {}); fn name(&self) -> &str { @@ -219,22 +268,56 @@ impl Indicator for RSI { } fn update(&mut self, data: &[Bar], from: usize) { + if !self.confirmed.begin(&mut self.values, data.len(), from) { + return; + } let (period, kind, length, deviation) = ( self.period, self.smoothing, self.smoothing_length, self.smoothing_deviation, ); + let first = 1 + kind.lines(); + let search = self.divergence.then(|| Search::regular(first)); + let mut found = Vec::new(); self.stepper .run(data, from, &mut self.values, |state, bar| { - match state.rsi.next(bar, period) { + let value = match state.rsi.next(bar, period) { // Without an average the value passes through, so skip the call on every bar. IndicatorValue::Single(rsi) if kind != SmoothingType::None => state .smoothed .next(kind, length, deviation, rsi, bar.volume), other => other, + }; + let Some(search) = &search else { + return value; + }; + let source = state.bar; + state.bar += 1; + let mut row = match value { + IndicatorValue::None => Vec::new(), + IndicatorValue::Single(rsi) => vec![rsi], + IndicatorValue::Multiple(row) => row, + }; + if [bar.high, bar.low, bar.close].iter().all(|v| v.is_finite()) { + let rsi = row.first().copied().filter(|v| v.is_finite()); + state.pivots.next( + search, + source, + rsi.unwrap_or(f64::NAN), + bar.high, + bar.low, + &mut found, + ); + } + if row.is_empty() { + return IndicatorValue::None; } + // The divergence outputs are empty until a later bar confirms one. + row.resize(first + 4, f64::NAN); + IndicatorValue::Multiple(row) }); + self.confirmed.draw(&mut self.values, found, data.len()); } fn is_incremental(&self) -> bool { @@ -245,17 +328,37 @@ impl Indicator for RSI { &self.values } - /// The RSI, the average, its upper and lower band, and the band between the levels. + /// The RSI, the average, its upper and lower band, the band between the levels, the bullish + /// and bearish segments, and the bullish and bearish marks. While the divergences are drawn, + /// the colours of their four plots also follow those of the average's plots, so that the + /// list starts with each plot's colour in turn. fn colors(&self) -> Vec { let [average, upper, lower] = self.smoothing_colors; - vec![self.color, average, upper, lower, self.fill_color] + let mut colors = vec![self.color, average, upper, lower, self.fill_color]; + colors.extend(self.divergence_colors); + if self.divergence { + let first = 1 + self.smoothing.lines(); + colors.splice(first..first, self.divergence_colors); + } + colors } fn fills(&self) -> Vec { self.smoothing.fills() } - fn set_colors(&mut self, colors: Vec) { + /// The two colours after the band between the levels colour each kind's segment and mark, + /// the two after them the marks alone, and the four divergence plots, where the list names + /// them, then take their own. + fn set_colors(&mut self, mut colors: Vec) { + let plots: Vec<_> = if self.divergence { + // The colours of the four divergence plots, where `colors` lists them. + let first = colors.len().min(1 + self.smoothing.lines()); + let end = colors.len().min(first + 4); + colors.drain(first..end).collect() + } else { + Vec::new() + }; if !colors.is_empty() { self.color = colors[0]; for (slot, color) in self.smoothing_colors.iter_mut().zip(&colors[1..]) { @@ -264,9 +367,64 @@ impl Indicator for RSI { self.fill_color = colors.get(4).copied().unwrap_or_else(|| { Color32::from_rgba_unmultiplied(self.color.r(), self.color.g(), self.color.b(), 16) }); + for (kind, color) in colors.iter().skip(5).take(2).enumerate() { + self.divergence_colors[kind] = *color; + self.divergence_colors[kind + 2] = *color; + } + let marks = self.divergence_colors[2..].iter_mut(); + for (slot, color) in marks.zip(colors.iter().skip(7)) { + *slot = *color; + } + } + for (slot, color) in self.divergence_colors.iter_mut().zip(plots) { + *slot = color; + } + } + + fn plot_style(&self, line: usize) -> crate::studies::PlotStyle { + use crate::studies::PlotType; + let (color, width, plot_type) = match self.divergence_output(line) { + Some(output) => ( + self.divergence_colors[output], + 2.0, + match output { + 2 => PlotType::TriangleUp, + 3 => PlotType::TriangleDown, + _ => PlotType::Line, + }, + ), + None => ( + self.colors().get(line).copied().unwrap_or(Color32::WHITE), + self.line_style(line).width, + PlotType::Line, + ), + }; + crate::studies::PlotStyle { + color, + width, + pattern: crate::model::LineStyle::Solid, + plot_type, + visible: true, } } + /// The RSI and its average keep their tags on the scale beside the divergence outputs. + fn plot_tagged(&self, line: usize) -> bool { + line < 1 + self.smoothing.lines() + } + + fn plot_label_colors(&self, line: usize) -> Option<(Color32, Color32)> { + let output = self.divergence_output(line).filter(|&output| output >= 2)?; + Some((self.divergence_colors[output], Color32::WHITE)) + } + + fn plot_text(&self, line: usize, bar: usize) -> Option { + let output = self.divergence_output(line).filter(|&output| output >= 2)?; + // Each regular mark is listed before its hidden one. + let mark = MARKS[(output % 2) * 2]; + self.values.value(line, bar).map(|_| mark.to_string()) + } + fn pane(&self) -> crate::studies::StudyPane { crate::studies::StudyPane { height: Some(138.0), @@ -297,12 +455,23 @@ impl Indicator for RSI { } fn line_count(&self) -> usize { - 1 + self.smoothing.lines() + 1 + self.smoothing.lines() + 4 * usize::from(self.divergence) } fn line_names(&self) -> Vec { let mut names = vec![format!("RSI({})", self.period)]; names.extend(self.smoothing.line_names("RSI-based MA")); + if self.divergence { + names.extend( + [ + "Regular Bullish", + "Regular Bearish", + "Regular Bullish Label", + "Regular Bearish Label", + ] + .map(String::from), + ); + } names } } @@ -406,4 +575,184 @@ mod tests { .unwrap(); assert_eq!(study.line_count(), 1); } + + /// Closes step by 1 from 100, so each rise moves an RSI(2) halfway to 100 and each fall + /// halves it: 100 on bar 2, five falls to 100/32 on bar 7, five rises to 100 * 993/1024 on + /// bar 13, four falls to 100 * 993/16384 on bar 17 and three rises to 100 * 115681/131072 on + /// bar 20. Bar 10 has no close and takes no place among them. Bar 21 falls by 2^-40, which + /// lowers the RSI by under 1e-10: a tie, so the later bar 21 is the pivot high, not bar 20. + /// Five falls follow, the last on bar 26. + /// + /// Every bar reaches 0.5 above and 0.25 below its close, but bar 17 falls to 90 and bar 21 + /// rises to 110. Pivot lows 7 and 17: the RSI rose and the low fell from 96.75 to 90 while + /// the close rose, which is bullish over ten usable bars, bar 11 a third of the way along. + /// Pivot highs 13 and 21: the RSI fell and the high rose from 102.5 to 110 while the close + /// fell, which is bearish once bar 26 confirms the pivot. A close of 1000 on bar 26 lifts its + /// RSI over the pivot's and withdraws that divergence. + #[test] + fn divergences_follow_the_wicks_through_a_gap_a_tie_and_a_correction() { + use crate::studies::InputValue; + let tie = 2f64.powi(-40); + let runs = [ + (1.0, 2), + (-1.0, 5), + (1.0, 2), + (f64::NAN, 1), + (1.0, 3), + (-1.0, 4), + (1.0, 3), + (-tie, 1), + (-1.0, 5), + ]; + let (mut last, mut closes) = (100.0, vec![100.0]); + for (step, count) in runs { + for _ in 0..count { + if step.is_nan() { + closes.push(f64::NAN); + } else { + last += step; + closes.push(last); + } + } + } + let mut bars = bars_from_closes(&closes); + for bar in &mut bars { + let near = if bar.close.is_nan() { 100.0 } else { bar.close }; + (bar.high, bar.low) = (near + 0.5, near - 0.25); + } + bars[17].low = 90.0; + bars[21].high = 110.0; + let (low, high) = (100.0 * 993.0 / 16384.0, 100.0 * 993.0 / 1024.0); + let tied = 100.0 * 115681.0 / 131072.0 / (1.0 + tie); + + // The four outputs follow the RSI, or the average and its bands. + for (smoothing, first) in [(0, 1), (2, 4)] { + let mut study = RSI::new(2); + study + .set_input("smoothing", InputValue::Choice(smoothing)) + .unwrap(); + study + .set_input("divergence", InputValue::Toggle(true)) + .unwrap(); + study.calculate(&bars); + assert_eq!(study.line_count(), first + 4); + let value = + |study: &RSI, output: usize, bar: usize| study.values().value(first + output, bar); + let drawn = |study: &RSI, output: usize| -> Vec { + (0..bars.len()) + .filter(|&bar| value(study, output, bar).is_some()) + .collect() + }; + assert_eq!(drawn(&study, 0), [7, 8, 9, 11, 12, 13, 14, 15, 16, 17]); + assert_eq!(value(&study, 0, 7), Some(3.125)); + let third = value(&study, 0, 11).unwrap(); + assert!((third - (3.125 + (low - 3.125) / 3.0)).abs() < 1e-12); + assert_eq!(value(&study, 0, 17), Some(low)); + assert_eq!(drawn(&study, 2), [17]); + assert_eq!(value(&study, 2, 17), Some(low)); + assert_eq!(study.plot_text(first + 2, 17).as_deref(), Some("Bull")); + + assert_eq!(drawn(&study, 1), [13, 14, 15, 16, 17, 18, 19, 20, 21]); + assert_eq!(value(&study, 1, 13), Some(high)); + assert_eq!(drawn(&study, 3), [21]); + assert!((value(&study, 3, 21).unwrap() - tied).abs() < 1e-11); + assert_eq!(study.plot_text(first + 3, 21).as_deref(), Some("Bear")); + + // A source takes the place of the close alone, so the wicks still decide. + let mut sourced = study.clone(); + sourced.update_source(&bars, 0, &closes); + assert_eq!( + format!("{:?}", sourced.values()), + format!("{:?}", study.values()) + ); + + // An update that changes nothing leaves the correction after it able to withdraw. + let mut corrected = bars.clone(); + corrected[26].close = 1000.0; + study.update(&bars, bars.len()); + study.update(&corrected, 26); + assert!(drawn(&study, 1).is_empty() && drawn(&study, 3).is_empty()); + assert_eq!(drawn(&study, 0).len(), 10); + } + } + + /// The divergence plots follow the average's, so an average with bands puts three plots + /// before them and no average takes those away again. Each divergence plot keeps the style + /// set for it and stays off the scale, and the average's plots start with their own. + #[test] + fn divergence_styles_stay_with_their_plots_when_the_average_changes() { + use crate::studies::{ConfiguredStudy, InputValue, PlotType}; + let mut study = ConfiguredStudy::new(Box::new(RSI::new(14).with_divergence(true))); + let mut settings = study.settings(); + settings.plots[1].color = Color32::BLUE; + for (smoothing, first) in [(2, 4), (0, 1)] { + let inputs = [("smoothing".to_owned(), InputValue::Choice(smoothing))]; + study.apply_settings(&inputs, settings).unwrap(); + assert_eq!(study.line_count(), first + 4); + assert!(first == 1 || study.plot_style(1).color == palette::YELLOW); + assert_eq!(study.plot_style(first).color, Color32::BLUE); + assert_eq!(study.plot_style(first + 1).color, palette::RED); + let marks = [first + 2, first + 3].map(|line| study.plot_style(line).plot_type); + assert_eq!(marks, [PlotType::TriangleUp, PlotType::TriangleDown]); + let tagged: Vec<_> = (0..first + 4).filter(|&l| study.plot_tagged(l)).collect(); + assert_eq!(tagged, (0..first).collect::>()); + settings = study.settings(); + } + assert_eq!(settings.plots[0].color, palette::PURPLE); + } + + /// A colour list names each plot in turn, so on a chart a new RSI colour leaves each + /// divergence plot the colour last set for it, a segment styled apart from its mark + /// included, and a colour for each of the eight plots reaches every one. + #[test] + fn a_colour_list_names_the_divergence_plots_in_turn() { + use crate::studies::{InputValue, StudyTemplate}; + let (green, red) = (palette::GREEN, palette::RED); + // Saved while the RSI kept one colour for both plots of a divergence, with the bullish + // segment styled light blue and the bearish mark brown, apart from their kind's other + // plot. It restores as it was saved. + let saved = r#"{"name":"RSI","inputs":[["period",{"Length":14}],["smoothing",{"Choice":1}],["smoothing_length",{"Length":14}],["smoothing_deviation",{"Number":2.0}],["divergence",{"Toggle":true}],["source",{"Source":{"Price":"Close"}}],["plot_offset",{"Integer":0}],["calculation_symbol",{"Symbol":""}],["calculation_timeframe",{"Timeframe":null}],["wait_for_close",{"Toggle":true}]],"settings":{"show_legend_values":true,"user_edit_enabled":true,"help_url":"https://userfrm.github.io/egui-charts/docs/api/egui_charts/studies/struct.RSI.html","plots":[{"color":[126,87,194,255],"width":1.0,"pattern":"Solid","plot_type":"Line","visible":true},{"color":[253,216,53,255],"width":1.0,"pattern":"Solid","plot_type":"Line","visible":true},{"color":[173,216,230,255],"width":2.0,"pattern":"Solid","plot_type":"Line","visible":true},{"color":[242,54,69,255],"width":2.0,"pattern":"Solid","plot_type":"Line","visible":true},{"color":[76,175,80,255],"width":2.0,"pattern":"Solid","plot_type":"TriangleUp","visible":true},{"color":[165,42,42,255],"width":2.0,"pattern":"Solid","plot_type":"TriangleDown","visible":true}],"precision":2,"hidden_intervals":[],"interval_range":"All","levels":[{"value":null,"color":[120,123,134,255],"pattern":"Dashed","width":1.0,"visible":true,"price_line":false},{"value":null,"color":[120,123,134,255],"pattern":"Dashed","width":1.0,"visible":true,"price_line":false},{"value":null,"color":[120,123,134,255],"pattern":"Dashed","width":1.0,"visible":true,"price_line":false}],"fill_between_levels":true,"level_fill_color":[13,9,20,26],"untagged_plots":[2,3,4,5],"price_line_plots":[],"plot_variants":[[],[],[],[],[],[]],"background":null,"background_visible":true,"fills":[],"gradients":[]},"visible":true,"scale":"Independent"}"#; + let mut study = serde_json::from_str::(saved) + .unwrap() + .create() + .unwrap(); + let (average, segment, mark) = (palette::YELLOW, Color32::LIGHT_BLUE, Color32::BROWN); + assert_eq!( + study.colors(), + [palette::PURPLE, average, segment, red, green, mark] + ); + study.set_colors(vec![Color32::BLUE]); + assert_eq!( + study.colors(), + [Color32::BLUE, average, segment, red, green, mark] + ); + // Recoloured while its divergences are off, the RSI brings each plot back in its colour. + let mut settings = study.settings(); + settings.plots[0].color = Color32::WHITE; + let off = [("divergence".to_owned(), InputValue::Toggle(false))]; + study.apply_settings(&off, settings).unwrap(); + let on = [("divergence".to_owned(), InputValue::Toggle(true))]; + let settings = study.settings(); + study.apply_settings(&on, settings).unwrap(); + assert_eq!( + study.colors(), + [Color32::WHITE, average, segment, red, green, mark] + ); + let banded = [("smoothing".to_owned(), InputValue::Choice(2))]; + let settings = study.settings(); + study.apply_settings(&banded, settings).unwrap(); + let (bullish, bearish) = (Color32::GOLD, Color32::KHAKI); + let plots = [ + Color32::BLUE, + average, + green, + green, + bullish, + bearish, + bullish, + bearish, + ]; + study.set_colors(plots.to_vec()); + assert_eq!(study.colors(), plots); + } } diff --git a/vendor/egui-charts/src/studies/builtin/rsi_divergence.rs b/vendor/egui-charts/src/studies/builtin/rsi_divergence.rs index ce7ba63..73e0fe7 100644 --- a/vendor/egui-charts/src/studies/builtin/rsi_divergence.rs +++ b/vendor/egui-charts/src/studies/builtin/rsi_divergence.rs @@ -52,8 +52,9 @@ use egui::Color32; /// scale together, as on a flat bar, but rounds to neighbouring floats. const RSI_TIE: f64 = 1e-9; -/// Text of the marks on outputs 5 to 8. -const MARKS: [&str; 4] = ["Bull", "H Bull", "Bear", "H Bear"]; +/// Text of the marks of the regular bullish, hidden bullish, regular bearish and hidden bearish +/// divergence. +pub(super) const MARKS: [&str; 4] = ["Bull", "H Bull", "Bear", "H Bear"]; /// RSI Divergence Indicator: the RSI with regular and hidden divergences against price. #[derive(Clone)] @@ -69,7 +70,7 @@ pub struct RsiDivergence { hidden_bearish: bool, values: IndicatorValues, stepper: Stepper, - undo: Vec<(usize, usize, f64)>, + undo: Confirmed, rsi_color: Color32, fill_color: Color32, bull_color: Color32, @@ -89,20 +90,218 @@ struct Pivot { #[derive(Clone, Default)] struct State { source: usize, - position: usize, rsi: RsiState, + pivots: Pivots, +} + +/// The pivots a divergence search compares and the outputs it draws each divergence on. +pub(super) struct Search { + left: usize, + right: usize, + min_range: usize, + max_range: usize, + /// The segment and mark outputs of the regular bullish, hidden bullish, regular bearish and + /// hidden bearish divergence, `None` for one that is not shown. + lines: [Option<(usize, usize)>; 4], +} + +impl Search { + /// The regular divergences between the default pivots: the bullish and bearish segments on + /// outputs `first` and `first + 1`, their marks on the two outputs after. + pub(super) fn regular(first: usize) -> Self { + let RsiDivergence { + left, + right, + min_range, + max_range, + .. + } = RsiDivergence::default(); + Self { + left, + right, + min_range, + max_range, + lines: [ + Some((first, first + 2)), + None, + Some((first + 1, first + 3)), + None, + ], + } + } +} + +/// The bars a divergence search still compares and the last pivot low and high. A study keeps +/// it in its checkpointed state. +#[derive(Clone, Default)] +pub(super) struct Pivots { + position: usize, window: std::collections::VecDeque, previous: [Option; 2], } -struct Segment { - line: usize, +/// A divergence found on bar `confirming`: its segment over `sources`, from one pivot's RSI to +/// the other's, and its mark on the last of them. +pub(super) struct Segment { + lines: (usize, usize), sources: Vec, from: f64, to: f64, confirming: usize, } +impl Pivots { + /// Adds bar `source`, whose prices are finite and whose RSI is NaN until it has a value, and + /// pushes the divergences that bar confirms onto `found`. A bar with a missing price is not + /// added, so it takes no place between pivots. + pub(super) fn next( + &mut self, + search: &Search, + source: usize, + rsi: f64, + high: f64, + low: f64, + found: &mut Vec, + ) { + let keep = search + .left + .max(search.max_range.saturating_add(1)) + .saturating_add(search.right) + .saturating_add(1); + self.window.push_back(Pivot { + source, + position: self.position, + rsi, + high, + low, + }); + self.position += 1; + if self.window.len() > keep { + self.window.pop_front(); + } + let Some(at) = self + .window + .len() + .checked_sub(search.right.saturating_add(1)) + .filter(|&at| at >= search.left) + else { + return; + }; + let p = self.window[at]; + let mut window = self.window.range(at - search.left..); + if !window.all(|pivot| pivot.rsi.is_finite()) { + return; + } + for high in [false, true] { + let before = self.window.range(at - search.left..at).all(|v| { + if high { + v.rsi <= p.rsi + RSI_TIE + } else { + v.rsi >= p.rsi - RSI_TIE + } + }); + let after = self.window.range(at + 1..).all(|v| { + if high { + v.rsi < p.rsi - RSI_TIE + } else { + v.rsi > p.rsi + RSI_TIE + } + }); + if !(before && after) { + continue; + } + let previous = self.previous[usize::from(high)].replace(p); + let Some(q) = previous else { + continue; + }; + if !(search.min_range..=search.max_range).contains(&(p.position - q.position - 1)) { + continue; + } + let divergences = if high { + [(2, false, true), (3, true, false)] + } else { + [(0, true, false), (1, false, true)] + }; + for (kind, rsi_rises, price_rises) in divergences { + let Some(lines) = search.lines[kind] else { + continue; + }; + // Prices compare exactly, so the rule holds at any price scale. + let moved = |rises: bool, from: f64, to: f64, tie: f64| { + if rises { + to > from + tie + } else { + to < from - tie + } + }; + let price = |pivot: Pivot| if high { pivot.high } else { pivot.low }; + if moved(rsi_rises, q.rsi, p.rsi, RSI_TIE) + && moved(price_rises, price(q), price(p), 0.0) + { + found.push(Segment { + lines, + sources: self + .window + .iter() + .filter(|v| (q.position..=p.position).contains(&v.position)) + .map(|v| v.source) + .collect(), + from: q.rsi, + to: p.rsi, + confirming: source, + }); + } + } + } + } +} + +/// What the divergences confirmed on the last bar replaced. A study keeps it beside its values, +/// so that a correction of that bar can withdraw them. +#[derive(Clone, Default)] +pub(super) struct Confirmed(Vec<(usize, usize, f64)>); + +impl Confirmed { + /// Readies `values` for an update from bar `from` of `len`: a last bar about to be + /// recalculated gives back what its divergences replaced. `false` when no bar changed, where + /// the update must do nothing so that a later correction can still withdraw them. + pub(super) fn begin(&mut self, values: &mut IndicatorValues, len: usize, from: usize) -> bool { + let old = values.len(); + if old > 0 && from == old && len == old { + return false; + } + if old > 0 && from == old - 1 && len >= old { + // A developing confirmation can be withdrawn, restoring the earlier segment it replaced. + for &(line, bar, value) in &self.0 { + values.set_value(line, bar, value); + } + } + self.0.clear(); + true + } + + /// Draws `found` on `values` of `len` bars, each segment interpolated so that the line joins + /// its two pivots. + pub(super) fn draw(&mut self, values: &mut IndicatorValues, found: Vec, len: usize) { + for segment in found { + let mut set = |line: usize, bar: usize, value: f64| { + if segment.confirming + 1 == len { + self.0 + .push((line, bar, values.value(line, bar).unwrap_or(f64::NAN))); + } + values.set_value(line, bar, value); + }; + let (line, mark) = segment.lines; + let last = segment.sources.len() - 1; + for (position, &bar) in segment.sources.iter().enumerate() { + let t = position as f64 / last as f64; + set(line, bar, segment.from + (segment.to - segment.from) * t); + } + set(mark, segment.sources[last], segment.to); + } + } +} + impl RsiDivergence { /// RSI of `period`, pivots with `left` and `right` bars on each side, lengths raised to /// at least 1, and `min_range` to `max_range` bars between two pivots compared. @@ -125,7 +324,7 @@ impl RsiDivergence { hidden_bearish: false, values: IndicatorValues::new(), stepper: Stepper::default(), - undo: Vec::new(), + undo: Confirmed::default(), rsi_color: palette::BLUE, fill_color: palette::LIGHT_BLUE.gamma_multiply_u8(26), bull_color: palette::GREEN, @@ -194,23 +393,22 @@ impl Indicator for RsiDivergence { } fn update(&mut self, data: &[Bar], from: usize) { - let len = self.values.len(); - if len > 0 && from == len && data.len() == len { + if !self.undo.begin(&mut self.values, data.len(), from) { return; } - if len > 0 && from == len - 1 && data.len() >= len { - // A developing confirmation can be withdrawn, restoring the earlier segment it replaced. - for &(line, bar, value) in &self.undo { - self.values.set_value(line, bar, value); - } - } - self.undo.clear(); - let mut segments = Vec::new(); - let keep = self - .left - .max(self.max_range.saturating_add(1)) - .saturating_add(self.right) - .saturating_add(1); + let search = Search { + left: self.left, + right: self.right, + min_range: self.min_range, + max_range: self.max_range, + lines: [ + self.bullish.then_some((1, 5)), + self.hidden_bullish.then_some((2, 6)), + self.bearish.then_some((3, 7)), + self.hidden_bearish.then_some((4, 8)), + ], + }; + let mut found = Vec::new(); self.stepper .run(data, from, &mut self.values, |state, bar| { let source = state.source; @@ -222,130 +420,14 @@ impl Indicator for RsiDivergence { IndicatorValue::Single(value) if value.is_finite() => value, _ => f64::NAN, }; - let current = Pivot { - source, - position: state.position, - rsi, - high: bar.high, - low: bar.low, - }; - state.position += 1; - state.window.push_back(current); - if state.window.len() > keep { - state.window.pop_front(); - } - if let Some(at) = state - .window - .len() - .checked_sub(self.right.saturating_add(1)) - .filter(|&at| at >= self.left) - { - let p = state.window[at]; - let window = state.window.range(at - self.left..); - if window.clone().all(|pivot| pivot.rsi.is_finite()) { - for high in [false, true] { - let before = state.window.range(at - self.left..at).all(|v| { - if high { - v.rsi <= p.rsi + RSI_TIE - } else { - v.rsi >= p.rsi - RSI_TIE - } - }); - let after = state.window.range(at + 1..).all(|v| { - if high { - v.rsi < p.rsi - RSI_TIE - } else { - v.rsi > p.rsi + RSI_TIE - } - }); - if !(before && after) { - continue; - } - let previous = state.previous[usize::from(high)].replace(p); - let Some(q) = previous else { - continue; - }; - if !(self.min_range..=self.max_range) - .contains(&(p.position - q.position - 1)) - { - continue; - } - let divergences = if high { - [ - (self.bearish, 3, false, true), - (self.hidden_bearish, 4, true, false), - ] - } else { - [ - (self.bullish, 1, true, false), - (self.hidden_bullish, 2, false, true), - ] - }; - for (shown, line, rsi_rises, price_rises) in divergences { - // Prices compare exactly, so the rule holds at any price scale. - let moved = |rises: bool, from: f64, to: f64, tie: f64| { - if rises { - to > from + tie - } else { - to < from - tie - } - }; - let price = - |pivot: Pivot| if high { pivot.high } else { pivot.low }; - if shown - && moved(rsi_rises, q.rsi, p.rsi, RSI_TIE) - && moved(price_rises, price(q), price(p), 0.0) - { - segments.push(Segment { - line, - sources: state - .window - .iter() - .filter(|v| { - (q.position..=p.position).contains(&v.position) - }) - .map(|v| v.source) - .collect(), - from: q.rsi, - to: p.rsi, - confirming: source, - }); - } - } - } - } - } + state + .pivots + .next(&search, source, rsi, bar.high, bar.low, &mut found); let mut row = vec![f64::NAN; 9]; row[0] = rsi; IndicatorValue::Multiple(row) }); - for segment in segments { - let last = segment.sources.len() - 1; - for (position, &bar) in segment.sources.iter().enumerate() { - if segment.confirming + 1 == data.len() { - self.undo.push(( - segment.line, - bar, - self.values.value(segment.line, bar).unwrap_or(f64::NAN), - )); - } - let t = position as f64 / last as f64; - self.values.set_value( - segment.line, - bar, - segment.from + (segment.to - segment.from) * t, - ); - } - let bar = segment.sources[last]; - if segment.confirming + 1 == data.len() { - self.undo.push(( - segment.line + 4, - bar, - self.values.value(segment.line + 4, bar).unwrap_or(f64::NAN), - )); - } - self.values.set_value(segment.line + 4, bar, segment.to); - } + self.undo.draw(&mut self.values, found, data.len()); } fn is_incremental(&self) -> bool { diff --git a/vendor/egui-charts/src/studies/builtin/seasonality.rs b/vendor/egui-charts/src/studies/builtin/seasonality.rs index e25e678..1b4c329 100644 --- a/vendor/egui-charts/src/studies/builtin/seasonality.rs +++ b/vendor/egui-charts/src/studies/builtin/seasonality.rs @@ -118,7 +118,7 @@ impl Seasonality { .map(String::from) .to_vec(), rows: Vec::new(), - ..StudyTable::default() + ..Default::default() }, projection: Vec::new(), colors: [palette::UP, gray, gray, gray, gray], diff --git a/vendor/egui-charts/src/studies/builtin/standard_error_bands.rs b/vendor/egui-charts/src/studies/builtin/standard_error_bands.rs index f799205..b561eac 100644 --- a/vendor/egui-charts/src/studies/builtin/standard_error_bands.rs +++ b/vendor/egui-charts/src/studies/builtin/standard_error_bands.rs @@ -1,28 +1,63 @@ use super::clamp_param; +use super::smoothing::{Smoothed, SmoothingType}; use crate::model::Bar; use crate::studies::palette; -use crate::studies::stepper::update_window; +use crate::studies::stepper::Stepper; use crate::studies::{Indicator, IndicatorValue, IndicatorValues}; use egui::Color32; +use std::collections::VecDeque; + +/// The averages the regression can be smoothed with, in the order the type input lists them. +const SMOOTHING: [SmoothingType; 6] = [ + SmoothingType::None, + SmoothingType::Sma, + SmoothingType::Ema, + SmoothingType::Smma, + SmoothingType::Wma, + SmoothingType::Vwma, +]; +/// The positions in [`SMOOTHING`] that use a length. +const WITH_LENGTH: [usize; 5] = [1, 2, 3, 4, 5]; /// Standard Error Bands - upper/middle (linear regression)/lower bands /// where upper = LinReg + multiplier * StdError, lower = LinReg - multiplier * StdError. +/// +/// The smoothing inputs average the regression value and its standard error before the bands are +/// formed, so the middle line and the distance of the bands from it follow the chosen average. +/// With no smoothing, the default, both are the values of the latest `period` closes. The three +/// lines are undefined while the window or the average lacks bars. A missing close makes them +/// undefined while it is in the window; an SMA, WMA or VWMA stays undefined until it has left the +/// average too, where an EMA or SMMA resumes from the value it held before the gap. #[derive(Clone)] pub struct StandardErrorBands { period: usize, multiplier: f64, + smoothing: SmoothingType, + smoothing_length: usize, values: IndicatorValues, + stepper: Stepper, colors: Vec, visible: bool, } +/// The latest `period` closes, and the averages of the regression value and its standard error. +#[derive(Clone, Default)] +struct Rolling { + window: VecDeque, + middle: Smoothed, + error: Smoothed, +} + impl StandardErrorBands { /// `multiplier` is clamped into 0 to `f64::MAX`, NaN to 0. pub fn new(period: usize, multiplier: f64) -> Self { Self { period: period.max(2), multiplier: clamp_param(multiplier, 0.0, f64::MAX), + smoothing: SmoothingType::None, + smoothing_length: 3, values: IndicatorValues::new(), + stepper: Stepper::default(), colors: vec![palette::LIGHT_BLUE, palette::ORANGE, palette::LIGHT_BLUE], visible: true, } @@ -78,35 +113,6 @@ impl Default for StandardErrorBands { } } -impl StandardErrorBands { - fn compute(&self, data: &[Bar]) -> IndicatorValues { - let mut values = IndicatorValues::new(); - - if data.is_empty() { - return values; - } - - for i in 0..data.len() { - if i + 1 < self.period { - values.push(IndicatorValue::None); - continue; - } - - let start = i + 1 - self.period; - let prices: Vec = data[start..=i].iter().map(|b| b.close).collect(); - let (slope, intercept, se) = Self::linreg_with_se(&prices); - - // Middle = linear regression value at end of window - let middle = intercept + slope * (self.period - 1) as f64; - let upper = middle + self.multiplier * se; - let lower = middle - self.multiplier * se; - - values.push_lines(&[upper, middle, lower]); - } - values - } -} - impl Indicator for StandardErrorBands { fn source(&self) -> Option { Some(crate::studies::StudySource::Price( @@ -116,7 +122,9 @@ impl Indicator for StandardErrorBands { crate::studies::inputs::study_inputs!(self; period: length("Period", 2, usize::MAX), - multiplier: number("Multiplier", 0.0, f64::MAX) + multiplier: number("Multiplier", 0.0, f64::MAX), + smoothing: choice("Smoothing", SMOOTHING), + smoothing_length: length("Smoothing length", 1, usize::MAX) if smoothing in WITH_LENGTH ; {}); fn name(&self) -> &str { @@ -132,15 +140,37 @@ impl Indicator for StandardErrorBands { } fn update(&mut self, data: &[Bar], from: usize) { - let mut values = std::mem::take(&mut self.values); - update_window( - &mut values, - data, - from, - |_data, from| from.saturating_sub(self.period - 1), - |data| self.compute(data), - ); - self.values = values; + let (period, multiplier) = (self.period, self.multiplier); + let (kind, length) = (self.smoothing, self.smoothing_length); + let mut prices = Vec::new(); + self.stepper + .run(data, from, &mut self.values, |state, bar| { + state.window.push_back(bar.close); + if state.window.len() > period { + state.window.pop_front(); + } + if state.window.len() < period { + return IndicatorValue::None; + } + prices.clear(); + prices.extend(&state.window); + // A missing close in the window makes all three values NaN. + let (slope, intercept, se) = Self::linreg_with_se(&prices); + let middle = intercept + slope * (period - 1) as f64; + let average = |smoothed: &mut Smoothed, value| match smoothed + .next(kind, length, 0.0, value, bar.volume) + { + IndicatorValue::Multiple(values) => values[1], + _ => value, + }; + let middle = average(&mut state.middle, middle); + let se = average(&mut state.error, se); + IndicatorValue::Multiple(vec![ + middle + multiplier * se, + middle, + middle - multiplier * se, + ]) + }); } fn is_incremental(&self) -> bool { @@ -191,3 +221,138 @@ impl Indicator for StandardErrorBands { ] } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::studies::{InputValue, StudyTemplate}; + + /// Bars whose open, high and low lie away from the close and whose volumes differ. + fn bars(closes: &[f64]) -> Vec { + closes + .iter() + .enumerate() + .map(|(i, &close)| { + let time = chrono::DateTime::from_timestamp(i as i64 * 60, 0).unwrap(); + let volume = [1.0, 3.0, 2.0, 4.0, 5.0, 6.0, 7.0][i % 7]; + Bar::new(time, close - 0.5, close + 2.0, close - 1.0, close, volume) + }) + .collect() + } + + fn assert_lines(study: &StandardErrorBands, bar: usize, want: [Option; 3]) { + for (line, want) in want.into_iter().enumerate() { + let got = study.values().value(line, bar); + let equal = match (got, want) { + (Some(got), Some(want)) => (got - want).abs() < 1e-9, + (got, want) => got == want, + }; + assert!(equal, "bar {bar}, line {line}: {got:?}, not {want:?}"); + } + } + + fn bands(middle: f64, error: f64) -> [Option; 3] { + [ + Some(middle + 2.0 * error), + Some(middle), + Some(middle - 2.0 * error), + ] + } + + /// Three-bar fits by hand, with x = 0, 1, 2 so the slope is (last - first) / 2, the endpoint + /// the mean plus the slope, and the squared error the spread about the mean minus twice the + /// squared slope (one degree of freedom left). Closes 1, 2, 2 give an endpoint 13/6 and an + /// error 1/sqrt(6); 2, 2, 4 (tied first closes) give 11/3 and sqrt(2/3); 2, 4, 3 give 7/2 and + /// sqrt(3/2). Each type then averages two of these on volumes 4 and 5 for the bars it reads: + /// the SMA is their midpoint, the WMA weighs them 1 and 2, the VWMA 4 and 5, and the EMA and + /// SMMA start from the mean of the first two and add 2/3 and 1/2 of the step to the third. + #[test] + fn the_smoothing_averages_the_regression_and_its_error() { + let (m, e) = ( + [13.0 / 6.0, 11.0 / 3.0, 3.5], + [1.0 / 6.0f64.sqrt(), (2.0f64 / 3.0).sqrt(), 1.5f64.sqrt()], + ); + let at_bar_4: [fn(f64, f64, f64) -> f64; 6] = [ + |_, _, c| c, + |_, b, c| (b + c) / 2.0, + |a, b, c| (a + b) / 6.0 + 2.0 * c / 3.0, + |a, b, c| (a + b) / 4.0 + c / 2.0, + |_, b, c| (b + 2.0 * c) / 3.0, + |_, b, c| (4.0 * b + 5.0 * c) / 9.0, + ]; + for (choice, average) in at_bar_4.into_iter().enumerate() { + let mut study = StandardErrorBands::new(3, 2.0); + study + .set_input("smoothing", InputValue::Choice(choice)) + .unwrap(); + study + .set_input("smoothing_length", InputValue::Length(2)) + .unwrap(); + study.calculate(&bars(&[1.0, 2.0, 2.0, 4.0, 3.0])); + let (middle, error) = (average(m[0], m[1], m[2]), average(e[0], e[1], e[2])); + assert_lines(&study, 4, bands(middle, error)); + if choice == 0 { + assert_lines(&study, 2, bands(m[0], e[0])); + } else { + // The first bar the average covers. + assert_lines(&study, 2, [None; 3]); + } + } + } + + /// A missing close leaves every band undefined while it is in the three-bar window and then + /// while the two-bar average still holds a value from it. After closes 4, 3, 5 (endpoint 9/2, + /// error sqrt(3/2)) and 3, 5, 6 (endpoint 37/6, error 1/sqrt(6)) the average of both is the + /// midpoint. Correcting the third close from 2 to 3 turns the first windows into 1, 2, 3 and + /// 2, 3, 4, exact lines with endpoints 3 and 4, and the next into 3, 4, 3: 10/3 and + /// sqrt(2/3), so the averages move from that bar on and an earlier bar stays as it was. + #[test] + fn a_missing_close_and_a_historical_correction_reach_every_later_band() { + let mut study = StandardErrorBands::new(3, 2.0); + for (id, value) in [ + ("smoothing", InputValue::Choice(1)), + ("smoothing_length", InputValue::Length(2)), + ] { + study.set_input(id, value).unwrap(); + } + study.calculate(&bars(&[1.0, 2.0, 2.0, f64::NAN, 4.0, 3.0, 5.0, 6.0])); + for bar in 3..7 { + assert_lines(&study, bar, [None; 3]); + } + let error = (1.5f64.sqrt() + (1.0 / 6.0f64.sqrt())) / 2.0; + assert_lines(&study, 7, bands((4.5 + 37.0 / 6.0) / 2.0, error)); + + study.calculate(&bars(&[1.0, 2.0, 2.0, 4.0, 3.0])); + study.update(&bars(&[1.0, 2.0, 3.0, 4.0, 3.0]), 2); + assert_lines(&study, 2, [None; 3]); + assert_lines(&study, 3, bands(3.5, 0.0)); + assert_lines( + &study, + 4, + bands((4.0 + 10.0 / 3.0) / 2.0, (2.0f64 / 3.0).sqrt() / 2.0), + ); + } + + /// A study saved before the smoothing inputs existed restores unsmoothed, with its three plots. + #[test] + fn a_study_saved_before_the_smoothing_inputs_restores_unsmoothed() { + let saved: StudyTemplate = serde_json::from_str( + r#"{"name":"StdErrBands","inputs":[["period",{"Length":3}],["multiplier",{"Number":2.0}]],"settings":{"show_legend_values":true,"user_edit_enabled":true,"help_url":"https://userfrm.github.io/egui-charts/docs/api/egui_charts/studies/struct.StandardErrorBands.html","plots":[{"color":[33,150,243,255],"width":1.0,"pattern":"Solid","plot_type":"Line","visible":true},{"color":[255,109,0,255],"width":1.0,"pattern":"Solid","plot_type":"Line","visible":true},{"color":[33,150,243,255],"width":1.0,"pattern":"Solid","plot_type":"Line","visible":true}],"precision":null,"hidden_intervals":[],"interval_range":"All","levels":[],"fill_between_levels":false,"level_fill_color":[2,9,15,16],"untagged_plots":[],"price_line_plots":[],"plot_variants":[[],[],[]],"background":null,"background_visible":true,"fills":[],"gradients":[]},"visible":true,"scale":"Main"}"#, + ) + .unwrap(); + let mut study = saved.create().unwrap(); + assert_eq!(study.line_count(), 3); + study.calculate(&bars(&[1.0, 2.0, 2.0])); + let values = study.values(); + let (middle, error) = (13.0 / 6.0, 1.0 / 6.0f64.sqrt()); + for (line, want) in [middle + 2.0 * error, middle, middle - 2.0 * error] + .into_iter() + .enumerate() + { + assert!( + (values.value(line, 2).unwrap() - want).abs() < 1e-9, + "line {line}" + ); + } + } +} diff --git a/vendor/egui-charts/src/studies/builtin/symbol_pair.rs b/vendor/egui-charts/src/studies/builtin/symbol_pair.rs index 9f3bbe8..a930def 100644 --- a/vendor/egui-charts/src/studies/builtin/symbol_pair.rs +++ b/vendor/egui-charts/src/studies/builtin/symbol_pair.rs @@ -26,6 +26,11 @@ //! //! Hosts supply the histories of the symbols named by the inputs, as for any other study with //! [`Indicator::data_requests`]; no market data service is included. +//! +//! # Presentation +//! +//! The correlation opens as an area from zero with dashed guides at its bounds, 1 and -1, and at +//! zero. The ratio and the spread open as lines without guides. use crate::model::{Bar, PriceSource}; use crate::studies::palette; @@ -316,6 +321,21 @@ impl Indicator for SymbolPair crate::studies::PlotStyle { + crate::studies::PlotStyle { + color: self.colors().get(line).copied().unwrap_or(Color32::WHITE), + width: self.line_style(line).width, + pattern: crate::model::LineStyle::Solid, + // The correlation is an area from zero; the ratio and the spread are lines. + plot_type: if CORRELATION { + crate::studies::PlotType::Area + } else { + crate::studies::PlotType::Line + }, + visible: true, + } + } + fn set_colors(&mut self, colors: Vec) { if let Some(color) = colors.first() { self.color = *color; @@ -325,8 +345,13 @@ impl Indicator for SymbolPair crate::studies::StudyPane { crate::studies::StudyPane { range: CORRELATION.then_some((-1.1, 1.1)), + // The bounds of a correlation, then zero. levels: if CORRELATION { - vec![(0.0, palette::GRAY.gamma_multiply_u8(128), "Zero")] + vec![ + (1.0, palette::GRAY, "Upper guide"), + (-1.0, palette::GRAY, "Lower guide"), + (0.0, palette::GRAY.gamma_multiply_u8(128), "Zero"), + ] } else { Vec::new() }, @@ -375,6 +400,25 @@ mod tests { .collect() } + /// Recalculates the study from bar `from`, with `other` as the host's series. + fn feed(study: &mut dyn Indicator, chart: &[Bar], other: &[Bar], from: usize) { + let sources: Vec<_> = study + .data_requests() + .into_iter() + .map(|request| StudyData { + request, + bars: other, + clock: BarClock::new(Timeframe::Day1), + instrument: None, + timeframe: Timeframe::Day1, + }) + .collect(); + study.update_data(chart, from, &sources); + } + + /// The study's values over the whole history. The same history streamed must give the same + /// values: every bar but the last, then a tick that leaves another value in both series on + /// the last bar, then the bar corrected to its final values. fn run( name: &str, inputs: &[(&str, InputValue)], @@ -391,21 +435,31 @@ mod tests { study.set_input(id, value.clone()).unwrap(); } let (chart, other) = (bars(chart), bars(other)); - let sources: Vec<_> = study - .data_requests() - .into_iter() - .map(|request| StudyData { - request, - bars: &other, - clock: BarClock::new(Timeframe::Day1), - instrument: None, - timeframe: Timeframe::Day1, - }) - .collect(); - study.update_data(&chart, 0, &sources); - (0..chart.len()) - .map(|at| study.values().value(0, at)) - .collect() + let last = chart.len() - 1; + let tick = |bars: &[Bar]| -> Vec { + bars.iter() + .map(|bar| { + if bar.time == chart[last].time { + let value = -2.0 * bar.close - 1.0; + Bar::new(bar.time, value, value, value, value, 1.0) + } else { + bar.clone() + } + }) + .collect() + }; + let values = |study: &dyn Indicator| -> Vec> { + (0..chart.len()) + .map(|at| study.values().value(0, at)) + .collect() + }; + let mut streamed = study.clone_box(); + feed(streamed.as_mut(), &chart[..last], &other, 0); + feed(streamed.as_mut(), &tick(&chart), &tick(&other), last); + feed(streamed.as_mut(), &chart, &other, last); + feed(study.as_mut(), &chart, &other, 0); + assert_eq!(values(streamed.as_ref()), values(study.as_ref()), "{name}"); + values(study.as_ref()) } fn near(actual: &[Option], expected: &[Option], case: &str) { diff --git a/vendor/egui-charts/src/studies/builtin/technical_ratings.rs b/vendor/egui-charts/src/studies/builtin/technical_ratings.rs index 71d0797..5592cf7 100644 --- a/vendor/egui-charts/src/studies/builtin/technical_ratings.rs +++ b/vendor/egui-charts/src/studies/builtin/technical_ratings.rs @@ -32,17 +32,70 @@ //! ``` //! //! The six outputs are the moving-average, oscillator and summary scores followed by their -//! coverages; the coverages are hidden by default. The table shows the latest bar's score, rating -//! and coverage of each group. +//! coverages; the coverages are hidden by default. The rating basis decides which groups the +//! summary averages: both by default, or only the moving averages or only the oscillators. +//! +//! The table shows the latest bar's score, rating and coverage of each group the basis uses, +//! each row on the background of its rating. With higher intervals shown, the study requests the +//! chart symbol's 1-minute, 5-minute, 15-minute, 30-minute, 1-hour, 4-hour, daily, weekly and +//! monthly bars longer than the chart interval, rates the latest bar of each with the same +//! components and adds a row with its summary score, rating and coverage. -use crate::model::Bar; +use crate::model::{Bar, Timeframe}; use crate::studies::palette; use crate::studies::{ CCI, EMA, Indicator, IndicatorValue, IndicatorValues, MACD, Momentum, RSI, SMA, Stochastic, - StudyCell, StudyTable, + StudyCell, StudyData, StudyDataRequest, StudyTable, TablePosition, TableTextSize, }; use egui::Color32; +/// The intervals rated in the table with higher intervals shown, where longer than the chart's. +const INTERVALS: [Timeframe; 9] = [ + Timeframe::Min1, + Timeframe::Min5, + Timeframe::Min15, + Timeframe::Min30, + Timeframe::Hour1, + Timeframe::Hour4, + Timeframe::Day1, + Timeframe::Week1, + Timeframe::Month1, +]; + +/// The groups whose votes the summary score averages. The `Debug` names are the choices its +/// input lists. +#[derive(Clone, Copy, Default, PartialEq, Eq)] +pub enum RatingBasis { + /// Every vote of the moving averages and the oscillators. + #[default] + All, + /// The moving averages' votes only. + MovingAverages, + /// The oscillators' votes only. + Oscillators, +} + +impl std::fmt::Debug for RatingBasis { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::All => "All", + Self::MovingAverages => "Moving averages", + Self::Oscillators => "Oscillators", + }) + } +} + +impl RatingBasis { + /// The groups it averages, as a range of group indices. + fn groups(self) -> std::ops::Range { + match self { + Self::All => 0..2, + Self::MovingAverages => 0..1, + Self::Oscillators => 1..2, + } + } +} + /// Group of a component, in the order of the score outputs. #[derive(Clone, Copy, PartialEq)] enum Group { @@ -122,6 +175,21 @@ pub struct TechnicalRatings { macd_signal: usize, momentum: bool, momentum_period: usize, + basis: RatingBasis, + table_intervals: bool, + table_position: TablePosition, + table_size: TableTextSize, + table_strong_buy_color: Color32, + table_buy_color: Color32, + table_neutral_color: Color32, + table_sell_color: Color32, + table_strong_sell_color: Color32, + table_header_color: Color32, + table_text_color: Color32, + /// The chart interval, which decides the higher intervals requested. + timeframe: Option, + /// The latest scores and coverages of each requested interval, `None` without its bars. + intervals: Vec<(Timeframe, Option<[f64; 6]>)>, components: Option>, /// The bars with a finite high, low and close, which every component reads, and their /// positions in the input. @@ -155,6 +223,19 @@ impl TechnicalRatings { macd_signal: 9, momentum: true, momentum_period: 10, + basis: RatingBasis::All, + table_intervals: false, + table_position: TablePosition::BottomRight, + table_size: TableTextSize::Normal, + table_strong_buy_color: palette::BLUE, + table_buy_color: Color32::from_rgb(91, 156, 246), + table_neutral_color: palette::DISABLED, + table_sell_color: Color32::from_rgb(239, 154, 154), + table_strong_sell_color: palette::BRIGHT_RED, + table_header_color: Color32::from_rgb(41, 91, 121), + table_text_color: Color32::WHITE, + timeframe: None, + intervals: Vec::new(), components: None, bars: Vec::new(), sources: Vec::new(), @@ -164,8 +245,7 @@ impl TechnicalRatings { columns: ["Group", "Score", "Rating", "Coverage"] .map(String::from) .to_vec(), - rows: Vec::new(), - ..StudyTable::default() + ..Default::default() }, colors: vec![ palette::DISABLED, @@ -182,6 +262,13 @@ impl TechnicalRatings { } } + /// The summary score averages the votes of the groups `basis` chooses. + pub fn with_basis(mut self, basis: RatingBasis) -> Self { + self.basis = basis; + self.components = None; + self + } + fn build(&self) -> Vec { let mut components = Vec::new(); let mut add = |group, rule, warmup, study: Box| { @@ -242,8 +329,8 @@ impl TechnicalRatings { components } - /// The scores and coverages on clean bar `at`. - fn row(components: &[Component], at: usize, close: f64) -> [f64; 6] { + /// The scores and coverages on clean bar `at`, the summary of the groups `basis` chooses. + fn row(components: &[Component], at: usize, close: f64, basis: RatingBasis) -> [f64; 6] { // Votes and enabled components of the moving averages, the oscillators and in total. let mut sum = [0.0; 2]; let mut votes = [0usize; 2]; @@ -273,15 +360,94 @@ impl TechnicalRatings { votes as f64 / enabled as f64 } }; + let chosen = basis.groups(); [ score(sum[0], votes[0]), score(sum[1], votes[1]), - score(sum[0] + sum[1], votes[0] + votes[1]), + score( + sum[chosen.clone()].iter().sum(), + votes[chosen.clone()].iter().sum(), + ), coverage(votes[0], enabled[0]), coverage(votes[1], enabled[1]), - coverage(votes[0] + votes[1], enabled[0] + enabled[1]), + coverage( + votes[chosen.clone()].iter().sum(), + enabled[chosen].iter().sum(), + ), ] } + + /// The scores and coverages of the latest of `bars`, or `None` when it has no finite high, + /// low and close. + fn latest(&self, bars: &[Bar]) -> Option<[f64; 6]> { + let bars: Vec<_> = bars.iter().filter(|bar| usable(bar)).cloned().collect(); + let at = bars.len().checked_sub(1)?; + let mut components = self.build(); + for component in &mut components { + component.study.calculate(&bars); + } + Some(Self::row(&components, at, bars[at].close, self.basis)) + } + + /// The table rows of the latest bar and of the requested intervals, on their ratings' + /// backgrounds. + fn fill_table(&mut self) { + let latest = self.values.len().checked_sub(1); + let at = |line: usize| latest.and_then(|bar| self.values.value(line, bar)); + let groups: &[usize] = match self.basis { + RatingBasis::All => &[0, 1, 2], + RatingBasis::MovingAverages => &[0], + RatingBasis::Oscillators => &[1], + }; + let labels = ["Moving averages", "Oscillators", "Summary"]; + let mut rows: Vec<_> = groups + .iter() + .map(|&group| (labels[group].to_string(), at(group), at(group + 3))) + .collect(); + if self.table_intervals { + let finite = |value: f64| value.is_finite().then_some(value); + rows.extend(self.intervals.iter().map(|(timeframe, latest)| { + ( + timeframe.as_str().into_owned(), + latest.and_then(|row| finite(row[2])), + latest.and_then(|row| finite(row[5])), + ) + })); + } + self.table.cell_colors = rows + .iter() + .map(|(_, score, _)| match score.map_or("Neutral", rating) { + "Strong Buy" => self.table_strong_buy_color, + "Buy" => self.table_buy_color, + "Sell" => self.table_sell_color, + "Strong Sell" => self.table_strong_sell_color, + _ => self.table_neutral_color, + }) + .collect(); + self.table.rows = rows + .into_iter() + .map(|(label, score, coverage)| { + vec![ + StudyCell::Text(label), + StudyCell::Text(score.map_or("N/A".into(), |score| format!("{score:+.2}"))), + StudyCell::Text(score.map_or("N/A", rating).into()), + StudyCell::Text( + coverage + .map_or("N/A".into(), |coverage| format!("{:.0}%", coverage * 100.0)), + ), + ] + }) + .collect(); + self.table.header_color = Some(self.table_header_color); + self.table.text_color = Some(self.table_text_color); + self.table.position = self.table_position; + self.table.text_size = self.table_size; + } +} + +/// Whether every component can read `bar`. +fn usable(bar: &Bar) -> bool { + bar.high.is_finite() && bar.low.is_finite() && bar.close.is_finite() } /// Construct with the conventional default parameters. @@ -324,7 +490,18 @@ impl Indicator for TechnicalRatings { macd_slow: length("MACD slow period", 1, usize::MAX), macd_signal: length("MACD signal period", 1, usize::MAX), momentum: toggle("Momentum"), - momentum_period: length("Momentum period", 1, usize::MAX) + momentum_period: length("Momentum period", 1, usize::MAX), + basis: choice("Rating basis", [RatingBasis::All, RatingBasis::MovingAverages, RatingBasis::Oscillators]), + table_intervals: toggle("Table shows higher intervals"), + table_position: choice("Table position", TablePosition::ALL), + table_size: choice("Table size", TableTextSize::ALL), + table_strong_buy_color: color("Table strong buy colour"), + table_buy_color: color("Table buy colour"), + table_neutral_color: color("Table neutral colour"), + table_sell_color: color("Table sell colour"), + table_strong_sell_color: color("Table strong sell colour"), + table_header_color: color("Table header colour"), + table_text_color: color("Table text colour") ; { self.components = None; }); @@ -341,6 +518,46 @@ impl Indicator for TechnicalRatings { self.update(data, 0); } + fn set_timeframe(&mut self, timeframe: Timeframe) { + self.timeframe = Some(timeframe); + } + + /// The chart symbol's bars of each higher interval, with higher intervals shown in the table. + fn data_requests(&self) -> Vec { + if !self.table_intervals { + return Vec::new(); + } + let chart = self + .timeframe + .map_or(0, |timeframe| timeframe.duration_ms()); + INTERVALS + .into_iter() + .filter(|timeframe| timeframe.duration_ms() > chart) + .map(|timeframe| StudyDataRequest { + symbol: String::new(), + timeframe: Some(timeframe), + metric: None, + }) + .collect() + } + + fn update_data(&mut self, data: &[Bar], from: usize, sources: &[StudyData<'_>]) { + if from == 0 { + self.intervals = self + .data_requests() + .into_iter() + .filter_map(|request| { + let source = sources.iter().find(|source| source.request == request); + Some(( + request.timeframe?, + source.and_then(|source| self.latest(source.bars)), + )) + }) + .collect(); + } + self.update(data, from); + } + fn update(&mut self, data: &[Bar], from: usize) { let mut from = from.min(self.values.len()).min(data.len()); if self.components.is_none() { @@ -351,8 +568,6 @@ impl Indicator for TechnicalRatings { let kept = self.sources.partition_point(|&source| source < from); self.sources.truncate(kept); self.bars.truncate(kept); - let usable = - |bar: &Bar| bar.high.is_finite() && bar.low.is_finite() && bar.close.is_finite(); for (source, bar) in data.iter().enumerate().skip(from) { if usable(bar) { self.sources.push(source); @@ -367,30 +582,13 @@ impl Indicator for TechnicalRatings { for bar in &data[from..] { if usable(bar) { self.values - .push_lines(&Self::row(components, at, bar.close)); + .push_lines(&Self::row(components, at, bar.close, self.basis)); at += 1; } else { self.values.push(IndicatorValue::None); } } - let latest = self.values.len().checked_sub(1); - self.table.rows = ["Moving averages", "Oscillators", "Summary"] - .into_iter() - .enumerate() - .map(|(group, label)| { - let at = |line: usize| latest.and_then(|bar| self.values.value(line, bar)); - let (score, coverage) = (at(group), at(group + 3)); - vec![ - StudyCell::Text(label.into()), - StudyCell::Text(score.map_or("N/A".into(), |score| format!("{score:+.2}"))), - StudyCell::Text(score.map_or("N/A", rating).into()), - StudyCell::Text( - coverage - .map_or("N/A".into(), |coverage| format!("{:.0}%", coverage * 100.0)), - ), - ] - }) - .collect(); + self.fill_table(); } fn is_incremental(&self) -> bool { @@ -519,19 +717,16 @@ impl Indicator for TechnicalRatings { #[cfg(test)] mod tests { use super::*; + use crate::model::BarClock; use crate::studies::InputValue; use chrono::{DateTime, Duration}; - /// Scores, coverages and ratings of two moving-average lengths and momentum, by hand. - /// - /// Closes 10, 12 and 11.4. SMA(2) is 11 and 11.7 on the last two bars; EMA(2) seeds with 10 and - /// moves 2/3 of the way: 34/3 and 34/9 + 22.8/3 = 11.3778. Momentum(1) is +2 and -0.6. - #[test] - fn scores_coverage_and_ratings_follow_the_votes() { - let bars: Vec<_> = [10.0, 12.0, 11.4] - .into_iter() + /// Bars of `closes` one day apart, with each price at the close. + fn bars(closes: &[f64]) -> Vec { + closes + .iter() .enumerate() - .map(|(i, c)| { + .map(|(i, &c)| { Bar::new( DateTime::UNIX_EPOCH + Duration::days(i as i64), c, @@ -541,7 +736,11 @@ mod tests { 1.0, ) }) - .collect(); + .collect() + } + + /// Ratings of three SMA(2), three EMA(2) and Momentum(1), the other oscillators off. + fn study(basis: usize) -> TechnicalRatings { let mut study = TechnicalRatings::default(); for (id, value) in [ ("fast", InputValue::Length(2)), @@ -552,49 +751,125 @@ mod tests { ("stochastic", InputValue::Toggle(false)), ("cci", InputValue::Toggle(false)), ("macd", InputValue::Toggle(false)), + ("basis", InputValue::Choice(basis)), + ("table_strong_sell_color", InputValue::Color(Color32::GOLD)), ] { study.set_input(id, value).unwrap(); } - study.calculate(&bars); - // Bar 0: no SMA or momentum yet; the three EMAs equal the close and vote neutral. - // Bar 1: all seven components buy. Bar 2: SMAs sell, EMAs buy, momentum sells. - let expected = [ - [0.0, f64::NAN, 0.0, 0.5, 0.0, 3.0 / 7.0], - [1.0, 1.0, 1.0, 1.0, 1.0, 1.0], - [0.0, -1.0, -1.0 / 7.0, 1.0, 1.0, 1.0], - ]; - for (bar, row) in expected.iter().enumerate() { - for (line, want) in row.iter().enumerate() { - match study.values().value(line, bar) { - Some(got) => assert!((got - want).abs() < 1e-12, "line {line} bar {bar}"), - None => assert!(want.is_nan(), "line {line} bar {bar}"), - } - } - } - let rows: Vec> = study - .table() - .unwrap() + study + } + + /// The label, score, rating and coverage of each table row, with its background. + fn table(study: &TechnicalRatings) -> Vec<([String; 4], Color32)> { + let table = study.table().unwrap(); + assert_eq!(table.cell_colors.len(), table.rows.len()); + table .rows .iter() - .map(|row| match &row[..] { + .zip(&table.cell_colors) + .map(|(row, &fill)| { + let text = |cell: &StudyCell| match cell { + StudyCell::Text(text) => text.clone(), + _ => panic!("text cells"), + }; + (std::array::from_fn(|column| text(&row[column])), fill) + }) + .collect() + } + + /// Scores, coverages, ratings and row backgrounds of each rating basis, by hand. + /// + /// Closes 10, 12, a bar without a close and 11.4. Every component skips the bar without a + /// close, which has no value. SMA(2) is 11 and 11.7 on the last two rated bars; EMA(2) seeds + /// with 10 and moves 2/3 of the way: 34/3 and 34/9 + 22.8/3 = 11.3778. Momentum(1) is +2 and + /// -0.6. The first bar has no SMA or momentum vote, which lowers its coverage, and the + /// three EMAs equal the close there and vote neutral. On the second bar all seven components + /// buy. On the last the SMAs sell and the EMAs buy, a tie, and momentum sells. + #[test] + fn scores_coverage_and_ratings_follow_the_votes() { + let bars = bars(&[10.0, 12.0, f64::NAN, 11.4]); + let nan = f64::NAN; + let row = |label: &str, score: &str, rating: &str, fill| { + ([label, score, rating, "100%"].map(String::from), fill) + }; + let sell = Color32::from_rgb(239, 154, 154); + for (basis, expected, rows) in [ + ( + RatingBasis::All, + [ + [0.0, nan, 0.0, 0.5, 0.0, 3.0 / 7.0], + [1.0; 6], + [nan; 6], + [0.0, -1.0, -1.0 / 7.0, 1.0, 1.0, 1.0], + ], + vec![ + row("Moving averages", "+0.00", "Neutral", palette::DISABLED), + row("Oscillators", "-1.00", "Strong Sell", Color32::GOLD), + row("Summary", "-0.14", "Sell", sell), + ], + ), + ( + RatingBasis::MovingAverages, [ - _, - StudyCell::Text(score), - StudyCell::Text(rating), - StudyCell::Text(coverage), - ] => { - vec![score.clone(), rating.clone(), coverage.clone()] + [0.0, nan, 0.0, 0.5, 0.0, 0.5], + [1.0; 6], + [nan; 6], + [0.0, -1.0, 0.0, 1.0, 1.0, 1.0], + ], + vec![row( + "Moving averages", + "+0.00", + "Neutral", + palette::DISABLED, + )], + ), + ( + RatingBasis::Oscillators, + [ + [0.0, nan, nan, 0.5, 0.0, 0.0], + [1.0; 6], + [nan; 6], + [0.0, -1.0, -1.0, 1.0, 1.0, 1.0], + ], + vec![row("Oscillators", "-1.00", "Strong Sell", Color32::GOLD)], + ), + ] { + let mut study = study(basis as usize); + study.calculate(&bars); + for (bar, row) in expected.iter().enumerate() { + for (line, want) in row.iter().enumerate() { + match study.values().value(line, bar) { + Some(got) => { + assert!( + (got - want).abs() < 1e-12, + "{basis:?} line {line} bar {bar}" + ) + } + None => assert!(want.is_nan(), "{basis:?} line {line} bar {bar}"), + } } - _ => panic!("text cells"), - }) - .collect(); + } + assert_eq!(table(&study), rows, "{basis:?}"); + let header = study.table().unwrap(); + assert_eq!( + (header.header_color, header.text_color), + (Some(Color32::from_rgb(41, 91, 121)), Some(Color32::WHITE)) + ); + } + // A correction of the latest close to 9: SMA(2) 10.5 and EMA(2) 34/3 - 2/3 * 7/3 = + // 9.7778 are above it and momentum is -3, so every component sells. + let mut corrected = study(0); + corrected.calculate(&bars); + let mut bars = bars; + bars[3].close = 9.0; + corrected.update(&bars, 3); + for line in 0..6 { + let want = if line < 3 { -1.0 } else { 1.0 }; + assert_eq!(corrected.values().value(line, 3), Some(want), "line {line}"); + } assert_eq!( - rows, - [ - ["+0.00", "Neutral", "100%"], - ["-1.00", "Strong Sell", "100%"], - ["-0.14", "Sell", "100%"], - ] + table(&corrected)[2], + row("Summary", "-1.00", "Strong Sell", Color32::GOLD) ); for (score, label) in [ (0.5, "Strong Buy"), @@ -608,4 +883,64 @@ mod tests { assert_eq!(rating(score), label, "{score}"); } } + + /// Higher intervals add one row each, rated from their own bars, and never repeat the chart + /// interval. Closes 10 and 12 make every component buy; 10, 12 and 11.4 rate as above. + #[test] + fn higher_intervals_add_rated_rows() { + let mut study = study(0); + study.set_timeframe(Timeframe::Hour1); + assert!(study.data_requests().is_empty()); + study + .set_input("table_intervals", InputValue::Toggle(true)) + .unwrap(); + let request = |timeframe| StudyDataRequest { + symbol: String::new(), + timeframe: Some(timeframe), + metric: None, + }; + let requests = [ + Timeframe::Hour4, + Timeframe::Day1, + Timeframe::Week1, + Timeframe::Month1, + ] + .map(request); + assert_eq!(study.data_requests(), requests); + let (rising, turning) = (bars(&[10.0, 12.0]), bars(&[10.0, 12.0, 11.4])); + let source = |request: &StudyDataRequest, bars| StudyData { + request: request.clone(), + bars, + clock: BarClock::new(request.timeframe.unwrap()), + instrument: None, + timeframe: request.timeframe.unwrap(), + }; + let sources = [ + source(&requests[0], &rising[..]), + source(&requests[1], &turning[..]), + source(&requests[2], &[][..]), + ]; + study.update_data(&rising, 0, &sources); + let missing = |label: &str| { + ( + [label, "N/A", "N/A", "N/A"].map(String::from), + palette::DISABLED, + ) + }; + assert_eq!( + table(&study)[3..], + [ + ( + ["4h", "+1.00", "Strong Buy", "100%"].map(String::from), + palette::BLUE + ), + ( + ["1D", "-0.14", "Sell", "100%"].map(String::from), + Color32::from_rgb(239, 154, 154) + ), + missing("1W"), + missing("1M"), + ] + ); + } } diff --git a/vendor/egui-charts/src/studies/builtin/trade_delta.rs b/vendor/egui-charts/src/studies/builtin/trade_delta.rs index 62476b4..6dfe038 100644 --- a/vendor/egui-charts/src/studies/builtin/trade_delta.rs +++ b/vendor/egui-charts/src/studies/builtin/trade_delta.rs @@ -5,6 +5,7 @@ use crate::model::Bar; /// One bar's trade-based delta, cumulative delta candle, and rolling totals. #[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] pub struct TradeDeltaValue { /// Buy minus sell volume in this bar. pub delta: f64, diff --git a/vendor/egui-charts/src/studies/builtin/trade_profile.rs b/vendor/egui-charts/src/studies/builtin/trade_profile.rs index 4a26aff..388e2c5 100644 --- a/vendor/egui-charts/src/studies/builtin/trade_profile.rs +++ b/vendor/egui-charts/src/studies/builtin/trade_profile.rs @@ -61,6 +61,7 @@ impl TradeProfileRanges { /// Executed volume over one session or composite, with the POC after each contributing bar. #[derive(Clone, Debug)] +#[non_exhaustive] pub struct TradeProfile { /// Half-open range of bar opening times. pub range: Range>, diff --git a/vendor/egui-charts/src/studies/builtin/visible_average_price.rs b/vendor/egui-charts/src/studies/builtin/visible_average_price.rs index 76c5f74..a1c0563 100644 --- a/vendor/egui-charts/src/studies/builtin/visible_average_price.rs +++ b/vendor/egui-charts/src/studies/builtin/visible_average_price.rs @@ -124,6 +124,93 @@ mod tests { use crate::studies::*; use chrono::{TimeZone, Utc}; + /// Guards #2927: on another interval or symbol the study averages its own bars that share + /// time with the chart bars in view, not those at the chart's indices, through a pan and a + /// streamed bar. + #[test] + fn visible_average_on_another_interval_uses_the_bars_in_view() { + use crate::model::{BarClock, Timeframe}; + let start = Utc.with_ymd_and_hms(2026, 3, 6, 0, 0, 0).unwrap(); + let bar = |minute: i64, c: f64| { + Bar::new(start + chrono::Duration::minutes(minute), c, c, c, c, 1.0) + }; + let mut chart: Vec<_> = (0..15).map(|i| bar(i, 100.0 + i as f64)).collect(); + let mut five: Vec<_> = [104.0, 109.0, 114.0] + .into_iter() + .enumerate() + .map(|(i, c)| bar(5 * i as i64, c)) + .collect(); + let mut study = ConfiguredStudy::new( + IndicatorFactory::new() + .create("Visible Average Price") + .expect("Visible Average Price study"), + ); + study.set_timeframe(Timeframe::Min1); + study.set_bar_clock(&BarClock::new(Timeframe::Min1)); + study + .set_input( + "calculation_timeframe", + InputValue::Timeframe(Some(Timeframe::Min5)), + ) + .unwrap(); + let update = |study: &mut ConfiguredStudy, chart: &[Bar], five: &[Bar], from| { + let source = StudyData { + request: study.data_requests()[0].clone(), + bars: five, + clock: BarClock::new(Timeframe::Min5), + instrument: None, + timeframe: Timeframe::Min5, + }; + study.update_data(chart, from, &[source]); + }; + // Chart bars 5 to 9 cover 00:05 to 00:09, the second five-minute bar, closing at 00:10 + // with chart bar 9. + study.set_visible_range(5..10); + update(&mut study, &chart, &five, 0); + assert_eq!(study.values().value(0, 9), Some(109.0)); + // A pan within the second five-minute bar asks for no recalculation. + assert!(!study.set_visible_range(6..10)); + // Panning to the third five-minute bar recalculates the mean. + assert!(study.set_visible_range(10..15)); + update(&mut study, &chart, &five, 0); + assert_eq!(study.values().value(0, 9), Some(114.0)); + // A streamed five-minute bar after the view keeps the mean of the bars in view. + chart.push(bar(15, 115.0)); + five.push(bar(15, 119.0)); + update(&mut study, &chart, &five, 15); + assert_eq!(study.values().value(0, 9), Some(114.0)); + // The chart empties a study that waits for a full recompute; the same view asks for none. + study.update(&[], 0); + assert!(!study.set_visible_range(10..15)); + + // Another symbol at the chart's interval whose history starts at 00:05 averages its + // closes from 00:05 to 00:09: 200 to 204. + let other: Vec<_> = (5..15).map(|i| bar(i, 195.0 + i as f64)).collect(); + study + .set_input("calculation_timeframe", InputValue::Timeframe(None)) + .unwrap(); + study + .set_input("calculation_symbol", InputValue::Symbol("OTHER".into())) + .unwrap(); + study.set_visible_range(5..10); + let source = StudyData { + request: study.data_requests()[0].clone(), + bars: &other, + clock: BarClock::new(Timeframe::Min1), + instrument: None, + timeframe: Timeframe::Min1, + }; + study.update_data(&chart, 0, &[source]); + assert_eq!(study.values().value(0, 9), Some(202.0)); + + // Back on the chart's bars it averages chart bars 5 to 9 again: 105 to 109. + study + .set_input("calculation_symbol", InputValue::Symbol(String::new())) + .unwrap(); + study.calculate(&chart); + assert_eq!(study.values().value(0, 9), Some(107.0)); + } + /// The visible mean uses exactly the supplied bars and changes with the viewport. A corrected /// visible bar moves it on every bar, and a bar streamed in past the range carries it. #[test] diff --git a/vendor/egui-charts/src/studies/builtin/volume.rs b/vendor/egui-charts/src/studies/builtin/volume.rs index 847f3df..2fd66fb 100644 --- a/vendor/egui-charts/src/studies/builtin/volume.rs +++ b/vendor/egui-charts/src/studies/builtin/volume.rs @@ -18,6 +18,7 @@ pub enum VolumeColorRule { /// Moving average formula for volume. #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum VolumeAverage { /// Arithmetic mean of a complete window. Simple, diff --git a/vendor/egui-charts/src/studies/builtin/volume_24h.rs b/vendor/egui-charts/src/studies/builtin/volume_24h.rs index 0b6adf6..fab6797 100644 --- a/vendor/egui-charts/src/studies/builtin/volume_24h.rs +++ b/vendor/egui-charts/src/studies/builtin/volume_24h.rs @@ -171,25 +171,11 @@ impl Volume24h { Self::CURRENCIES.get(self.target.checked_sub(1)?).copied() } - /// Whether two currency codes name the same currency: exact for a code that mixes cases - /// (`GBp`, pence), else regardless of case. - fn same_currency(a: &str, b: &str) -> bool { - let mixed = |code: &str| { - code.bytes().any(|c| c.is_ascii_lowercase()) - && code.bytes().any(|c| c.is_ascii_uppercase()) - }; - if mixed(a) || mixed(b) { - a == b - } else { - a.eq_ignore_ascii_case(b) - } - } - /// The exchange rates converting quote amounts into a target currency other than the quote /// currency. fn rate_request(&self) -> Option { let (from, to) = (self.currency.as_deref()?, self.target()?); - (self.quote_units && !Self::same_currency(from, to)) + (self.quote_units && !crate::model::same_currency(from, to)) .then(|| StudyDataRequest::exchange_rate(from, to)) } @@ -231,7 +217,7 @@ impl Volume24h { } Some(_) => "Quote amount unavailable".into(), })]], - ..StudyTable::default() + ..Default::default() }); } diff --git a/vendor/egui-charts/src/studies/builtin/volume_price_trend.rs b/vendor/egui-charts/src/studies/builtin/volume_price_trend.rs index b3a6c45..4129e28 100644 --- a/vendor/egui-charts/src/studies/builtin/volume_price_trend.rs +++ b/vendor/egui-charts/src/studies/builtin/volume_price_trend.rs @@ -116,8 +116,8 @@ impl Indicator for VolumePriceTrend { } } -/// Length of the NVI and PVI signal line, the published one-year EMA of the index. -const SIGNAL_LEN: f64 = 255.0; +/// Default length of the NVI and PVI signal line, the published one-year EMA of the index. +const DEFAULT_SIGNAL_LENGTH: usize = 255; /// Resume the volume-gated index and its first-value-seeded signal. fn volume_index( @@ -125,8 +125,10 @@ fn volume_index( values: &mut IndicatorValues, data: &[Bar], from: usize, + length: usize, counts: fn(f64, f64) -> bool, ) { + let alpha = 2.0 / (length as f64 + 1.0); stepper.run(data, from, values, |state, bar| { if !bar.close.is_finite() || !bar.volume.is_finite() { return IndicatorValue::None; @@ -135,7 +137,7 @@ fn volume_index( if counts(bar.volume, volume) && close != 0.0 { state.1 += state.1 * ((bar.close - close) / close); } - state.2 += (state.1 - state.2) * (2.0 / (SIGNAL_LEN + 1.0)); + state.2 += (state.1 - state.2) * alpha; } else { state.1 = 1000.0; state.2 = 1000.0; @@ -148,14 +150,16 @@ fn volume_index( /// Negative Volume Index (NVI) /// /// Starts at 1000 and moves by the close's percentage change only on bars whose volume fell. -/// Outputs `Multiple([index, signal])`: the signal line is the 255-bar EMA of the index, seeded -/// with the first index value so that it starts at bar 0 like the index. +/// Outputs `Multiple([index, signal])`: the signal line is the EMA of the index over the EMA +/// length, 255 by default, seeded with the first index value so that it starts at bar 0 like the +/// index. #[derive(Clone)] pub struct NegativeVolumeIndex { values: IndicatorValues, stepper: Stepper<(Option<[f64; 2]>, f64, f64)>, color: Color32, signal_color: Color32, + signal_length: usize, visible: bool, } @@ -167,6 +171,7 @@ impl NegativeVolumeIndex { stepper: Stepper::default(), color: palette::BLUE, signal_color: palette::WARM_ORANGE, + signal_length: DEFAULT_SIGNAL_LENGTH, visible: true, } } @@ -176,6 +181,12 @@ impl NegativeVolumeIndex { self.color = color; self } + + /// Set the signal EMA length in bars, clamped to at least one. + pub fn with_signal_length(mut self, length: usize) -> Self { + self.signal_length = length.max(1); + self + } } impl Default for NegativeVolumeIndex { @@ -191,6 +202,10 @@ impl Indicator for NegativeVolumeIndex { )) } + crate::studies::inputs::study_inputs!(self; + signal_length: length("EMA length", 1, usize::MAX) + ; {}); + fn name(&self) -> &str { "NVI" } @@ -209,6 +224,7 @@ impl Indicator for NegativeVolumeIndex { &mut self.values, data, from, + self.signal_length, |volume, prev| volume < prev, ); } @@ -262,14 +278,16 @@ impl Indicator for NegativeVolumeIndex { /// Positive Volume Index (PVI) /// /// Starts at 1000 and moves by the close's percentage change only on bars whose volume rose. -/// Outputs `Multiple([index, signal])`: the signal line is the 255-bar EMA of the index, seeded -/// with the first index value so that it starts at bar 0 like the index. +/// Outputs `Multiple([index, signal])`: the signal line is the EMA of the index over the EMA +/// length, 255 by default, seeded with the first index value so that it starts at bar 0 like the +/// index. #[derive(Clone)] pub struct PositiveVolumeIndex { values: IndicatorValues, stepper: Stepper<(Option<[f64; 2]>, f64, f64)>, color: Color32, signal_color: Color32, + signal_length: usize, visible: bool, } @@ -281,6 +299,7 @@ impl PositiveVolumeIndex { stepper: Stepper::default(), color: palette::BLUE, signal_color: palette::WARM_ORANGE, + signal_length: DEFAULT_SIGNAL_LENGTH, visible: true, } } @@ -290,6 +309,12 @@ impl PositiveVolumeIndex { self.color = color; self } + + /// Set the signal EMA length in bars, clamped to at least one. + pub fn with_signal_length(mut self, length: usize) -> Self { + self.signal_length = length.max(1); + self + } } impl Default for PositiveVolumeIndex { @@ -305,6 +330,10 @@ impl Indicator for PositiveVolumeIndex { )) } + crate::studies::inputs::study_inputs!(self; + signal_length: length("EMA length", 1, usize::MAX) + ; {}); + fn name(&self) -> &str { "PVI" } @@ -323,6 +352,7 @@ impl Indicator for PositiveVolumeIndex { &mut self.values, data, from, + self.signal_length, |volume, prev| volume > prev, ); } @@ -376,6 +406,7 @@ impl Indicator for PositiveVolumeIndex { #[cfg(test)] mod tests { use super::*; + use crate::studies::InputValue; use chrono::Utc; fn make_bar(close: f64, volume: f64) -> Bar { @@ -424,6 +455,14 @@ mod tests { /// trading year, seeded with its first value as the crate's EMA is. Expected values were /// computed independently in exact rational arithmetic. Hand check, NVI bar 1: the index /// rises 5% to 1050 and the signal is 1000 + (1050 - 1000) * 2 / 256 = 1000.390625. + /// + /// Second pass with an EMA length of 2 (weight 2 / 3), with a bar whose close is NaN + /// (no value, the state is kept), an equal-volume bar and a correction. Hand check, NVI + /// bar 1: the index is 1050 and the signal 1000 + 50 * 2 / 3 = 3100 / 3; the NaN bar + /// leaves both untouched, so bar 3 (volume up) gives 3100 / 3 + (1050 - 3100 / 3) * 2 / 3 + /// = 9400 / 9. PVI bar 3 multiplies 1000 by 108 / 105 = 7200 / 7, and its signal is + /// 1000 + (7200 / 7 - 1000) * 2 / 3 = 21400 / 21. Bar 5 (volume down) takes the NVI index to + /// 1050 * 99 / 110 = 945. #[test] fn nvi_pvi_match_published_definition() { // Volume down, up, unchanged with a zero close, down after a zero close, unchanged, up after @@ -491,5 +530,88 @@ mod tests { ); } } + + let closes = [ + Some(100.0), + Some(105.0), + None, + Some(108.0), + Some(110.0), + Some(99.0), + Some(120.0), + ]; + let volumes = [1000.0, 800.0, 700.0, 1200.0, 1200.0, 1000.0, 1500.0]; + let bars = |closes: &[Option]| -> Vec { + closes + .iter() + .zip(volumes) + .map(|(close, volume)| make_bar(close.unwrap_or(f64::NAN), volume)) + .collect() + }; + let nvi = [ + Some((1000.0, 1000.0)), + Some((1050.0, 3100.0 / 3.0)), + None, + Some((1050.0, 9400.0 / 9.0)), + Some((1050.0, 28300.0 / 27.0)), + Some((945.0, 79330.0 / 81.0)), + Some((945.0, 232420.0 / 243.0)), + ]; + let pvi = [ + Some((1000.0, 1000.0)), + Some((1000.0, 1000.0)), + None, + Some((7200.0 / 7.0, 21400.0 / 21.0)), + Some((7200.0 / 7.0, 64600.0 / 63.0)), + Some((7200.0 / 7.0, 194200.0 / 189.0)), + Some((96000.0 / 77.0, 7320200.0 / 6237.0)), + ]; + // Bar 6 corrected to a close of 90: the NVI keeps 945 and its signal, the PVI index is + // 7200 / 7 * 90 / 99 = 72000 / 77 and its signal 194200 / 189 + (72000 / 77 - 194200 / 189) + // * 2 / 3 = 860600 / 891. + let cases = [ + ( + Box::new(NegativeVolumeIndex::new()) as Box, + nvi, + [945.0, 232420.0 / 243.0], + ), + ( + Box::new(PositiveVolumeIndex::new()), + pvi, + [72000.0 / 77.0, 860600.0 / 891.0], + ), + ]; + let rows = |study: &dyn Indicator| study.values().to_rows(); + for (mut study, expected, corrected_last) in cases { + study + .set_input("signal_length", InputValue::Length(2)) + .unwrap(); + study.calculate(&bars(&closes)); + for (bar, (value, want)) in rows(&*study).iter().zip(&expected).enumerate() { + match (value, want) { + (IndicatorValue::None, None) => {} + (IndicatorValue::Multiple(lines), Some((index, signal))) => assert!( + (lines[0] - index).abs() < 1e-9 && (lines[1] - signal).abs() < 1e-9, + "{} bar {bar}: got {lines:?}, expected [{index}, {signal}]", + study.name() + ), + _ => panic!("{} bar {bar}: got {value:?}", study.name()), + } + } + + // Correcting the last bar resumes from the state kept before it. + let mut corrected = closes; + corrected[6] = Some(90.0); + study.update(&bars(&corrected), 6); + let IndicatorValue::Multiple(lines) = &rows(&*study)[6] else { + panic!("{} correction: got {:?}", study.name(), rows(&*study)[6]); + }; + assert!( + (lines[0] - corrected_last[0]).abs() < 1e-9 + && (lines[1] - corrected_last[1]).abs() < 1e-9, + "{} correction: got {lines:?}, expected {corrected_last:?}", + study.name() + ); + } } } diff --git a/vendor/egui-charts/src/studies/builtin/volume_profile.rs b/vendor/egui-charts/src/studies/builtin/volume_profile.rs index 0ec6741..eb3b2bf 100644 --- a/vendor/egui-charts/src/studies/builtin/volume_profile.rs +++ b/vendor/egui-charts/src/studies/builtin/volume_profile.rs @@ -40,6 +40,7 @@ use std::sync::Arc; /// What a volume profile was built from. #[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] pub struct ProfileInput { /// The chart bars the profile covers. pub bars: Range, diff --git a/vendor/egui-charts/src/studies/builtin/vwap.rs b/vendor/egui-charts/src/studies/builtin/vwap.rs index fb03755..a5ec7be 100644 --- a/vendor/egui-charts/src/studies/builtin/vwap.rs +++ b/vendor/egui-charts/src/studies/builtin/vwap.rs @@ -90,6 +90,12 @@ const VWAP_ANCHORS: [VwapAnchor; 11] = [ /// The most bands that the study inputs can hold. const MAX_BANDS: usize = 10; +/// The colours of successive band pairs: green, olive and dark teal. +pub(super) const BAND_COLORS: [Color32; 3] = [ + palette::GREEN, + Color32::from_rgb(128, 128, 0), + Color32::from_rgb(0, 137, 123), +]; /// The most event anchors that the study inputs can hold. const MAX_EVENTS: usize = 1000; @@ -183,6 +189,8 @@ pub struct VolumeWeightedAvgPrice { shared: Option, /// Whether no two consecutive bars shared a UTC date at the last update. daily: bool, + /// Whether the study has no values on intervals of a day or longer. + hide_daily: bool, timeframe: Option, /// One per line: the VWAP, then the upper and lower band of each multiplier. colors: Vec, @@ -217,6 +225,7 @@ impl VolumeWeightedAvgPrice { stepper: Stepper::default(), shared: None, daily: true, + hide_daily: false, timeframe: None, colors: vec![palette::BLUE], visible: true, @@ -274,14 +283,9 @@ impl VolumeWeightedAvgPrice { /// One colour per line, with green, olive and dark teal for successive band pairs. fn fit_colors(&mut self) { - let colors = [ - palette::GREEN, - Color32::from_rgb(128, 128, 0), - Color32::from_rgb(0, 137, 123), - ]; while self.colors.len() < self.line_count() { let band = (self.colors.len() - 1) / 2; - self.colors.push(colors[band.min(2)]); + self.colors.push(BAND_COLORS[band.min(2)]); } } @@ -330,6 +334,13 @@ impl Indicator for VolumeWeightedAvgPrice { fn inputs(&self) -> Vec { use crate::studies::{InputKind, InputValue, StudyInput}; let mut inputs = vec![ + StudyInput::new( + "hide_daily", + "Hide on daily and longer intervals", + InputValue::Toggle(self.hide_daily), + InputKind::Toggle, + ) + .with_default(InputValue::Toggle(false)), StudyInput::new( "anchor", "Anchor", @@ -415,7 +426,9 @@ impl Indicator for VolumeWeightedAvgPrice { /// local time takes its first occurrence. Events are applied sorted and deduplicated. /// `time_zone` and `day_start` count trading days while the chart passes no instrument; an /// instrument's time zone and session, given with - /// [`set_instrument`](Indicator::set_instrument), take their place. + /// [`set_instrument`](Indicator::set_instrument), take their place. `hide_daily` leaves every + /// line without values while the bars are a day or longer: by the chart interval, or without + /// one when no two consecutive bars share a UTC date. fn set_input( &mut self, id: &str, @@ -441,6 +454,7 @@ impl Indicator for VolumeWeightedAvgPrice { return Err(crate::studies::StudyError::invalid_input(id)); } match (id, value) { + ("hide_daily", InputValue::Toggle(value)) => self.hide_daily = value, ("anchor", InputValue::Choice(index)) => self.anchor = VWAP_ANCHORS[index], ("time_zone", InputValue::Text(name)) => { self.time_zone = TimezoneId::named(&name).ok_or_else(|| { @@ -545,10 +559,12 @@ impl Indicator for VolumeWeightedAvgPrice { events.dedup(); self.stepper .run(data, from, &mut self.values, |state, bar| { - // A bar with a non-finite price or volume has no value and adds nothing. - if ![bar.high, bar.low, bar.close, bar.volume] - .iter() - .all(|x| x.is_finite()) + // A bar with a non-finite price or volume has no value and adds nothing, and + // no bar has one while the study is hidden on this interval. + if (self.hide_daily && daily) + || ![bar.high, bar.low, bar.close, bar.volume] + .iter() + .all(|x| x.is_finite()) { return IndicatorValue::None; } @@ -1148,7 +1164,7 @@ mod tests { if interval_first { chart.set_timeframe(crate::model::Timeframe::Hour1); } - chart.add_indicator( + let id = chart.add_indicator( crate::studies::IndicatorFactory::new() .create("VWAP") .unwrap(), @@ -1165,6 +1181,20 @@ mod tests { chart.indicators().next().unwrap().1.values().value(0, 1), Some(14.0) ); + // Hidden on daily intervals, the VWAP and its band have no values on this one and + // return on the hourly one below. + chart + .indicator_mut(id) + .unwrap() + .set_input("hide_daily", InputValue::Toggle(true)) + .unwrap(); + shapes(&egui::Context::default(), &mut chart, 1.5, Vec::new()); + let values = chart.indicators().next().unwrap().1.values(); + assert_eq!(values.len(), 2); + assert!( + (0..3).all(|line| values.line(line).iter().all(|v| v.is_nan())), + "{values:?}" + ); chart.set_timeframe(crate::model::Timeframe::Hour1); chart.set_symbol("UTC"); chart.set_instrument(Some(Instrument::new("UTC"))); diff --git a/vendor/egui-charts/src/studies/builtin/vwap_auto_anchored.rs b/vendor/egui-charts/src/studies/builtin/vwap_auto_anchored.rs index 098a67c..695a0ba 100644 --- a/vendor/egui-charts/src/studies/builtin/vwap_auto_anchored.rs +++ b/vendor/egui-charts/src/studies/builtin/vwap_auto_anchored.rs @@ -11,6 +11,8 @@ //! # Calculation //! VWAP = Sum(Source * Volume) / Sum(Volume) from the anchor bar, Source = (High + Low + Close) / 3 //! by default; the source itself while the volume sum is zero. +//! Band = VWAP +/- k * multiplier * unit for k = 1, 2 and 3, where the unit is sigma, +//! sigma^2 = Sum(Volume * Source^2) / Sum(Volume) - VWAP^2, or one percent of the absolute VWAP. //! //! # Example //! ``` @@ -26,6 +28,7 @@ //! ``` use super::anchor_period::{AnchorPeriod, ExchangeDays}; +use super::vwap::BAND_COLORS; use crate::model::{Bar, Instrument, PriceSource, Timeframe}; use crate::studies::stepper::Stepper; use crate::studies::{Indicator, IndicatorValue, IndicatorValues}; @@ -61,7 +64,10 @@ pub enum AutoAnchor { Century, } -/// VWAP from an automatically found anchor bar to the latest bar. +/// VWAP from an automatically found anchor bar to the latest bar, with three pairs of bands +/// at one, two and three times a multiple of the volume-weighted standard deviation of the +/// source, or of one percent of the absolute VWAP. The first pair is drawn and filled between +/// its lines at 5% opacity; the second and third start hidden. /// /// Periods are counted in exchange trading days, as /// [`VolumeWeightedAvgPrice`](super::VolumeWeightedAvgPrice) counts them. The chart supplies @@ -73,6 +79,8 @@ pub struct VwapAutoAnchored { anchor: AutoAnchor, length: usize, source: PriceSource, + percentage_bands: bool, + band_multiplier: f64, interval: Timeframe, days: ExchangeDays, values: IndicatorValues, @@ -100,18 +108,66 @@ struct State { intraday: bool, period: Option<(i32, u32)>, start: usize, + sums: Sums, + candidates: std::collections::VecDeque, +} + +/// The volume-weighted sums of the bars from the anchor bar. +#[derive(Clone, Copy, Default)] +struct Sums { volume: f64, weighted: f64, - candidates: std::collections::VecDeque, + squared: f64, +} + +impl Sums { + /// Adds a bar and returns the VWAP, then the upper and lower band at one, two and three + /// band widths: `multiplier` deviations of the price, or percent of the absolute VWAP. + fn add( + &mut self, + price: f64, + volume: f64, + percentage: bool, + multiplier: f64, + ) -> IndicatorValue { + self.volume += volume; + self.weighted += price * volume; + self.squared += price * price * volume; + let (vwap, sigma) = if self.volume == 0.0 { + (price, 0.0) + } else { + let vwap = self.weighted / self.volume; + // Clamped: cancellation can leave a tiny negative variance. + let variance = self.squared / self.volume - vwap * vwap; + (vwap, variance.max(0.0).sqrt()) + }; + let width = multiplier + * if percentage { + vwap.abs() / 100.0 + } else { + sigma + }; + IndicatorValue::Multiple( + std::iter::once(vwap) + .chain( + [1.0, 2.0, 3.0] + .into_iter() + .flat_map(|k| [vwap + k * width, vwap - k * width]), + ) + .collect(), + ) + } } impl VwapAutoAnchored { - /// Anchor Auto, length 20, source hlc3. + /// Anchor Auto, length 20, source hlc3, standard deviation bands at a multiplier of 1. pub fn new() -> Self { Self { anchor: AutoAnchor::Auto, length: 20, source: PriceSource::HLC3, + percentage_bands: false, + band_multiplier: 1.0, interval: Timeframe::Min1, days: ExchangeDays::default(), values: IndicatorValues::new(), @@ -119,7 +175,9 @@ impl VwapAutoAnchored { intraday: false, shown_start: 0, shown_indices: Vec::new(), - colors: vec![Color32::from_rgb(30, 136, 229)], + colors: std::iter::once(Color32::from_rgb(30, 136, 229)) + .chain(BAND_COLORS.into_iter().flat_map(|color| [color, color])) + .collect(), visible: true, } } @@ -175,7 +233,9 @@ impl Indicator for VwapAutoAnchored { crate::studies::inputs::study_inputs!(self; anchor: choice("Anchor Period", [AutoAnchor::Auto, AutoAnchor::HighestHigh, AutoAnchor::LowestLow, AutoAnchor::HighestVolume, AutoAnchor::Session, AutoAnchor::Week, AutoAnchor::Month, AutoAnchor::Quarter, AutoAnchor::Year, AutoAnchor::Decade, AutoAnchor::Century]), length: length("Length", 1, usize::MAX), - source: choice("Source", PriceSource::all()) + source: choice("Source", PriceSource::all()), + percentage_bands: toggle("Percentage bands"), + band_multiplier: number("Bands multiplier", 0.0, f64::MAX) ; {}); fn name(&self) -> &str { @@ -193,6 +253,7 @@ impl Indicator for VwapAutoAnchored { fn update(&mut self, data: &[Bar], mut from: usize) { let period = self.period(); let price_source = self.source; + let (percentage, multiplier) = (self.percentage_bands, self.band_multiplier); let usable = |bar: &Bar| { price_source .compute(bar.open, bar.high, bar.low, bar.close) @@ -234,16 +295,9 @@ impl Indicator for VwapAutoAnchored { if key != state.period { state.period = key; state.start = source; - state.volume = 0.0; - state.weighted = 0.0; + state.sums = Sums::default(); } - state.volume += bar.volume; - state.weighted += price * bar.volume; - IndicatorValue::Single(if state.volume == 0.0 { - price - } else { - state.weighted / state.volume - }) + state.sums.add(price, bar.volume, percentage, multiplier) }); if period.is_none() || self.intraday == self.stepper.state().intraday { break; @@ -260,23 +314,14 @@ impl Indicator for VwapAutoAnchored { } } else if start < self.shown_start { // Withdrawing a new anchor period restores the previously visible line. - let (mut volume, mut weighted) = (0.0, 0.0); + let mut sums = Sums::default(); for (i, bar) in data.iter().enumerate().take(self.shown_start).skip(start) { if !usable(bar) { continue; } let price = price_source.compute(bar.open, bar.high, bar.low, bar.close); - volume += bar.volume; - weighted += price * bar.volume; - self.values.set_value( - 0, - i, - if volume == 0.0 { - price - } else { - weighted / volume - }, - ); + self.values + .set(i, sums.add(price, bar.volume, percentage, multiplier)); } } self.shown_start = start; @@ -296,18 +341,11 @@ impl Indicator for VwapAutoAnchored { let start = (0..candidates.len()) .max_by(|&a, &b| key(&candidates[a]).total_cmp(&key(&candidates[b]))) .unwrap_or(candidates.len()); - let (mut volume, mut weighted) = (0.0, 0.0); + let mut sums = Sums::default(); for point in candidates.iter().skip(start) { - volume += point.volume; - weighted += point.price * point.volume; - self.values.set_value( - 0, + self.values.set( point.source, - if volume == 0.0 { - point.price - } else { - weighted / volume - }, + sums.add(point.price, point.volume, percentage, multiplier), ); self.shown_indices.push(point.source); } @@ -334,12 +372,41 @@ impl Indicator for VwapAutoAnchored { self.colors.clone() } + /// Sets the colors line by line; lines without a color keep theirs. fn set_colors(&mut self, colors: Vec) { - if let Some(color) = colors.first() { - self.colors = vec![*color]; + for (line, color) in self.colors.iter_mut().zip(colors) { + *line = color; } } + /// The second and third band pairs start hidden. + fn plot_style(&self, line: usize) -> crate::studies::PlotStyle { + crate::studies::PlotStyle { + color: self.colors.get(line).copied().unwrap_or(Color32::WHITE), + width: self.line_style(line).width, + pattern: crate::model::LineStyle::Solid, + plot_type: crate::studies::PlotType::Line, + visible: line < 3, + } + } + + /// The lines drawn by default, the VWAP and the first band pair, have tags on the price + /// scale, as a VWAP with one band has. The second and third pairs start without, since seven + /// tags would crowd the scale. + fn plot_tagged(&self, line: usize) -> bool { + line < 3 + } + + /// One band between the first upper and lower line. + fn fills(&self) -> Vec { + vec![crate::studies::StudyFill { + first: crate::studies::FillBoundary::Plot(1), + second: crate::studies::FillBoundary::Plot(2), + color: self.colors[1].gamma_multiply_u8(13), + inverted_color: None, + }] + } + fn is_overlay(&self) -> bool { true } @@ -356,7 +423,18 @@ impl Indicator for VwapAutoAnchored { Box::new(self.clone()) } + fn line_count(&self) -> usize { + 7 + } + fn line_names(&self) -> Vec { - vec!["VWAP".to_string()] + let unit = if self.percentage_bands { "%" } else { "σ" }; + std::iter::once("VWAP".to_string()) + .chain([1.0, 2.0, 3.0].into_iter().flat_map(|k| { + // Single precision reads short: three times 0.1 as 0.3. + let k = (k * self.band_multiplier) as f32; + [format!("Upper {k}{unit}"), format!("Lower {k}{unit}")] + })) + .collect() } } diff --git a/vendor/egui-charts/src/studies/builtin/wedge.rs b/vendor/egui-charts/src/studies/builtin/wedge.rs index 88d1a16..3be4545 100644 --- a/vendor/egui-charts/src/studies/builtin/wedge.rs +++ b/vendor/egui-charts/src/studies/builtin/wedge.rs @@ -129,7 +129,7 @@ impl Wedge { .into(), columns: ["Wedge", "Anchors", "Confirmed"].map(String::from).to_vec(), rows: Vec::new(), - ..StudyTable::default() + ..Default::default() }, colors: if RISING { [palette::GREEN, palette::GREEN, palette::RED] diff --git a/vendor/egui-charts/src/studies/builtin/williams_r.rs b/vendor/egui-charts/src/studies/builtin/williams_r.rs index f7e41f9..6ba5957 100644 --- a/vendor/egui-charts/src/studies/builtin/williams_r.rs +++ b/vendor/egui-charts/src/studies/builtin/williams_r.rs @@ -8,7 +8,8 @@ //! - Readings from -100 to -80: Oversold //! //! The pane draws both levels, dashed and muted, with the band between them filled in the study's -//! colour at a tenth of full opacity. +//! colour at a tenth of full opacity. The pane fits its values and visible levels, so a source from +//! another study that reads outside -100 to 0 stays in view. //! //! # Calculation //! %R = (Highest High - Source) / (Highest High - Lowest Low) * -100 @@ -198,8 +199,7 @@ impl Indicator for WilliamsR { fn pane(&self) -> crate::studies::StudyPane { crate::studies::StudyPane { height: None, - // A fitted pane's margin around -100 to 0, so a reading at either end stays whole. - range: Some((-110.0, 10.0)), + range: None, levels: vec![ (-20.0, palette::MUTED, "Overbought"), (-80.0, palette::MUTED, "Oversold"), @@ -290,7 +290,6 @@ mod tests { (-80.0, palette::MUTED, "Oversold"), ] ); - assert_eq!(study.pane().range, Some((-110.0, 10.0))); for level in &settings.levels { assert_eq!( (level.pattern, level.width, level.visible), diff --git a/vendor/egui-charts/src/studies/builtin/zero_trend_vol.rs b/vendor/egui-charts/src/studies/builtin/zero_trend_vol.rs index bac896b..d3b8c94 100644 --- a/vendor/egui-charts/src/studies/builtin/zero_trend_vol.rs +++ b/vendor/egui-charts/src/studies/builtin/zero_trend_vol.rs @@ -7,12 +7,16 @@ use egui::Color32; /// Zero-mean close-to-close volatility, without subtracting the mean log return. /// -/// `sqrt(mean(ln(close / previous_close)^2)) * sqrt(252) * 100`. -/// Annualisation assumes daily bars and 252 trading days per year (see #672). +/// `sqrt(mean(ln(close / previous_close)^2)) * sqrt(trading_days) * 100`. +/// Annualisation takes the bars per year, 252 by default (daily bars), from the trading days +/// input. /// A full `period` of returns from positive closes is required before a value exists. #[derive(Clone)] pub struct ZeroTrendVol { period: usize, + /// Trading days per year the result is annualized over, one bar per day (252 for stocks, 365 + /// for crypto); bars shorter than a day need the bars in a year instead + trading_days: f64, values: IndicatorValues, colors: Vec, visible: bool, @@ -23,11 +27,19 @@ impl ZeroTrendVol { pub fn new(period: usize) -> Self { Self { period: period.max(1), + trading_days: 252.0, values: IndicatorValues::new(), colors: vec![palette::LIGHT_BLUE], visible: true, } } + + /// Set the bars per year the volatility is annualized over, clamped into 0 to + /// `f64::MAX`, NaN to 0. + pub fn with_trading_days(mut self, days: f64) -> Self { + self.trading_days = super::clamp_param(days, 0.0, f64::MAX); + self + } } impl Default for ZeroTrendVol { @@ -59,7 +71,7 @@ impl ZeroTrendVol { return IndicatorValue::None; } let mean_squared = window.iter().map(|r| r * r).sum::() / self.period as f64; - IndicatorValue::Single(mean_squared.sqrt() * 252.0_f64.sqrt() * 100.0) + IndicatorValue::Single(mean_squared.sqrt() * self.trading_days.sqrt() * 100.0) }) .collect() } @@ -73,7 +85,8 @@ impl Indicator for ZeroTrendVol { } crate::studies::inputs::study_inputs!(self; - period: length("Period", 1, usize::MAX) + period: length("Period", 1, usize::MAX), + trading_days: number("Trading days per year", 0.0, f64::MAX) ; {}); fn value_format(&self) -> crate::scales::StudyFormat { @@ -85,7 +98,7 @@ impl Indicator for ZeroTrendVol { } fn desc(&self) -> &str { - "Zero-Trend Close-to-Close Volatility - Annualised percentage assuming daily bars" + "Zero-Trend Close-to-Close Volatility - Annualised percentage" } fn calculate(&mut self, data: &[Bar]) { @@ -142,3 +155,40 @@ impl Indicator for ZeroTrendVol { vec![format!("Zero-Trend Vol({})", self.period)] } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::studies::test_support::make_bar; + + /// Closes 100, 110, a bar without a close, 110 and 99 (a tie in the middle of the window), then + /// the second close corrected to 105. Expected values come from the definition over the three + /// returns of the usable bars, evaluated independently, annualized over 252 and 365 bars. + #[test] + fn zero_trend_annualizes_over_the_bars_per_year_across_gaps_ties_and_corrections() { + let bars = |second: f64| -> Vec { + [100.0, second, f64::NAN, 110.0, 99.0] + .map(make_bar) + .to_vec() + }; + for (days, as_saved, corrected) in [ + (252.0, 130.21247886655595, 114.63926638193587), + (365.0, 156.7107425738662, 137.96837844741043), + ] { + let mut study = ZeroTrendVol::new(3).with_trading_days(days); + let mut data = bars(110.0); + study.calculate(&data); + assert_eq!( + study.values().value(0, 2), + None, + "{days}: bar without a close" + ); + let got = study.values().value(0, 4).unwrap(); + assert!((got - as_saved).abs() < 1e-9, "{days}: {got}"); + data = bars(105.0); + study.update(&data, 1); + let got = study.values().value(0, 4).unwrap(); + assert!((got - corrected).abs() < 1e-9, "{days} corrected: {got}"); + } + } +} diff --git a/vendor/egui-charts/src/studies/builtin/zigzag.rs b/vendor/egui-charts/src/studies/builtin/zigzag.rs index e4deb93..ba67751 100644 --- a/vendor/egui-charts/src/studies/builtin/zigzag.rs +++ b/vendor/egui-charts/src/studies/builtin/zigzag.rs @@ -7,6 +7,7 @@ use egui::Color32; /// ZigZag mode - what price to use #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +#[non_exhaustive] pub enum ZigZagMode { /// Use high/low for zigzag points #[default] @@ -30,6 +31,7 @@ pub enum ZigZagChange { /// One swing extreme in source-bar order. The last pivot is provisional and can move. #[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] pub struct ZigZagPivot { /// Index in the bars passed to [`Indicator::calculate`], including skipped bars. pub bar_index: usize, diff --git a/vendor/egui-charts/src/studies/chart_state.rs b/vendor/egui-charts/src/studies/chart_state.rs index 170cbb4..9de778a 100644 --- a/vendor/egui-charts/src/studies/chart_state.rs +++ b/vendor/egui-charts/src/studies/chart_state.rs @@ -13,13 +13,13 @@ use std::sync::Arc; /// The chart maintains a stack of these snapshots so the user can press /// "zoom out" to return to a previous view. #[derive(Debug, Clone, Copy)] -pub struct ZoomState { +struct ZoomState { /// Pixels per bar at the time of the snapshot. - pub bar_spacing: f32, + bar_spacing: f32, /// Right offset in bars from the chart edge. - pub right_offset: f64, + right_offset: f64, /// Manual price range in prices, or `None` when auto-scaled. - pub price_range: Option<(f64, f64)>, + price_range: Option<(f64, f64)>, } /// Backend chart state -- owns bar data, time-scale coordinate system, @@ -374,16 +374,20 @@ impl ChartState { .len() .checked_add_signed(study.plot_offset(index)) .unwrap_or(0); - (study_start..study_end.min(available_end)) + let mut values = (study_start..study_end.min(available_end)) .filter_map(move |bar| study.plot_value(index, bar)) - .chain(std::iter::once(0.0).filter(move |_| { - matches!( - study.plot_style(index).plot_type, - crate::studies::PlotType::Histogram - | crate::studies::PlotType::Columns - | crate::studies::PlotType::Area - ) - })) + .filter(|value| value.is_finite()) + .peekable(); + // Columns and areas reach down to zero beside a value, never in a view + // without one. + let zero = values.peek().is_some() + && matches!( + study.plot_style(index).plot_type, + crate::studies::PlotType::Histogram + | crate::studies::PlotType::Columns + | crate::studies::PlotType::Area + ); + values.chain(zero.then_some(0.0)) }) .chain( study @@ -428,7 +432,7 @@ impl ChartState { }); let main = main_visible .then(|| { - let range = main_range.or_else(|| { + let range = |transform: PriceTransform| { visible .iter() .flat_map(|bar| [bar.low, bar.high]) @@ -444,7 +448,11 @@ impl ChartState { (min.min(value), max.max(value)) })) }) - }); + }; + // Without a positive value a logarithmic scale fits the prices as they are. + let range = main_range + .or_else(|| range(transform)) + .or_else(|| range(PriceTransform::default())); match autoscale { Some(provider) => provider.info(visible, range), None => range.map(Into::into), @@ -452,17 +460,33 @@ impl ChartState { }) .flatten(); let margins = main.map_or_else(Default::default, |info| info.margins); + let mut raw = (f64::INFINITY, f64::NEG_INFINITY); let (min, max) = main .into_iter() .flat_map(|info| [info.price_range.0, info.price_range.1]) .chain(study_values) .chain(prices) + .inspect(|value| { + if value.is_finite() { + raw = (raw.0.min(*value), raw.1.max(*value)); + } + }) .map(|value| transform.to_scale(value)) .chain(series_values) .filter(|value| value.is_finite()) .fold((f64::INFINITY, f64::NEG_INFINITY), |(min, max), value| { (min.min(value), max.max(value)) }); + // No positive value in view: this frame shows the prices as they are. With no value in + // view at all, a scale showing prices keeps showing them, as the other scales do. + let (transform, min, max) = if transform.mode == PriceScaleMode::Logarithmic + && !min.is_finite() + && (raw.0.is_finite() || self.price_scale.transform().mode == PriceScaleMode::Normal) + { + (PriceTransform::default(), raw.0, raw.1) + } else { + (transform, min, max) + }; self.price_scale.rebase(transform); self.price_scale.autoscale(min, max); ( diff --git a/vendor/egui-charts/src/studies/custom.rs b/vendor/egui-charts/src/studies/custom.rs index 497b28e..6290dbe 100644 --- a/vendor/egui-charts/src/studies/custom.rs +++ b/vendor/egui-charts/src/studies/custom.rs @@ -73,6 +73,14 @@ pub struct CustomIndicator { plot_color: Option, } +impl std::fmt::Debug for CustomIndicator { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CustomIndicator") + .field("name", &self.name) + .finish_non_exhaustive() + } +} + impl CustomIndicator { /// Create a new custom indicator. /// diff --git a/vendor/egui-charts/src/studies/factory/builtin_properties.rs b/vendor/egui-charts/src/studies/factory/builtin_properties.rs index 94af643..35612c4 100644 --- a/vendor/egui-charts/src/studies/factory/builtin_properties.rs +++ b/vendor/egui-charts/src/studies/factory/builtin_properties.rs @@ -19,7 +19,7 @@ fn builtins_with(l: impl Fn(usize) -> usize, x: impl Fn(f64) -> f64) -> Vec usize, x: impl Fn(f64) -> f64) -> Vec usize, x: impl Fn(f64) -> f64) -> Vec usize, x: impl Fn(f64) -> f64) -> Vec usize, x: impl Fn(f64) -> f64) -> Vec usize, x: impl Fn(f64) -> f64) -> Vec = vec![[0; 9], [1; 9], [usize::MAX; 9]]; - for k in 0..9 { - let mut huge = [1; 9]; + let mut lengths: Vec<[usize; 12]> = vec![[0; 12], [1; 12], [usize::MAX; 12]]; + for k in 0..12 { + let mut huge = [1; 12]; huge[k] = usize::MAX; - let mut longer = [20; 9]; + let mut longer = [20; 12]; longer[k] = 50; lengths.extend([huge, longer]); } diff --git a/vendor/egui-charts/src/studies/factory/mod.rs b/vendor/egui-charts/src/studies/factory/mod.rs index 100019a..3dd3dd7 100644 --- a/vendor/egui-charts/src/studies/factory/mod.rs +++ b/vendor/egui-charts/src/studies/factory/mod.rs @@ -66,9 +66,9 @@ macro_rules! register_builtins { /// or source range. Additional indicators can be registered at runtime with /// [`register`](Self::register). /// -/// [`create`](Self::create) and [`has`](Self::has) also resolve the names of seven exported +/// [`create`](Self::create) and [`has`](Self::has) also resolve the names of six exported /// studies the catalogue leaves out, so that a template, a copied study or a saved layout of -/// one is recreated: `CVD`, `C2C Vol`, `HL2`, `HLC3`, `Price Channel`, `Ehlers Fisher` and +/// one is recreated: `CVD`, `HL2`, `HLC3`, `Price Channel`, `Ehlers Fisher` and /// `MA Combination`, which creates [`MACombination::ribbon`] for its inputs to reshape. They have /// no category and are not in [`list`](Self::list) or [`count`](Self::count). pub struct IndicatorFactory { @@ -79,6 +79,14 @@ pub struct IndicatorFactory { saved_study_resolver: Option Option> + Send + Sync>>, } +impl std::fmt::Debug for IndicatorFactory { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("IndicatorFactory") + .field("constructors", &self.constructors.keys()) + .finish_non_exhaustive() + } +} + impl IndicatorFactory { /// The category of every indicator added with [`register`](Self::register). pub const CUSTOM: &'static str = "Custom"; @@ -115,12 +123,11 @@ impl IndicatorFactory { /// listed study of the same name would replace them. fn register_builtin(&mut self) { // Exported studies outside the catalogue, resolved by name so that saved copies load. - register_builtins!(@help self, "struct", CVD, CloseToCloseVol, HL2, HLC3, PriceChannel, EhlersFisher, MACombination, OrderFlowStudy, ChartPatterns, OptionsVolumeProfile); + register_builtins!(@help self, "struct", CVD, HL2, HLC3, PriceChannel, EhlersFisher, MACombination, OrderFlowStudy, ChartPatterns, OptionsVolumeProfile); #[cfg(feature = "drawings")] register_builtins!(@help self, "struct", AutoDrawing); - let unlisted: [fn() -> Box; 7] = [ + let unlisted: [fn() -> Box; 6] = [ || Box::new(CVD::default()), - || Box::new(CloseToCloseVol::default()), || Box::new(HL2::default()), || Box::new(HLC3::default()), || Box::new(PriceChannel::default()), @@ -240,6 +247,7 @@ impl IndicatorFactory { DonchianChannels, StandardDeviation, HistoricalVolatility, + CloseToCloseVol, ChaikinVolatility, ChandelierExit, AccelerationBands, diff --git a/vendor/egui-charts/src/studies/indicator_trait.rs b/vendor/egui-charts/src/studies/indicator_trait.rs index 6ee32e8..faadea8 100644 --- a/vendor/egui-charts/src/studies/indicator_trait.rs +++ b/vendor/egui-charts/src/studies/indicator_trait.rs @@ -69,6 +69,7 @@ pub struct IndicatorFill { /// Width, optional direction colours and optional bottom fill of an overlay line. #[derive(Clone, Copy, Debug)] +#[non_exhaustive] pub struct IndicatorLineStyle { /// Stroke width in logical pixels. pub width: f32, @@ -93,6 +94,7 @@ impl Default for IndicatorLineStyle { /// Default layout and reference levels supplied by a study for its separate pane. #[derive(Clone, Debug, Default)] +#[non_exhaustive] pub struct StudyPane { /// Preferred initial height in logical pixels; `None` shares the available space. pub height: Option, @@ -437,7 +439,7 @@ pub trait Indicator: Send { let _ = timeframe; } - /// Source bar calendar, including the chart's selected timezone and session anchor. + /// Source bar calendar, including the zone that dates the chart's bars and its session anchor. /// Returns whether cached values must be recalculated. Direct callers default to UTC. fn set_bar_clock(&mut self, clock: &crate::model::BarClock) -> bool { let _ = clock; diff --git a/vendor/egui-charts/src/studies/inputs.rs b/vendor/egui-charts/src/studies/inputs.rs index 3285362..4c32811 100644 --- a/vendor/egui-charts/src/studies/inputs.rs +++ b/vendor/egui-charts/src/studies/inputs.rs @@ -30,6 +30,7 @@ pub enum InputKind { /// An editable input, with a stable study-local id and its current value. #[derive(Clone, Debug)] +#[non_exhaustive] pub struct StudyInput { /// Id passed to [`Indicator::set_input`](super::Indicator::set_input). pub id: String, diff --git a/vendor/egui-charts/src/studies/metric.rs b/vendor/egui-charts/src/studies/metric.rs index e376d11..22814e9 100644 --- a/vendor/egui-charts/src/studies/metric.rs +++ b/vendor/egui-charts/src/studies/metric.rs @@ -14,7 +14,7 @@ use egui::Color32; /// Connected charts request its history and live updates through the datafeed. Hosts /// supplying study data directly convert [`crate::data::MetricPoint`] into [`Bar`] /// and pass them to `Chart::set_study_data` with this study's request. -#[derive(Clone)] +#[derive(Debug, Clone)] pub struct MetricStudy { metric: MetricSeries, values: IndicatorValues, diff --git a/vendor/egui-charts/src/studies/mod.rs b/vendor/egui-charts/src/studies/mod.rs index 6354997..faf55d1 100644 --- a/vendor/egui-charts/src/studies/mod.rs +++ b/vendor/egui-charts/src/studies/mod.rs @@ -30,6 +30,8 @@ #[cfg(feature = "studies")] #[cfg_attr(docsrs, doc(cfg(feature = "studies")))] +// Debug for these types remains follow-up work from #1315. +#[allow(missing_debug_implementations)] mod builtin; mod custom; mod error; @@ -59,7 +61,7 @@ pub use settings::{ ConfiguredStudy, FillStyle, GradientStyle, LevelStyle, PlotStyle, PlotType, PlotVariant, StudyIntervalRange, StudySettings, StudySettingsSnapshot, }; -pub use table::{StudyCell, StudyTable, StudyTablePosition}; +pub use table::{StudyCell, StudyTable, StudyTablePosition, TablePosition, TableTextSize}; mod values; pub use values::IndicatorValues; #[cfg(all(test, feature = "studies"))] @@ -82,7 +84,7 @@ pub use indicator_trait::{ }; mod chart_state; -pub use chart_state::{ChartState, ZoomState}; +pub use chart_state::ChartState; #[cfg(feature = "studies")] mod template; @@ -119,6 +121,14 @@ pub struct IndicatorRegistry { indicators: Vec>, } +impl std::fmt::Debug for IndicatorRegistry { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("IndicatorRegistry") + .field("indicators", &self.indicators.len()) + .finish_non_exhaustive() + } +} + impl IndicatorRegistry { /// Create an empty registry with no indicators. pub fn new() -> Self { diff --git a/vendor/egui-charts/src/studies/plots.rs b/vendor/egui-charts/src/studies/plots.rs index c80884e..ff862f0 100644 --- a/vendor/egui-charts/src/studies/plots.rs +++ b/vendor/egui-charts/src/studies/plots.rs @@ -4,6 +4,7 @@ use egui::Color32; /// One boundary of a study band, in the study's value scale. #[derive(Clone, Copy, Debug)] +#[non_exhaustive] pub enum FillBoundary { /// A zero-based output line, including its offset. Its visibility does not hide the fill. Plot(usize), diff --git a/vendor/egui-charts/src/studies/reference.rs b/vendor/egui-charts/src/studies/reference.rs index 56ac0db..3940b72 100644 --- a/vendor/egui-charts/src/studies/reference.rs +++ b/vendor/egui-charts/src/studies/reference.rs @@ -30,7 +30,9 @@ //! Chop Zone. //! - The conventional floor-trader pivot points with Tom DeMark's and Nick Stott's Camarilla levels, //! from the previous period of UTC dates; the time-weighted mean of ohlc4 and Berkowitz, Logue and -//! Noser's volume-weighted mean of hlc3 since an anchor bar. +//! Noser's volume-weighted mean of hlc3 since an anchor bar, with bands at one, two and three +//! volume-weighted population standard deviations of hlc3 since that bar, or multiples of a +//! percentage of the mean. //! - Time-study rows run on hand-built series in calendar time: 24-hour volume over the bars opening //! in the last 24 hours; relative volume at time as the cumulative or single-bar volume over its //! mean at the same offset into the previous periods (the last earlier bar of a period at that @@ -1128,6 +1130,13 @@ fn staple_studies_match_published_definitions() { let mut monthly = PivotPoints::new().with_method(PivotMethod::Woodie); monthly.set_timeframe(crate::model::Timeframe::Day1); let auto = |anchor| Box::new(VwapAutoAnchored::new().with_anchor(anchor)); + let mut auto_percent = VwapAutoAnchored::new(); + for (id, value) in [ + ("percentage_bands", crate::studies::InputValue::Toggle(true)), + ("band_multiplier", crate::studies::InputValue::Number(1.5)), + ] { + auto_percent.set_input(id, value).unwrap(); + } studies.extend([ ( "Pivots-Woodie-auto-daily", @@ -1162,6 +1171,8 @@ fn staple_studies_match_published_definitions() { ("AutoVWAP-HH", auto(AutoAnchor::HighestHigh), bars.clone()), ("AutoVWAP-LL", auto(AutoAnchor::LowestLow), bars.clone()), ("AutoVWAP-HV", auto(AutoAnchor::HighestVolume), bars.clone()), + // Bands at 1.5, 3 and 4.5 percent of the VWAP. + ("AutoVWAP-pct", Box::new(auto_percent), bars.clone()), ]); let available = |name: &str| match name { "RVOL-chicago" | "Sessions-default" => cfg!(feature = "timezones"), diff --git a/vendor/egui-charts/src/studies/reference/expected.txt b/vendor/egui-charts/src/studies/reference/expected.txt index 8e404b2..4efd7d1 100644 --- a/vendor/egui-charts/src/studies/reference/expected.txt +++ b/vendor/egui-charts/src/studies/reference/expected.txt @@ -293,9 +293,27 @@ Pivots-DM-monthly-back2 9 - - - - - - - - - - - - - - - - - - - - - - - - - - - Pivots-DM-monthly-back2 10 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TWAP 0 100.1875 100.1875 100.375 100.640625 100.8 100.75 100.741071429 100.7578125 100.756944444 100.725 100.744318182 100.8125 100.899038462 100.995535714 101.095833333 101.1953125 101.352941176 101.5 101.621710526 101.7125 101.764880952 101.8125 101.891304348 101.9609375 102.045 102.161057692 102.266203704 102.370535714 102.474137931 102.570833333 102.659274194 102.744140625 102.821969697 102.908088235 103.0125 103.138888889 103.270270270 103.398026316 103.530448718 103.6859375 103.846036585 103.994047619 104.139534884 104.269886364 104.397222222 104.538043478 104.686170213 104.841145833 105 105.1575 105.318627451 105.467548077 105.595518868 105.734953704 105.873863636 105.979910714 106.078947368 106.167025862 106.244703390 106.336458333 106.448770492 106.567540323 106.676587302 106.776367188 106.878846154 107.008522727 107.146455224 107.294117647 107.442028986 107.594642857 107.755281690 107.926215278 108.107020548 108.286317568 108.463333333 108.658717105 108.835227273 108.994391026 109.139240506 109.27734375 109.406635802 109.522103659 109.626506024 109.719494048 109.807352941 109.872093023 109.931034483 109.988636364 110.042134831 110.097222222 110.141483516 110.185461957 110.235887097 110.291223404 110.343421053 110.405598958 110.468427835 110.53125 110.585227273 110.635 110.675123762 110.701593137 110.724514563 110.748197115 110.777380952 110.817216981 110.854556075 115.25 115.0625 114.708333333 114.59375 114.525 114.479166667 114.446428571 114.421875 114.451388889 114.4 114.306818182 114.197916667 114.067307692 113.973214286 113.883333333 113.75390625 113.606617647 113.479166667 113.444078947 113.390625 113.327380952 113.267045455 113.209239130 113.106770833 112.9625 112.793269231 112.590277778 112.370535714 112.183189655 111.99375 111.822580645 111.64453125 111.492424242 111.365808824 111.257142857 111.171875 111.065878378 110.958881579 110.844551282 110.71875 110.605182927 110.501488095 110.406976744 AutoVWAP 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 115.333333333 114.839566929 114.558507156 114.460200115 114.409405055 114.378381534 114.357466358 114.342411252 114.367278348 114.333490836 114.148241206 114.008940445 113.851543860 113.715993056 113.687877416 113.641882324 113.544053694 113.476402247 113.425889492 113.408075670 113.390845335 113.341343302 113.196741379 112.959384465 112.760264215 112.473064803 112.191714143 111.864743280 111.742044705 111.695449939 111.542580086 111.492784022 111.320975776 111.275015173 111.181695624 111.079384165 111.029879798 110.919835330 110.748822371 110.520062261 110.333491274 110.168460162 110.104835045 +AutoVWAP 1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 115.333333333 115.049864672 114.990240746 114.844469400 114.755926332 114.695699002 114.651633250 114.617734217 114.651347295 114.643318075 114.626962887 114.605101149 114.590543348 114.486098504 114.470659516 114.472336552 114.485261063 114.481572072 114.412929658 114.396766072 114.385587446 114.348479479 114.260393344 114.230419399 114.252836705 114.274582799 114.316166072 114.328481814 114.296310372 114.284569889 114.237241937 114.223930857 114.144853390 114.115657464 114.043265412 113.941602142 113.909527841 113.834846154 113.734697231 113.618231518 113.490182160 113.363557926 113.309548073 +AutoVWAP 2 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 115.333333333 114.629269187 114.126773566 114.075930830 114.062883779 114.061064066 114.063299466 114.067088287 114.083209401 114.023663597 113.669519525 113.412779741 113.112544371 112.945887607 112.905095317 112.811428095 112.602846325 112.471232423 112.438849327 112.419385268 112.396103224 112.334207124 112.133089413 111.688349532 111.267691724 110.671546807 110.067262214 109.401004745 109.187779038 109.106329988 108.847918235 108.761637187 108.497098162 108.434372882 108.320125836 108.217166187 108.150231756 108.004824506 107.762947511 107.421893003 107.176800387 106.973362397 106.900122016 +AutoVWAP 3 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 115.333333333 115.260162414 115.421974336 115.228738685 115.102447609 115.013016470 114.945800142 114.893057183 114.935416241 114.953145314 115.105684567 115.201261853 115.329542836 115.256203953 115.253441615 115.302790781 115.426468432 115.486741896 115.399969823 115.385456474 115.380329557 115.355615657 115.324045310 115.501454333 115.745409196 116.076100795 116.440618002 116.792220348 116.850576039 116.873689839 116.931903789 116.955077692 116.968731004 116.956299755 116.904835200 116.803820120 116.789175884 116.749856979 116.720572090 116.716400776 116.646873047 116.558655691 116.514261102 +AutoVWAP 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 115.333333333 114.418971444 113.695039975 113.691661544 113.716362502 113.743746598 113.769132574 113.791765322 113.799140454 113.713836358 113.190797845 112.816619037 112.373544883 112.175782159 112.122313218 111.980973866 111.661638955 111.466062598 111.451809162 111.430694866 111.401361113 111.327070947 111.069437448 110.417314598 109.775119234 108.870028811 107.942810284 106.937266211 106.633513371 106.517210038 106.153256384 106.030490352 105.673220547 105.593730591 105.458556048 105.354948209 105.270583713 105.089813681 104.777072652 104.323723745 104.020109501 103.778264632 103.695408988 +AutoVWAP 5 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 115.333333333 115.470460157 115.853707926 115.613007970 115.448968886 115.330333939 115.239967035 115.168380148 115.219485188 115.262972553 115.584406248 115.797422556 116.068542324 116.026309401 116.036223715 116.133245010 116.367675802 116.491911721 116.387009988 116.374146876 116.375071668 116.362751834 116.387697275 116.772489267 117.237981686 117.877618791 118.565069931 119.255958882 119.404841706 119.462809789 119.626565640 119.686224528 119.792608618 119.796942046 119.766404987 119.666038098 119.668823926 119.664867803 119.706446950 119.814570034 119.803563933 119.753753456 119.718974130 +AutoVWAP 6 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 115.333333333 114.208673701 113.263306385 113.307392259 113.369841225 113.426429130 113.474965682 113.516442357 113.515071508 113.404009119 112.712076164 112.220458334 111.634545395 111.405676710 111.339531118 111.150519637 110.720431586 110.460892774 110.464768997 110.442004464 110.406619002 110.319934769 110.005785482 109.146279664 108.282546743 107.068510815 105.818358355 104.473527677 104.079247704 103.928090088 103.458594533 103.299343517 102.849342933 102.753088300 102.596986261 102.492730232 102.390935670 102.174802857 101.791197792 101.225554487 100.863418614 100.583166867 100.490695960 AutoVWAP-HH 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 110.5 110.010116236 109.467126291 108.940091283 108.418140821 108.287719422 108.236860147 108.084031187 108.030180623 107.899209077 107.878926953 107.864400288 107.898075821 107.871291103 107.815055333 107.695715522 107.506423571 107.389979683 107.300272522 107.271556530 +AutoVWAP-HH 1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 110.5 110.620336362 110.370380337 110.210549202 109.960556485 109.828156389 109.781604128 109.631620883 109.588422867 109.425714505 109.385637200 109.319626024 109.292561359 109.253293513 109.168751461 109.048027599 108.914724752 108.787613957 108.676456824 108.634231696 +AutoVWAP-HH 2 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 110.5 109.399896109 108.563872244 107.669633364 106.875725158 106.747282454 106.692116166 106.536441491 106.471938378 106.372703650 106.372216705 106.409174552 106.503590283 106.489288694 106.461359205 106.343403445 106.098122389 105.992345409 105.924088220 105.908881364 +AutoVWAP-HH 3 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 110.5 111.230556489 111.273634384 111.481007121 111.502972148 111.368593356 111.326348109 111.179210579 111.146665112 110.952219932 110.892347447 110.774851759 110.687046897 110.635295923 110.522447589 110.400339676 110.323025934 110.185248231 110.052641127 109.996906862 +AutoVWAP-HH 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 110.5 108.789675983 107.660618198 106.399175445 105.333309494 105.206845487 105.147372185 104.988851795 104.913696133 104.846198222 104.865506458 104.953948817 105.109104745 105.107286284 105.107663077 104.991091368 104.689821207 104.594711135 104.547903917 104.546206198 +AutoVWAP-HH 5 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 110.5 111.840776615 112.176888431 112.751465041 113.045387812 112.909030324 112.871092090 112.726800275 112.704907357 112.478725360 112.399057694 112.230077495 112.081532435 112.017298333 111.876143717 111.752651752 111.731327115 111.582882505 111.428825429 111.359582028 +AutoVWAP-HH 6 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 110.5 108.179455856 106.757364151 105.128717526 103.790893831 103.666408519 103.602628205 103.441262099 103.355453889 103.319692795 103.358796211 103.498723081 103.714619207 103.725283874 103.753966948 103.638779292 103.281520026 103.197076861 103.171719615 103.183531032 AutoVWAP-LL 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 106.166666667 106.634666949 106.758870241 107.051068082 107.423176535 107.381497926 107.310704801 107.121602322 106.832466928 106.718624263 106.651207944 106.637638536 AutoVWAP-HV 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 110.5 110.010116236 109.467126291 108.940091283 108.418140821 108.287719422 108.236860147 108.084031187 108.030180623 107.899209077 107.878926953 107.864400288 107.898075821 107.871291103 107.815055333 107.695715522 107.506423571 107.389979683 107.300272522 107.271556530 +AutoVWAP-pct 1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 117.063333333 116.562160433 116.276884763 116.177103116 116.125546131 116.094057257 116.072828354 116.057547421 116.082787523 116.048493198 115.860464824 115.719074552 115.559317018 115.421732951 115.393195578 115.346510558 115.247214499 115.178548281 115.127277835 115.109196805 115.091708015 115.041463451 114.894692499 114.653775232 114.451668178 114.160160775 113.874589855 113.542714429 113.418175376 113.370881688 113.215718787 113.165175782 112.990790412 112.944140400 112.849421058 112.745574927 112.695327995 112.583632860 112.410054707 112.177863194 111.988493643 111.820987064 111.756407571 +AutoVWAP-pct 2 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 113.603333333 113.116973425 112.840129548 112.743297113 112.693263980 112.662705811 112.642104363 112.627275083 112.651769173 112.618488473 112.436017588 112.298806338 112.143770702 112.010253160 111.982559255 111.937254089 111.840892889 111.774256213 111.724501150 111.706954535 111.689982655 111.641223152 111.498790258 111.264993698 111.068860251 110.785968831 110.508838431 110.186772130 110.065914035 110.020018189 109.869441385 109.820392262 109.651161139 109.605889945 109.513970190 109.413193402 109.364431601 109.256037800 109.087590035 108.862261327 108.678488905 108.515933259 108.453262519 +AutoVWAP-pct 3 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 118.793333333 118.284753937 117.995262370 117.894006118 117.841687207 117.809732980 117.788190349 117.772683590 117.798296698 117.763495561 117.572688442 117.429208658 117.267090175 117.127472847 117.098513739 117.051138793 116.950375305 116.880694315 116.828666177 116.810317940 116.792570695 116.741583601 116.592643620 116.348165999 116.143072141 115.847256747 115.557465567 115.220685578 115.094306046 115.046313437 114.888857489 114.837567543 114.660605049 114.613265628 114.517146493 114.411765690 114.360776192 114.247430390 114.071287042 113.835664128 113.643496012 113.473513966 113.407980096 +AutoVWAP-pct 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 111.873333333 111.394379921 111.121751941 111.026394111 110.977122904 110.947030088 110.926742367 110.912138915 110.936259997 110.903486111 110.723793970 110.588672232 110.435997544 110.304513264 110.277241094 110.232625854 110.137732083 110.072110180 110.023112808 110.005833400 109.989119975 109.941103003 109.800839137 109.570602931 109.377456288 109.098872859 108.825962719 108.508800981 108.389783364 108.344586440 108.196302684 108.148000501 107.981346502 107.936764718 107.846244755 107.747002640 107.698983404 107.592240270 107.426357700 107.204460393 107.023486535 106.863406357 106.801689994 +AutoVWAP-pct 5 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 120.523333333 120.007347441 119.713639978 119.610909120 119.557828283 119.525408703 119.503552344 119.487819758 119.513805873 119.478497923 119.284912060 119.139342765 118.974863333 118.833212743 118.803831900 118.755767028 118.653536110 118.582840348 118.530054520 118.511439075 118.493433375 118.441703751 118.290594741 118.042556766 117.834476104 117.534352719 117.240341279 116.898656727 116.770436717 116.721745186 116.561996190 116.509959303 116.330419685 116.282390856 116.184871927 116.077956452 116.026224389 115.911227920 115.732519378 115.493465062 115.298498381 115.126040869 115.059552622 +AutoVWAP-pct 6 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 110.143333333 109.671786417 109.403374334 109.309491110 109.260981828 109.231354365 109.211380372 109.197002746 109.220750822 109.188483748 109.011570352 108.878538125 108.728224386 108.598773368 108.571922933 108.527997619 108.434571278 108.369964146 108.321724465 108.304712265 108.288257295 108.240982853 108.102888017 107.876212164 107.686052325 107.411776887 107.143087006 106.830829832 106.713652693 106.669154691 106.523163982 106.475608741 106.311531866 106.267639490 106.178519321 106.080811877 106.033535207 105.928442740 105.765125364 105.546659459 105.368484166 105.210879454 105.150117468 Volume24h 0 2879 10229 15463 24282 27613 35656 39171 48957 50221 53544 55574 63813 66314 75148 84709 93411 102151 112114 119379 127886 130479 138335 148112 157019 159231 168369 171190 179098 186159 193601 202961 206497 216470 220829 223893 230544 240471 244806 248994 257953 262154 265492 266528 275842 277868 285427 290984 299689 303915 308232 311491 314969 324465 327131 331261 339621 344066 348829 358318 364750 367702 370661 377018 380998 388100 390395 399029 400516 403711 406695 410476 417613 423749 426401 431737 439166 448919 450269 454348 457880 464269 470268 472872 480859 488874 494012 498682 501665 505852 509806 514700 516428 521559 526933 533536 539935 549296 552121 559058 561909 565316 575210 578296 583075 592646 595650 601647 602739 608759 612338 617338 622338 627338 632338 637338 639657 641858 650999 657293 663397 672880 674566 676264 679446 681810 687801 689229 690314 693803 703014 712797 719102 727418 734345 742189 745702 747015 751496 752897 758582 760374 764588 770480 772554 777352 784288 793047 801617 810039 813634 Volume24h-hand 0 10 30 60 100 140 180 70 150 90 Volume24h-weekly 0 - - - - diff --git a/vendor/egui-charts/src/studies/settings.rs b/vendor/egui-charts/src/studies/settings.rs index 689647f..b261196 100644 --- a/vendor/egui-charts/src/studies/settings.rs +++ b/vendor/egui-charts/src/studies/settings.rs @@ -302,6 +302,7 @@ impl StudyIntervalRange { /// Host-serializable presentation settings of an applied study. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq)] +#[non_exhaustive] pub struct StudySettings { /// Show values in the status line when the chart enables study values. Defaults to true. #[serde(default = "enabled_by_default")] @@ -369,13 +370,39 @@ pub struct StudySettings { pub gradients: Vec, } +impl Default for StudySettings { + /// No plot styles, the chart's default precision and no hidden intervals, with the status + /// line values and the pane tint shown, as older saved settings restore them. + fn default() -> Self { + Self { + show_legend_values: true, + user_edit_enabled: None, + help_url: None, + plots: Vec::new(), + precision: None, + hidden_intervals: Vec::new(), + interval_range: StudyIntervalRange::default(), + levels: Vec::new(), + fill_between_levels: false, + level_fill_color: Color32::TRANSPARENT, + untagged_plots: Vec::new(), + price_line_plots: Vec::new(), + plot_variants: Vec::new(), + background: None, + background_visible: true, + fills: Vec::new(), + gradients: Vec::new(), + } + } +} + fn enabled_by_default() -> bool { true } /// An owned settings and input snapshot without calculated study data. /// Used by chart history; restoring it requires recalculation on the current bars. -#[derive(Clone)] +#[derive(Debug, Clone)] pub struct StudySettingsSnapshot { inputs: Vec<(String, InputValue)>, pub(crate) settings: StudySettings, @@ -478,7 +505,8 @@ impl StudySettingsSnapshot { /// /// Calculated on another interval or symbol, a study's volume profiles and zones span the chart /// bars that share time with their bars, its markers sit on the last such chart bar once the -/// values on the chart reach their bar, and its labels are hidden. +/// values on the chart reach their bar, and its labels are hidden. Its visible range is the range +/// of its own bars that share time with the chart bars in view. #[derive(Clone)] pub struct ConfiguredStudy { study: Box, @@ -500,6 +528,8 @@ pub struct ConfiguredStudy { /// For each chart bar, the bars of another interval or symbol that share its time, by which /// the study's profiles, zones and markers are placed on chart bars. spans: Vec>, + /// The chart bars in view, from `set_visible_range`. + visible: Option>, /// The study's markers and zones on chart bars while it runs on another interval or symbol. aligned_markers: Vec, aligned_zones: Vec, @@ -516,6 +546,15 @@ struct Kept { shift: usize, } +impl std::fmt::Debug for ConfiguredStudy { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ConfiguredStudy") + .field("settings", &self.settings) + .field("timeframe", &self.timeframe) + .finish_non_exhaustive() + } +} + impl ConfiguredStudy { /// Retain the study's current colours, widths and calculation parameters. pub fn new(study: Box) -> Self { @@ -545,6 +584,7 @@ impl ConfiguredStudy { aligned: None, aligned_bars: Vec::new(), spans: Vec::new(), + visible: None, aligned_markers: Vec::new(), aligned_zones: Vec::new(), kept: None, @@ -737,14 +777,19 @@ impl Indicator for ConfiguredStudy { InputValue::Toggle(value) => self.wait_for_close = value, _ => unreachable!(), } - // The study missed the chart's interval and clock while it ran on other bars. + // The study missed the chart's interval, clock and bars in view while it ran on + // other bars. if id != "wait_for_close" && self.calculation_symbol.is_empty() && self.calculation_timeframe.is_none() - && let Some(timeframe) = self.timeframe { - self.study.set_timeframe(timeframe); - self.study.set_bar_clock(&self.clock); + if let Some(timeframe) = self.timeframe { + self.study.set_timeframe(timeframe); + self.study.set_bar_clock(&self.clock); + } + if let Some(visible) = &self.visible { + self.study.set_visible_range(visible.clone()); + } } self.aligned = None; self.kept = None; @@ -841,6 +886,11 @@ impl Indicator for ConfiguredStudy { self.study.set_instrument(source.instrument); self.study.set_timeframe(source.timeframe); self.study.set_bar_clock(&source.clock); + self.spans = spans_of(data, &self.clock, source); + if let Some(visible) = &self.visible { + self.study + .set_visible_range(source_bars(&self.spans, visible)); + } if self.data_requests().len() > 1 { self.study.update_data(source.bars, 0, sources); } else { @@ -876,7 +926,6 @@ impl Indicator for ConfiguredStudy { aligned.push(super::IndicatorValue::Multiple(values)); } self.aligned = Some(aligned); - self.spans = spans_of(data, &self.clock, source); // A marker appears once the values on the chart reach its bar (Wait for interval close). let shown = self.aligned_bars.iter().flatten().max().copied(); self.aligned_markers = self @@ -977,7 +1026,15 @@ impl Indicator for ConfiguredStudy { } } fn set_visible_range(&mut self, range: std::ops::Range) -> bool { - self.study.set_visible_range(range) + self.visible = Some(range.clone()); + if self.calculation_symbol.is_empty() && self.calculation_timeframe.is_none() { + return self.study.set_visible_range(range); + } + // Mapped by the spans of the last calculation; `update_data` maps it again on its bars. + // Without spans there is nothing to recalculate until it does. + self.study + .set_visible_range(source_bars(&self.spans, &range)) + && !self.spans.is_empty() } fn set_bar_clock(&mut self, clock: &crate::model::BarClock) -> bool { self.clock = clock.clone(); @@ -1312,16 +1369,41 @@ impl Indicator for ConfiguredStudy { edited.set_input(id, value.clone())?; } // Styles and tags of the plots before the inputs changed their number keep their place, - // and plots they add start with the study's own style and tag. + // and plots they add start with the study's own style and tag. Plots that keep their + // names at the end, behind plots the inputs add or remove, keep theirs under those names. if settings.plots.len() == self.line_count() && edited.line_count() != self.line_count() { let defaults = edited.study.settings(); - let kept = settings.plots.len().min(defaults.plots.len()); - settings.plots.truncate(kept); - settings.plots.extend_from_slice(&defaults.plots[kept..]); - settings.untagged_plots.retain(|&line| line < kept); - settings - .untagged_plots - .extend(defaults.untagged_plots.iter().filter(|&&line| line >= kept)); + let (old, new) = (settings.plots.len(), defaults.plots.len()); + let (before, after) = (self.line_names(), edited.line_names()); + let moved = if (before.len(), after.len()) == (old, new) { + let same = |(a, b): &(&String, &String)| a == b; + let head = before.iter().zip(&after).take_while(same).count(); + let (before, after) = (before[head..].iter().rev(), after[head..].iter().rev()); + before.zip(after).take_while(same).count() + } else { + 0 + }; + // The plot of the study before the edit that plot `line` continues. + let was = |line: usize| { + if line + moved >= new { + Some(old - (new - line)) + } else { + (line + moved < old).then_some(line) + } + }; + let flagged = |flags: &[usize], declared: &[usize]| -> Vec { + (0..new) + .filter(|&line| match was(line) { + Some(from) => flags.contains(&from), + None => declared.contains(&line), + }) + .collect() + }; + settings.untagged_plots = flagged(&settings.untagged_plots, &defaults.untagged_plots); + settings.price_line_plots = flagged(&settings.price_line_plots, &[]); + settings.plots = (0..new) + .map(|line| was(line).map_or(defaults.plots[line], |from| settings.plots[from])) + .collect(); } if settings.plots.len() != edited.line_count() { return Err(super::StudyError::PlotCount { @@ -2509,4 +2591,14 @@ mod tests { study.snapshot_settings().restore(&mut study).unwrap(); assert_eq!(study.fills()[0].color, own); } + + /// `StudySettings::default()`, where an `Indicator::settings` override starts, holds what + /// settings saved with only the original fields restore, so it shows the status line values + /// and the pane tint. + #[test] + fn default_settings_match_settings_saved_without_the_newer_fields() { + let saved: StudySettings = + serde_json::from_str(r#"{"plots":[],"precision":null,"hidden_intervals":[]}"#).unwrap(); + assert_eq!(StudySettings::default(), saved); + } } diff --git a/vendor/egui-charts/src/studies/stepper.rs b/vendor/egui-charts/src/studies/stepper.rs index 2f12557..8b6b573 100644 --- a/vendor/egui-charts/src/studies/stepper.rs +++ b/vendor/egui-charts/src/studies/stepper.rs @@ -59,7 +59,7 @@ use crate::studies::IndicatorValues; /// fresh.calculate(&bars); /// assert_eq!(format!("{:?}", study.values()), format!("{:?}", fresh.values())); /// ``` -#[derive(Clone, Default)] +#[derive(Debug, Clone, Default)] pub struct Stepper { state: S, before_last: S, diff --git a/vendor/egui-charts/src/studies/table.rs b/vendor/egui-charts/src/studies/table.rs index 18b6878..da9942b 100644 --- a/vendor/egui-charts/src/studies/table.rs +++ b/vendor/egui-charts/src/studies/table.rs @@ -2,6 +2,7 @@ /// A cell in a study table. #[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] pub enum StudyCell { /// A row label or other text. Text(String), @@ -9,8 +10,9 @@ pub enum StudyCell { Percent(Option), } -/// A labelled table drawn in the lower right of the study's pane. +/// A labelled table drawn in a corner, an edge or the middle of the study's pane. #[derive(Clone, Debug, Default, PartialEq)] +#[non_exhaustive] pub struct StudyTable { /// Caption above the column headings. pub title: String, @@ -18,47 +20,127 @@ pub struct StudyTable { pub columns: Vec, /// Cells in each row, in column order. pub rows: Vec>, - /// Optional background colour per cell, aligned with `rows`; empty or `None` uses the theme. + /// Optional background colour per cell, aligned with `rows`. pub cell_bg: Vec>>, - /// Optional text colour per cell, aligned with `rows`; empty or `None` uses the theme. + /// Optional text colour per cell, aligned with `rows`. pub cell_text: Vec>>, - /// The pane corner or edge the table sits in. - pub position: StudyTablePosition, + /// Background of every cell of each row, in row order. + pub cell_colors: Vec, + /// Background of the column headings, or `None` for the default. + pub header_color: Option, + /// Text colour for styled rows and headings. + pub text_color: Option, + /// Where the table sits in its pane. + pub position: TablePosition, + /// Size of the table's text. + pub text_size: TableTextSize, } -/// Where a study table sits in its pane. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -#[non_exhaustive] -pub enum StudyTablePosition { - /// The upper left corner. +/// Backwards-compatible name used by TradeCraft's Pine integration. +pub type StudyTablePosition = TablePosition; + +/// Where a study table sits in its pane. The `Debug` names are the choices study inputs list. +#[derive(Clone, Copy, Default, PartialEq, Eq)] +pub enum TablePosition { + /// Upper left corner. TopLeft, - /// The top edge, centred. + /// Middle of the upper edge. TopCenter, - /// The upper right corner. + /// Upper right corner. TopRight, - /// The left edge, centred. + /// Middle of the left edge. MiddleLeft, - /// The centre of the pane. + /// Centre of the pane. MiddleCenter, - /// The right edge, centred. + /// Middle of the right edge. MiddleRight, - /// The lower left corner. + /// Lower left corner. BottomLeft, - /// The bottom edge, centred. + /// Middle of the lower edge. BottomCenter, - /// The lower right corner. + /// Lower right corner. #[default] BottomRight, } -#[cfg(feature = "widget")] -fn rating_color(rating: &str) -> egui::Color32 { - match rating { - "Strong Buy" => super::palette::BLUE, - "Buy" => egui::Color32::from_rgb(91, 156, 246), - "Strong Sell" => super::palette::BRIGHT_RED, - "Sell" => egui::Color32::from_rgb(239, 154, 154), - _ => super::palette::DISABLED, +impl TablePosition { + /// Every position, top row first, each row from left to right. + pub const ALL: [Self; 9] = [ + Self::TopLeft, + Self::TopCenter, + Self::TopRight, + Self::MiddleLeft, + Self::MiddleCenter, + Self::MiddleRight, + Self::BottomLeft, + Self::BottomCenter, + Self::BottomRight, + ]; +} + +impl std::fmt::Debug for TablePosition { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::TopLeft => "Top left", + Self::TopCenter => "Top center", + Self::TopRight => "Top right", + Self::MiddleLeft => "Middle left", + Self::MiddleCenter => "Middle center", + Self::MiddleRight => "Middle right", + Self::BottomLeft => "Bottom left", + Self::BottomCenter => "Bottom center", + Self::BottomRight => "Bottom right", + }) + } +} + +/// The text size of a study table. The `Debug` names are the choices study inputs list. +#[derive(Clone, Copy, Default, PartialEq, Eq)] +pub enum TableTextSize { + /// 8 points. + Tiny, + /// 10 points. + Small, + /// 11 points. + #[default] + Normal, + /// 14 points. + Large, + /// 18 points. + Huge, +} + +impl TableTextSize { + /// Every size, smallest first. + pub const ALL: [Self; 5] = [ + Self::Tiny, + Self::Small, + Self::Normal, + Self::Large, + Self::Huge, + ]; + + /// The font size in points. + pub fn points(self) -> f32 { + match self { + Self::Tiny => 8.0, + Self::Small => 10.0, + Self::Normal => 11.0, + Self::Large => 14.0, + Self::Huge => 18.0, + } + } +} + +impl std::fmt::Debug for TableTextSize { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Tiny => "Tiny", + Self::Small => "Small", + Self::Normal => "Normal", + Self::Large => "Large", + Self::Huge => "Huge", + }) } } @@ -72,10 +154,12 @@ pub(crate) fn paint( use crate::theme::ThemeExt; use egui::{Align2, FontId, Rect, Stroke, StrokeKind, pos2, vec2}; - let rating_table = table.title == "Technical Ratings"; + let styled = table.header_color.is_some(); let painter = ui.painter().clone(); let theme = ui.active_theme(); - let font = FontId::proportional(11.0); + let font = FontId::proportional(table.text_size.points()); + // Rows are twice the font size high: 22 points at the normal size. + let row_height = 2.0 * table.text_size.points(); let text = |cell: &StudyCell| match cell { StudyCell::Text(text) => text.clone(), StudyCell::Percent(Some(value)) if value.is_finite() => format!("{value:+.2}%"), @@ -104,7 +188,7 @@ pub(crate) fn paint( } } let width = widths.iter().sum::(); - let height = 22.0 * (table.rows.len() + 2) as f32; + let height = row_height * (table.rows.len() + 2) as f32; let mut available = rect.shrink(8.0); available.min.y += 24.0; if !available.is_positive() || rect.height() < 44.0 { @@ -119,23 +203,19 @@ pub(crate) fn paint( width.max(title_width).min(available.width()), height.min(available.height()).min(rect.height() * 0.5), ); - let (align_x, align_y) = match table.position { - StudyTablePosition::TopLeft => (0.0, 0.0), - StudyTablePosition::TopCenter => (0.5, 0.0), - StudyTablePosition::TopRight => (1.0, 0.0), - StudyTablePosition::MiddleLeft => (0.0, 0.5), - StudyTablePosition::MiddleCenter => (0.5, 0.5), - StudyTablePosition::MiddleRight => (1.0, 0.5), - StudyTablePosition::BottomLeft => (0.0, 1.0), - StudyTablePosition::BottomCenter => (0.5, 1.0), - StudyTablePosition::BottomRight => (1.0, 1.0), + let (across, down) = match table.position { + TablePosition::TopLeft => (0.0, 0.0), + TablePosition::TopCenter => (0.5, 0.0), + TablePosition::TopRight => (1.0, 0.0), + TablePosition::MiddleLeft => (0.0, 0.5), + TablePosition::MiddleCenter => (0.5, 0.5), + TablePosition::MiddleRight => (1.0, 0.5), + TablePosition::BottomLeft => (0.0, 1.0), + TablePosition::BottomCenter => (0.5, 1.0), + TablePosition::BottomRight => (1.0, 1.0), }; let bounds = Rect::from_min_size( - available.min - + vec2( - (available.width() - size.x) * align_x, - (available.height() - size.y) * align_y, - ), + available.min + (available.size() - size) * vec2(across, down), size, ); let painter = painter.with_clip_rect(bounds.intersect(ui.clip_rect())); @@ -144,8 +224,8 @@ pub(crate) fn paint( bounds, 3.0, Stroke::new( - if rating_table { 2.0 } else { 1.0 }, - if rating_table { + if styled { 2.0 } else { 1.0 }, + if styled { egui::Color32::WHITE } else { theme.ui.border @@ -154,7 +234,7 @@ pub(crate) fn paint( StrokeKind::Inside, ); painter.text( - bounds.min + vec2(8.0, 11.0), + bounds.min + vec2(8.0, row_height / 2.0), Align2::LEFT_CENTER, &table.title, font.clone(), @@ -163,14 +243,17 @@ pub(crate) fn paint( let mut child = ui.new_child( egui::UiBuilder::new() .id_salt(id) - .max_rect(Rect::from_min_max(bounds.min + vec2(0.0, 22.0), bounds.max)), + .max_rect(Rect::from_min_max( + bounds.min + vec2(0.0, row_height), + bounds.max, + )), ); child.set_clip_rect(painter.clip_rect()); egui::ScrollArea::both() .auto_shrink([false, false]) .show(&mut child, |ui| { let (content, _) = - ui.allocate_exact_size(vec2(width, height - 22.0), egui::Sense::hover()); + ui.allocate_exact_size(vec2(width, height - row_height), egui::Sense::hover()); let painter = ui.painter(); let mut y = content.top(); for (row_index, row) in std::iter::once( @@ -185,91 +268,72 @@ pub(crate) fn paint( .enumerate() { let mut x = content.left(); - // The heading row is synthesised above `rows`, so data colours shift by one. let data_row = row_index.checked_sub(1); for (column, (cell, width)) in row.iter().zip(&widths).enumerate() { - let cell_rect = Rect::from_min_size(pos2(x, y), vec2(*width, 22.0)); let own = |colors: &Vec>>| { - data_row - .and_then(|row| colors.get(row)) - .and_then(|cells| cells.get(column)) - .copied() - .flatten() + data_row.and_then(|row| colors.get(row)).and_then(|cells| cells.get(column)).copied().flatten() }; let bg = own(&table.cell_bg); let ink = own(&table.cell_text); - let mut color = match cell { - _ if rating_table && row_index == 0 => { - painter.rect_filled( - cell_rect, - 0.0, - egui::Color32::from_rgb(41, 91, 121), - ); - egui::Color32::WHITE - } - _ if rating_table => { - let rating = match row.get(2) { - Some(StudyCell::Text(text)) => text.as_str(), - _ => "Neutral", - }; - let fill = rating_color(rating); - painter.rect_filled(cell_rect, 0.0, fill); + let cell_rect = Rect::from_min_size(pos2(x, y), vec2(*width, row_height)); + let fill = match row_index { + 0 => table.header_color, + row => table.cell_colors.get(row - 1).copied(), + }; + let mut color = if let Some(fill) = fill { + painter.rect_filled(cell_rect, 0.0, fill); + if row_index > 0 { painter.rect_stroke( cell_rect, 0.0, Stroke::new(1.0, egui::Color32::WHITE), StrokeKind::Inside, ); - crate::theme::readable_color( - egui::Color32::WHITE, - egui::Color32::BLACK, - &[fill], - 4.5, - ) } - StudyCell::Percent(Some(value)) if value.is_finite() => { - let color = if *value >= 0.0 { - egui::Color32::from_rgb(8, 153, 129) - } else { - egui::Color32::from_rgb(242, 55, 69) - }; - let tint = color.gamma_multiply( - 0.1 + if table.title == "Seasonality" { - 0.4 + let text = table.text_color.unwrap_or(egui::Color32::WHITE); + crate::theme::readable_color(text, egui::Color32::BLACK, &[fill], 4.5) + } else { + match cell { + StudyCell::Percent(Some(value)) if value.is_finite() => { + let color = if *value >= 0.0 { + egui::Color32::from_rgb(8, 153, 129) } else { - 0.2 - } * (value.abs() / 10.0).min(1.0) as f32, - ); - painter.rect_filled( - Rect::from_min_size(pos2(x, y), vec2(*width, 22.0)), - 0.0, - tint, - ); - crate::theme::readable_color( - color, - theme.ui.text, - &[theme.ui.panel_bg_floating.blend(tint)], - 4.5, - ) - } - _ if matches!(table.title.as_str(), "Performance" | "Seasonality") => { - let alpha = if matches!(cell, StudyCell::Percent(None)) { - if table.title == "Seasonality" { - 128 + egui::Color32::from_rgb(242, 55, 69) + }; + let tint = color.gamma_multiply( + 0.1 + if table.title == "Seasonality" { + 0.4 + } else { + 0.2 + } * (value.abs() / 10.0).min(1.0) as f32, + ); + painter.rect_filled(cell_rect, 0.0, tint); + crate::theme::readable_color( + color, + theme.ui.text, + &[theme.ui.panel_bg_floating.blend(tint)], + 4.5, + ) + } + _ if matches!(table.title.as_str(), "Performance" | "Seasonality") => { + let alpha = if matches!(cell, StudyCell::Percent(None)) { + if table.title == "Seasonality" { + 128 + } else { + 26 + } } else { - 26 - } - } else { - 51 - }; - painter.rect_filled( - cell_rect, - 0.0, - egui::Color32::from_rgba_unmultiplied(120, 123, 134, alpha), - ); - theme.ui.text + 51 + }; + painter.rect_filled( + cell_rect, + 0.0, + egui::Color32::from_rgba_unmultiplied(120, 123, 134, alpha), + ); + theme.ui.text + } + _ => theme.ui.text, } - _ => theme.ui.text, }; if let Some(bg) = bg { painter.rect_filled(cell_rect, 0.0, bg); @@ -279,7 +343,7 @@ pub(crate) fn paint( color = ink; } painter.text( - pos2(x + 8.0, y + 11.0), + pos2(x + 8.0, y + row_height / 2.0), Align2::LEFT_CENTER, text(cell), font.clone(), @@ -287,22 +351,33 @@ pub(crate) fn paint( ); x += width; } - y += 22.0; + y += row_height; } }); - bounds + if matches!( + table.position, + TablePosition::BottomLeft | TablePosition::BottomCenter | TablePosition::BottomRight + ) { + bounds + } else { + // shortcut: only tables at the bottom stack upwards, so two tables at the top or in the + // middle of one pane overlap; give them their own stacks when a pane needs several. + Rect::from_min_size(pos2(rect.min.x, rect.max.y + 8.0), egui::Vec2::ZERO) + } } #[cfg(all(test, feature = "widget"))] mod tests { use super::*; - /// A narrow or short pane keeps overflowing columns and years within a scrollable table. + /// A narrow or short pane keeps overflowing columns and years within a scrollable table, at + /// the table's position and text size. Only a table at the bottom takes the space below the + /// next table. #[test] fn overflowing_tables_fit_the_pane() { use egui::{Event, MouseWheelUnit, RawInput, Rect, Shape, TouchPhase, vec2}; - let table = StudyTable { + let lower_right = StudyTable { title: "Seasonality".into(), columns: (0..13).map(|i| format!("Column {i}")).collect(), rows: (0..40) @@ -312,16 +387,30 @@ mod tests { row }) .collect(), - ..StudyTable::default() + ..Default::default() }; - for (_, theme) in crate::theme::presets() { + let upper_left = StudyTable { + position: TablePosition::TopLeft, + text_size: TableTextSize::Large, + ..lower_right.clone() + }; + for ((_, theme), table) in crate::theme::presets() + .into_iter() + .flat_map(|theme| [(theme.clone(), &lower_right), (theme, &upper_left)]) + { + let top = table.position == TablePosition::TopLeft; for width in [240.0, 800.0] { let ctx = egui::Context::default(); crate::theme::apply_to_egui(&ctx, &theme); let rect = Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 300.0)); for frame in 0..20 { - let mut events = - vec![Event::PointerMoved(rect.right_bottom() - vec2(100.0, 50.0))]; + // The wheel scrolls the table under the pointer. + let pointer = if top { + rect.left_top() + vec2(100.0, 100.0) + } else { + rect.right_bottom() - vec2(100.0, 50.0) + }; + let mut events = vec![Event::PointerMoved(pointer)]; if frame == 1 { events.push(Event::MouseWheel { unit: MouseWheelUnit::Point, @@ -339,10 +428,28 @@ mod tests { ..Default::default() }, |ui| { - let bounds = paint(ui, rect, &table, ui.scope_id().with("table")); - assert!(rect.contains_rect(bounds), "{bounds:?} outside {rect:?}"); + let bounds = paint(ui, rect, table, ui.scope_id().with("table")); + if top { + assert_eq!(bounds.top() - 8.0, rect.max.y); + } else { + assert!(rect.contains_rect(bounds), "{bounds:?} outside {rect:?}"); + } }, ); + let title = output + .shapes + .iter() + .find_map(|clipped| match &clipped.shape { + Shape::Text(text) if text.galley.text() == "Seasonality" => Some(text), + _ => None, + }); + let title = title.expect("title painted"); + assert_eq!( + title.galley.job.sections[0].format.font_id.size, + table.text_size.points() + ); + // Below the pane's 8-point margin and its 24-point legend row at the top. + assert_eq!(title.galley.rect.top() + title.pos.y < 50.0, top); if frame == 19 { assert!(output.shapes.iter().any(|clipped| matches!(&clipped.shape, Shape::Text(text) if text.galley.text() == "Last 39" diff --git a/vendor/egui-charts/src/studies/template.rs b/vendor/egui-charts/src/studies/template.rs index 3992a77..2fd815b 100644 --- a/vendor/egui-charts/src/studies/template.rs +++ b/vendor/egui-charts/src/studies/template.rs @@ -7,6 +7,7 @@ use crate::studies::{ /// Serializable inputs and presentation of one study. Hosts may resolve `name` through their /// own study factory when they supply custom studies. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] pub struct StudyTemplate { /// Study factory name. pub name: String, @@ -254,6 +255,26 @@ impl StudyTemplate { .inputs .push(("auto_interval".to_owned(), InputValue::Toggle(false))); } + // A majority rule drew the signed direction before it could report the percentage, and + // no guide before it opened with one at 50; hidden, the guide leaves the pane as saved. + "MajRule" if !has("mode") || self.settings.levels.is_empty() => { + if !has("mode") { + template + .inputs + .push(("mode".to_owned(), InputValue::Choice(1))); + } + if self.settings.levels.is_empty() { + let declared = crate::studies::MajorityRule::default(); + let (levels, ..) = super::settings::declared_levels(&declared); + template.settings.levels = levels + .into_iter() + .map(|level| crate::studies::LevelStyle { + visible: false, + ..level + }) + .collect(); + } + } // An RSI drew no average and no middle line before it opened with both; the hidden // level keeps the styles saved for the other two and stays within their band. Its // average then chose from None, SMA and EMA, under ids of its own, before it took the @@ -320,6 +341,24 @@ impl StudyTemplate { }) .collect(); } + // A Correlation Coefficient drew its zero guide alone before it opened with guides at + // its bounds; hidden, they leave the pane as it was saved. One guide bounded no band, + // so a fill saved on draws none between them either. A host study under the name, + // which has no log returns, keeps its own guides. + "Correlation Coefficient" + if self.settings.levels.len() < 2 && declares("log_returns") => + { + let (mut levels, ..) = + super::settings::declared_levels(&crate::studies::Correlation::default()); + for bound in &mut levels[..2] { + bound.visible = false; + } + if let Some(zero) = self.settings.levels.first() { + levels[2] = *zero; + } + template.settings.levels = levels; + template.settings.fill_between_levels = false; + } // A Rank Correlation had no average, and drew no levels, before it opened with an // average, three levels and the band between them filled. "RankCorr" if !has("smoothing") || self.settings.levels.is_empty() => { @@ -340,6 +379,27 @@ impl StudyTemplate { .collect(); } } + // An auto anchored VWAP drew one line before it had bands; hidden, the bands and their + // fill keep the styles they take once shown. + "VWAP Auto Anchored" if !has("band_multiplier") && self.settings.plots.len() == 1 => { + let declared = crate::studies::VwapAutoAnchored::new().settings(); + template.inputs.extend([ + ("percentage_bands".to_owned(), InputValue::Toggle(false)), + ("band_multiplier".to_owned(), InputValue::Number(1.0)), + ]); + for mut plot in declared.plots.into_iter().skip(1) { + plot.visible = false; + template.settings.plots.push(plot); + } + template + .settings + .untagged_plots + .extend(declared.untagged_plots); + template.settings.fills = declared.fills; + for fill in &mut template.settings.fills { + fill.visible = false; + } + } // Profile endpoints were Unix milliseconds before they read as UTC dates and times. "Vol Profile FR" | "Vol Profile Anchored" if self @@ -470,11 +530,12 @@ mod tests { let rows: Vec> = vec![ // Exported studies outside the catalogue. Box::new(CVD::default()), - Box::new(CloseToCloseVol::default()), Box::new(HL2::default()), Box::new(HLC3::default()), Box::new(PriceChannel::default()), Box::new(EhlersFisher::default()), + // A catalogue study with the bars per year it is annualized over. + Box::new(CloseToCloseVol::default().with_trading_days(365.0)), // Fewer averages than the ribbon that the name creates, with a crossing pair. Box::new( MACombination::new(vec![ @@ -713,6 +774,33 @@ mod tests { vec![("auto_interval", Toggle(true))], vec![("auto_interval", Toggle(true))], ), + // Saved before the bars per year could be set, when every volatility used 252. + ( + "C2C Vol", + vec![("period", Length(20))], + vec![("period", Length(20)), ("trading_days", Number(252.0))], + ), + ( + "GK Vol", + vec![("period", Length(20))], + vec![("period", Length(20)), ("trading_days", Number(252.0))], + ), + ( + "Zero-Trend Vol", + vec![("period", Length(20))], + vec![("period", Length(20)), ("trading_days", Number(252.0))], + ), + ( + "Zero-Trend Vol", + vec![("trading_days", Number(365.0))], + vec![("trading_days", Number(365.0))], + ), + // Saved before the output could be chosen, when it was the signed direction. + ( + "MajRule", + vec![("period", Length(10))], + vec![("period", Length(10)), ("mode", Choice(1))], + ), // Saved as Unix milliseconds before the endpoints read as UTC dates and times. ( "Vol Profile FR", @@ -741,6 +829,12 @@ mod tests { ("extend_val", Toggle(false)), ], ), + // Saved before the twelve lengths were inputs. + ( + "GMMA", + vec![], + vec![("periods [0]", Length(3)), ("periods [11]", Length(60))], + ), ]; let factory = IndicatorFactory::new(); let periods = (0..7).map(|period| { @@ -783,9 +877,10 @@ mod tests { } } - /// An RSI and a VWAP saved before their defaults gained an average and a band restore with the - /// plots they had, and a Rank Correlation saved before it had an average, levels and a filled - /// band restores without them. + /// An RSI, a VWAP, an auto anchored VWAP and a Correlation Coefficient saved before their + /// defaults gained an average, bands, and an area with guides at its bounds restore with the + /// plots and guides they had, and a Rank Correlation saved before it had an average, levels + /// and a filled band, and a Majority Rule saved before its guide at 50, restore without them. #[test] fn saved_studies_keep_the_plots_they_had_before_their_defaults_gained_more() { let mut rsi = ConfiguredStudy::new(Box::new(RSI::new(9))); @@ -808,6 +903,21 @@ mod tests { ); assert!(!restored.settings().levels[2].visible); + // Saved with a banded average by the release before the divergence input, an RSI restores + // its four plots as they were styled and calculates no divergences. + let banded: StudyTemplate = serde_json::from_str( + r#"{"name":"RSI","inputs":[["period",{"Length":14}],["smoothing",{"Choice":2}],["smoothing_length",{"Length":14}],["smoothing_deviation",{"Number":2.0}]],"settings":{"show_legend_values":true,"user_edit_enabled":true,"help_url":"https://userfrm.github.io/egui-charts/docs/api/egui_charts/studies/struct.RSI.html","plots":[{"color":[126,87,194,255],"width":1.0,"pattern":"Solid","plot_type":"Line","visible":true},{"color":[253,216,53,255],"width":1.0,"pattern":"Solid","plot_type":"Line","visible":true},{"color":[76,175,80,255],"width":1.0,"pattern":"Solid","plot_type":"Line","visible":true},{"color":[76,175,80,255],"width":1.0,"pattern":"Solid","plot_type":"Line","visible":true}],"precision":2,"hidden_intervals":[],"interval_range":"All","levels":[{"value":null,"color":[120,123,134,255],"pattern":"Dashed","width":1.0,"visible":true,"price_line":false},{"value":null,"color":[120,123,134,255],"pattern":"Dashed","width":1.0,"visible":true,"price_line":false},{"value":null,"color":[120,123,134,255],"pattern":"Dashed","width":1.0,"visible":true,"price_line":false}],"fill_between_levels":true,"level_fill_color":[13,9,20,26],"untagged_plots":[],"price_line_plots":[],"plot_variants":[[],[],[],[]],"background":null,"background_visible":true,"fills":[{"color":[8,18,8,26],"inverted_color":null,"visible":true}],"gradients":[]},"visible":true,"scale":"Independent"}"#, + ) + .unwrap(); + let restored = banded.create().unwrap(); + assert_eq!(restored.settings().plots, banded.settings.plots); + let divergence = restored.inputs().into_iter().find(|i| i.id == "divergence"); + assert_eq!(divergence.unwrap().value, InputValue::Toggle(false)); + // Saved since with the input on, it restores the four divergence plots too. + let marked = ConfiguredStudy::new(Box::new(RSI::default().with_divergence(true))); + let restored = StudyTemplate::from_study(&marked).create().unwrap(); + assert_eq!(restored.line_count(), 6); + // Saved with an EMA from the shorter list of types, under the average's earlier ids. let mut older = StudyTemplate::from_study(&RSI::default()); older.inputs.retain(|(id, _)| !id.starts_with("smoothing")); @@ -846,6 +956,68 @@ mod tests { let filled = StudyTemplate::from_study(&bands).create().unwrap(); assert_eq!(filled.fills().len(), 2); + // A Correlation Coefficient opens as an area with guides at its bounds and at zero. Saved + // as a line with the zero guide alone, here dotted, 3 px wide and orange with its value + // line, it restores as that line with the bounds hidden, and a bound shown since stays + // shown through a template. + let fresh = + ConfiguredStudy::new(Box::new(crate::studies::Correlation::default())).settings(); + assert_eq!(fresh.plots[0].plot_type, crate::studies::PlotType::Area); + assert!(fresh.levels.iter().all(|level| level.visible)); + let saved = r#"{"name":"Correlation Coefficient","inputs":[["symbol_0",{"Symbol":""}],["source_0",{"Choice":3}],["symbol_1",{"Symbol":""}],["source_1",{"Choice":3}],["length",{"Length":20}],["log_returns",{"Toggle":false}],["calculation_timeframe",{"Timeframe":null}],["wait_for_close",{"Toggle":true}]],"settings":{"show_legend_values":true,"user_edit_enabled":true,"help_url":"https://userfrm.github.io/egui-charts/docs/api/egui_charts/studies/type.Correlation.html","plots":[{"color":[33,150,243,255],"width":1.0,"pattern":"Solid","plot_type":"Line","visible":true}],"precision":2,"hidden_intervals":[],"interval_range":"All","levels":[{"value":null,"color":[255,152,0,255],"pattern":"Dotted","width":3.0,"visible":true,"price_line":true}],"fill_between_levels":false,"level_fill_color":[2,9,15,16],"untagged_plots":[],"price_line_plots":[0],"plot_variants":[[]],"background":null,"background_visible":true,"fills":[],"gradients":[]},"visible":true,"scale":"Independent"}"#; + let mut restored = serde_json::from_str::(saved) + .unwrap() + .create() + .unwrap(); + let settings = restored.settings(); + assert_eq!(settings.plots[0].plot_type, crate::studies::PlotType::Line); + let values: Vec<_> = restored.pane().levels.iter().map(|l| l.0).collect(); + assert_eq!(values, [1.0, -1.0, 0.0]); + let [upper, lower, zero] = settings.levels[..] else { + panic!("three guides"); + }; + assert!(!upper.visible && !lower.visible); + assert_eq!( + zero, + crate::studies::LevelStyle { + value: None, + color: Color32::from_rgb(255, 152, 0), + pattern: crate::model::LineStyle::Dotted, + width: 3.0, + visible: true, + price_line: true, + } + ); + let mut shown = settings.clone(); + shown.levels[0].visible = true; + restored.apply_settings(&[], shown.clone()).unwrap(); + let again = StudyTemplate::from_study(restored.as_ref()) + .create() + .unwrap(); + assert_eq!(again.settings().levels, shown.levels); + // A host could switch the fill on while the one guide bounded no band. + let mut filled: StudyTemplate = serde_json::from_str(saved).unwrap(); + filled.settings.fill_between_levels = true; + assert!(!filled.create().unwrap().pane().fill_between_levels); + + // An auto anchored VWAP as a chart saved it before the study had bands, its line edited + // to orange at two pixels and its length to 30: it draws that line alone, and the hidden + // bands are tagged as on a study added now. + let saved = r#"{"name":"VWAP Auto Anchored","inputs":[["anchor",{"Choice":0}],["length",{"Length":30}],["source",{"Choice":5}],["calculation_timeframe",{"Timeframe":null}],["wait_for_close",{"Toggle":true}]],"settings":{"show_legend_values":true,"user_edit_enabled":true,"help_url":"https://userfrm.github.io/egui-charts/docs/api/egui_charts/studies/struct.VwapAutoAnchored.html","plots":[{"color":[230,81,0,255],"width":2.0,"pattern":"Solid","plot_type":"Line","visible":true}],"precision":null,"hidden_intervals":[],"interval_range":"All","levels":[],"fill_between_levels":false,"level_fill_color":[2,9,14,16],"untagged_plots":[],"price_line_plots":[],"plot_variants":[[]],"background":null,"background_visible":true,"fills":[],"gradients":[]},"visible":true,"scale":"Main"}"#; + let saved: StudyTemplate = serde_json::from_str(saved).unwrap(); + let restored = saved.create().unwrap(); + assert_eq!(restored.plot_style(0), saved.settings.plots[0]); + let lines = 0..restored.line_count(); + let drawn: Vec<_> = lines + .clone() + .filter(|&line| restored.plot_style(line).visible) + .collect(); + let tagged: Vec<_> = lines.filter(|&line| restored.plot_tagged(line)).collect(); + assert_eq!((drawn, tagged), (vec![0], vec![0, 1, 2])); + assert!(restored.fills().is_empty()); + let length = restored.inputs().into_iter().find(|i| i.id == "length"); + assert_eq!(length.unwrap().value, InputValue::Length(30)); + // A Rank Correlation as the release before its levels saved it draws none of them and // fills no band, one saved before it had an average draws none, and one saved since draws // the average, all three levels and the band. @@ -870,6 +1042,53 @@ mod tests { assert_eq!(drawn(&oldest), (1, (3, 0), false)); let current = StudyTemplate::from_study(&RankCorrelationIndex::default()); assert_eq!(drawn(¤t), (2, (3, 3), true)); + + // A Majority Rule saved before its guide at 50 draws none, one saved since draws it, and + // one in direction mode has none to draw. + let current = StudyTemplate::from_study(&crate::studies::MajorityRule::default()); + let mut older = current.clone(); + older.settings.levels.clear(); + assert_eq!(drawn(&older), (1, (1, 0), false)); + assert_eq!(drawn(¤t), (1, (1, 1), false)); + let direction = crate::studies::MajorityRule::default() + .with_mode(crate::studies::MajorityMode::Direction); + assert_eq!( + drawn(&StudyTemplate::from_study(&direction)), + (1, (0, 0), false) + ); + // A Technical Ratings as the release before its table inputs saved it, its fast length + // edited to 20 and its summary to orange: it rates every vote, requests no other interval + // and draws its table where and as it did. + let saved: StudyTemplate = serde_json::from_str( + r#"{"name":"Technical Ratings","inputs":[["fast",{"Length":20}],["medium",{"Length":50}],["slow",{"Length":200}],["simple",{"Toggle":true}],["exponential",{"Toggle":true}],["rsi",{"Toggle":true}],["rsi_period",{"Length":14}],["stochastic",{"Toggle":true}],["stochastic_period",{"Length":14}],["cci",{"Toggle":true}],["cci_period",{"Length":20}],["macd",{"Toggle":true}],["macd_fast",{"Length":12}],["macd_slow",{"Length":26}],["macd_signal",{"Length":9}],["momentum",{"Toggle":true}],["momentum_period",{"Length":10}],["calculation_timeframe",{"Timeframe":null}],["wait_for_close",{"Toggle":true}]],"settings":{"show_legend_values":true,"user_edit_enabled":true,"help_url":"https://userfrm.github.io/egui-charts/docs/api/egui_charts/studies/struct.TechnicalRatings.html","plots":[{"color":[168,173,188,255],"width":1.0,"pattern":"Solid","plot_type":"Columns","visible":true},{"color":[168,173,188,255],"width":1.0,"pattern":"Solid","plot_type":"Columns","visible":true},{"color":[230,81,0,255],"width":1.0,"pattern":"Solid","plot_type":"Columns","visible":true},{"color":[168,173,188,255],"width":1.0,"pattern":"Solid","plot_type":"Columns","visible":false},{"color":[168,173,188,255],"width":1.0,"pattern":"Solid","plot_type":"Columns","visible":false},{"color":[168,173,188,255],"width":1.0,"pattern":"Solid","plot_type":"Columns","visible":false}],"precision":2,"hidden_intervals":[],"interval_range":"All","levels":[{"value":null,"color":[46,78,123,128],"pattern":"Dashed","width":1.0,"visible":true,"price_line":false},{"value":null,"color":[120,77,77,128],"pattern":"Dashed","width":1.0,"visible":true,"price_line":false}],"fill_between_levels":false,"level_fill_color":[11,11,12,16],"untagged_plots":[0,1,2,3,4,5],"price_line_plots":[],"plot_variants":[[],[],[],[],[],[]],"background":null,"background_visible":true,"fills":[],"gradients":[]},"visible":true,"scale":"Independent"}"#, + ) + .unwrap(); + let mut restored = saved.create().unwrap(); + assert_eq!(restored.settings().plots, saved.settings.plots); + assert!(restored.data_requests().is_empty()); + let inputs = restored.inputs(); + let value = |id: &str| inputs.iter().find(|i| i.id == id).unwrap().value.clone(); + assert_eq!( + [value("fast"), value("basis")], + [InputValue::Length(20), InputValue::Choice(0)] + ); + restored.calculate(&[]); + let table = restored.table().unwrap(); + assert_eq!( + ( + table.position, + table.text_size, + table.header_color, + table.text_color + ), + ( + crate::studies::TablePosition::BottomRight, + crate::studies::TableTextSize::Normal, + Some(Color32::from_rgb(41, 91, 121)), + Some(Color32::WHITE) + ) + ); + assert_eq!(table.rows.len(), 3); } /// A host study registered under a built-in's name replaces it (`IndicatorFactory::register`), @@ -884,6 +1103,7 @@ mod tests { let rows = [ ("RSI", vec![], 1), ("VWAP", vec![], 1), + ("VWAP Auto Anchored", vec![], 1), ("Trading Sessions", vec![], 1), // Built-in templates with `offset_percent` restore as Envelopes, which draws three // lines too. diff --git a/vendor/egui-charts/src/tokens/resolved.rs b/vendor/egui-charts/src/tokens/resolved.rs index 9a75e5c..20a29e8 100644 --- a/vendor/egui-charts/src/tokens/resolved.rs +++ b/vendor/egui-charts/src/tokens/resolved.rs @@ -10,6 +10,7 @@ use super::sizing::{LayoutTokens, RoundingTokens, ShadowTokens, SizingTokens, St /// and semantic color tokens. UI colors and text, spacing and radius scales come /// from the applied `theme::Theme` (requires `widget`). #[derive(Clone, Debug)] +#[non_exhaustive] pub struct DesignTokens { /// Spacing defaults. pub spacing: SpacingTokens, diff --git a/vendor/egui-charts/src/tokens/semantic.rs b/vendor/egui-charts/src/tokens/semantic.rs index 3080956..7827b64 100644 --- a/vendor/egui-charts/src/tokens/semantic.rs +++ b/vendor/egui-charts/src/tokens/semantic.rs @@ -16,6 +16,7 @@ use egui::Color32; /// Each field groups defaults and fallbacks for a specific domain, including chart /// rendering and drawing tools. UI chrome reads the applied theme. #[derive(Clone, Debug)] +#[non_exhaustive] pub struct SemanticTokens { /// Neutral engine fallback; UI chrome reads the applied theme. pub ui: UiSemanticTokens, @@ -39,6 +40,7 @@ pub struct SemanticTokens { /// Neutral fallback still used by volume bubbles. UI chrome reads the applied theme. #[derive(Clone, Debug)] +#[non_exhaustive] pub struct UiSemanticTokens { /// Neutral default retained for engine volume bubbles. pub text_muted_dark: Color32, @@ -51,6 +53,7 @@ pub struct UiSemanticTokens { /// Defines colors for the chart background, grid lines, axis text, crosshair, /// candle/bar colors (bullish/bearish), volume bar alpha, and watermark. #[derive(Clone, Debug)] +#[non_exhaustive] pub struct ChartSemanticTokens { /// Background color. pub bg: Color32, @@ -86,6 +89,7 @@ pub struct ChartSemanticTokens { /// Brand accent colors (consistent across light/dark themes). #[derive(Clone, Debug)] +#[non_exhaustive] pub struct BrandSemanticTokens { /// Accent color. pub accent: Color32, @@ -162,6 +166,7 @@ pub struct TpoSemanticTokens { /// Legacy moving average colours still used by drawing defaults. Studies use `studies::palette`. #[derive(Clone, Debug)] +#[non_exhaustive] pub struct IndicatorSemanticTokens { /// Generic moving average line color. pub ma: Color32, diff --git a/vendor/egui-charts/src/tokens/sizing.rs b/vendor/egui-charts/src/tokens/sizing.rs index 338bfa9..0246634 100644 --- a/vendor/egui-charts/src/tokens/sizing.rs +++ b/vendor/egui-charts/src/tokens/sizing.rs @@ -17,6 +17,7 @@ /// General sizing values (icons, buttons, list items) are at the top level. /// Component-specific sizing is nested in sub-structs (toolbar, panel, dialog, etc.). #[derive(Clone, Debug)] +#[non_exhaustive] pub struct SizingTokens { /// Target minimum, in egui logical points. pub target_min: f32, diff --git a/vendor/egui-charts/src/ui/context_menu/axis.rs b/vendor/egui-charts/src/ui/context_menu/axis.rs index 0cb3a63..b83e071 100644 --- a/vendor/egui-charts/src/ui/context_menu/axis.rs +++ b/vendor/egui-charts/src/ui/context_menu/axis.rs @@ -51,10 +51,11 @@ impl AxisMenus { if egui::Popup::is_any_open(ctx) { return false; } + // A touch held in place asks for the menu as a secondary click does. egui reports the + // hold to the widget a tap would click, which every axis that takes clicks is part of. + let held = ctx.interaction_snapshot(|widgets| widgets.long_touched.is_some()); let Some(pos) = ctx.input(|input| { - input - .pointer - .secondary_clicked() + (held || input.pointer.secondary_clicked()) .then(|| input.pointer.interact_pos()) .flatten() }) else { @@ -214,6 +215,22 @@ impl AxisMenus { row("Scale settings…", Action::Settings, false), MenuEntry::Separator, ]); + // The fit and symbol label rows switch settings of the price chart, so only the axes + // of the main series' pane offer them. + if chart.series_pane(SeriesId::MAIN).unwrap_or(PaneId::MAIN) != pane { + entries.retain(|entry| match entry { + MenuEntry::Item(item) => !matches!( + item.action, + Action::PriceOnly + | Action::LastValue + | Action::PreviousClose + | Action::Countdown + | Action::BidAsk + | Action::HighLow + ), + MenuEntry::Submenu { .. } | MenuEntry::Separator => true, + }); + } entries.extend(Self::layout_rows(chart, pane)); entries } diff --git a/vendor/egui-charts/src/ui/context_menu/chart_menus/tests.rs b/vendor/egui-charts/src/ui/context_menu/chart_menus/tests.rs index 1250d56..84794d5 100644 --- a/vendor/egui-charts/src/ui/context_menu/chart_menus/tests.rs +++ b/vendor/egui-charts/src/ui/context_menu/chart_menus/tests.rs @@ -345,12 +345,14 @@ fn axis_right_clicks_open_menus_and_apply_choices() { ] }; for theme in [Theme::light(), Theme::dark()] { - for (time, left, ratio, short) in [ - (false, false, false, false), - (false, true, false, false), - (true, false, false, false), - (false, false, true, false), - (false, false, false, true), + for (time, left, ratio, short, pane, hours) in [ + (false, false, false, false, false, false), + (false, true, false, false, false, false), + (true, false, false, false, false, false), + (false, false, true, false, false, false), + (false, false, false, true, false, false), + (false, false, false, false, true, false), + (true, false, false, false, false, true), ] { let ctx = Context::default(); crate::theme::apply_to_egui(&ctx, &theme); @@ -362,11 +364,22 @@ fn axis_right_clicks_open_menus_and_apply_choices() { let mut chart = crate::widget::test_frames::chart(&[100.0], &[110.0]); chart.config_mut().show_left_axis = left; chart.config_mut().show_right_axis = !left; + let pane = pane + .then(|| chart.add_indicator(Box::new(crate::studies::RSI::new(14)))) + .and_then(|study| chart.series_pane(study)); let mut menus = ChartMenus::default(); paint(&ctx, &mut chart, &mut menus, vec![], size); let plot = chart.get_rendered_price_rect(); let anchor = if time { Pos2::new(plot.center().x, plot.bottom() + 10.0) + } else if pane.is_some() { + Pos2::new( + plot.right() + 25.0, + chart.get_rendered_indicator_panes()[0] + .panel_rect + .center() + .y, + ) } else { Pos2::new( if left { @@ -417,8 +430,28 @@ fn axis_right_clicks_open_menus_and_apply_choices() { ); } } + if pane.is_some() { + assert!(chart.menu_open, "a study pane's axis menu is an open menu"); + // One menu, with the rows of a scale that holds no price chart. + for (label, count) in [ + ("Invert scale", 1), + ("Lock price to bar ratio", 1), + ("Hide unused axes", 1), + ("Indicator values", 1), + ("Scale price chart only", 0), + ("Last price label", 0), + ] { + let rows = shapes + .iter() + .filter(|shape| matches!(&shape.shape, Shape::Text(text) if text.galley.text() == label)) + .count(); + assert_eq!(rows, count, "{label} on a study pane's axis"); + } + } let label = if short { "High and low" + } else if hours { + "Extended hours" } else if time { "Local time" } else if ratio { @@ -463,11 +496,23 @@ fn axis_right_clicks_open_menus_and_apply_choices() { assert!( (chart.state().price_scale().range().length() - before / 2.0).abs() < 0.00001 ); + } else if hours { + assert!(chart.extended_hours(), "redo applies the choice again"); + assert!(chart.undo()); + assert!(!chart.extended_hours(), "undo restores the earlier session"); + chart.set_extended_hours(true); + assert!(!chart.can_undo(), "a host call is no user action"); } else if time { assert_eq!( chart.chart_options().time_scale.timezone, TimezoneMode::Local ); + } else if let Some(pane) = pane { + let axis = crate::widget::PaneScale::Named(crate::model::SeriesScale::Right); + assert_eq!( + chart.pane_scale(pane, axis).unwrap().options().mode, + PriceScaleMode::Percentage + ); } else { assert_eq!( chart.state().price_scale().options().mode, @@ -478,6 +523,151 @@ fn axis_right_clicks_open_menus_and_apply_choices() { } } +/// A touch held on a price axis or on the time axis opens that axis' menu, which stays open once +/// the finger lifts. A drag still zooms the scale and a double tap resets it, and neither opens +/// a menu. +#[test] +fn long_press_opens_the_axis_menus() { + use egui::{Shape, TouchDeviceId, TouchId, TouchPhase}; + // The main price axis, a study pane's axis, an added series' axis and the time axis. + let key = crate::model::SeriesScale::Separate(1); + for axis in ["price", "pane", "series", "time"] { + let ctx = Context::default(); + let mut chart = crate::widget::test_frames::chart(&[100.0], &[110.0]); + let study = chart.add_indicator(Box::new(crate::studies::RSI::new(14))); + if axis == "series" { + let series = chart.add_series(crate::widget::SeriesOptions { + scale: key, + ..Default::default() + }); + chart.set_data(series, chart.state().data().bars.clone()); + } + let mut menus = ChartMenus::default(); + let mut now = 0.0; + let mut frame = |chart: &mut Chart, menus: &mut ChartMenus, wait: f64, events| { + now += wait; + let mut output = ctx.run_ui( + RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0))), + time: Some(now), + events, + ..Default::default() + }, + |ui| { + egui::CentralPanel::default().show(ui, |ui| { + chart.show(ui); + }); + menus.show(ui.ctx(), chart); + }, + ); + let shapes = std::mem::take(&mut output.shapes); + output.drop_without_applying_deltas(); + shapes + }; + frame(&mut chart, &mut menus, 0.0, vec![]); + let pane = chart.series_pane(study).unwrap(); + let plot = chart.get_rendered_price_rect(); + let panel = chart.get_rendered_indicator_panes()[0].panel_rect; + let (pos, slide) = match axis { + "price" => ( + Pos2::new(plot.right() + 25.0, plot.center().y), + Vec2::new(0.0, 40.0), + ), + "pane" => ( + Pos2::new(plot.right() + 25.0, panel.center().y), + Vec2::new(0.0, 40.0), + ), + "series" => ( + Pos2::new(plot.left() - 10.0, plot.center().y), + Vec2::new(0.0, 40.0), + ), + _ => ( + Pos2::new(plot.center().x, panel.bottom() + 10.0), + Vec2::new(40.0, 0.0), + ), + }; + let zoomed = |chart: &Chart| match axis { + "price" => chart.state().price_scale().is_manual(), + "pane" => { + let axis = crate::widget::PaneScale::Named(crate::model::SeriesScale::Right); + chart.pane_scale(pane, axis).unwrap().is_manual() + } + "series" => { + let axis = crate::widget::PaneScale::Named(key); + let pane = crate::widget::PaneId::MAIN; + chart.pane_scale(pane, axis).unwrap().is_manual() + } + _ => chart.get_time_scale_state().0 != chart.chart_options().time_scale.bar_spacing, + }; + assert!(!zoomed(&chart), "{axis}: the scale starts fitted"); + let touch = |phase, pos| Event::Touch { + device_id: TouchDeviceId(1), + id: TouchId(1), + phase, + pos, + force: None, + }; + let button = |pos, pressed| Event::PointerButton { + pos, + button: PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }; + let press = |pos| { + vec![ + touch(TouchPhase::Start, pos), + Event::PointerMoved(pos), + button(pos, true), + ] + }; + let slide_to = |pos| vec![touch(TouchPhase::Move, pos), Event::PointerMoved(pos)]; + let lift = |pos| { + vec![ + touch(TouchPhase::End, pos), + button(pos, false), + Event::PointerGone, + ] + }; + + // A drag, held at its end for longer than a long press takes. + frame(&mut chart, &mut menus, 0.1, press(pos)); + frame(&mut chart, &mut menus, 0.1, slide_to(pos + slide / 2.0)); + frame(&mut chart, &mut menus, 0.1, slide_to(pos + slide)); + frame(&mut chart, &mut menus, 1.0, vec![]); + frame(&mut chart, &mut menus, 0.1, lift(pos + slide)); + assert!(!chart.menu_open, "{axis}: a drag opens no menu"); + assert!(zoomed(&chart), "{axis}: a drag zooms the scale"); + + for _ in 0..2 { + frame(&mut chart, &mut menus, 0.1, press(pos)); + frame(&mut chart, &mut menus, 0.05, lift(pos)); + } + assert!(!chart.menu_open, "{axis}: a double tap opens no menu"); + assert!(!zoomed(&chart), "{axis}: a double tap resets the scale"); + + frame(&mut chart, &mut menus, 1.0, press(pos)); + frame(&mut chart, &mut menus, 0.5, vec![]); + assert!(!chart.menu_open, "{axis}: a touch held for half a second"); + frame(&mut chart, &mut menus, 0.5, vec![]); + let shapes = frame(&mut chart, &mut menus, 0.1, lift(pos)); + assert!( + chart.menu_open, + "{axis}: the menu stays once the finger lifts" + ); + let row = if axis == "time" { + "Session breaks" + } else { + "Auto scale" + }; + assert!( + shapes.iter().any( + |shape| matches!(&shape.shape, Shape::Text(text) if text.galley.text() == row) + ), + "{axis}: a held touch opens the menu with {row}" + ); + } +} + #[test] fn opening_a_menu_suppresses_hover_paint_in_the_same_frame() { use egui::{Event, PointerButton, RawInput, Shape}; diff --git a/vendor/egui-charts/src/ui/dialogs/alert_dialog/dialog.rs b/vendor/egui-charts/src/ui/dialogs/alert_dialog/dialog.rs index e6c2e90..a5c2afc 100644 --- a/vendor/egui-charts/src/ui/dialogs/alert_dialog/dialog.rs +++ b/vendor/egui-charts/src/ui/dialogs/alert_dialog/dialog.rs @@ -12,7 +12,7 @@ use super::{AlertDialogAction, AlertDialogConfig}; use crate::data::{FeedError, inbox::Inbox}; use crate::model::{ Alert, AlertChannelComparison, AlertComparison, AlertCondition, AlertFrequency, AlertRule, - AlertSource, NotificationSchedule, NotificationWindow, Timeframe, TimezoneId, + AlertSource, AlertSourceName, NotificationSchedule, NotificationWindow, Timeframe, TimezoneId, }; use crate::services::{Storage, StoreKind}; use crate::ui_kit::FormGrid; @@ -28,10 +28,10 @@ pub struct AlertDialog { pub is_open: bool, /// Staged edits. Cancel never submits them. pub alert: Alert, - /// Host-provided study outputs and drawings, as stable identifiers and display names. Presets - /// compare the names to tell a study they store from another chart's study with the same - /// identifier. - pub sources: Vec<(AlertSource, String)>, + /// Host-provided study outputs and drawings, as stable identifiers and names, which are + /// translated when shown. Presets compare the names' English text to tell a study they + /// store from another chart's study with the same identifier. + pub sources: Vec<(AlertSource, AlertSourceName)>, /// Host-provided watchlist identifiers and display names. pub watchlists: Vec<(String, String)>, /// The zone the expiry date and time are entered in, UTC by default. Set it before @@ -1043,19 +1043,23 @@ fn rule_preview( source: &AlertSource, condition: &AlertCondition, interval: Timeframe, - sources: &[(AlertSource, String)], + sources: &[(AlertSource, AlertSourceName)], ) -> String { let name = |source: &AlertSource| { - let label = sources + sources .iter() .find(|(value, _)| value == source) - .map(|(_, label)| label.clone()) - .unwrap_or_else(|| match source { - AlertSource::Price => "Price".into(), - AlertSource::Volume => "Volume".into(), - _ => format!("{source:?}"), - }); - l10n::text(ctx, label) + .map(|(_, label)| label.text(ctx)) + .unwrap_or_else(|| { + l10n::text( + ctx, + match source { + AlertSource::Price => "Price".into(), + AlertSource::Volume => "Volume".into(), + _ => format!("{source:?}"), + }, + ) + }) }; let others: Vec<_> = condition .partners() @@ -1079,24 +1083,26 @@ fn source_picker( ui: &mut Ui, id: &str, source: &mut AlertSource, - sources: &[(AlertSource, String)], + sources: &[(AlertSource, AlertSourceName)], ) { let label = sources .iter() .find(|(value, _)| value == source) - .map(|(_, name)| name.clone()) - .unwrap_or_else(|| format!("{source:?}")); + .map_or_else( + || l10n::text(ui.ctx(), format!("{source:?}")), + |(_, name)| name.text(ui.ctx()), + ); egui::ComboBox::from_id_salt(id) .width(ui.available_width().min(200.0)) .truncate() - .selected_text(l10n::text(ui.ctx(), label)) + .selected_text(label) .show_ui(ui, |ui| { if !id.starts_with("boundary_") { ui.selectable_value(source, AlertSource::Price, l10n::text(ui.ctx(), "Price")); ui.selectable_value(source, AlertSource::Volume, l10n::text(ui.ctx(), "Volume")); } for (value, name) in sources { - ui.selectable_value(source, value.clone(), l10n::text(ui.ctx(), name)); + ui.selectable_value(source, value.clone(), name.text(ui.ctx())); } }) .response @@ -1122,7 +1128,7 @@ fn drawing_id(source: &AlertSource) -> Option<&str> { fn drawing_channel( source: &AlertSource, condition: &AlertCondition, - sources: &[(AlertSource, String)], + sources: &[(AlertSource, AlertSourceName)], ) -> Option { if let AlertCondition::Channel { .. } = condition { return Some(condition.clone()); @@ -1158,7 +1164,7 @@ pub(crate) fn rule_form( ui: &mut Ui, source: &mut AlertSource, condition: &mut AlertCondition, - sources: &[(AlertSource, String)], + sources: &[(AlertSource, AlertSourceName)], ) { ui.add_enabled_ui( !matches!( @@ -1580,6 +1586,70 @@ mod tests { } } + /// Names the chart builds keep their parts through storage, so the source list shows the + /// study output, drawing tool and level translated around the study name, drawing number and + /// level value, and an alert saved with finished names restores its source and takes the + /// chart's parts when edited. + #[test] + fn chart_built_source_names_reach_the_translator_and_saved_names_restore() { + use crate::drawings::{ChartPoint, Drawing, DrawingToolType}; + use crate::model::{AlertInputs, Bar, BarData}; + use egui_kittest::{Harness, kittest::Queryable}; + let bars = (0..4) + .map(|i| { + let time = DateTime::from_timestamp(60 * i, 0).unwrap(); + Bar::new(time, 100.0, 100.0, 100.0, 100.0, 1.0) + }) + .collect(); + let mut chart = crate::Chart::new(BarData::from_bars(bars)); + chart.add_indicator(Box::new(crate::studies::MACD::new(12, 26, 9))); + let mut fork = Drawing::new(7, DrawingToolType::Pitchfork); + fork.chart_points = vec![ + ChartPoint::new(0.0, 100.0), + ChartPoint::new(1.0, 200.0), + ChartPoint::new(2.0, 50.0), + ]; + // Saved without a config: levels 0, 0.5, 1 and 1.5, all shown. + fork.pitchfork = None; + fork.completed = true; + let line = fork.alert_source(2); + chart.drawings_mut().drawings.push(fork); + + let stored = serde_json::to_string(&chart.alert_inputs()).unwrap(); + let inputs: AlertInputs = serde_json::from_str(&stored).unwrap(); + let mut fresh = AlertDialog::new(); + fresh.open("SAMPLE".into(), 100.0); + fresh.sources = inputs.sources; + + let mut saved = Alert::new("SAMPLE", AlertCondition::Crossing(100.0)); + saved.source = line; + saved.inputs = Some(Box::new(chart.alert_inputs())); + let mut stored = serde_json::to_value(&saved).unwrap(); + // Alerts saved before names kept their parts hold the finished English text. + stored["inputs"]["sources"] = + serde_json::json!([[{"Drawing": "7#2"}, "Pitchfork 7: 0.5: first line"]]); + let mut saved: Alert = serde_json::from_value(stored).unwrap(); + chart.prepare_alert(&mut saved); + let mut restored = AlertDialog::new(); + restored.edit(saved); + + // Words drop out under `mark_keys` and values stay: MACD's Signal and Histogram, the + // median, and the first and second lines at 0.5, of which the restored alert saved one. + for dialog in [fresh, restored] { + let mut h = Harness::builder() + .with_size(egui::vec2(600.0, 900.0)) + .build_ui_state(|ui, dialog: &mut AlertDialog| dialog.form(ui), dialog); + h.run(); + h.get_by_label("Source").click(); + h.run(); + crate::localization::mark_keys(&h.ctx); + h.run(); + for (label, count) in [("~MACD~~~", 2), ("~~~7~~~", 1), ("~~~7~0.5~", 2)] { + assert_eq!(h.query_all_by_label(label).count(), count, "{label}"); + } + } + } + #[test] fn form_controls_fill_the_dialog_width_for_each_source() { for (source, condition) in [ @@ -1647,7 +1717,7 @@ mod tests { dialog.alert.frequency = AlertFrequency::OncePerBarClose; dialog.sources.push(( AlertSource::Drawing("7".into()), - "A long drawing name".repeat(4), + "A long drawing name".repeat(4).into(), )); dialog.alert.additional_conditions.push(AlertRule { source: AlertSource::Volume, @@ -1665,7 +1735,7 @@ mod tests { }); dialog.sources.push(( AlertSource::Drawing("7#1".into()), - "A long second boundary name".repeat(4), + "A long second boundary name".repeat(4).into(), )); dialog.alert.additional_conditions.push(AlertRule { source: AlertSource::Price, @@ -2074,7 +2144,7 @@ mod tests { assert!(failing.presets.is_empty()); assert!(failing.error.is_some()); - *store.0.lock().unwrap() = Some(r#"{"version":3,"presets":{}}"#.into()); + *store.0.lock().unwrap() = Some(r#"{"version":4,"presets":{}}"#.into()); restored.set_storage(store); restored.poll(&ctx); assert!(!restored.loaded); diff --git a/vendor/egui-charts/src/ui/dialogs/alert_dialog/preset.rs b/vendor/egui-charts/src/ui/dialogs/alert_dialog/preset.rs index 6ae9307..756eff3 100644 --- a/vendor/egui-charts/src/ui/dialogs/alert_dialog/preset.rs +++ b/vendor/egui-charts/src/ui/dialogs/alert_dialog/preset.rs @@ -8,14 +8,15 @@ use serde::{Deserialize, Serialize}; use crate::model::{ Alert, AlertChannelComparison, AlertComparison, AlertCondition, AlertDelivery, AlertFrequency, - AlertRule, AlertSource, NotificationSchedule, Timeframe, + AlertRule, AlertSource, AlertSourceName, NotificationSchedule, Timeframe, }; /// How many presets the user can keep. pub(super) const MAX_PRESETS: usize = 5; -/// The stored document's current version. Version 1 kept whole alerts. -const VERSION: u32 = 2; +/// The stored document's current version. Version 1 kept whole alerts, version 2 source names +/// as finished text. +const VERSION: u32 = 3; /// Which groups of settings a preset stores and restores. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -71,7 +72,7 @@ pub(super) struct AlertPreset { rules: Vec, /// The saving chart's names for what `rules` test: studies are numbered per chart, so an id /// alone may name another study elsewhere. Presets saved without names have none. - source_names: Vec<(AlertSource, String)>, + source_names: Vec<(AlertSource, AlertSourceName)>, timeframe: Option, additional_timeframes: Vec>, frequency: AlertFrequency, @@ -88,7 +89,7 @@ impl AlertPreset { /// entered times do. `sources` names what its chart offers. pub(super) fn capture( alert: &Alert, - sources: &[(AlertSource, String)], + sources: &[(AlertSource, AlertSourceName)], fields: PresetFields, now: DateTime, ) -> Self { @@ -162,7 +163,7 @@ impl AlertPreset { pub(super) fn apply( &self, alert: &mut Alert, - sources: &[(AlertSource, String)], + sources: &[(AlertSource, AlertSourceName)], now: DateTime, ) { let fills = matches!(alert.condition, AlertCondition::StrategyFills(_)); @@ -300,8 +301,8 @@ fn restored_condition( stored: &AlertCondition, current: &AlertCondition, replaces: bool, - names: &[(AlertSource, String)], - sources: &[(AlertSource, String)], + names: &[(AlertSource, AlertSourceName)], + sources: &[(AlertSource, AlertSourceName)], ) -> Option { use AlertCondition as C; let levels = match current { @@ -379,8 +380,8 @@ fn restored_condition( fn restored_source( stored: &AlertSource, current: &AlertSource, - names: &[(AlertSource, String)], - sources: &[(AlertSource, String)], + names: &[(AlertSource, AlertSourceName)], + sources: &[(AlertSource, AlertSourceName)], ) -> AlertSource { if matches!(current, AlertSource::Drawing(_)) || !offered(stored, names, sources) { current.clone() @@ -394,8 +395,8 @@ fn restored_source( /// accepts the identifier only when it is unambiguous. fn offered( source: &AlertSource, - names: &[(AlertSource, String)], - sources: &[(AlertSource, String)], + names: &[(AlertSource, AlertSourceName)], + sources: &[(AlertSource, AlertSourceName)], ) -> bool { match source { AlertSource::Price | AlertSource::Volume => true, @@ -453,7 +454,7 @@ pub(super) fn to_document( /// Read a stored document. Whole alerts from version 1 become presets of every group except an /// expiry, whose duration they did not record; a later save rewrites them without their excluded /// values. Any other version is an error, so that a save cannot overwrite it. The remembered -/// schedule is read from either version. +/// schedule is read from each of them. pub(super) fn from_document( document: &str, now: DateTime, @@ -475,7 +476,8 @@ pub(super) fn from_document( .collect() }) .map_err(|error| error.to_string()), - VERSION => serde_json::from_value(document.presets).map_err(|error| error.to_string()), + // Version 2 holds every source name as finished text, which loads as a name without parts. + 2 | VERSION => serde_json::from_value(document.presets).map_err(|error| error.to_string()), _ => Err("Unsupported alert preset version".into()), }; presets.map(|presets| (presets, document.last_schedule)) @@ -823,7 +825,7 @@ mod tests { C::Below(100.0), ), ]; - let sources = [(study(), "RSI signal".to_owned())]; + let sources = [(study(), AlertSourceName::from("RSI signal"))]; for (stored_source, stored, current_source, current, source, condition) in cases { let mut saved = Alert::new("OLD", stored.clone()); saved.source = stored_source; @@ -981,7 +983,7 @@ mod tests { fn rules_a_preset_adds_take_their_stored_operators() { use AlertCondition as C; let now = Utc.with_ymd_and_hms(2026, 1, 1, 10, 0, 0).unwrap(); - let sources = [(study(), "RSI signal".to_owned())]; + let sources = [(study(), AlertSourceName::from("RSI signal"))]; let rule = |source, condition| AlertRule { source, condition }; let crossing_up_plot = C::Compare { other: study(), @@ -1045,7 +1047,7 @@ mod tests { id: "2".into(), output: 0, }; - let named = |name: &str| (plot.clone(), name.to_owned()); + let named = |name: &str| (plot.clone(), AlertSourceName::from(name)); let crossing_up_plot = AlertCondition::Compare { other: plot.clone(), comparison: AlertComparison::CrossingUp, @@ -1069,6 +1071,26 @@ mod tests { serde_json::json!({"Compare": {"other": study, "comparison": "CrossingUp"}}), serde_json::json!("Price"), ); + // What this file stored before names kept their parts: the name as finished text. + let saved_on_rsi = from_document( + r#"{"version": 2, "presets": {"P": { + "rules": [{"source": {"Study": {"id": "2", "output": 0}}, "condition": {"Above": 0.0}}], + "source_names": [[{"Study": {"id": "2", "output": 0}}, "RSI: RSI"]] + }}}"#, + now, + ) + .unwrap() + .0 + .remove("P") + .unwrap(); + let built_rsi = [( + plot.clone(), + AlertSourceName::new( + "{study}: {output}", + &[("study", "RSI")], + &[("output", "RSI")], + ), + )]; let rsi = [named("RSI: RSI")]; let sma = [named("SMA: SMA")]; @@ -1080,7 +1102,7 @@ mod tests { let crossing_level = (AlertSource::Price, AlertCondition::CrossingUp(100.0)); let reused_source = (plot.clone(), AlertCondition::Above(100.0)); let reused_other = (AlertSource::Price, crossing_up_plot); - let rows: [(&AlertPreset, &[(AlertSource, String)], _); 8] = [ + let rows: [(&AlertPreset, &[(AlertSource, AlertSourceName)], _); 10] = [ // Another chart's study 2 is not the stored one. (&on_plot, &macd, &kept_on_level), (&crossing, &macd, &crossing_level), @@ -1092,6 +1114,9 @@ mod tests { (&unnamed_crossing, &macd, &reused_other), (&unnamed_on_plot, &twice, &kept_on_level), (&unnamed_crossing, &twice, &crossing_level), + // A name saved as finished text is the chart's name with the same English text. + (&saved_on_rsi, &built_rsi, &reused_source), + (&saved_on_rsi, &macd, &kept_on_level), ]; for (index, (preset, sources, expected)) in rows.into_iter().enumerate() { let mut alert = Alert::new("NEW", AlertCondition::Crossing(100.0)); diff --git a/vendor/egui-charts/src/ui/dialogs/chart_settings/mod.rs b/vendor/egui-charts/src/ui/dialogs/chart_settings/mod.rs index dc1e382..4c0ba0e 100644 --- a/vendor/egui-charts/src/ui/dialogs/chart_settings/mod.rs +++ b/vendor/egui-charts/src/ui/dialogs/chart_settings/mod.rs @@ -68,6 +68,10 @@ pub struct SettingsDialog { sound_preview: Option<(String, f32)>, /// Heatmap, book, individual orders and bubbles offered by the host. order_flow_layers: [bool; 4], + /// Whether the host's feed answers analyst price targets for the chart's instrument. + price_targets_offered: bool, + /// The axis font family the dialog was opened with, shown while the settings hold none. + opened_font_family: Option, } #[derive(Clone, Default)] @@ -187,6 +191,8 @@ impl SettingsDialog { execution_sounds: Vec::new(), sound_preview: None, order_flow_layers: [true; 4], + price_targets_offered: true, + opened_font_family: None, } } @@ -206,27 +212,31 @@ impl SettingsDialog { } } - /// Restrict Order flow controls to services explicitly declared for the chart's instrument. + /// Restrict Order flow controls and the Analyst price targets setting to services explicitly + /// declared for the chart's instrument + /// ([`FeedService::PriceTargets`](crate::model::FeedService::PriceTargets) for the targets). /// Pass [`Chart::feed_capabilities`](crate::Chart::feed_capabilities) and /// [`Chart::instrument`](crate::Chart::instrument) again when they change. A missing instrument - /// or a non-positive, non-finite or missing tick size hides the tab. Before the first call, - /// all layers are offered. Hidden controls retain their saved values. + /// hides both; a non-positive, non-finite or missing tick size hides the Order flow tab only. + /// Before the first call, everything is offered. Hidden controls retain their saved values. pub fn set_feed_capabilities( &mut self, capabilities: Option<&crate::data::FeedCapabilities>, instrument: Option<&crate::model::Instrument>, ) { use crate::model::FeedService; - let declares = |service| { + let declared = |service| { instrument.is_some_and(|instrument| { - instrument - .tick_size - .is_some_and(|tick| tick.is_finite() && tick > 0.0) - && capabilities - .unwrap_or(&crate::data::FeedCapabilities::default()) - .declares(service, instrument) + capabilities + .unwrap_or(&crate::data::FeedCapabilities::default()) + .declares(service, instrument) }) }; + // The tick size gates Order flow only: targets are prices from the feed. + let ticked = instrument + .and_then(|instrument| instrument.tick_size) + .is_some_and(|tick| tick.is_finite() && tick > 0.0); + let declares = |service| ticked && declared(service); let depth = declares(FeedService::Depth); self.order_flow_layers = [ depth || declares(FeedService::DepthHistory), @@ -234,6 +244,7 @@ impl SettingsDialog { depth && declares(FeedService::OrderDepth), declares(FeedService::Trades) || declares(FeedService::LiveTrades), ]; + self.price_targets_offered = declared(FeedService::PriceTargets); if !self.order_flow_layers.iter().any(|available| *available) && self.active_tab == SettingsTab::OrderFlow { @@ -247,6 +258,7 @@ impl SettingsDialog { self.template_menu_open = false; self.save_name = None; self.sound_preview = None; + self.opened_font_family = settings.scales_appearance.font_family.clone(); self.settings = settings; self.active_tab = SettingsTab::Symbol; self.update_color_pickers_from_settings(); @@ -458,7 +470,7 @@ impl SettingsDialog { .or_else(|| { (self.margin_top_str.parse::().is_err() || self.margin_bottom_str.parse::().is_err() - || self.margin_right_str.parse::().is_err()) + || self.margin_right_str.parse::().is_err()) .then(|| "Enter valid margins".to_owned()) }); let (ok, cancel) = DialogFooter::new("Ok") @@ -743,10 +755,38 @@ impl SettingsDialog { .clone() .or_else(|| self.settings.chart_type_params.clone()); let source = template.price_source.or(self.settings.price_source); + // Choices a template saved before they existed lacks stay as the dialog shows + // them. Its font family stays unset: that keeps the chart's, and tells + // `apply_to_chart` that the template holds the whole bars of a right margin. + let scales = &self.settings.scales_and_lines; + let line_source = template + .scales_and_lines + .price_line_source + .or(scales.price_line_source); + let separator = template + .scales_and_lines + .thousands_sep + .or(scales.thousands_sep); + let session_breaks = template + .show_session_breaks + .or(self.settings.show_session_breaks); + // The whole bars of the margin shown are an unedited margin, which stays as shown. + let shown = self.settings.margins.right_bars; + let right_bars = if template.scales_appearance.font_family.is_none() + && template.margins.right_bars == shown.trunc() + { + shown + } else { + template.margins.right_bars + }; self.settings = template.clone(); self.settings.chart_type = kind; self.settings.chart_type_params = params; self.settings.price_source = source; + self.settings.scales_and_lines.price_line_source = line_source; + self.settings.scales_and_lines.thousands_sep = separator; + self.settings.show_session_breaks = session_breaks; + self.settings.margins.right_bars = right_bars; // A template saved before volume candles had a style shows what they drew, which // Ok then applies with any edits made before it. if kind == crate::model::ChartType::VolumeCandles @@ -815,8 +855,14 @@ impl SettingsDialog { chart_type: self.settings.chart_type, chart_type_params: Some(Default::default()), price_source: Some(Default::default()), + show_session_breaks: Some(false), ..Default::default() }; + // What a new chart holds, where the default settings hold no choice. + self.settings.scales_appearance.font_family = Some(Default::default()); + self.settings.scales_and_lines.price_line_source = Some(Default::default()); + self.settings.scales_and_lines.thousands_sep = + Some(crate::widget::settings::ThousandsSeparator::Comma); let palette = crate::config::ChartConfig::default().with_theme(theme); // The default styles of the chart types hold the dark preset's candle colours. let params = self.settings.chart_type_params.get_or_insert_default(); @@ -898,6 +944,8 @@ mod tests { settings.grid_lines.vertical_color = Color32::BLUE; settings.crosshair.color = Color32::YELLOW; settings.watermark.color = Color32::RED; + settings.margins.top_percent = 12.5; + settings.margins.bottom_percent = 7.5; let mut dialog = SettingsDialog::new(); dialog.set_control_visible(Control::Templates, templates_visible); dialog.open(settings); @@ -1041,10 +1089,149 @@ mod tests { mismatches.is_empty(), "{preset}, templates visible: {templates_visible}, {size:?}: {mismatches:?}" ); + // A new chart keeps a tenth of the pane free above and below, and 2.5 bars after + // the last one. + let price = chart.state().price_scale().options().scale_margins; + assert_eq!( + ( + price.top, + price.bottom, + chart.chart_options().time_scale.right_offset + ), + (0.1, 0.1, 2.5), + "{preset}: margins" + ); } } } + /// A palette swatch recolours a Canvas colour at the opacity its well shows, which no other + /// control of the tab sets; an invisible colour takes the swatch's opacity. Expected: the + /// swatch rgb(49, 27, 146) at the seeded alpha of 128, and opaque where the well showed an + /// invisible colour or the theme's opaque crosshair. + #[test] + fn palette_colour_keeps_the_watermark_opacity() { + use crate::widget::settings::{BackgroundType, GridLinesMode}; + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + + type Row = fn(&mut ChartSettingsState) -> &mut Color32; + let translucent = Color32::from_rgba_unmultiplied(255, 0, 255, 128); + let theme = Theme::light(); + let rows: [(&str, Row, Color32, u8); 11] = [ + ("watermark", |s| &mut s.watermark.color, translucent, 128), + ( + "background", + |s| &mut s.chart_basic_styles.background_color, + translucent, + 128, + ), + ( + "gradient top", + |s| &mut s.chart_basic_styles.background_gradient_top, + translucent, + 128, + ), + ( + "gradient bottom", + |s| &mut s.chart_basic_styles.background_gradient_bottom, + translucent, + 128, + ), + ( + "horizontal grid", + |s| &mut s.grid_lines.horizontal_color, + translucent, + 128, + ), + ( + "vertical grid", + |s| &mut s.grid_lines.vertical_color, + translucent, + 128, + ), + ("crosshair", |s| &mut s.crosshair.color, translucent, 128), + ( + "scale text", + |s| &mut s.scales_appearance.text_color, + translucent, + 128, + ), + ( + "scale lines", + |s| &mut s.scales_appearance.lines_color, + translucent, + 128, + ), + ( + "invisible scale lines", + |s| &mut s.scales_appearance.lines_color, + Color32::TRANSPARENT, + 255, + ), + // The well shows the theme's opaque crosshair, not the translucent placeholder. + ( + "crosshair following the theme", + |s| &mut s.crosshair.color, + Color32::PLACEHOLDER, + 255, + ), + ]; + for (name, row, seeded, alpha) in rows { + let shown = if seeded == Color32::PLACEHOLDER { + theme.chart.crosshair_line + } else { + seeded + }; + let mut settings = ChartSettingsState::default(); + settings.grid_lines.mode = GridLinesMode::Both; + if name.starts_with("gradient") { + settings.chart_basic_styles.background_type = BackgroundType::VerticalGradient; + } + *row(&mut settings) = seeded; + let mut dialog = SettingsDialog::new(); + dialog.set_control_visible(Control::Templates, false); + dialog.open(settings); + dialog.active_tab = SettingsTab::Canvas; + let (shown_theme, setup_theme) = (theme.clone(), theme.clone()); + let mut harness = Harness::builder() + .with_context_setup(move |ctx| { + egui_extras::install_image_loaders(ctx); + crate::theme::apply_to_egui(ctx, &setup_theme); + }) + .with_size(Vec2::new(1440.0, 900.0)) + .build_ui_state( + move |ui, (dialog, accepted): &mut (SettingsDialog, _)| { + if let SettingsAction::Apply(settings) = dialog.show(ui.ctx(), &shown_theme) + { + *accepted = Some(settings); + } + }, + (dialog, None), + ); + harness.run(); + let [r, g, b, _] = shown.to_srgba_unmultiplied(); + let well = format!("#{r:02X}{g:02X}{b:02X}"); + harness + .get_by_role_and_label(Role::ColorWell, &well) + .click(); + harness.run(); + harness + .get_by_role_and_label(Role::ColorWell, "#311B92") + .click(); + harness.run(); + harness.get_by_label("Ok").click(); + harness.run(); + let (_, accepted) = harness.state_mut(); + let accepted: &mut ChartSettingsState = accepted.as_mut().expect("accepted"); + assert_eq!( + *row(accepted), + Color32::from_rgba_unmultiplied(49, 27, 146, alpha), + "{name}" + ); + } + } + #[test] fn enabled_sound_controls_offer_a_preview_without_applying_settings() { let ctx = Context::default(); @@ -1443,37 +1630,56 @@ mod tests { Depth, DepthHistory, OrderDepth, + PriceTargets, ]); - for (services, tick, expected) in [ - (None, Some(0.25), [true, true, true, true]), + for (services, tick, expected, targets) in [ + (None, Some(0.25), [true, true, true, true], true), ( Some(vec![LiveTrades]), Some(0.25), [false, false, false, true], + false, + ), + ( + Some(vec![Trades]), + Some(0.25), + [false, false, false, true], + false, + ), + ( + Some(vec![Depth]), + Some(0.25), + [true, true, false, false], + false, ), - (Some(vec![Trades]), Some(0.25), [false, false, false, true]), - (Some(vec![Depth]), Some(0.25), [true, true, false, false]), ( Some(vec![DepthHistory]), Some(0.25), [true, false, false, false], + false, ), ( Some(vec![Depth, OrderDepth]), Some(0.25), [true, true, true, false], + false, ), - (Some(vec![OrderDepth]), Some(0.25), [false; 4]), - (Some(vec![]), Some(0.25), [false; 4]), - (Some(vec![Depth]), None, [false; 4]), - (Some(vec![Depth]), Some(0.0), [false; 4]), - (Some(vec![Depth]), Some(f64::NAN), [false; 4]), + (Some(vec![OrderDepth]), Some(0.25), [false; 4], false), + (Some(vec![]), Some(0.25), [false; 4], false), + (Some(vec![Depth]), None, [false; 4], false), + (Some(vec![Depth]), Some(0.0), [false; 4], false), + (Some(vec![Depth]), Some(f64::NAN), [false; 4], false), + (Some(vec![PriceTargets]), Some(0.25), [false; 4], true), + (Some(vec![PriceTargets]), None, [false; 4], true), ] { let ctx = Context::default(); let theme = Theme::light(); crate::theme::apply_to_egui(&ctx, &theme); let mut dialog = SettingsDialog::new(); - dialog.open(ChartSettingsState::default()); + dialog.open(ChartSettingsState { + show_price_targets: true, + ..Default::default() + }); let mut instrument = Instrument::new("A"); instrument.services = services; instrument.tick_size = tick; @@ -1492,15 +1698,23 @@ mod tests { dialog.show(ui.ctx(), &theme); }, ); - let tab = output.shapes.iter().any(|shape| { - matches!(&shape.shape, - egui::Shape::Text(text) if text.galley.text() == "Order flow") - }); + let shown = |label: &str| { + output.shapes.iter().any(|shape| { + matches!(&shape.shape, + egui::Shape::Text(text) if text.galley.text() == label) + }) + }; + let (tab, offered) = (shown("Order flow"), shown("Analyst price targets")); output.drop_without_applying_deltas(); if pass == 2 { assert_eq!(tab, expected.iter().any(|available| *available)); + assert_eq!(offered, targets, "price targets"); } } + assert!( + dialog.settings.show_price_targets, + "a hidden setting keeps its value" + ); // Existing overlay configs define fallback behaviour for these values. dialog.settings.order_flow.heatmap.full_intensity_size = Some(0.0); dialog.settings.order_flow.volume_bubbles.grouping = @@ -1529,14 +1743,17 @@ mod tests { dialog.active_tab = SettingsTab::OrderFlow; dialog.set_feed_capabilities(Some(&feed), None); assert_eq!(dialog.active_tab, SettingsTab::Symbol); + assert!(!dialog.price_targets_offered); } let mut dialog = SettingsDialog::new(); assert_eq!(dialog.order_flow_layers, [true; 4]); + assert!(dialog.price_targets_offered); let instrument = Instrument::new("A") .with_tick_size(0.25) .with_services([Depth]); dialog.set_feed_capabilities(None, Some(&instrument)); assert_eq!(dialog.order_flow_layers, [true, true, false, false]); + assert!(!dialog.price_targets_offered); dialog.set_feed_capabilities( Some(&FeedCapabilities::new().with_services([])), Some(&instrument), @@ -1544,6 +1761,11 @@ mod tests { assert_eq!(dialog.order_flow_layers, [false; 4]); dialog.set_feed_capabilities(None, Some(&Instrument::new("A").with_tick_size(0.25))); assert_eq!(dialog.order_flow_layers, [false; 4]); + dialog.set_feed_capabilities( + None, + Some(&Instrument::new("A").with_services([PriceTargets])), + ); + assert!(dialog.price_targets_offered); } #[test] @@ -1822,4 +2044,265 @@ mod tests { assert_eq!([style.border_up, style.wick_down], [up, down], "{entry}"); } } + + /// Clicks the texts `labels` name one after the other in a 1440 by 900 window, as opening a + /// dropdown, picking an entry and pressing Ok do, and returns the action of the last click. + fn click_through(dialog: &mut SettingsDialog, labels: &[&str]) -> SettingsAction { + fn center(shape: &egui::Shape, label: &str) -> Option { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().find_map(|shape| center(shape, label)), + egui::Shape::Text(text) if text.galley.text() == label => { + Some(text.pos + text.galley.size() / 2.0) + } + _ => None, + } + } + let ctx = Context::default(); + let theme = Theme::light(); + crate::theme::apply_to_egui(&ctx, &theme); + let mut frame = |events, label: &str| { + let mut action = SettingsAction::None; + let output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::new(1440.0, 900.0))), + events, + ..Default::default() + }, + |ui| action = dialog.show(ui.ctx(), &theme), + ); + let pos = output + .shapes + .iter() + .find_map(|shape| center(&shape.shape, label)); + output.drop_without_applying_deltas(); + (action, pos) + }; + let mut action = SettingsAction::None; + for label in labels { + frame(vec![], label); + let pos = frame(vec![], label).1.expect(label); + frame(vec![egui::Event::PointerMoved(pos)], label); + for pressed in [true, false] { + action = frame( + vec![egui::Event::PointerButton { + pos, + pressed, + button: egui::PointerButton::Primary, + modifiers: Default::default(), + }], + label, + ) + .0; + } + } + action + } + + /// Choosing a family next to the font size draws the labels of the price, study and time + /// axes in it. + #[test] + fn axis_font_family_is_chosen_in_the_dialog() { + use crate::widget::test_frames::{chart, frame, shapes}; + use egui::FontFamily; + let ctx = Context::default(); + let mut chart = chart(&[100.0, 105.0], &[110.0, 115.0]); + chart.add_indicator(Box::new(crate::studies::RSI::new(14))); + frame(&ctx, &mut chart, 0.0, Vec::new()); + let mut dialog = SettingsDialog::new(); + dialog.open(ChartSettingsState::from_chart(&chart)); + dialog.active_tab = SettingsTab::Canvas; + let action = click_through(&mut dialog, &["Proportional", "Monospace", "Ok"]); + let SettingsAction::Apply(settings) = action else { + panic!("Ok must apply the settings"); + }; + settings.apply_to_chart(&mut chart).unwrap(); + frame(&ctx, &mut chart, 0.1, Vec::new()); + let painted = shapes(&ctx, &mut chart, 0.2, Vec::new()); + let plot = chart.get_rendered_price_rect(); + let panes = chart.get_rendered_indicator_panes(); + let pane = panes[0].chart_rect; + // The time axis lies below every pane. + let panes_bottom = panes.iter().fold(plot.bottom(), |bottom, pane| { + bottom.max(pane.panel_rect.bottom()) + }); + let mut families = [Vec::new(), Vec::new(), Vec::new()]; + for shape in &painted { + let egui::Shape::Text(text) = shape else { + continue; + }; + let axis = if text.pos.x >= plot.right() && plot.y_range().contains(text.pos.y) { + 0 + } else if text.pos.x >= pane.right() && pane.y_range().contains(text.pos.y) { + 1 + } else if text.pos.y >= panes_bottom && text.pos.x < plot.right() { + 2 + } else { + continue; + }; + let sections = &text.galley.job.sections; + families[axis].extend( + sections + .iter() + .map(|section| §ion.format.font_id.family), + ); + } + for (axis, families) in ["price", "study", "time"].iter().zip(&families) { + assert!( + !families.is_empty() && families.iter().all(|f| **f == FontFamily::Monospace), + "{axis} axis: {families:?}" + ); + } + } + + /// Choosing a thousands separator on the Scales and lines tab groups the digits of the last + /// price tag with it, or leaves them plain. + #[test] + fn thousands_separator_is_chosen_in_the_dialog() { + use crate::widget::test_frames::{chart, frame, shapes}; + let ctx = Context::default(); + let mut chart = chart(&[42_500.0], &[42_541.77]); + chart.config_mut().show_volume = false; + chart.set_instrument(Some( + crate::model::Instrument::new("SAMPLE").with_tick_size(0.01), + )); + for (step, (labels, last)) in [ + (["Comma", "Space", "Ok"], "42 541.77"), + (["Space", "None", "Ok"], "42541.77"), + ] + .into_iter() + .enumerate() + { + let time = step as f64; + frame(&ctx, &mut chart, time, Vec::new()); + let mut dialog = SettingsDialog::new(); + dialog.open(ChartSettingsState::from_chart(&chart)); + dialog.active_tab = SettingsTab::ScalesAndLines; + let SettingsAction::Apply(settings) = click_through(&mut dialog, &labels) else { + panic!("Ok must apply the settings"); + }; + settings.apply_to_chart(&mut chart).unwrap(); + frame(&ctx, &mut chart, time + 0.1, Vec::new()); + let painted = shapes(&ctx, &mut chart, time + 0.2, Vec::new()); + let plot = chart.get_rendered_price_rect(); + let axis: Vec<_> = painted + .iter() + .filter_map(|shape| match shape { + egui::Shape::Text(text) if text.pos.x > plot.right() => { + Some(text.galley.text()) + } + _ => None, + }) + .collect(); + assert!(axis.contains(&last), "{last}: {axis:?}"); + } + } + + /// A template saved before the right margin could hold part of a bar, and before the font + /// family, the thousands separator, session breaks and the bar of the last price could be + /// chosen, holds the whole bars of a margin and none of those choices. Loaded on a chart + /// with a margin in bars or in pixels, it shows what it can of the chart's and Ok keeps the + /// chart's margin and choices. + #[test] + fn old_templates_keep_the_right_margin_and_the_choices_they_lack() { + use crate::model::PriceLineSource; + use crate::widget::{SeriesId, settings::ThousandsSeparator, test_frames::chart}; + use egui::FontFamily; + // The margin of a new chart, and 60 pixels at the default bar spacing of 6 points; the + // margin row after loading the template. + for (pixels, row) in [(None, 2.5), (Some(60.0), 2.0)] { + let mut saved = + serde_json::to_value(ChartSettingsState::from_chart(&chart(&[100.0], &[110.0]))) + .unwrap(); + saved["margins"] = serde_json::from_str( + r#"{"top_percent":10.0,"bottom_percent":10.0,"right_bars":2}"#, + ) + .unwrap(); + for (group, choice) in [ + ("", "show_session_breaks"), + ("/scales_and_lines", "price_line_source"), + ("/scales_and_lines", "thousands_sep"), + ("/scales_appearance", "font_family"), + ] { + let group = saved.pointer_mut(group).unwrap().as_object_mut().unwrap(); + group.remove(choice).expect(choice); + } + let mut options = crate::config::ChartOptions::default(); + options.time_scale.right_offset_pixels = pixels; + let mut chart = chart(&[100.0], &[110.0]).with_chart_options(options); + chart.config_mut().axis_font_family = FontFamily::Monospace; + chart.config_mut().thousands_sep = Some('\''); + chart.config_mut().show_session_breaks = true; + let style = chart.series_style_mut(SeriesId::MAIN).unwrap(); + style.price_line_source = PriceLineSource::LastVisible; + let margin = chart.chart_options().time_scale.clone(); + let mut dialog = SettingsDialog::new(); + dialog + .templates + .save("Old", serde_json::from_value(saved).unwrap()) + .unwrap(); + dialog.open(ChartSettingsState::from_chart(&chart)); + let ctx = Context::default(); + let mut item = None; + for step in 0..4 { + let events = match (step, item) { + (2, Some(pos)) | (3, Some(pos)) => vec![ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { + pos, + pressed: step == 2, + button: egui::PointerButton::Primary, + modifiers: Default::default(), + }, + ], + _ => vec![], + }; + let output = ctx.run_ui( + egui::RawInput { + events, + ..Default::default() + }, + |ui| { + dialog.draw_template_item( + ui, + &Theme::light(), + "Old".into(), + SettingsAction::None, + ); + }, + ); + item = item.or(output.shapes.iter().find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == "Old" => { + Some(text.pos + text.galley.size() / 2.0) + } + _ => None, + })); + output.drop_without_applying_deltas(); + } + assert_eq!(dialog.template_name, "Old", "{pixels:?}"); + let shown = dialog.settings(); + assert_eq!(shown.margins.right_bars, row, "{pixels:?}"); + assert_eq!(dialog.margin_right_str, row.to_string(), "{pixels:?}"); + assert_eq!( + ( + shown.show_session_breaks, + shown.scales_and_lines.price_line_source, + shown.scales_and_lines.thousands_sep, + ), + ( + Some(true), + Some(PriceLineSource::LastVisible), + Some(ThousandsSeparator::Apostrophe), + ), + "{pixels:?}" + ); + dialog.settings().apply_to_chart(&mut chart).unwrap(); + assert_eq!(chart.chart_options().time_scale, margin, "{pixels:?}"); + let config = chart.config(); + assert_eq!(config.axis_font_family, FontFamily::Monospace); + assert_eq!(config.thousands_sep, Some('\'')); + assert!(config.show_session_breaks); + let style = chart.series_style(SeriesId::MAIN).unwrap(); + assert_eq!(style.price_line_source, PriceLineSource::LastVisible); + } + } } diff --git a/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/canvas.rs b/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/canvas.rs index 0276752..5379aaf 100644 --- a/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/canvas.rs +++ b/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/canvas.rs @@ -7,9 +7,10 @@ use crate::model::LineStyle; use crate::theme::Theme; use crate::theme::ThemeExt; use crate::tokens::DESIGN_TOKENS; -use crate::ui_kit::ColorPicker; +use crate::ui_kit::color_picker::keep_opacity; +use crate::ui_kit::{ColorPicker, ColorPickerState}; use crate::widget::settings::{BackgroundType, ButtonVisibility, GridLinesMode, WatermarkMode}; -use egui::Ui; +use egui::{Color32, Ui}; impl SettingsDialog { pub(in super::super) fn draw_canvas_tab(&mut self, ui: &mut Ui, theme: &Theme) { @@ -44,38 +45,29 @@ impl SettingsDialog { // Color swatch(es) match dialog.settings.chart_basic_styles.background_type { BackgroundType::Solid => { - if let Some(color) = ColorPicker::new( + pick_color( + ui, &mut dialog.color_picker_states.background, "bg_color", - ) - .show(ui) - .inner - { - dialog.settings.chart_basic_styles.background_color = color; - } + &mut dialog.settings.chart_basic_styles.background_color, + ); } _ => { - if let Some(color) = ColorPicker::new( + pick_color( + ui, &mut dialog.color_picker_states.background_gradient_top, "bg_grad_top", - ) - .show(ui) - .inner - { - dialog.settings.chart_basic_styles.background_gradient_top = color; - } - if let Some(color) = ColorPicker::new( + &mut dialog.settings.chart_basic_styles.background_gradient_top, + ); + pick_color( + ui, &mut dialog.color_picker_states.background_gradient_bottom, "bg_grad_bot", - ) - .show(ui) - .inner - { - dialog + &mut dialog .settings .chart_basic_styles - .background_gradient_bottom = color; - } + .background_gradient_bottom, + ); } } }); @@ -105,35 +97,34 @@ impl SettingsDialog { GridLinesMode::Horizontal | GridLinesMode::Both ) { ui.add_space(ui.active_theme().spacing.lg); - if let Some(color) = - ColorPicker::new(&mut dialog.color_picker_states.grid_h, "grid_h") - .show(ui) - .inner - { - dialog.settings.grid_lines.horizontal_color = color; - } + pick_color( + ui, + &mut dialog.color_picker_states.grid_h, + "grid_h", + &mut dialog.settings.grid_lines.horizontal_color, + ); } if matches!( dialog.settings.grid_lines.mode, GridLinesMode::Vertical | GridLinesMode::Both - ) && let Some(color) = - ColorPicker::new(&mut dialog.color_picker_states.grid_v, "grid_v") - .show(ui) - .inner - { - dialog.settings.grid_lines.vertical_color = color; + ) { + pick_color( + ui, + &mut dialog.color_picker_states.grid_v, + "grid_v", + &mut dialog.settings.grid_lines.vertical_color, + ); } }); // Crosshair self.draw_setting_row_with_controls(ui, "Crosshair", theme, |ui, dialog| { - if let Some(color) = - ColorPicker::new(&mut dialog.color_picker_states.crosshair, "crosshair") - .show(ui) - .inner - { - dialog.settings.crosshair.color = color; - } + pick_color( + ui, + &mut dialog.color_picker_states.crosshair, + "crosshair", + &mut dialog.settings.crosshair.color, + ); ui.add_space(ui.active_theme().spacing.lg); @@ -197,13 +188,12 @@ impl SettingsDialog { ui.add_space(ui.active_theme().spacing.lg); - if let Some(color) = - ColorPicker::new(&mut dialog.color_picker_states.watermark, "watermark") - .show(ui) - .inner - { - dialog.settings.watermark.color = color; - } + pick_color( + ui, + &mut dialog.color_picker_states.watermark, + "watermark", + &mut dialog.settings.watermark.color, + ); }); ui.add_space(ui.active_theme().spacing.xxl); @@ -212,25 +202,21 @@ impl SettingsDialog { self.draw_section_header(ui, "SCALES APPEARANCE", theme); self.draw_setting_row_with_controls(ui, "Text", theme, |ui, dialog| { - if let Some(color) = - ColorPicker::new(&mut dialog.color_picker_states.scales_text, "scales_text") - .show(ui) - .inner - { - dialog.settings.scales_appearance.text_color = color; - } + pick_color( + ui, + &mut dialog.color_picker_states.scales_text, + "scales_text", + &mut dialog.settings.scales_appearance.text_color, + ); }); self.draw_setting_row_with_controls(ui, "Lines", theme, |ui, dialog| { - if let Some(color) = ColorPicker::new( + pick_color( + ui, &mut dialog.color_picker_states.scales_lines, "scales_lines", - ) - .show(ui) - .inner - { - dialog.settings.scales_appearance.lines_color = color; - } + &mut dialog.settings.scales_appearance.lines_color, + ); }); self.draw_setting_row_with_controls(ui, "Font size", theme, |ui, dialog| { @@ -250,6 +236,33 @@ impl SettingsDialog { } }, ); + // The families installed in the context, and the chosen one when it is not + // among them: the axes draw it proportional until the host installs it. + let mut families = ui.ctx().fonts(|fonts| fonts.families()); + let family = &mut dialog.settings.scales_appearance.font_family; + let chosen = family + .clone() + .or_else(|| dialog.opened_font_family.clone()) + .unwrap_or_default(); + if !families.contains(&chosen) { + families.push(chosen.clone()); + } + styled_dropdown( + ui, + "scales_font_family", + DESIGN_TOKENS.sizing.settings_dialog.dropdown_width, + theme.ui.text, + &chosen.to_string(), + |ui| { + for option in families { + let name = l10n::text(ui.ctx(), option.to_string()); + if ui.selectable_label(option == chosen, name).clicked() { + *family = Some(option); + } + } + }, + ) + .accessible_name(l10n::text(ui.ctx(), "Font family")); }); ui.add_space(ui.active_theme().spacing.xxl); @@ -294,7 +307,7 @@ impl SettingsDialog { &mut dialog.margin_right_str, DESIGN_TOKENS.sizing.settings_dialog.input_width_margin, ); - if let Ok(v) = dialog.margin_right_str.parse::() { + if let Ok(v) = dialog.margin_right_str.parse::() { dialog.settings.margins.right_bars = v; } }, @@ -347,6 +360,18 @@ impl SettingsDialog { } } +/// Shows the colour well of `state` and assigns a pick to `color`. Palette swatches are opaque, +/// so a swatch keeps the opacity the well shows unless the Custom editor set it. +fn pick_color(ui: &mut Ui, state: &mut ColorPickerState, id: &str, color: &mut Color32) { + // The well's colour, not `color`, which may be the placeholder that follows the theme. + let current = state.sel_color; + let custom = state.custom_mode; + if let Some(picked) = ColorPicker::new(state, id).show(ui).inner { + *color = keep_opacity(picked, current, custom || state.custom_mode); + state.sel_color = *color; + } +} + fn line_style_preview(ls: LineStyle) -> &'static str { match ls { LineStyle::Solid => "Solid", diff --git a/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/mod.rs b/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/mod.rs index d1079a2..bbac3a6 100644 --- a/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/mod.rs +++ b/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/mod.rs @@ -115,6 +115,7 @@ fn price_line_dropdown(ui: &mut Ui, id: &str, color: Color32, label: &mut bool, (*label, *line) = mode; } +/// A settings dropdown showing `selected`; returns the response of its closed box. fn styled_dropdown( ui: &mut Ui, id: &str, @@ -122,7 +123,7 @@ fn styled_dropdown( text_color: Color32, selected: &str, add_contents: impl FnOnce(&mut Ui) -> R, -) { +) -> Response { egui::ComboBox::from_id_salt(id) .icon(crate::ui_kit::buttons::combo_chevron) .width(width) @@ -131,7 +132,8 @@ fn styled_dropdown( .size(ui.active_theme().text.title) .color(text_color), ) - .show_ui(ui, add_contents); + .show_ui(ui, add_contents) + .response } /// The width of the Trading tab's labels, where its dropdowns start. diff --git a/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/scales.rs b/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/scales.rs index 5a5658a..3655297 100644 --- a/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/scales.rs +++ b/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/scales.rs @@ -3,8 +3,10 @@ use super::super::SettingsDialog; use super::{price_line_dropdown, styled_checkbox, styled_dropdown, trading_option}; use crate::localization as l10n; +use crate::model::PriceLineSource; use crate::theme::Theme; use crate::ui_kit::ColorPicker; +use crate::widget::settings::ThousandsSeparator; use egui::Ui; impl SettingsDialog { @@ -38,6 +40,44 @@ impl SettingsDialog { }, ); }); + self.draw_setting_row_with_controls( + ui, + "Thousands separator", + theme, + |ui, dialog| { + use ThousandsSeparator::{Apostrophe, Comma, Off, Other, Space}; + let separator = &mut dialog.settings.scales_and_lines.thousands_sep; + let ctx = ui.ctx().clone(); + let name = |separator| match separator { + Off => "None".to_owned(), + Comma => "Comma".to_owned(), + Space => "Space".to_owned(), + Apostrophe => "Apostrophe".to_owned(), + Other(character) => l10n::format_text( + &ctx, + "Other ({character})", + &[("character", character.to_string())], + ), + }; + // A separator the host set stays listed while it is the chart's. + let host = separator.filter(|separator| matches!(separator, Other(_))); + styled_dropdown( + ui, + "thousands_separator", + 150.0, + theme.ui.text, + &name(separator.unwrap_or(Comma)), + |ui| { + for option in + [Off, Comma, Space, Apostrophe].into_iter().chain(host) + { + let label = l10n::text(ui.ctx(), name(option)); + ui.selectable_value(separator, Some(option), label); + } + }, + ); + }, + ); self.draw_setting_row_with_controls(ui, "Pane axes", theme, |ui, dialog| { use crate::model::AxisSide; let side = &mut dialog.settings.scales_and_lines.axis_layout.side; @@ -129,6 +169,33 @@ impl SettingsDialog { &mut dialog.settings.scales_and_lines.show_price_line, ); }); + self.draw_setting_row_with_controls( + ui, + "Last price follows", + theme, + |ui, dialog| { + let source = &mut dialog.settings.scales_and_lines.price_line_source; + let name = |source| match source { + PriceLineSource::LastBar => "Newest bar", + PriceLineSource::LastVisible => "Newest bar in view", + }; + styled_dropdown( + ui, + "last_price_source", + 180.0, + theme.ui.text, + name(source.unwrap_or_default()), + |ui| { + for option in + [PriceLineSource::LastBar, PriceLineSource::LastVisible] + { + let label = l10n::text(ui.ctx(), name(option)); + ui.selectable_value(source, Some(option), label); + } + }, + ); + }, + ); self.draw_setting_row_with_controls(ui, "Symbol color", theme, |ui, dialog| { if let Some(color) = ColorPicker::new( &mut dialog.color_picker_states.symbol_value, diff --git a/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/symbol.rs b/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/symbol.rs index f9c2c63..72681d9 100644 --- a/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/symbol.rs +++ b/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/symbol.rs @@ -18,12 +18,14 @@ impl SettingsDialog { ui.horizontal(|ui| { ui.add_space(0.0); ui.vertical(|ui| { - styled_checkbox( - ui, - &mut self.settings.show_price_targets, - "Analyst price targets", - theme.ui.text, - ); + if self.price_targets_offered { + styled_checkbox( + ui, + &mut self.settings.show_price_targets, + "Analyst price targets", + theme.ui.text, + ); + } let kind = self.settings.chart_type; if kind.is_time_independent() || !kind.uses_ohlc() diff --git a/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/trading.rs b/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/trading.rs index 449dd09..e52f8ae 100644 --- a/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/trading.rs +++ b/vendor/egui-charts/src/ui/dialogs/chart_settings/tabs/trading.rs @@ -28,6 +28,11 @@ impl SettingsDialog { ] { styled_checkbox(ui, value, label, theme.ui.text); } + // Settings that hold no choice keep the chart's until the switch is used. + let mut session_breaks = self.settings.show_session_breaks.unwrap_or_default(); + if styled_checkbox(ui, &mut session_breaks, "Session breaks", theme.ui.text) { + self.settings.show_session_breaks = Some(session_breaks); + } } pub(in super::super) fn draw_trading_tab(&mut self, ui: &mut Ui, theme: &Theme) { diff --git a/vendor/egui-charts/src/ui/dialogs/data_table.rs b/vendor/egui-charts/src/ui/dialogs/data_table.rs index d75f246..be29904 100644 --- a/vendor/egui-charts/src/ui/dialogs/data_table.rs +++ b/vendor/egui-charts/src/ui/dialogs/data_table.rs @@ -38,10 +38,11 @@ pub enum DataTableAction { } /// Inputs to the table, without copying bars, study settings or the instrument, whose changes -/// move the chart's table revision. +/// move the chart's table revision, and the added series, which it reads by their own revisions. #[derive(PartialEq)] struct Source { revision: (u64, u64), + series: Vec, symbol: String, timeframe: Option, len: usize, @@ -53,6 +54,7 @@ impl Source { fn of(chart: &Chart) -> Self { Self { revision: chart.data_table_revision(), + series: chart.data_table_series(), symbol: chart.symbol().to_owned(), timeframe: chart.timeframe(), len: chart.bars(SeriesId::MAIN).len(), @@ -218,10 +220,10 @@ impl DataTableDialog { action = DataTableAction::Export(csv); } ui.label( - egui::RichText::new(format!( - "{} {}", - table.rows.len(), - l10n::text(ui.ctx(), "loaded bars") + egui::RichText::new(l10n::format_text( + ui.ctx(), + "{count} loaded bars", + &[("count", table.rows.len().to_string())], )) .color(ui.visuals().weak_text_color()), ); @@ -1002,4 +1004,52 @@ mod tests { chart.restore(&mixed).unwrap(); assert_eq!(shown(&chart, None), ["EMA: EMA(9)", "SMA: SMA(20)"]); } + + /// The open table shows a new last bar of an added series, which leaves the chart's revisions + /// as they are. A column turned off for an added series stays off when the chart restores its + /// own layout, which adds the series again under a new id. + #[test] + fn added_series_column_follows_its_last_bar_and_keeps_its_choice_through_a_restore() { + let start = DateTime::from_timestamp(1_700_000_000, 0).unwrap(); + let bars: Vec<_> = (0..5) + .map(|i| Bar::from_value(start + chrono::Duration::days(i), 10.0 + i as f64)) + .collect(); + let mut chart = Chart::new(BarData::from_bars(bars)); + let [_, other] = ["Peer", "Other"].map(|name| { + chart.add_series(crate::widget::SeriesOptions { + name: name.into(), + ..Default::default() + }) + }); + let layout = chart.snapshot().unwrap(); + let ctx = Context::default(); + let mut dialog = DataTableDialog::new(); + dialog.open(); + shown_rows(&ctx, &mut dialog, &chart); + chart.update( + other, + Bar::from_value(start + chrono::Duration::days(4), 42.0), + ); + shown_rows(&ctx, &mut dialog, &chart); + // Newest row first: time, the five main columns, Peer, Other. + assert_eq!(dialog.cached.as_ref().unwrap().1.rows[0][7], "42.00"); + let headers = &dialog.cached.as_ref().unwrap().1.headers; + let at = headers.iter().position(|h| h == "Peer").unwrap(); + let column = dialog.column_ids[at].clone(); + dialog + .hidden + .get_mut(&chart.data_table_identity()) + .unwrap() + .insert(column); + chart.restore(&layout).unwrap(); + shown_rows(&ctx, &mut dialog, &chart); + let hidden = &dialog.hidden[&chart.data_table_identity()]; + let shown: Vec<_> = dialog.cached.as_ref().unwrap().1.headers[6..] + .iter() + .zip(&dialog.column_ids[6..]) + .filter(|(_, column)| !hidden.contains(*column)) + .map(|(header, _)| header.as_str()) + .collect(); + assert_eq!(shown, ["Other"]); + } } diff --git a/vendor/egui-charts/src/ui/dialogs/drawing_properties/actions.rs b/vendor/egui-charts/src/ui/dialogs/drawing_properties/actions.rs index 215c143..9aea2fb 100644 --- a/vendor/egui-charts/src/ui/dialogs/drawing_properties/actions.rs +++ b/vendor/egui-charts/src/ui/dialogs/drawing_properties/actions.rs @@ -927,8 +927,10 @@ mod tests { line.timeframe_visibility = TimeframeVisibility::specific(&["1h"]); // A sticker keeps its kind in its text, which it does not show. let sticker = Drawing::new(4, DrawingToolType::Sticker); - // A price label shows no text, and its border shares the colour of its badge. - let label = Drawing::new(5, DrawingToolType::PriceLabel); + // A price label shows no text, and its border shares the colour of its badge, as an older + // save holds it. + let mut label = Drawing::new(5, DrawingToolType::PriceLabel); + label.border_color = Some(label.color); let drawings = vec![alpha, beta, line, sticker, label]; let mut chart = Chart::new(crate::model::BarData::new()); chart.drawings_mut().drawings = drawings.clone(); diff --git a/vendor/egui-charts/src/ui/dialogs/drawing_properties/tabs/inputs.rs b/vendor/egui-charts/src/ui/dialogs/drawing_properties/tabs/inputs.rs index 0f536f8..468fbdf 100644 --- a/vendor/egui-charts/src/ui/dialogs/drawing_properties/tabs/inputs.rs +++ b/vendor/egui-charts/src/ui/dialogs/drawing_properties/tabs/inputs.rs @@ -4,12 +4,12 @@ use crate::drawings::domain::{GANN_MAX_ARC, GANN_SQUARE_UNITS}; use crate::drawings::{ BarsPatternMode, Drawing, DrawingToolType as Tool, ElliottDegree, FibonacciLevel, GannConfig, GannFanDirection, GannLevel, PitchforkConfig, PitchforkLevel, PositionSize, - RegressionTrendConfig, VwapBand, + RegressionTrendConfig, VwapBand, VwapBandMode, VwapFill, VwapPlotType, }; use crate::data::{ProfileDisplay, VolumeProfileConfig}; use crate::localization as l10n; -use crate::model::LineStyle; +use crate::model::{LineStyle, PriceSource}; use crate::ui_kit::color_picker::keep_opacity; use crate::ui_kit::ext::UiExt; use crate::ui_kit::{ColorPicker, ColorPickerState, FormGrid, buttons::Button}; @@ -457,7 +457,8 @@ impl InputsTab { let original = drawing.vwap.unwrap_or_default(); let mut config = original; let pickers = grid_pickers(pickers, 0); - pickers.resize_with(config.bands.len(), ColorPickerState::default); + // One picker per band, then the band fill's and the background's. + pickers.resize_with(config.bands.len() + 2, ColorPickerState::default); for (i, band) in config.bands.iter_mut().enumerate() { ui.push_id(i, |ui| { ui.horizontal(|ui| { @@ -483,6 +484,81 @@ impl InputsTab { }); }); } + let (band_color, line_color) = (config.bands[0].color, drawing.color); + let [band_picker, background_picker] = &mut pickers[3..] else { + unreachable!("resized above") + }; + vwap_fill( + ui, + "Band 1 fill", + &mut config.band_fill, + band_color, + band_picker, + ); + vwap_fill( + ui, + "Background", + &mut config.background, + line_color, + background_picker, + ); + FormGrid::new("vwap_inputs").show(ui, |ui| { + let label = ui.label(l10n::text(ui.ctx(), "Source")); + ui.label_inputs_by(label.id, |ui| { + ui.combo_select( + "vwap_source", + &mut config.source, + PriceSource::all(), + |s| s.label().into(), + ); + }); + ui.end_row(); + let label = ui.label(l10n::text(ui.ctx(), "Bands calculation")); + ui.label_inputs_by(label.id, |ui| { + let ctx = ui.ctx().clone(); + ui.combo_select( + "vwap_band_mode", + &mut config.band_mode, + [VwapBandMode::Deviation, VwapBandMode::Percentage], + |mode| match mode { + VwapBandMode::Deviation => l10n::text(&ctx, "Standard deviation"), + VwapBandMode::Percentage => l10n::text(&ctx, "Percentage"), + }, + ); + }); + ui.end_row(); + ui.label(""); + ui.checkbox(&mut config.show_line, l10n::text(ui.ctx(), "VWAP line")); + ui.end_row(); + let label = ui.label(l10n::text(ui.ctx(), "Plot type")); + ui.label_inputs_by(label.id, |ui| { + let ctx = ui.ctx().clone(); + ui.combo_select( + "vwap_plot_type", + &mut config.plot_type, + VwapPlotType::ALL, + |plot| l10n::text(&ctx, plot.name()), + ); + }); + ui.end_row(); + ui.label(""); + ui.checkbox(&mut config.track_price, l10n::text(ui.ctx(), "Price line")); + ui.end_row(); + let label = ui.label(l10n::text(ui.ctx(), "Precision")); + ui.label_inputs_by(label.id, |ui| { + let ctx = ui.ctx().clone(); + ui.combo_select( + "vwap_precision", + &mut config.precision, + std::iter::once(None).chain((0..=8).map(Some)), + |places| { + places + .map_or_else(|| l10n::text(&ctx, "Default"), |p| p.to_string()) + }, + ); + }); + ui.end_row(); + }); if config != original { drawing.vwap = Some(config); } @@ -504,6 +580,7 @@ impl InputsTab { | Tool::ElliottTripleCombo => { FormGrid::new("elliott_inputs").show(ui, |ui| { let label = ui.label(l10n::text(ui.ctx(), "Degree")); + let ctx = ui.ctx().clone(); ui.label_inputs_by(label.id, |ui| { ui.combo_select( "elliott_degree", @@ -512,7 +589,7 @@ impl InputsTab { |degree| { format!( "{}: {}, {}", - degree.name(), + l10n::text(&ctx, degree.name()), degree.label('1'), degree.label('A') ) @@ -644,6 +721,41 @@ fn number(ui: &mut Ui, label: &str, value: &mut f64, range: std::ops::RangeInclu ui.end_row(); } +/// A checkbox, colour and opacity row for an anchored VWAP fill whose colour follows `fallback` +/// until one is picked. +fn vwap_fill( + ui: &mut Ui, + name: &str, + fill: &mut VwapFill, + fallback: [u8; 4], + picker: &mut ColorPickerState, +) { + ui.push_id(name, |ui| { + ui.horizontal(|ui| { + ui.checkbox(&mut fill.visible, l10n::text(ui.ctx(), name)); + let mut color = fill.color.unwrap_or(fallback); + if level_color(ui, &mut color, picker) { + fill.color = Some(color); + } + let mut percent = fill.opacity() * 100.0; + if ui + .add_enabled( + fill.visible, + egui::DragValue::new(&mut percent) + .range(0.0..=100.0) + .max_decimals(1) + .suffix("%") + .prefix(l10n::text(ui.ctx(), "Opacity ")), + ) + .changed() + && let Some(updated) = VwapFill::new(fill.visible, fill.color, percent / 100.0) + { + *fill = updated; + } + }); + }); +} + fn background(ui: &mut Ui, show: &mut bool, opacity: &mut u8) { ui.horizontal(|ui| { ui.checkbox(show, l10n::text(ui.ctx(), "Background")); diff --git a/vendor/egui-charts/src/ui/dialogs/drawing_properties/tabs/style.rs b/vendor/egui-charts/src/ui/dialogs/drawing_properties/tabs/style.rs index fbb3039..93feead 100644 --- a/vendor/egui-charts/src/ui/dialogs/drawing_properties/tabs/style.rs +++ b/vendor/egui-charts/src/ui/dialogs/drawing_properties/tabs/style.rs @@ -441,7 +441,7 @@ fn badge_rows(ui: &mut Ui, props: &mut DrawingProps, pickers: &mut [ColorPickerS (text, colors.fill, colors.border.color) } else { let colors = shown.price_label_colors(); - // A label saved without a border colour shows its fill, which is what it draws there. + // A label without a border shows its fill, which is what it draws there. let border = if colors.border.is_empty() { colors.fill } else { diff --git a/vendor/egui-charts/src/ui/dialogs/indicator_dialog/settings.rs b/vendor/egui-charts/src/ui/dialogs/indicator_dialog/settings.rs index a54a304..2aa332f 100644 --- a/vendor/egui-charts/src/ui/dialogs/indicator_dialog/settings.rs +++ b/vendor/egui-charts/src/ui/dialogs/indicator_dialog/settings.rs @@ -35,7 +35,8 @@ pub struct StudyEdit { pub struct IndicatorSettingsDialog { edit: Option, inputs: Vec, - title: String, + /// The edited study's name, for the title. + study: String, line_names: Vec, levels: Vec<(f64, &'static str)>, gradient_names: Vec<&'static str>, @@ -95,7 +96,7 @@ impl IndicatorSettingsDialog { settings: study.settings(), }); self.inputs = study.inputs(); - self.title = format!("{} settings", study.name()); + self.study = study.name().to_owned(); self.line_names = study.line_names(); self.gradient_names = study.gradients().iter().map(|fill| fill.name).collect(); self.levels = study @@ -243,7 +244,8 @@ impl IndicatorSettingsDialog { let mut open = true; let mut apply = false; let mut cancel = false; - Modal::new("indicator_settings", &self.title) + let title = l10n::format_text(ctx, "{name} settings", &[("name", self.study.as_str())]); + Modal::new("indicator_settings", title) .width(620.0) .height(560.0) .top(120.0) @@ -509,10 +511,10 @@ impl IndicatorSettingsDialog { ui.horizontal_wrapped(|ui| { ui.checkbox( &mut fill.visible, - format!( - "{} {}", - l10n::text(ui.ctx(), "Band"), - index + 1 + l10n::format_text( + ui.ctx(), + "Band {number}", + &[("number", (index + 1).to_string())], ), ); ui.color_edit_button_srgba(&mut fill.color) diff --git a/vendor/egui-charts/src/ui/dialogs/keyboard_shortcuts/mod.rs b/vendor/egui-charts/src/ui/dialogs/keyboard_shortcuts/mod.rs index 31d38f2..b636e9f 100644 --- a/vendor/egui-charts/src/ui/dialogs/keyboard_shortcuts/mod.rs +++ b/vendor/egui-charts/src/ui/dialogs/keyboard_shortcuts/mod.rs @@ -13,6 +13,76 @@ use crate::tokens::DESIGN_TOKENS; use crate::ui_kit::dialog::{DialogFrame, dialog_header}; use crate::widget::ShortcutMap; +/// One key combination of a listed entry. +enum Keys { + /// A combination of the chart's shortcut map or of a fixed key. + Shortcut(KeyboardShortcut), + /// Keys typed as text, which no shortcut describes. + Typed(&'static str), +} + +/// One listed entry: a label and its key combinations. +struct Entry { + label: String, + keys: Vec, +} + +/// The keys the chart and the library's controls read outside the shortcut map, by category. +/// +/// They are not rebindable, so the list is fixed. The state an entry needs is in its label or +/// its category. +fn fixed_categories() -> Vec<(&'static str, Vec)> { + let entry = |label: &str, keys: Vec| Entry { + label: label.to_owned(), + keys, + }; + let key = |key, modifiers| Keys::Shortcut(KeyboardShortcut::new(modifiers, key)); + let none = Modifiers::NONE; + vec![ + ( + "Typing", + vec![ + entry("Change the symbol", vec![Keys::Typed("Type a ticker")]), + entry( + "Change the interval", + vec![Keys::Typed("0-9"), Keys::Typed(",")], + ), + ], + ), + ( + "Selected drawing", + vec![ + entry("Move one bar earlier", vec![key(Key::ArrowLeft, none)]), + entry("Move one bar later", vec![key(Key::ArrowRight, none)]), + entry("Move up one tick", vec![key(Key::ArrowUp, none)]), + entry("Move down one tick", vec![key(Key::ArrowDown, none)]), + ], + ), + ( + "Replay", + vec![ + entry("Play or pause the replay", vec![key(Key::Space, none)]), + entry("Go to the replay start", vec![key(Key::Home, none)]), + entry("Go to the replay end", vec![key(Key::End, none)]), + entry( + "Replay one bar back", + vec![ + key(Key::ArrowLeft, none), + key(Key::ArrowLeft, Modifiers::SHIFT), + ], + ), + entry( + "Replay one bar forward", + vec![ + key(Key::ArrowRight, none), + key(Key::ArrowRight, Modifiers::SHIFT), + ], + ), + ], + ), + ] +} + /// Action returned by the keyboard shortcuts dialog #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] @@ -121,12 +191,26 @@ impl KeyboardShortcutsDialog { ); ui.add_space(theme.spacing.lg); - let categories = shortcuts.by_category(); + let categories: Vec<(&str, Vec)> = shortcuts + .by_category() + .into_iter() + .map(|(name, actions)| { + let entries = actions + .into_iter() + .map(|action| Entry { + label: action.label().to_owned(), + keys: shortcuts.keys_for(action).map(Keys::Shortcut).collect(), + }) + .collect(); + (name, entries) + }) + .chain(fixed_categories()) + .collect(); let font = FontId::proportional(theme.text.body); let labels: Vec<_> = categories .iter() - .flat_map(|(_, actions)| actions) - .map(|action| l10n::text(ui.ctx(), action.label())) + .flat_map(|(_, entries)| entries) + .map(|entry| l10n::text(ui.ctx(), &entry.label)) .collect(); let widest = ui.fonts_mut(|f| { labels @@ -147,7 +231,7 @@ impl KeyboardShortcutsDialog { .auto_shrink([false, true]) .max_height(ui.available_height()) .show(ui, |ui| { - for (idx, (name, actions)) in categories.iter().enumerate() { + for (idx, (name, entries)) in categories.iter().enumerate() { if idx > 0 { ui.add_space(theme.spacing.xxl - ui.spacing().item_spacing.y); } @@ -165,13 +249,12 @@ impl KeyboardShortcutsDialog { .min_col_width(label_w) .max_col_width(label_w) .show(ui, |ui| { - for action in actions { + for entry in entries { ui.label( - RichText::new(l10n::text(ui.ctx(), action.label())) + RichText::new(l10n::text(ui.ctx(), &entry.label)) .size(theme.text.body), ); - let keys: Vec<_> = shortcuts.keys_for(*action).collect(); - ui.horizontal_wrapped(|ui| key_badges(ui, &theme, &keys)); + ui.horizontal_wrapped(|ui| key_badges(ui, &theme, &entry.keys)); ui.end_row(); } }); @@ -206,8 +289,8 @@ pub(crate) fn shortcut_key_labels( } /// One badge per key combination, joined by a muted "or". -fn key_badges(ui: &mut Ui, theme: &Theme, shortcuts: &[KeyboardShortcut]) { - for (idx, shortcut) in shortcuts.iter().enumerate() { +fn key_badges(ui: &mut Ui, theme: &Theme, keys: &[Keys]) { + for (idx, combination) in keys.iter().enumerate() { if idx > 0 { ui.label( RichText::new(l10n::text(ui.ctx(), "or")) @@ -216,9 +299,19 @@ fn key_badges(ui: &mut Ui, theme: &Theme, shortcuts: &[KeyboardShortcut]) { ); } // Screen readers get the name. - let font = FontId::proportional(theme.text.small); - let text = shortcut_key_labels(ui.ctx(), &font, shortcut).join("+"); - let name = ui.ctx().format_shortcut(shortcut); + let (text, name) = match combination { + Keys::Shortcut(shortcut) => { + let font = FontId::proportional(theme.text.small); + ( + shortcut_key_labels(ui.ctx(), &font, shortcut).join("+"), + ui.ctx().format_shortcut(shortcut), + ) + } + Keys::Typed(text) => { + let text = l10n::text(ui.ctx(), text); + (text.clone(), text) + } + }; Frame::new() .fill(theme.ui.panel_bg_secondary) .stroke(Stroke::new(1.0, theme.ui.border_control)) @@ -245,6 +338,7 @@ fn key_badges(ui: &mut Ui, theme: &Theme, shortcuts: &[KeyboardShortcut]) { #[cfg(test)] mod tests { use super::*; + use egui_kittest::kittest::Queryable as _; #[test] fn a_popup_opened_this_frame_gets_escape_before_the_dialog() { @@ -271,4 +365,33 @@ mod tests { ) .drop_without_applying_deltas(); } + + /// Guards #2811: the list also shows the keys read outside the shortcut map, so it is a + /// complete guide to the keyboard. + #[test] + fn the_list_shows_typed_entry_drawing_arrows_and_replay_keys() { + let mut dialog = KeyboardShortcutsDialog::new(); + dialog.open(); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(900.0, 2400.0)) + .with_context_setup(|ctx| { + egui_extras::install_image_loaders(ctx); + crate::theme::apply_to_egui(ctx, &Theme::dark()); + }) + .build_ui_state( + |ui, d: &mut KeyboardShortcutsDialog| _ = d.show(ui.ctx()), + dialog, + ); + h.run_steps(3); + for label in [ + "Change the symbol", + "Change the interval", + "Move one bar earlier", + "Move down one tick", + "Play or pause the replay", + "Replay one bar forward", + ] { + assert!(h.query_by_label(label).is_some(), "missing {label}"); + } + } } diff --git a/vendor/egui-charts/src/ui/dialogs/series_settings/dialog.rs b/vendor/egui-charts/src/ui/dialogs/series_settings/dialog.rs index 5096273..80a67e6 100644 --- a/vendor/egui-charts/src/ui/dialogs/series_settings/dialog.rs +++ b/vendor/egui-charts/src/ui/dialogs/series_settings/dialog.rs @@ -82,12 +82,15 @@ impl SeriesSettingsDialog { let mut action = SeriesSettingsAction::None; - let object = if self.series_id == Some(SeriesId::MAIN) { - "Main series".to_owned() - } else { - format!("Series {:?}", self.series_id) + let object = match self.series_id { + Some(SeriesId::MAIN) => l10n::text(ctx, "Main series"), + Some(id) => l10n::format_text(ctx, "Series {number}", &[("number", id.0.to_string())]), + None => l10n::text(ctx, "Series"), }; - let title = format!("{object} · {}", self.settings.chart_type.name()); + let title = format!( + "{object} · {}", + l10n::text(ctx, self.settings.chart_type.name()) + ); let mut open = true; Modal::new("series_settings", title) .width(self.config.width + 32.0) diff --git a/vendor/egui-charts/src/ui/dialogs/series_settings/tabs/symbol.rs b/vendor/egui-charts/src/ui/dialogs/series_settings/tabs/symbol.rs index 79cd533..0684f85 100644 --- a/vendor/egui-charts/src/ui/dialogs/series_settings/tabs/symbol.rs +++ b/vendor/egui-charts/src/ui/dialogs/series_settings/tabs/symbol.rs @@ -265,22 +265,7 @@ impl SymbolTab { .into_iter() .enumerate() { - let label = ui.label(l10n::text(ui.ctx(), name)); - ui.horizontal(|ui| { - let color = &mut params.footprint_colors[i]; - let mut selected = color.unwrap_or(default); - if Self::color_picker(ui, &mut selected) { - *color = Some(selected); - } - if ui - .small_button(l10n::text(ui.ctx(), "Auto")) - .labelled_by(label.id) - .clicked() - { - *color = None; - } - }); - ui.end_row(); + Self::followed_color(ui, name, &mut params.footprint_colors[i], default, "Auto"); } }); Self::section(ui, "Rows", true, |ui| { @@ -341,6 +326,18 @@ impl SymbolTab { ) .labelled_by(label.id); ui.end_row(); + // Unset, the marks of a side take its buy or sell colour. + let sides = [ + params.footprint_colors[0].unwrap_or(up), + params.footprint_colors[1].unwrap_or(down), + ]; + for (i, name) in ["Buy imbalance colour", "Sell imbalance colour"] + .into_iter() + .enumerate() + { + let color = &mut params.footprint_imbalance_colors[i]; + Self::followed_color(ui, name, color, sides[i], "Same as cells"); + } }); Self::section(ui, "Annotations", false, |ui| { for (name, value) in [ @@ -434,11 +431,43 @@ impl SymbolTab { .filter(|r| if *r == row { enabled } else { rows.contains(r) }) .collect(); } + if enabled && row == FootprintStatistic::CumulativeDelta { + Self::switch( + ui, + "Restart CVD each session", + &mut params.footprint_session_cumulative_delta, + ); + } } } }); } + /// A colour row whose `reset` button returns the colour to following `default`. + fn followed_color( + ui: &mut Ui, + name: &str, + color: &mut Option, + default: Color32, + reset: &str, + ) { + let label = ui.label(l10n::text(ui.ctx(), name)); + ui.horizontal(|ui| { + let mut selected = color.unwrap_or(default); + if Self::color_picker(ui, &mut selected) { + *color = Some(selected); + } + if ui + .small_button(l10n::text(ui.ctx(), reset)) + .labelled_by(label.id) + .clicked() + { + *color = None; + } + }); + ui.end_row(); + } + fn value_area(ui: &mut Ui, share: &mut Option) { let mut percent = share.map(|share| share * 100.0); Self::optional_number(ui, "Value area", &mut percent, 70.0, 1.0..=100.0, "%"); diff --git a/vendor/egui-charts/src/ui/drawing_toolbar/utilities/templates.rs b/vendor/egui-charts/src/ui/drawing_toolbar/utilities/templates.rs index 3f743d9..f5defbe 100644 --- a/vendor/egui-charts/src/ui/drawing_toolbar/utilities/templates.rs +++ b/vendor/egui-charts/src/ui/drawing_toolbar/utilities/templates.rs @@ -24,6 +24,7 @@ impl TemplatesButton { ui: &mut Ui, templates: &[DrawingTemplate], ) -> Option { + let ctx = ui.ctx().clone(); let mut builder = SubmenuBuilder::new(ui).add_text_item_with_action( "Save as template…", "Save current drawing properties as a reusable template", @@ -40,13 +41,21 @@ impl TemplatesButton { for template in templates { let template_id = template.id.clone(); let name = if template.is_default { - format!("{} (default)", template.name) + l10n::format_text( + &ctx, + "{name} (default)", + &[("name", template.name.as_str())], + ) } else { template.name.clone() }; - let tooltip = format!( - "Load template: {} ({})", - template.name, template.drawing_type + let tooltip = l10n::format_text( + &ctx, + "Load template: {name} ({tool})", + &[ + ("name", template.name.as_str()), + ("tool", template.drawing_type.as_str()), + ], ); builder = builder.add_text_item_with_action(&name, &tooltip, move || { diff --git a/vendor/egui-charts/src/ui/financials.rs b/vendor/egui-charts/src/ui/financials.rs index 10e67c3..1b56527 100644 --- a/vendor/egui-charts/src/ui/financials.rs +++ b/vendor/egui-charts/src/ui/financials.rs @@ -1,6 +1,7 @@ //! A company's financials in place of the price chart: a chart of one row over the periods and //! the table of every row, page by page, from figures the host supplies. +pub use crate::data::{CompanyFinancials, FinancialPage, FinancialRow}; use crate::icons::icons; use crate::localization as l10n; use crate::scales::StudyFormat; @@ -18,67 +19,6 @@ const PERIOD_WIDTH: f32 = 96.0; /// Height of a table row. const ROW_HEIGHT: f32 = 32.0; -/// A company's reported figures, as the host supplies them. -#[derive(Clone, Debug, Default, PartialEq)] -#[non_exhaustive] -pub struct CompanyFinancials { - /// The currency of the amounts, shown above the tables. - pub currency: Option, - /// The pages, such as the income statement, the balance sheet and the statistics, each - /// chosen with its own pill. - pub pages: Vec, -} - -/// One page of [`CompanyFinancials`]: rows of figures by period. -#[derive(Clone, Debug, Default, PartialEq)] -#[non_exhaustive] -pub struct FinancialPage { - /// The page's name, such as "Income statement". - pub name: String, - /// The periods, oldest first, such as "FY 2024" or "Q3 '25": the table's columns. - pub periods: Vec, - /// The rows of the table. - pub rows: Vec, -} - -/// One row of a [`FinancialPage`]. -#[derive(Clone, Debug, Default, PartialEq)] -#[non_exhaustive] -pub struct FinancialRow { - /// The row's name, such as "Total revenue". - pub name: String, - /// One value per period of the page; `None` where the company reported none. Non-finite - /// values are shown as unavailable. - pub values: Vec>, -} - -impl FinancialPage { - /// A page named `name` with columns `periods` and no rows. - pub fn new(name: impl Into, periods: Vec) -> Self { - Self { - name: name.into(), - periods, - rows: Vec::new(), - } - } - - /// Adds a row named `name` with one value per period. - pub fn with_row(mut self, name: impl Into, values: Vec>) -> Self { - self.rows.push(FinancialRow { - name: name.into(), - values, - }); - self - } -} - -impl CompanyFinancials { - /// Financials made of `pages`, with amounts in `currency`. - pub fn new(currency: Option, pages: Vec) -> Self { - Self { currency, pages } - } -} - /// A page's pill. #[derive(Clone, Copy, PartialEq)] struct Page<'a>(&'a str); diff --git a/vendor/egui-charts/src/ui/floating_toolbar/toolbar.rs b/vendor/egui-charts/src/ui/floating_toolbar/toolbar.rs index a18c516..f6d16da 100644 --- a/vendor/egui-charts/src/ui/floating_toolbar/toolbar.rs +++ b/vendor/egui-charts/src/ui/floating_toolbar/toolbar.rs @@ -783,6 +783,8 @@ mod tests { ctx.global_style_mut(|style| style.animation_time = 0.0); let mut chart = Chart::new(crate::model::BarData::new()); let mut label = Drawing::new(7, DrawingToolType::PriceLabel); + // A border kept in the label's colour, as an older save holds it. + label.border_color = Some(label.color); label.completed = true; label.points = vec![Pos2::new(100.0, 100.0)]; chart.drawings_mut().drawings = vec![label]; diff --git a/vendor/egui-charts/src/ui/replay/floating.rs b/vendor/egui-charts/src/ui/replay/floating.rs index f242891..28caee6 100644 --- a/vendor/egui-charts/src/ui/replay/floating.rs +++ b/vendor/egui-charts/src/ui/replay/floating.rs @@ -567,11 +567,18 @@ impl FloatingReplayControl { && let Some(mut interval) = self.update_interval && ui .add_enabled_ui(!self.selecting, |ui| { + let ctx = ui.ctx().clone(); ui.combo_select_width( "replay_update_interval", &mut interval, self.update_intervals.iter().copied(), - |interval| format!("{} updates", interval), + |interval| { + l10n::format_text( + &ctx, + "{count} updates", + &[("count", interval.to_string())], + ) + }, 110.0, ) }) diff --git a/vendor/egui-charts/src/ui/replay/session.rs b/vendor/egui-charts/src/ui/replay/session.rs index 087f6c1..3627898 100644 --- a/vendor/egui-charts/src/ui/replay/session.rs +++ b/vendor/egui-charts/src/ui/replay/session.rs @@ -21,7 +21,8 @@ impl ReplayController { } /// The exclusive cutoff after the current source bar, suitable for `Chart::set_replay_time`. - /// Pass the source interval's clock, including its calendar timezone. + /// Pass the source interval's clock, including its calendar timezone. For the chart's own + /// interval that is [`Chart::bar_clock`](crate::widget::Chart::bar_clock). pub fn cutoff(&self, clock: &crate::model::BarClock) -> Option> { if !self.state.is_active() { return None; diff --git a/vendor/egui-charts/src/ui/strategy_report/tester.rs b/vendor/egui-charts/src/ui/strategy_report/tester.rs index 4e61a47..ba7acf2 100644 --- a/vendor/egui-charts/src/ui/strategy_report/tester.rs +++ b/vendor/egui-charts/src/ui/strategy_report/tester.rs @@ -494,7 +494,14 @@ impl StrategyTester { ui.label(l10n::text(ui.ctx(), "Waiting for host history")); } if self.job.is_some() || self.pending.is_some() { - ui.label(format!("{} / {} trials", self.completed.get(), self.total)); + ui.label(l10n::format_text( + ui.ctx(), + "{done} / {total} trials", + &[ + ("done", self.completed.get().to_string()), + ("total", self.total.to_string()), + ], + )); if ui.button(l10n::text(ui.ctx(), "Cancel run")).clicked() { self.changed(); } @@ -590,7 +597,11 @@ impl StrategyTester { } match optimisation::grid(&self.ranges) { Ok((count, _)) => { - ui.label(format!("{count} trials")); + ui.label(l10n::format_text( + ui.ctx(), + "{count} trials", + &[("count", count.to_string())], + )); optimise = ui .add_enabled( self.job.is_none() && self.pending.is_none(), diff --git a/vendor/egui-charts/src/ui/top_toolbar/components/layout_menu.rs b/vendor/egui-charts/src/ui/top_toolbar/components/layout_menu.rs index 5e7945b..4ba680f 100644 --- a/vendor/egui-charts/src/ui/top_toolbar/components/layout_menu.rs +++ b/vendor/egui-charts/src/ui/top_toolbar/components/layout_menu.rs @@ -104,6 +104,8 @@ pub struct LayoutMenu { /// A changed edit count with the input time it was first seen. changed: Option<(u64, f64)>, error: Option, + /// The context of the last poll, to translate errors of calls between frames. + ctx: Option, share: ShareControls, } @@ -136,6 +138,7 @@ impl LayoutMenu { observed_layout: None, changed: None, error: None, + ctx: None, share: ShareControls::default(), } } @@ -211,7 +214,13 @@ impl LayoutMenu { self.saved_edits = Some(self.edits); match layout.to_json() { Ok(document) => self.request(Request::Save(name.to_owned(), document)), - Err(error) => self.error = Some(format!("Could not save {name}: {error}")), + Err(error) => { + self.error = Some(l10n::format_text_or_english( + self.ctx.as_ref(), + "Could not save {name}: {error}", + &[("name", name), ("error", error.to_string().as_str())], + )) + } } } @@ -231,7 +240,13 @@ impl LayoutMenu { self.saved_edits = Some(self.edits); match layout.to_json() { Ok(document) => self.request(Request::Rename(old, name.to_owned(), document)), - Err(error) => self.error = Some(format!("Could not rename to {name}: {error}")), + Err(error) => { + self.error = Some(l10n::format_text_or_english( + self.ctx.as_ref(), + "Could not rename to {name}: {error}", + &[("name", name), ("error", error.to_string().as_str())], + )) + } } } @@ -244,6 +259,7 @@ impl LayoutMenu { /// Returns a layout [`open`](Self::open) read, now the current layout, for the host to /// restore before its next [`autosave_due`](Self::autosave_due). pub fn poll(&mut self, ctx: &egui::Context) -> Option<(String, SavedLayout)> { + self.ctx = Some(ctx.clone()); let repaint = ctx.clone(); self.inbox.set_waker(move || repaint.request_repaint()); let mut opened = None; diff --git a/vendor/egui-charts/src/ui/top_toolbar/components/timeframe_selector/mod.rs b/vendor/egui-charts/src/ui/top_toolbar/components/timeframe_selector/mod.rs index 3450297..35b443c 100644 --- a/vendor/egui-charts/src/ui/top_toolbar/components/timeframe_selector/mod.rs +++ b/vendor/egui-charts/src/ui/top_toolbar/components/timeframe_selector/mod.rs @@ -1197,14 +1197,9 @@ mod tests { .iter() .any(|(label, _)| *label == display_long(custom)) ); - let add = labels.iter().find(|(label, _)| label == "Add").unwrap().1; - assert_eq!(click(&mut restored, add), TimeframeAction::None); - assert!(restored.custom_dialog.error.is_some()); - assert_eq!(restored.preferences(), saved); - restored.custom_dialog.unit = TimeframeUnit::Millisecond; - restored.custom_dialog.value_input = "1".to_owned(); - assert_eq!(click(&mut restored, add), TimeframeAction::None); - assert!(restored.custom_dialog.error.is_some()); + // TradeCraft hides custom entry when the feed supports only presets. + assert!(!labels.iter().any(|(label, _)| label == "Add")); + assert!(!restored.show_custom_input); assert_eq!(restored.preferences(), saved); restored.set_supported_timeframes(None); let (_, labels, _) = frame(&mut restored, vec![]); diff --git a/vendor/egui-charts/src/ui/top_toolbar/toolbar.rs b/vendor/egui-charts/src/ui/top_toolbar/toolbar.rs index ed12fc0..47aeb0f 100644 --- a/vendor/egui-charts/src/ui/top_toolbar/toolbar.rs +++ b/vendor/egui-charts/src/ui/top_toolbar/toolbar.rs @@ -240,6 +240,8 @@ pub struct TopToolbar { pub host_menu_image: Option>, /// Optional status displayed after the left-hand toolbar controls. pub host_status: Option, + /// Optional host action displayed alongside the left-hand controls. + pub host_inline_action: Option<(String, String, egui::Color32, f32)>, /// Host call to action as (id, label), drawn as a filled pill at the right end after the host /// action slot. Choosing it emits [`TopToolbarAction::Host`] with the id; `None` shows nothing. pub call_to_action: Option<(String, String)>, @@ -262,6 +264,7 @@ impl Default for TopToolbar { host_menu_entries: Vec::new(), host_menu_image: None, host_status: None, + host_inline_action: None, call_to_action: None, } } @@ -554,6 +557,12 @@ impl TopToolbar { ui.add_space(ui.active_theme().spacing.lg); self.show_groups(ui, LEFT, symbol, &mut action); + if let Some((id, label, color, size)) = &self.host_inline_action { + ui.add_space(gap(ui)); + if ui.add(egui::Button::new(egui::RichText::new(label).size(*size).color(*color).strong()).frame(false)).clicked() { + action = TopToolbarAction::Host(id.clone()); + } + } if let Some(status) = &self.host_status { ui.add_space(gap(ui)); ui.label(status); diff --git a/vendor/egui-charts/src/ui/trading/dom.rs b/vendor/egui-charts/src/ui/trading/dom.rs index e106e0b..18f836a 100644 --- a/vendor/egui-charts/src/ui/trading/dom.rs +++ b/vendor/egui-charts/src/ui/trading/dom.rs @@ -314,6 +314,7 @@ impl Ladder { let position = (market.positions.iter()).find(|position| position.symbol == symbol); let quantity_decimals = decimals(market.rules.quantity_step); let numbers = market.numbers(); + let ctx = ui.ctx().clone(); let order = |side, order_type| -> Result { if market.offline.is_some() { return Err("Waiting for the broker to connect".into()); @@ -327,7 +328,8 @@ impl Ladder { if entry_price(&order_type).is_some_and(|price| !price.is_finite() || price <= 0.0) { return Err("Enter a positive price".into()); } - let quantity = order_quantity(wanted, market.rules)?; + let quantity = + order_quantity(wanted, market.rules).map_err(|limit| limit.message(&ctx))?; let mut request = OrderRequest::new(symbol, side, quantity, order_type); request.time_in_force = tif; Ok(request) @@ -1016,11 +1018,11 @@ impl Ladder { let label = format!( "{} {} · {}", format_size(order.request.quantity - order.filled), - tag(&order.request.order_type), + l10n::text(ui.ctx(), tag(&order.request.order_type)), order.id.0, ); if ui - .selectable_label(order.id == working.id, l10n::text(ui.ctx(), label)) + .selectable_label(order.id == working.id, label) .clicked() { self.selected = Some(order.id.clone()); diff --git a/vendor/egui-charts/src/ui/trading/executions.rs b/vendor/egui-charts/src/ui/trading/executions.rs index d435515..5a15d38 100644 --- a/vendor/egui-charts/src/ui/trading/executions.rs +++ b/vendor/egui-charts/src/ui/trading/executions.rs @@ -195,7 +195,7 @@ pub(super) fn show( ) // Written only while it shows: a mark can hold every fill of the list. .on_hover_ui(|ui| { - let time = chart.build_time_formatter(); + let time = chart.time_formatter_in(chart.display_timezone()); let decimals = numbers.decimals; let mut lines: Vec<_> = run .iter() diff --git a/vendor/egui-charts/src/ui/trading/ticket/form.rs b/vendor/egui-charts/src/ui/trading/ticket/form.rs index 48a33a1..7610541 100644 --- a/vendor/egui-charts/src/ui/trading/ticket/form.rs +++ b/vendor/egui-charts/src/ui/trading/ticket/form.rs @@ -36,7 +36,7 @@ impl OrderTicket { } } } - let request = self.request(market); + let request = self.request(ui.ctx(), market); let entry = self .entry(market) .map(|price| to_step(price, market.tick, f64::round)); @@ -88,10 +88,21 @@ impl OrderTicket { _ => "Last", }; let ticks = ((*price - touch) / market.tick).round(); + let key = match (reference, ticks < 0.0) { + ("Ask", false) => "Ask + {ticks}", + ("Ask", true) => "Ask - {ticks}", + ("Bid", false) => "Bid + {ticks}", + ("Bid", true) => "Bid - {ticks}", + (_, false) => "Last + {ticks}", + (_, true) => "Last - {ticks}", + }; match ticks { 0.0 => reference.to_owned(), - ticks if ticks < 0.0 => format!("{reference} - {}", -ticks), - ticks => format!("{reference} + {ticks}"), + ticks => l10n::format_text( + ui.ctx(), + key, + &[("ticks", ticks.abs().to_string())], + ), } }; muted(ui, &suffix); @@ -527,10 +538,13 @@ impl OrderTicket { let mut mode = bracket.mode; let enabled = ui .horizontal(|ui| { - let response = dropdown( - ui, - format!("{title}, {}", bracket.mode.name(market.currency)), + let mode_name = l10n::text(ui.ctx(), bracket.mode.name(market.currency)); + let caption = l10n::format_text( + ui.ctx(), + "{exit}, {mode}", + &[("exit", title), ("mode", mode_name.as_str())], ); + let response = dropdown(ui, caption); egui::Popup::menu(&response).show(|ui| { for option in BracketMode::ALL { ui.selectable_value( @@ -626,7 +640,7 @@ impl OrderTicket { let title = l10n::format_text(ui.ctx(), "Take profit {0}", &[("0", "1".to_owned())]); (title, level_per_point(0, rest)) } else { - ("Take profit".to_owned(), per_point) + (l10n::text(ui.ctx(), "Take profit"), per_point) }; let (on, bracket) = &mut self.take_profit; exit_fields( @@ -644,12 +658,13 @@ impl OrderTicket { if several { ui.add_enabled_ui(false, |ui| share_field(ui, 0, &mut rest)); } + let stop_loss = l10n::text(ui.ctx(), "Stop loss"); let (on, bracket) = &mut self.stop_loss; exit_fields( ui, per_point, false, - "Stop loss", + &stop_loss, 0, bracket, &mut |ui: &mut Ui| { diff --git a/vendor/egui-charts/src/ui/trading/ticket/mod.rs b/vendor/egui-charts/src/ui/trading/ticket/mod.rs index 8673224..e190b43 100644 --- a/vendor/egui-charts/src/ui/trading/ticket/mod.rs +++ b/vendor/egui-charts/src/ui/trading/ticket/mod.rs @@ -8,8 +8,9 @@ mod view; use super::dom::Ladder; use super::format::{Numbers, TradingFormatter}; -use super::widgets::{grouped, side_name}; +use super::widgets::grouped; use crate::chart::TradingLineAction; +use crate::localization as l10n; use crate::model::{ Capabilities, Order, OrderBook, OrderId, OrderPreview, OrderRequest, OrderSide, OrderType, Position, TakeProfitLevel, Tick, TimeInForce, TradingRules, @@ -416,6 +417,7 @@ impl OrderTicket { /// a share is not above 0 or a level falls below the minimum quantity. fn take_profits( &self, + ctx: &egui::Context, market: &Market<'_>, side: OrderSide, entry: f64, @@ -446,9 +448,10 @@ impl OrderTicket { .into_iter() .map(|(bracket, quantity)| { if quantity < rules.min_quantity { - return Err(format!( - "Each take-profit level needs at least the minimum quantity of {}", - rules.min_quantity + return Err(l10n::format_text( + ctx, + "Each take-profit level needs at least the minimum quantity of {minimum}", + &[("minimum", rules.min_quantity.to_string())], )); } let per_point = quantity * rules.point_value; @@ -463,6 +466,7 @@ impl OrderTicket { /// from the order's own side, entry and quantity. fn with_brackets( &self, + ctx: &egui::Context, mut order: OrderRequest, market: &Market<'_>, ) -> Result { @@ -480,12 +484,16 @@ impl OrderTicket { .ok_or("Enter a positive price")?; order.stop_loss = self.exit(market, order.side, entry, Some(order.quantity), false)?; (order.take_profit, order.take_profit_levels) = - self.take_profits(market, order.side, entry, order.quantity)?; + self.take_profits(ctx, market, order.side, entry, order.quantity)?; Ok(order) } /// The order the ticket describes, or what is wrong with it. - pub fn request(&self, market: &Market<'_>) -> Result { + pub fn request( + &self, + ctx: &egui::Context, + market: &Market<'_>, + ) -> Result { if market.offline.is_some() { return Err("Waiting for the broker to connect".into()); } @@ -516,11 +524,13 @@ impl OrderTicket { let rules = market.rules; // Units and value size the order before its exits; risk sizing needs the stop loss first. let mut quantity = match self.sizing { - Sizing::Units => Some(order_quantity(self.quantity, rules)?), - Sizing::Value => Some(order_quantity( - self.amount / (entry * rules.point_value), - rules, - )?), + Sizing::Units => { + Some(order_quantity(self.quantity, rules).map_err(|limit| limit.message(ctx))?) + } + Sizing::Value => Some( + order_quantity(self.amount / (entry * rules.point_value), rules) + .map_err(|limit| limit.message(ctx))?, + ), Sizing::Risk => None, }; let stop_loss = self.exit(market, self.side, entry, quantity, false)?; @@ -533,10 +543,11 @@ impl OrderTicket { .filter(|balance| balance.is_finite() && *balance > 0.0) .ok_or("Sizing by risk needs the account's balance")?; let risk = balance * self.amount / 100.0; - order_quantity(risk / ((entry - stop).abs() * rules.point_value), rules)? + order_quantity(risk / ((entry - stop).abs() * rules.point_value), rules) + .map_err(|limit| limit.message(ctx))? } }; - let (take_profit, levels) = self.take_profits(market, self.side, entry, quantity)?; + let (take_profit, levels) = self.take_profits(ctx, market, self.side, entry, quantity)?; let mut request = OrderRequest::new(&self.symbol, self.side, quantity, order_type); request.take_profit = take_profit; @@ -562,9 +573,9 @@ impl OrderTicket { .map_or((false, self.stop_loss.1), |bracket| (true, bracket)); } - fn preset(&self, name: String, market: &Market<'_>) -> OrderPreset { + fn preset(&self, ctx: &egui::Context, name: String, market: &Market<'_>) -> OrderPreset { let quantity = self - .request(market) + .request(ctx, market) .map_or(self.quantity, |request| request.quantity); OrderPreset { name, @@ -625,59 +636,107 @@ fn round_down(quantity: f64, step: f64) -> f64 { to_step(quantity, step, |steps| (steps + 1e-9).floor()) } +/// A minimum or maximum order quantity of the symbol's rules that a quantity breaks. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum QuantityLimit { + /// Below this minimum. + Minimum(f64), + /// Above this maximum. + Maximum(f64), +} + +impl QuantityLimit { + /// What the ticket shows for this limit, translated for `ctx`. + pub(crate) fn message(self, ctx: &egui::Context) -> String { + match self { + Self::Minimum(minimum) => l10n::format_text( + ctx, + "The quantity is below the minimum of {minimum}", + &[("minimum", minimum.to_string())], + ), + Self::Maximum(maximum) => l10n::format_text( + ctx, + "The quantity is above the maximum of {maximum}", + &[("maximum", maximum.to_string())], + ), + } + } +} + /// Rounds a quantity down to the symbol's step and checks its bounds. -pub(super) fn order_quantity(quantity: f64, rules: &TradingRules) -> Result { +pub(super) fn order_quantity(quantity: f64, rules: &TradingRules) -> Result { let quantity = round_down(quantity, rules.quantity_step); if !quantity.is_finite() || quantity < rules.min_quantity { - return Err(format!( - "The quantity is below the minimum of {}", - rules.min_quantity - )); + return Err(QuantityLimit::Minimum(rules.min_quantity)); } - if rules.max_quantity.is_some_and(|max| quantity > max) { - return Err(format!( - "The quantity is above the maximum of {}", - rules.max_quantity.unwrap_or_default() - )); + if let Some(max) = rules.max_quantity.filter(|max| quantity > *max) { + return Err(QuantityLimit::Maximum(max)); } Ok(quantity) } /// An order as the send button and the confirmation write it: "1 ES @ 4,000.25 LIMIT". -fn summary(request: &OrderRequest, numbers: &Numbers<'_>, quantity_decimals: usize) -> String { - let at = |price: f64, kind: &str| format!(" @ {} {kind}", numbers.price(price)); - let order_type = match request.order_type { - OrderType::Limit(price) => at(price, "LIMIT"), - OrderType::Stop(price) => at(price, "STOP"), - OrderType::StopLimit { stop, .. } => at(stop, "STOP LIMIT"), - _ => " MKT".to_owned(), +fn summary( + ctx: &egui::Context, + request: &OrderRequest, + numbers: &Numbers<'_>, + quantity_decimals: usize, +) -> String { + let (key, price) = match request.order_type { + OrderType::Limit(price) => ("{quantity} {symbol} @ {price} LIMIT", Some(price)), + OrderType::Stop(price) => ("{quantity} {symbol} @ {price} STOP", Some(price)), + OrderType::StopLimit { stop, .. } => { + ("{quantity} {symbol} @ {price} STOP LIMIT", Some(stop)) + } + _ => ("{quantity} {symbol} MKT", None), }; - format!( - "{} {}{order_type}", - numbers.quantity(request.quantity, quantity_decimals), - request.symbol + let quantity = numbers.quantity(request.quantity, quantity_decimals); + let price = price.map(|price| numbers.price(price)).unwrap_or_default(); + l10n::format_text( + ctx, + key, + &[ + ("quantity", quantity.as_str()), + ("symbol", request.symbol.as_str()), + ("price", price.as_str()), + ], ) } /// The question that confirms an order: "Buy 1 ES @ 4,000.25 LIMIT?", then its exits. -fn confirmation(request: &OrderRequest, numbers: &Numbers<'_>, quantity_decimals: usize) -> String { - let mut text = format!( - "{} {}?", - side_name(request.side), - summary(request, numbers, quantity_decimals) - ); +fn confirmation( + ctx: &egui::Context, + request: &OrderRequest, + numbers: &Numbers<'_>, + quantity_decimals: usize, +) -> String { + let order = summary(ctx, request, numbers, quantity_decimals); + let question = match request.side { + OrderSide::Buy => "Buy {order}?", + OrderSide::Sell => "Sell {order}?", + }; + let mut text = l10n::format_text(ctx, question, &[("order", order)]); + let mut line = |key: &str, values: &[(&str, String)]| { + text.push('\n'); + text.push_str(&l10n::format_text(ctx, key, values)); + }; if let Some(price) = request.take_profit { - text.push_str(&format!("\nTake profit {}", numbers.price(price))); + line("Take profit {price}", &[("price", numbers.price(price))]); } for level in &request.take_profit_levels { - text.push_str(&format!( - "\nTake profit {} for {}", - numbers.price(level.price), - numbers.quantity(level.quantity, quantity_decimals) - )); + line( + "Take profit {price} for {quantity}", + &[ + ("price", numbers.price(level.price)), + ( + "quantity", + numbers.quantity(level.quantity, quantity_decimals), + ), + ], + ); } if let Some(price) = request.stop_loss { - text.push_str(&format!("\nStop loss {}", numbers.price(price))); + line("Stop loss {price}", &[("price", numbers.price(price))]); } text } @@ -685,22 +744,28 @@ fn confirmation(request: &OrderRequest, numbers: &Numbers<'_>, quantity_decimals /// What the dialog shows for a previewed order: its confirmation, then the broker's estimates /// and warnings. pub(super) fn preview_message( + ctx: &egui::Context, request: &OrderRequest, estimate: &OrderPreview, rules: &TradingRules, numbers: &Numbers<'_>, currency: &str, ) -> String { - let mut text = confirmation(request, numbers, decimals(rules.quantity_step)); - for (label, value) in [ - ("Cost", estimate.cost), - ("Commission", estimate.commission), - ("Margin", estimate.margin), + let mut text = confirmation(ctx, request, numbers, decimals(rules.quantity_step)); + for (key, value) in [ + ("Cost: {amount} {currency}", estimate.cost), + ("Commission: {amount} {currency}", estimate.commission), + ("Margin: {amount} {currency}", estimate.margin), ] { if let Some(value) = value.filter(|value| value.is_finite()) { - text.push_str(&format!( - "\n{label}: {} {currency}", - grouped(value, 2, false) + text.push('\n'); + text.push_str(&l10n::format_text( + ctx, + key, + &[ + ("amount", grouped(value, 2, false).as_str()), + ("currency", currency), + ], )); } } @@ -807,13 +872,13 @@ mod tests { stop_loss: ticks(8.0), ..OrderTicket::default() }; - let request = ticket.request(&market).unwrap(); + let ctx = egui::Context::default(); + let request = ticket.request(&ctx, &market).unwrap(); assert_eq!( (request.quantity, request.take_profit, request.stop_loss), (50.0, Some(103.0), Some(97.0)) ); // The control is on the Order tab for the pending kind. - let ctx = egui::Context::default(); let output = ctx.run_ui(egui::RawInput::default(), |ui| { ticket.show(ui, &market, &mut vec![], &mut false); }); @@ -824,19 +889,19 @@ mod tests { assert!(risk, "limit orders offer the risk control"); // A sell stop from the ladder: exits lie the other way from the buy above. let order = OrderRequest::new("ES", OrderSide::Sell, 3.0, OrderType::Stop(98.0)); - let order = ticket.with_brackets(order, &market).unwrap(); + let order = ticket.with_brackets(&ctx, order, &market).unwrap(); assert_eq!( (order.take_profit, order.stop_loss), (Some(94.0), Some(100.0)) ); assert_eq!( - confirmation(&order, &market.numbers(), 0), + confirmation(&ctx, &order, &market.numbers(), 0), "Sell 3 ES @ 98.00 STOP?\nTake profit 94.00\nStop loss 100.00" ); // A level at 24 ticks = 6 points for half of 3: 1.5 rounds down to 1 and the first takes 2. ticket.levels = vec![(ticks(24.0).1, 50.0)]; let order = OrderRequest::new("ES", OrderSide::Sell, 3.0, OrderType::Stop(98.0)); - let order = ticket.with_brackets(order, &market).unwrap(); + let order = ticket.with_brackets(&ctx, order, &market).unwrap(); assert_eq!(order.take_profit, None); assert_eq!( order.take_profit_levels, @@ -846,12 +911,19 @@ mod tests { ] ); assert_eq!( - confirmation(&order, &market.numbers(), 0), + confirmation(&ctx, &order, &market.numbers(), 0), "Sell 3 ES @ 98.00 STOP?\nTake profit 94.00 for 2\nTake profit 92.00 for 1\nStop loss 100.00" ); + // Each line reaches the host's lookup as one template. + let marked = egui::Context::default(); + crate::localization::mark_keys(&marked); + assert_eq!( + confirmation(&marked, &order, &market.numbers(), 0), + "~~3~ES~98.00~~\n~94.00~2~\n~92.00~1~\n~100.00~" + ); ticket.stop_loss = ticks(0.0); let order = OrderRequest::new("ES", OrderSide::Sell, 3.0, OrderType::Stop(98.0)); - assert!(ticket.with_brackets(order, &market).is_err()); + assert!(ticket.with_brackets(&ctx, order, &market).is_err()); } /// Guards sizing and brackets against the published definitions: value sizing buys @@ -1044,7 +1116,7 @@ mod tests { ..OrderTicket::default() }; let actual = ticket(take_profit, stop_loss) - .request(&market) + .request(&egui::Context::default(), &market) .map(|r| (r.quantity, r.take_profit, r.stop_loss)) .map_err(|_| ()); assert_eq!(actual, expected, "{side:?} {sizing:?} {amount}"); @@ -1060,7 +1132,7 @@ mod tests { Bracket::at(mode, price, side, 4_000.0, 0.25, per_point, profit) }; let actual = ticket(Some(at(take_profit, true)), Some(at(stop_loss, false))) - .request(&market) + .request(&egui::Context::default(), &market) .map(|r| (r.quantity, r.take_profit, r.stop_loss)); assert_eq!(actual, Ok(expected.unwrap()), "{side:?} {mode:?}"); } @@ -1186,7 +1258,7 @@ mod tests { stop_loss: (stop_loss.is_some(), stop_loss.unwrap_or(ticks(1.0))), ..OrderTicket::default() }; - let request = ticket.request(&market); + let request = ticket.request(&egui::Context::default(), &market); let actual = request.as_ref().map_err(|_| ()).map(|request| { ( request.take_profit, @@ -1198,7 +1270,10 @@ mod tests { if let Ok(request) = request { let mut reopened = OrderTicket::default(); reopened.open(&request); - assert_eq!(reopened.request(&market), Ok(request)); + assert_eq!( + reopened.request(&egui::Context::default(), &market), + Ok(request) + ); } } // A quoted market order enters a buy at the ask and a sell at the bid: 4 ticks = 1 point. @@ -1214,7 +1289,7 @@ mod tests { take_profit: (true, ticks(4.0)), ..OrderTicket::default() }; - let request = ticket.request("ed).unwrap(); + let request = ticket.request(&egui::Context::default(), "ed).unwrap(); assert_eq!(request.take_profit, Some(take_profit), "{side:?}"); } } diff --git a/vendor/egui-charts/src/ui/trading/ticket/view.rs b/vendor/egui-charts/src/ui/trading/ticket/view.rs index 477cb2f..ac1a063 100644 --- a/vendor/egui-charts/src/ui/trading/ticket/view.rs +++ b/vendor/egui-charts/src/ui/trading/ticket/view.rs @@ -70,7 +70,7 @@ impl OrderTicket { // A new order from the ladder waits for confirmation without one-click trading. match ladder { Some(Action::Place(request)) => { - let bracketed = self.with_brackets(request, market); + let bracketed = self.with_brackets(ui.ctx(), request, market); self.dom_error = bracketed.as_ref().err().cloned(); match bracketed { Ok(request) if *one_click => Some(Action::Place(request)), @@ -135,6 +135,7 @@ impl OrderTicket { if let Some(request) = &self.confirm { let mut open = true; let message = confirmation( + ui.ctx(), request, &market.numbers(), decimals(market.rules.quantity_step), @@ -266,7 +267,7 @@ impl OrderTicket { ) .clicked() { - let preset = self.preset(name.to_owned(), market); + let preset = self.preset(ui.ctx(), name.to_owned(), market); presets.retain(|existing| existing.name != preset.name); presets.push(preset); self.preset_name.clear(); @@ -315,7 +316,7 @@ impl OrderTicket { /// The full-width send button in the side's colour, or what keeps the order from being sent. fn send(&mut self, ui: &mut Ui, market: &Market<'_>) -> Option { let theme = ui.active_theme(); - let request = self.request(market); + let request = self.request(ui.ctx(), market); if let Err(reason) = &request { ui.label( RichText::new(l10n::text(ui.ctx(), reason)) @@ -341,16 +342,13 @@ impl OrderTicket { let name = side_name(self.side); let detail = request.as_ref().map_or(String::new(), |request| { summary( + ui.ctx(), request, &market.numbers(), decimals(market.rules.quantity_step), ) }); - let translated_label = format!( - "{} {}", - l10n::text(ui.ctx(), name), - l10n::text(ui.ctx(), &detail) - ); + let translated_label = format!("{} {detail}", l10n::text(ui.ctx(), name)); response .widget_info(|| WidgetInfo::labeled(Role::Button, request.is_ok(), &translated_label)); let mut fill = side_fill(&theme, self.side); @@ -504,7 +502,7 @@ mod tests { ticket.price, price, "an invalid entered price must not become the market price" ); - assert!(ticket.request(&market).is_err()); + assert!(ticket.request(&egui::Context::default(), &market).is_err()); } } } diff --git a/vendor/egui-charts/src/ui/trading/view.rs b/vendor/egui-charts/src/ui/trading/view.rs index 96c2435..1b32b6e 100644 --- a/vendor/egui-charts/src/ui/trading/view.rs +++ b/vendor/egui-charts/src/ui/trading/view.rs @@ -362,6 +362,7 @@ impl Trading { "order_preview", "Order preview", ticket::preview_message( + ui.ctx(), request, estimate, &self.rules, @@ -414,7 +415,7 @@ impl Trading { return; } let market = self.market(chart, &colors); - if let Ok(request) = self.ticket.request(&market) + if let Ok(request) = self.ticket.request(ui.ctx(), &market) && request.order_type != OrderType::Market { let _theme = chart diff --git a/vendor/egui-charts/src/ui/widget_bar/panels/alerts_panel.rs b/vendor/egui-charts/src/ui/widget_bar/panels/alerts_panel.rs index 3cfa943..5a77501 100644 --- a/vendor/egui-charts/src/ui/widget_bar/panels/alerts_panel.rs +++ b/vendor/egui-charts/src/ui/widget_bar/panels/alerts_panel.rs @@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize}; use crate::data::{FeedError, inbox::Inbox}; use crate::icons::icons; -use crate::model::{Alert, AlertCondition, AlertId, AlertSource, AlertStatus}; +use crate::model::{Alert, AlertCondition, AlertId, AlertSource, AlertSourceName, AlertStatus}; use crate::services::{AlertEvent, Alerts, Listener}; use crate::theme::ThemeExt; use crate::ui::dialogs::alert_dialog::rule_form; @@ -163,7 +163,7 @@ pub struct AlertsPanel { restoring: Option, staged_display: Vec<(u64, PresentationEdit, bool)>, next_reply: u64, - sources: Vec<(AlertSource, String)>, + sources: Vec<(AlertSource, AlertSourceName)>, symbol: String, draft: Alert, inputs: Option<(crate::model::AlertInputs, Option)>, @@ -331,9 +331,9 @@ impl AlertsPanel { } } - /// Offer these study outputs and drawings, as stable identifiers and display names, to the - /// inline alert form. - pub fn set_sources(&mut self, sources: Vec<(AlertSource, String)>) { + /// Offer these study outputs and drawings, as stable identifiers and names, which are + /// translated when shown, to the inline alert form. + pub fn set_sources(&mut self, sources: Vec<(AlertSource, AlertSourceName)>) { self.sources = sources; } diff --git a/vendor/egui-charts/src/ui/widget_bar/panels/object_tree/panel.rs b/vendor/egui-charts/src/ui/widget_bar/panels/object_tree/panel.rs index 2cf354e..aacf1d5 100644 --- a/vendor/egui-charts/src/ui/widget_bar/panels/object_tree/panel.rs +++ b/vendor/egui-charts/src/ui/widget_bar/panels/object_tree/panel.rs @@ -538,12 +538,15 @@ impl ObjectTreePanel { ("3", format!("{}", visible)), ( "4", - (if selected > 0 { - format!(" • {selected} selected") + if selected > 0 { + l10n::format_text( + ui.ctx(), + " • {count} selected", + &[("count", selected.to_string())], + ) } else { String::new() - }) - .to_string(), + }, ), ], )) diff --git a/vendor/egui-charts/src/ui/widget_bar/panels/object_tree/source_tree.rs b/vendor/egui-charts/src/ui/widget_bar/panels/object_tree/source_tree.rs index ea84fd3..2af5efe 100644 --- a/vendor/egui-charts/src/ui/widget_bar/panels/object_tree/source_tree.rs +++ b/vendor/egui-charts/src/ui/widget_bar/panels/object_tree/source_tree.rs @@ -171,7 +171,11 @@ fn render_group( }; if IconButton::new(icon) .size(ButtonSize::SM) - .tooltip(format!("Toggle {name}")) + .tooltip(l10n::format_text( + ui.ctx(), + "Toggle {name}", + &[("name", l10n::text(ui.ctx(), name))], + )) .show(ui) .clicked() { @@ -369,4 +373,33 @@ mod tests { } } } + + /// The group's toggle names the group as its header shows it, in the host's language. + #[test] + fn group_toggle_names_the_translated_group() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut harness = Harness::builder() + .with_context_setup(|ctx| { + crate::icons::install_loader(ctx); + l10n::set_translator(ctx, |english| match english { + "Indicators" => Some("Indikatoren".into()), + "Toggle {name}" => Some("{name} umschalten".into()), + _ => None, + }); + }) + .build_ui(|ui| { + let mut sources = [SourceItem::indicator(1, "SMA", egui::Color32::RED)]; + render_source_tree( + ui, + &mut sources, + &ObjectTreeConfig { + group_by_type: true, + ..Default::default() + }, + &mut ObjectTreeState::new(), + ); + }); + harness.run(); + assert!(harness.query_by_label("Indikatoren umschalten").is_some()); + } } diff --git a/vendor/egui-charts/src/ui/widget_bar/panels/symbol_details.rs b/vendor/egui-charts/src/ui/widget_bar/panels/symbol_details.rs index 6a53cc5..338397e 100644 --- a/vendor/egui-charts/src/ui/widget_bar/panels/symbol_details.rs +++ b/vendor/egui-charts/src/ui/widget_bar/panels/symbol_details.rs @@ -14,7 +14,7 @@ use super::market_details::{MarketDetail, MarketDetailRequest, PeriodReturn, Sea use super::price_decimals; use super::{HEADER_HEIGHT, grouped, signed, weighted}; use crate::data::inbox::Inbox; -use crate::data::{Datafeed, FeedError, SymbolDetails}; +use crate::data::{CompanyFinancials, Datafeed, FeedError, SymbolDetails}; use crate::icons::icons; use crate::model::{ExtendedSession, Instrument, Quote, TimezoneId}; use crate::scales::StudyFormat; @@ -59,6 +59,7 @@ struct Notes { /// What an inbox answer is for. enum Request { Details(String), + Financials(String), Load(String), Save(String, String), } @@ -76,13 +77,16 @@ enum Request { /// [`SymbolDetails::url`] gets a link to the instrument beside its name, and one that supplies /// [`SymbolDetails::category`] gets the category under it. For each new symbol the panel asks the /// feed for [`Datafeed::symbol_details`] and shows the statistics, on a card, and the profile it -/// answers; an empty section, or a feed that does not support the request, shows nothing. Notes +/// answers; an empty section, or a feed that does not support the request, shows nothing. It also +/// asks for [`Datafeed::financials`] and holds a nonempty answer in +/// [`financials`](Self::financials). Notes /// are kept in memory per symbol, and with a storage service attached they are read from and /// written to one [`StoreKind::SymbolNotes`] document per symbol as they are edited, one write per /// document at a time. Call [`poll`](Self::poll) each frame, even while the panel is hidden, then /// [`show`](Self::show) while it is open. The More menu's Financials item is reported by /// [`take_financials_request`](Self::take_financials_request), for the host to open a -/// [`FinancialsPanel`](crate::ui::financials::FinancialsPanel) with the company's figures. +/// [`FinancialsPanel`](crate::ui::financials::FinancialsPanel) with the company's figures, such +/// as [`financials`](Self::financials). /// /// The Performance and Seasonality sections show what the host supplies. Call /// [`take_market_requests`](Self::take_market_requests) each frame: the first call for a symbol @@ -99,6 +103,7 @@ pub struct SymbolDetailsPanel { timezone: TimezoneId, hidden: HashSet<&'static str>, details: Option, + financials: Option, returns: Option>>, seasonality: Option>, error: Option, @@ -118,7 +123,8 @@ impl SymbolDetailsPanel { Self::default() } - /// Ask `feed` for the details of each symbol from now on, starting with the shown one. + /// Ask `feed` for the details and financials of each symbol from now on, starting with the + /// shown one. pub fn set_feed(&mut self, feed: Arc) { self.feed = Some(feed); if let Some(symbol) = self.symbol().map(str::to_owned) { @@ -131,7 +137,7 @@ impl SymbolDetailsPanel { self.storage = Some(storage); self.notes.clear(); self.requests - .retain(|_, request| matches!(request, Request::Details(_))); + .retain(|_, request| matches!(request, Request::Details(_) | Request::Financials(_))); if let Some(symbol) = self.symbol().map(str::to_owned) { self.load_notes(symbol); } @@ -147,6 +153,7 @@ impl SymbolDetailsPanel { self.quote = None; self.average_volume = None; self.details = None; + self.financials = None; self.returns = None; self.seasonality = None; self.error = None; @@ -192,6 +199,11 @@ impl SymbolDetailsPanel { } } + /// The shown symbol's [`Datafeed::financials`] once the feed answers with at least one page. + pub fn financials(&self) -> Option<&CompanyFinancials> { + self.financials.as_ref() + } + /// Whether the user chose Financials in the More menu since the last call. pub fn take_financials_request(&mut self) -> bool { std::mem::take(&mut self.financials_requested) @@ -251,6 +263,8 @@ impl SymbolDetailsPanel { if let Some(feed) = self.feed.clone() { let key = self.key(Request::Details(symbol.clone())); feed.symbol_details(&symbol, self.inbox.reply(key)); + let key = self.key(Request::Financials(symbol.clone())); + feed.financials(&symbol, self.inbox.reply(key)); } } @@ -296,6 +310,28 @@ impl SymbolDetailsPanel { } } } + Request::Financials(symbol) => { + let result = *answer + .downcast::>() + .expect("company financials"); + if !current(&symbol) { + continue; + } + match result { + Ok(financials) => { + self.financials = + Some(financials).filter(|figures| !figures.pages.is_empty()); + } + Err(FeedError::NotSupported) => {} + Err(error) => { + self.error = Some(l10n::format_text( + ctx, + "Financials unavailable: {error}", + &[("error", error.to_string().as_str())], + )) + } + } + } Request::Load(symbol) => { let result = answer .downcast::, FeedError>>() @@ -926,10 +962,11 @@ fn volume_bar(ui: &mut Ui, volume: f64, average: f64) { #[cfg(test)] mod tests { use super::*; - use crate::data::{HistoryPage, HistoryRequest, Reply}; + use crate::data::{FinancialPage, HistoryPage, HistoryRequest, Reply}; use std::sync::Mutex; - /// Keeps detail requests for the test to answer in any order. + /// Keeps detail requests for the test to answer in any order, and answers financials at once + /// with a page named after the symbol. #[derive(Default)] struct Feed(Mutex)>>); @@ -938,6 +975,11 @@ mod tests { reply.send(Ok(HistoryPage::default())); } + fn financials(&self, symbol: &str, reply: Reply) { + let page = FinancialPage::new(symbol, Vec::new()); + reply.send(Ok(CompanyFinancials::new(None, vec![page]))); + } + fn symbol_details(&self, symbol: &str, reply: Reply) { self.0.lock().unwrap().push((symbol.into(), reply)); } @@ -1018,9 +1060,10 @@ mod tests { let store = Arc::new(Store::default()); let mut panel = SymbolDetailsPanel::new(); panel.set_feed(feed.clone()); - panel.set_storage(store.clone()); panel.set_instrument(&Instrument::new("AAPL")); panel.set_instrument(&Instrument::new("MSFT")); + // Storage attached while the feed's answers are on their way does not drop them. + panel.set_storage(store.clone()); // The answer for the previous symbol arrives last and must not replace the current one. let requests = std::mem::take(&mut *feed.0.lock().unwrap()); for (symbol, reply) in requests.into_iter().rev() { @@ -1037,6 +1080,7 @@ mod tests { assert!(shown.contains(&"Facts".into()), "{shown:?}"); assert!(!shown.contains(&"Key statistics".into()), "{shown:?}"); assert!(!shown.contains(&"Profile".into()), "{shown:?}"); + assert_eq!(panel.financials().unwrap().pages[0].name, "MSFT"); // A second edit waits for the first write of the same document, then writes the latest text. let edit = |panel: &mut SymbolDetailsPanel, text: &str| { diff --git a/vendor/egui-charts/src/ui/widget_bar/panels/watchlist.rs b/vendor/egui-charts/src/ui/widget_bar/panels/watchlist.rs index 7fb1f4e..cdb18b8 100644 --- a/vendor/egui-charts/src/ui/widget_bar/panels/watchlist.rs +++ b/vendor/egui-charts/src/ui/widget_bar/panels/watchlist.rs @@ -131,6 +131,8 @@ pub enum WatchlistAction { None, /// Show this symbol on the chart. The panel already marks it selected. SelectSymbol(String), + /// Open the host's options view for this symbol. + Options(String), /// Let the user pick a symbol, such as with symbol search, and pass it to /// [`WatchlistPanel::add_symbol`]. AddSymbol, @@ -172,6 +174,7 @@ struct RowDrag(egui::Id, usize); /// expands its symbols. Unsorted rows are dragged to reorder, and rows are right-clicked to /// flag, rename or remove. The host persists [`lists`](Self::lists) and handles file intents. pub struct WatchlistPanel { + options_action: bool, lists: Vec, active: usize, quotes: HashMap, @@ -227,6 +230,7 @@ impl WatchlistPanel { lists.push(Watchlist::new("Watchlist")); } Self { + options_action: false, lists, active: 0, quotes: HashMap::new(), @@ -248,6 +252,9 @@ impl WatchlistPanel { } } + /// Enable the host-provided options action on symbol context menus. + pub fn set_options_action(&mut self, enabled: bool) { self.options_action = enabled; } + /// Shows these columns after the symbol, in order; the default is /// [`WatchlistColumn::DEFAULT`]. A quote without a column's figure shows a dash, apart from a /// symbol without a quote, which shows nothing. A sort by a column no longer shown is dropped. @@ -456,6 +463,7 @@ impl WatchlistPanel { section, flag_filter, selected, + options_action, .. } = self; let theme = ui.active_theme(); @@ -1036,6 +1044,10 @@ impl WatchlistPanel { }); } response.context_menu(|ui| { + if *options_action && ui.button("View options").clicked() { + action = WatchlistAction::Options(symbol.clone()); + ui.close(); + } ui.horizontal(|ui| { for choice in WatchlistFlag::ALL { let (swatch, response) = ui diff --git a/vendor/egui-charts/src/ui_kit/command_palette/fuzzy.rs b/vendor/egui-charts/src/ui_kit/command_palette/fuzzy.rs index 0e01d3d..3edc678 100644 --- a/vendor/egui-charts/src/ui_kit/command_palette/fuzzy.rs +++ b/vendor/egui-charts/src/ui_kit/command_palette/fuzzy.rs @@ -9,10 +9,95 @@ pub struct FuzzyMatch { pub matched_indices: Vec, } +/// How much a tier of match outweighs the bonuses within it. +const TIER: i32 = 1_000_000; + +fn is_separator(c: char) -> bool { + c == ' ' || c == '_' || c == '-' +} + +/// Score `indices` (ascending positions in `target`) with the per-letter bonuses. +fn score_indices(target: &[char], indices: &[usize]) -> i32 { + let mut score = 0i32; + for (k, &i) in indices.iter().enumerate() { + score += 10; + if k > 0 && indices[k - 1] + 1 == i { + score += 15; + } + if i == 0 || is_separator(target[i - 1]) { + score += 20; + } + if i == 0 { + score += 25; + } + } + // Penalty for unmatched characters + score -= (target.len() - indices.len()) as i32; + // Bonus for exact match + if indices.len() == target.len() { + score += 50; + } + score +} + +/// Match `query` against `target`, both lowercase. Returns the tier of the match (4 the query is +/// the whole target or one of its words, 3 it starts a word, 2 it occurs inside a word, 1 its +/// letters occur in order) with the match itself, preferring the best occurrence of the tier. +fn locate(query: &[char], target: &[char]) -> Option<(i32, FuzzyMatch)> { + let n = query.len(); + let mut best: Option<(i32, usize)> = None; + for start in 0..=target.len().saturating_sub(n) { + if target.len() < n || target[start..start + n] != *query { + continue; + } + let word_start = start == 0 || is_separator(target[start - 1]); + let word_end = start + n == target.len() || is_separator(target[start + n]); + let tier = match (word_start, word_end) { + (true, true) => 4, + (true, false) => 3, + _ => 2, + }; + if best.is_none_or(|(t, _)| tier > t) { + best = Some((tier, start)); + } + } + let (tier, indices) = match best { + Some((tier, start)) => (tier, (start..start + n).collect()), + None => { + // Letters in order, each at its first occurrence after the previous one. + let mut indices = Vec::new(); + let mut wanted = query.iter().peekable(); + for (i, c) in target.iter().enumerate() { + if wanted.next_if(|&w| w == c).is_some() { + indices.push(i); + } + } + if wanted.peek().is_some() { + return None; + } + (1, indices) + } + }; + Some(( + tier, + FuzzyMatch { + score: score_indices(target, &indices), + matched_indices: indices, + }, + )) +} + +fn lowercase(text: &str) -> Vec { + text.to_lowercase().chars().collect() +} + /// Perform fuzzy matching of a query against a target string /// /// Returns `Some(FuzzyMatch)` if the query matches, `None` otherwise. -/// The match is case-insensitive and supports non-contiguous matching. +/// The match is case-insensitive and supports non-contiguous matching. A query that is the target +/// or one of its words scores above one that starts a word, above one inside a word, above one +/// whose letters are only found in order; when the query occurs contiguously, that occurrence is +/// the one matched. pub fn fuzzy_match(query: &str, target: &str) -> Option { if query.is_empty() { return Some(FuzzyMatch { @@ -20,65 +105,35 @@ pub fn fuzzy_match(query: &str, target: &str) -> Option { matched_indices: Vec::new(), }); } + let (tier, mut m) = locate(&lowercase(query), &lowercase(target))?; + m.score += tier * TIER; + Some(m) +} - let query_lower: Vec = query.to_lowercase().chars().collect(); - let target_lower: Vec = target.to_lowercase().chars().collect(); - - let mut score = 0i32; - let mut matched_indices = Vec::new(); - let mut query_idx = 0; - let mut prev_matched = false; - let mut prev_was_separator = true; // Start of string counts as separator - - for (target_idx, &target_char) in target_lower.iter().enumerate() { - let is_separator = target_char == ' ' || target_char == '_' || target_char == '-'; - - if query_idx < query_lower.len() && target_char == query_lower[query_idx] { - matched_indices.push(target_idx); - query_idx += 1; - - // Scoring bonuses - if prev_matched { - // Consecutive match bonus - score += 15; - } - if prev_was_separator { - // Word boundary bonus (match at start of word) - score += 20; - } - if target_idx == 0 { - // First character bonus - score += 25; - } - - // Base score for a match - score += 10; - prev_matched = true; - } else { - prev_matched = false; +/// Rank a command for `query`: its `label` counts above `other` text (description, category, +/// keywords). From the top: the label is or has a word equal to the query, a label word starts +/// with it, the label contains it, `other` contains it contiguously, then letters in order over +/// the label and `other` as one text. The indices point into `label`, and are empty when `other` +/// made the match. +pub(super) fn rank(query: &str, label: &str, other: &str) -> Option { + let query = lowercase(query); + let (label, other) = (lowercase(label), lowercase(other)); + // Levels 5, 4, 3 are a label tier of 4, 3, 2; level 2 is `other` at tier 2 or above. + let (level, mut m) = match (locate(&query, &label), locate(&query, &other)) { + (Some((tier, m)), _) if tier >= 2 => (tier + 1, m), + (_, Some((tier, mut m))) if tier >= 2 => { + m.matched_indices.clear(); + (2, m) } - - prev_was_separator = is_separator; - } - - // Did we match all query characters? - if query_idx == query_lower.len() { - // Penalty for unmatched characters - let unmatched_count = target_lower.len() - matched_indices.len(); - score -= unmatched_count as i32; - - // Bonus for exact match - if matched_indices.len() == target_lower.len() { - score += 50; + _ => { + // A query may run from the label into the other text, as the row reads. + let (_, mut m) = locate(&query, &[&label[..], &[' '], &other[..]].concat())?; + m.matched_indices.retain(|&i| i < label.len()); + (1, m) } - - Some(FuzzyMatch { - score, - matched_indices, - }) - } else { - None - } + }; + m.score += level * TIER; + Some(m) } /// Search through a list of items and return matches sorted by score @@ -124,11 +179,87 @@ mod tests { } #[test] - fn test_word_boundary_bonus() { - // "nc" should score higher on "New Chart" than "branch" - // because N matches at word boundary - let score_nc = fuzzy_match("nc", "New Chart").unwrap().score; - let score_branch = fuzzy_match("nc", "branch").unwrap().score; - assert!(score_nc > score_branch); + fn a_command_the_query_names_ranks_above_scattered_letters() { + // (query, (label, other text) listed first, (label, other text) listed after it). Each + // pair is worked by hand from the tiers: label word, label word start, label substring, + // other text contiguous, letters in order. + for (query, (hi_label, hi_other), (lo_label, lo_other)) in [ + // "sma" is a word of "Add SMA"; "Add AO" has no label match and the s, m, a of + // "Studies Momentum Awesome oscillator" are scattered over three words. + ( + "sma", + ("Add SMA", "Studies"), + ("Add AO", "Studies Momentum Awesome oscillator"), + ), + // "log" starts the word "logarithmic"; "long position tool" holds l, o, g apart. + ( + "log", + ("Toggle logarithmic scale", "Chart"), + ("Long Position tool", "Drawings"), + ), + // "atr" is a word of "Add ATR"; "add tr" holds a, t, r apart. + ("atr", ("Add ATR", "Studies"), ("Add TR", "Studies")), + // "cci" is a word of "Add CCI"; "cyclic lines" holds c, c, i apart. + ( + "cci", + ("Add CCI", "Studies"), + ("Curve tool", "Drawings cyclic lines"), + ), + // "grid" is a word of "Toggle grid"; "gann retrace indicator" holds g, r, i, d apart. + ( + "grid", + ("Toggle grid", "Chart"), + ("Gann Box tool", "Gann retrace indicator"), + ), + // "settings" is a word of "Chart settings"; the other text holds s, e, t, t, i, n, + // g, s over several words. + ( + "settings", + ("Chart settings", "Chart"), + ("Toggle grid", "Chart set tight inner grid spacing"), + ), + // Letters that begin three words are still only letters in order. + ("sma", ("Add SMA", "Studies"), ("Show Many Assets", "Chart")), + // The label tiers, then other text, then letters in order, for one query. + ("log", ("Log scale", ""), ("Logarithmic scale", "")), + ("log", ("Logarithmic scale", ""), ("Backlog view", "")), + ( + "log", + ("Backlog view", ""), + ("Chart", "Show logarithmic prices"), + ), + ( + "log", + ("Chart", "Show logarithmic prices"), + ("Long Position tool", ""), + ), + ] { + let rank = |label, other| { + rank(query, label, other) + .unwrap_or_else(|| panic!("{query:?} in {label:?}")) + .score + }; + assert!( + rank(hi_label, hi_other) > rank(lo_label, lo_other), + "{query:?}: {hi_label:?} before {lo_label:?}" + ); + } + } + + #[test] + fn highlight_indices_follow_the_label_only() { + // "log" inside "Toggle logarithmic scale" sits at 7..10, not at the scattered first + // l, o, g of the text. + let m = rank("log", "Toggle logarithmic scale", "Chart").unwrap(); + assert_eq!(m.matched_indices, [7, 8, 9]); + let m = rank("log", "Chart", "Show logarithmic prices").unwrap(); + assert!(m.matched_indices.is_empty()); + } + + #[test] + fn letters_in_order_may_run_from_the_label_into_the_other_text() { + // The space after "grid" is the one before the category; the indices stop at the label. + let m = rank("grid ", "Toggle grid", "Chart").unwrap(); + assert_eq!(m.matched_indices, [7, 8, 9, 10]); } } diff --git a/vendor/egui-charts/src/ui_kit/command_palette/palette.rs b/vendor/egui-charts/src/ui_kit/command_palette/palette.rs index 17705b4..8c16b9f 100644 --- a/vendor/egui-charts/src/ui_kit/command_palette/palette.rs +++ b/vendor/egui-charts/src/ui_kit/command_palette/palette.rs @@ -1,7 +1,7 @@ //! Command palette widget use super::command::Command; -use super::fuzzy::{FuzzyMatch, fuzzy_match}; +use super::fuzzy::{FuzzyMatch, rank}; use crate::icons::icons; use crate::localization as l10n; use crate::theme::ThemeExt; @@ -19,6 +19,8 @@ pub struct CommandPalette { selected_index: usize, /// Cached filtered results (command index, match) filtered: Vec<(usize, FuzzyMatch)>, + /// The query `filtered` was built for; a different query puts the highlight back on row 0. + filtered_query: String, focus_search: bool, context: Option, } @@ -31,6 +33,7 @@ impl CommandPalette { search_query: String::new(), selected_index: 0, filtered: Vec::new(), + filtered_query: String::new(), focus_search: true, context: None, } @@ -56,6 +59,7 @@ impl CommandPalette { self.search_query.clear(); self.selected_index = 0; self.filtered.clear(); + self.filtered_query.clear(); self.focus_search = true; } @@ -66,17 +70,27 @@ impl CommandPalette { // An empty query lists nothing, so no command is highlighted before the user types. if !self.search_query.is_empty() { for (idx, cmd) in self.commands.iter().enumerate() { - let mut searchable = cmd.searchable_text(); + // The row paints the translated text, but the English text matches too. + let mut labels = vec![cmd.label.clone()]; + let mut other: Vec = cmd + .description + .iter() + .chain(cmd.category.iter()) + .chain(cmd.keywords.iter()) + .cloned() + .collect(); if let Some(ctx) = &self.context { - for text in std::iter::once(&cmd.label) - .chain(cmd.description.iter()) - .chain(cmd.category.iter()) - { - searchable.push(' '); - searchable.push_str(&l10n::text(ctx, text)); + labels.insert(0, l10n::text(ctx, &cmd.label)); + for text in cmd.description.iter().chain(cmd.category.iter()) { + other.push(l10n::text(ctx, text)); } } - if let Some(m) = fuzzy_match(&self.search_query, &searchable) { + let other = other.join(" "); + let best = labels + .iter() + .filter_map(|label| rank(&self.search_query, label, &other)) + .reduce(|a, b| if b.score > a.score { b } else { a }); + if let Some(m) = best { self.filtered.push((idx, m)); } } @@ -85,9 +99,10 @@ impl CommandPalette { self.filtered.sort_by_key(|m| std::cmp::Reverse(m.1.score)); } - // Reset selection if out of bounds - if self.selected_index >= self.filtered.len() { + // Arrow keys move within the list they were pressed in; a new query starts at the best match. + if self.filtered_query != self.search_query || self.selected_index >= self.filtered.len() { self.selected_index = 0; + self.filtered_query.clone_from(&self.search_query); } } @@ -142,12 +157,15 @@ impl CommandPalette { return None; } + let before = self.selected_index; if move_up && self.selected_index > 0 { self.selected_index -= 1; } if move_down && self.selected_index + 1 < self.filtered.len() { self.selected_index += 1; } + // Only a key or a new query scrolls to the highlight, so the wheel still scrolls freely. + let mut reveal_selected = self.selected_index != before; if execute && !self.filtered.is_empty() { ctx.input_mut(|i| i.consume_key(i.modifiers, Key::Enter)); @@ -196,6 +214,7 @@ impl CommandPalette { } if response.changed() { self.update_filter(); + reveal_selected = true; } }, ); @@ -219,7 +238,12 @@ impl CommandPalette { .show(ui, |ui| { for (list_idx, (cmd_idx, _)) in self.filtered.iter().enumerate() { let cmd = &self.commands[*cmd_idx]; - if command_row(ui, cmd, list_idx == self.selected_index).clicked() { + let selected = list_idx == self.selected_index; + let row = command_row(ui, cmd, selected); + if selected && reveal_selected { + row.scroll_to_me(None); + } + if row.clicked() { executed_command = Some(cmd.id.clone()); } } @@ -659,4 +683,102 @@ mod tests { p.remove_command("c"); assert_eq!(frame(&ctx, &mut p, Some(Key::Enter)).as_deref(), Some("b")); } + + #[test] + fn typing_returns_the_highlight_to_the_first_result() { + let (ctx, mut p) = ( + Context::default(), + CommandPalette::new(vec![ + Command::new("sto", "Add Stochastic RSI"), + Command::new("con", "Add Connors RSI"), + Command::new("rsi", "Add RSI"), + Command::new("ao", "Add AO"), + ]), + ); + p.search_query = "a".into(); + frame(&ctx, &mut p, None); + frame(&ctx, &mut p, None); + frame(&ctx, &mut p, Some(Key::ArrowDown)); + frame(&ctx, &mut p, Some(Key::ArrowDown)); + p.search_query = "add rsi".into(); + assert_eq!( + frame(&ctx, &mut p, Some(Key::Enter)).as_deref(), + Some("rsi") + ); + } + + #[test] + fn arrow_keys_keep_the_highlighted_row_in_view() { + let (ctx, mut p) = ( + Context::default(), + CommandPalette::new( + (0..60) + .map(|i| Command::new(format!("a{i}"), format!("Action {i}"))) + .collect(), + ), + ); + p.search_query = "ction".into(); + frame(&ctx, &mut p, None); + frame(&ctx, &mut p, None); + let selected = ctx.global_style().visuals.selection.bg_fill; + // Runs one frame, a second after the last so the scroll animation completes, and counts + // the highlight rows painted inside the list. + let mut time = 0.0; + let mut run = |event: Option| { + let mut open = true; + time += 1.0; + let output = ctx.run_ui( + RawInput { + time: Some(time), + events: event.into_iter().collect(), + screen_rect: Some(Rect::from_min_size( + egui::Pos2::ZERO, + Vec2::new(1440.0, 900.0), + )), + ..Default::default() + }, + |ui| { + p.show(ui.ctx(), &mut open); + }, + ); + let visible = output + .shapes + .iter() + .filter(|clipped| { + matches!(&clipped.shape, egui::Shape::Rect(r) + if r.fill == selected && clipped.clip_rect.contains_rect(r.rect)) + }) + .count(); + output.drop_without_applying_deltas(); + visible + }; + let key = |key| { + Some(Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers: Modifiers::NONE, + }) + }; + // Down and Up past the rows that fit, then settle. + let mut visible_highlights = 0; + for event in std::iter::repeat_n(key(Key::ArrowDown), 35) + .chain(std::iter::repeat_n(key(Key::ArrowUp), 3)) + .chain([None, None]) + { + visible_highlights = run(event); + } + assert_eq!( + visible_highlights, 1, + "the highlighted row is painted in view" + ); + // More text (typed at the start, where the field's cursor begins) puts the highlight on the + // first row, which must come into view as well. + for event in [Some(Event::Text("a".into())), None, None] { + visible_highlights = run(event); + } + assert_eq!(visible_highlights, 1, "the first result is painted in view"); + assert_eq!((p.search_query.as_str(), p.selected_index), ("action", 0)); + } } diff --git a/vendor/egui-charts/src/ui_kit/notifications/panel.rs b/vendor/egui-charts/src/ui_kit/notifications/panel.rs index 08c5d40..e2781ab 100644 --- a/vendor/egui-charts/src/ui_kit/notifications/panel.rs +++ b/vendor/egui-charts/src/ui_kit/notifications/panel.rs @@ -149,8 +149,10 @@ impl NotificationPanel { toasts.expanded = false; } - // Request repaint if there are toasts - ctx.request_repaint(); + // A timed toast animates its progress bar and expires, also behind the collapsed stack. + if toasts.toasts().iter().any(|toast| toast.duration > 0.0) { + ctx.request_repaint(); + } } /// Internal: show toasts and return IDs of dismissed toasts and the stack control pressed @@ -691,6 +693,41 @@ mod tests { } } + /// The panel asks for a repaint only while a queued toast counts down, also one hidden behind + /// the collapsed stack, so a permanent notice leaves an idle app idle. + #[test] + fn only_a_timed_toast_keeps_the_panel_repainting() { + use std::time::Duration; + let cases = [ + (vec![Toast::info("Saved").permanent()], Duration::MAX), + (vec![Toast::info("Saved")], Duration::ZERO), + ( + vec![Toast::info("Older"), Toast::info("Saved").permanent()], + Duration::ZERO, + ), + ]; + for (queued, expected) in cases { + let ctx = Context::default(); + let mut toasts = Toasts::new(); + for toast in queued { + toasts.add(toast); + } + let mut delay = Duration::ZERO; + for pass in 0..3 { + let output = ctx.run_ui( + egui::RawInput { + time: Some(f64::from(pass)), + ..Default::default() + }, + |ui| NotificationPanel::new().show_with_toasts(ui.ctx(), &mut toasts), + ); + delay = output.viewport_output[&egui::ViewportId::ROOT].repaint_delay; + output.drop_without_applying_deltas(); + } + assert_eq!(delay, expected, "{} queued", toasts.len()); + } + } + /// Each toast is one live node named by its title and message, polite except for errors, and /// the node goes with the toast when it is dismissed. #[test] diff --git a/vendor/egui-charts/src/widget/alerts.rs b/vendor/egui-charts/src/widget/alerts.rs index a9e7a24..17c0b8b 100644 --- a/vendor/egui-charts/src/widget/alerts.rs +++ b/vendor/egui-charts/src/widget/alerts.rs @@ -2,7 +2,7 @@ use crate::Chart; use crate::chart::series::SeriesId; -use crate::model::AlertSource; +use crate::model::{AlertSource, AlertSourceName}; impl Chart { /// Lend loaded live bars to the alert evaluator. A paused chart, or one in candle or market @@ -134,7 +134,9 @@ impl Chart { /// Every output of every study and every level of every completed drawing, with the name the /// alert dialog shows, for `AlertDialog::sources`. Drawing levels are those at the newest bar. - pub fn alert_sources(&self) -> Vec<(AlertSource, String)> { + /// A name keeps the study's name, the drawing's number and a fork level's value as given and + /// translates the study output, the drawing tool and the level when shown. + pub fn alert_sources(&self) -> Vec<(AlertSource, AlertSourceName)> { let bar = self.bars(SeriesId::MAIN).len().saturating_sub(1) as f64; let scale = self.config().right_axis_scale_mode; let studies = self.indicators().flat_map(|(id, study)| { @@ -148,7 +150,11 @@ impl Chart { id: id.0.to_string(), output, }, - format!("{}: {name}", study.name()), + AlertSourceName::new( + "{study}: {output}", + &[("study", study.name())], + &[("output", name.as_str())], + ), ) }) }); @@ -161,15 +167,24 @@ impl Chart { let levels = d.alert_levels_with_bars(bar, scale, self.bars(SeriesId::MAIN)); let single = levels.len() == 1; levels.into_iter().map(move |(level, name, _)| { - let drawing = format!("{} {}", d.tool_type.as_str(), d.id); - ( - d.alert_source(level), - if single { - drawing - } else { - format!("{drawing}: {name}") - }, - ) + let id = d.id.to_string(); + let tool = ("tool", d.tool_type.as_str()); + let name = if single { + AlertSourceName::new("{tool} {id}", &[("id", id.as_str())], &[tool]) + } else if let Some((line, value)) = d.fork_line(level) { + AlertSourceName::new( + line, + &[("id", id.as_str()), ("value", value.as_str())], + &[tool], + ) + } else { + AlertSourceName::new( + "{tool} {id}: {level}", + &[("id", id.as_str())], + &[tool, ("level", name.as_str())], + ) + }; + (d.alert_source(level), name) }) }); studies.chain(drawings).collect() @@ -200,6 +215,16 @@ mod tests { line.chart_points = vec![ChartPoint::new(0.0, 100.0), ChartPoint::new(2.0, 120.0)]; line.completed = true; chart.drawings_mut().drawings.push(line); + let mut fork = Drawing::new(9, DrawingToolType::Pitchfork); + fork.chart_points = vec![ + ChartPoint::new(0.0, 100.0), + ChartPoint::new(1.0, 200.0), + ChartPoint::new(2.0, 50.0), + ]; + // Saved without a config: levels 0, 0.5, 1 and 1.5, all shown. + fork.pitchfork = None; + fork.completed = true; + chart.drawings_mut().drawings.push(fork); let average = AlertSource::Study { id: study.0.to_string(), output: 0, @@ -240,11 +265,20 @@ mod tests { "{source:?} at {bar}" ); } + // Names keep the English text of the names that alerts and presets saved before. + let fork = |level: &str| AlertSource::Drawing(format!("9{level}")); assert_eq!( chart.alert_sources(), [ - (average, "SMA: SMA(2)".to_owned()), - (trend, "Trend Line 7".to_owned()) + (average, AlertSourceName::from("SMA: SMA(2)")), + (trend, "Trend Line 7".into()), + (fork(""), "Pitchfork 9: Median".into()), + (fork("#2"), "Pitchfork 9: 0.5: first line".into()), + (fork("#3"), "Pitchfork 9: 0.5: second line".into()), + (fork("#4"), "Pitchfork 9: 1: first line".into()), + (fork("#5"), "Pitchfork 9: 1: second line".into()), + (fork("#6"), "Pitchfork 9: 1.5: first line".into()), + (fork("#7"), "Pitchfork 9: 1.5: second line".into()), ] ); } diff --git a/vendor/egui-charts/src/widget/anchors.rs b/vendor/egui-charts/src/widget/anchors.rs index f7d0868..793e887 100644 --- a/vendor/egui-charts/src/widget/anchors.rs +++ b/vendor/egui-charts/src/widget/anchors.rs @@ -495,7 +495,8 @@ mod tests { &coords, &chart.build_time_formatter(), &chart.chart_options.time_scale, - chart.calendar_timezone().as_ref(), + Chart::calendar_zone(chart.label_timezone(|| chart.time_label_seconds())) + .as_ref(), |index| chart.index_to_time(index), ); // Key indices are shifted by the slots the keys reach before the first bar. diff --git a/vendor/egui-charts/src/widget/builder.rs b/vendor/egui-charts/src/widget/builder.rs index 87e3f73..f3ecf86 100644 --- a/vendor/egui-charts/src/widget/builder.rs +++ b/vendor/egui-charts/src/widget/builder.rs @@ -98,11 +98,12 @@ impl Chart { desired_visible_bars: None, last_visible_bars: 0, apply_visible_bars_once: false, - price_axis_drag: None, + scroll_start_spacing: None, pending_start_idx: None, pending_scroll_time: None, scroll_animation: None, time_axis_rect: egui::Rect::NOTHING, + price_plot_double_click: false, chart_type: ChartType::Candles, chart_type_params: ChartTypeParams::default(), #[cfg(feature = "studies")] @@ -245,6 +246,7 @@ impl Chart { marks: Default::default(), marker_options: Default::default(), change_marks: None, + frame_clock: None, price_lines: Vec::new(), next_price_line: 0, #[cfg(feature = "ui")] @@ -476,16 +478,10 @@ impl Chart { /// What a Range chart's bars are built from, or `None` for another chart type. The chart /// builds them from the trades the feed supplied, including during replay up to its cutoff, - /// and falls back to the OHLC approximation while it holds none. + /// after the OHLC approximation of the bars before the one holding the first trade, and + /// falls back to the approximation alone while it holds none. pub fn range_bar_source(&self) -> Option { - use crate::model::RangeBarSource::{Executions, OhlcApproximation}; - (self.chart_type == ChartType::Range).then(|| { - if self.execution_ranges.in_use() { - Executions - } else { - OhlcApproximation - } - }) + (self.chart_type == ChartType::Range).then(|| self.execution_ranges.source()) } /// Sets the parameters of the price-based chart types (Renko, Kagi, Range, Point and Figure, @@ -499,7 +495,34 @@ impl Chart { /// clears the zoom history and selection and keeps the right-edge item by time and rank. /// A volume candles style read from a document saved before that style existed takes the /// defaults; applying the document's chart settings builds it from their body colours. - pub fn set_chart_type_params(&mut self, mut params: ChartTypeParams) { + pub fn set_chart_type_params(&mut self, params: ChartTypeParams) { + let pending = params + .size_methods() + .map(|method| method != crate::model::BoxSizeMethod::Fixed); + self.replace_chart_type_params(params, pending); + } + + /// Sets `params` as settings apply them: a size whose method is unchanged keeps its resolved + /// value, or keeps waiting for history, and only a changed method resolves again. + pub(crate) fn apply_chart_type_params(&mut self, mut params: ChartTypeParams) { + let mut pending = self.pending_box_sizes; + let methods = params.size_methods().into_iter(); + let current = self.chart_type_params.size_methods(); + let sizes = params.sizes_mut().into_iter(); + let kept = self.chart_type_params.sizes_mut(); + for (((method, current), (size, kept)), pending) in + methods.zip(current).zip(sizes.zip(kept)).zip(&mut pending) + { + if method != current { + *pending = method != crate::model::BoxSizeMethod::Fixed; + } else if method != crate::model::BoxSizeMethod::Fixed { + *size = *kept; + } + } + self.replace_chart_type_params(params, pending); + } + + fn replace_chart_type_params(&mut self, mut params: ChartTypeParams, pending: [bool; 4]) { if params.styles.volume_candles.is_saved_without_style() { params.styles.volume_candles = Default::default(); } @@ -510,10 +533,7 @@ impl Chart { self.drawings.deselect(); } self.chart_type_params = params; - self.pending_box_sizes = self - .chart_type_params - .size_methods() - .map(|method| method != crate::model::BoxSizeMethod::Fixed); + self.pending_box_sizes = pending; self.chart_type_params .resolve_sizes(&self.state.data().bars, &mut self.pending_box_sizes); } @@ -529,7 +549,7 @@ impl Chart { if visible_bars == 0 { self.chart_options.time_scale.bar_spacing } else { - width / visible_bars as f32 + (width - 1.0) / visible_bars as f32 } } @@ -625,6 +645,16 @@ pub struct ChartBuilder { study_factory: Option, } +impl std::fmt::Debug for ChartBuilder { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ChartBuilder") + .field("symbol", &self.symbol) + .field("timeframe", &self.timeframe) + .field("chart_type", &self.chart_type) + .finish_non_exhaustive() + } +} + impl ChartBuilder { /// Create a new chart builder with sensible defaults /// @@ -1270,9 +1300,10 @@ mod tests { } } - /// Both entry points fit 50 slots once and leave the same view at the latest bar. + /// Both entry points fit 50 slots once and leave the same view at the latest bar, and the + /// time scale reads a set count back, also below one point per bar. #[test] - fn visible_bars_matches_the_setter_on_initial_frames() { + fn visible_bars_matches_the_setter_on_initial_frames_and_reads_back() { let start = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(); let data = BarData::from_bars( (0..600) @@ -1310,7 +1341,7 @@ mod tests { ); assert_eq!( built.state.time_scale().bar_spacing(), - built.get_rendered_price_rect().width() / 50.0 + (built.get_rendered_price_rect().width() - 1.0) / 50.0 ); assert_eq!(built.get_visible_bars(), set.get_visible_bars()); assert_eq!(built.get_visible_bars(), 49); @@ -1322,5 +1353,22 @@ mod tests { built.apply_timescale_config(width - 166.0); assert_eq!(built.state.time_scale().bar_spacing(), 20.0); } + // The time scale reads the count back, also at less than a point per bar. + for (width, count) in [(600.0, 1000), (801.0, 800), (740.0, 50)] { + let mut chart = Chart::new(data.clone()); + chart.state.time_scale_mut().set_min_bar_spacing(0.01); + chart.set_visible_bars(count); + chart.apply_timescale_config(width); + let candles = chart.state.time_scale().visible_candles(); + assert_eq!(candles, count, "width {width}"); + } + } + + /// A host can move a chart to another thread or share it behind `Arc>`. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn charts_are_send() { + fn needs_send() {} + needs_send::(); } } diff --git a/vendor/egui-charts/src/widget/change_marks.rs b/vendor/egui-charts/src/widget/change_marks.rs index 9d6c867..48ad707 100644 --- a/vendor/egui-charts/src/widget/change_marks.rs +++ b/vendor/egui-charts/src/widget/change_marks.rs @@ -20,6 +20,37 @@ struct Mark { close: f64, up: bool, at: Option, + /// The first pass that can show the update and the input time of the pass it was made in; + /// `None` for a chart not yet shown. + born: Option<(u64, f64)>, +} + +/// The egui context and viewport of the pass that last showed a chart. An update made while no +/// frame runs through the chart is dated by it. +pub(super) struct FrameClock { + ctx: egui::Context, + viewport: egui::ViewportId, + /// Passes the viewport had completed when the chart last ran. + shown: u64, +} + +impl FrameClock { + /// The clock of the pass in progress, in which the chart runs. + pub(super) fn shown_in(ctx: &egui::Context) -> Self { + Self { + ctx: ctx.clone(), + viewport: ctx.viewport_id(), + shown: ctx.cumulative_pass_nr(), + } + } + + /// The first pass that can show an update made now and the input time of the latest pass. + fn stamp(&self) -> (u64, f64) { + let passes = self.ctx.cumulative_pass_nr_for(self.viewport); + // The pass in progress has already run the chart, so only the next one shows the update. + let first = passes + u64::from(passes == self.shown); + (first, self.ctx.input_for(self.viewport, |input| input.time)) + } } impl ChangeMarks { @@ -39,12 +70,14 @@ impl ChangeMarks { .collect() } - /// Marks each slot of `before` whose close in `bars` differs from the close it had. + /// Marks each slot of `before` whose close in `bars` differs from the close it had, dated + /// by `frames`, the clock of the chart's last frame. pub(super) fn record( &mut self, bars: &[Bar], clock: &BarClock, before: Vec<(DateTime, f64)>, + frames: Option<&FrameClock>, ) { self.retain_bars(bars, clock); let marks = self.marks.get_mut(); @@ -62,6 +95,7 @@ impl ChangeMarks { close, up: close > old, at: None, + born: frames.map(FrameClock::stamp), }); } } @@ -87,13 +121,20 @@ impl ChangeMarks { self.marks.get_mut().clear(); } - /// Starts the fade of marks recorded since the last frame at `now` and drops the marks whose - /// duration has passed, whether or not the series is painted. - pub(super) fn expire(&self, now: f64) { + /// Starts the fade of marks recorded since the last frame, at the frame of the update when + /// frames ran without the chart, and drops the marks whose duration has passed, whether or + /// not the series is painted. + pub(super) fn expire(&self, ctx: &egui::Context) { + let (now, passes) = (ctx.input(|input| input.time), ctx.cumulative_pass_nr()); let duration = self.options.duration.as_secs_f64(); - self.marks - .borrow_mut() - .retain_mut(|mark| now - *mark.at.get_or_insert(now) < duration); + self.marks.borrow_mut().retain_mut(|mark| { + let start = match mark.born { + // A later time belongs to another context or viewport. + Some((first, time)) if passes > first && time <= now => time, + _ => now, + }; + now - *mark.at.get_or_insert(start) < duration + }); } /// Paints fading marks placed by `position`, removes expired marks and requests another @@ -104,7 +145,7 @@ impl ChangeMarks { position: impl Fn(DateTime, f64) -> Option, ) { let now = painter.ctx().input(|input| input.time); - self.expire(now); + self.expire(painter.ctx()); let duration = self.options.duration.as_secs_f64(); for mark in self.marks.borrow().iter() { let elapsed = now - mark.at.unwrap_or(now); @@ -153,13 +194,17 @@ impl Chart { /// or fell against the close of the bar the update replaced: a dot at the new close with a /// chevron above it for a rise and below it for a fall. Each mark fades linearly to /// transparent over that duration, and another changed close of the same bar restarts its - /// fade. Fades run on egui's frame clock from the first frame after the change, whether or - /// not the series is drawn, so a series shown again draws only the marks still within their - /// duration. Updates that leave the close unchanged, new bars, whitespace fills and history + /// fade. Fades run on egui's frame clock, whether or not the series is drawn. A mark starts to + /// fade on the first frame that can show its update; when egui runs frames that do not show + /// the chart first, as for a chart in an inactive tab, it starts at the frame of the update, + /// so a chart shown again draws only the marks still within their duration. A chart that + /// has not been shown yet has no frame to start from, and its marks start on its first + /// frame. Updates that leave the close unchanged, new bars, whitespace fills and history /// mark nothing. `None` removes the markers. /// - /// Bar series accept change markers; unknown ids and study ids are ignored with a warning. - pub fn set_change_markers(&mut self, series: SeriesId, options: Option) { + /// Returns `false` when `series` holds no bars, such as an unknown or removed series or a + /// study, and logs a warning. + pub fn set_change_markers(&mut self, series: SeriesId, options: Option) -> bool { let marks = options.map(|options| ChangeMarks { options, marks: RefCell::default(), @@ -170,7 +215,10 @@ impl Chart { && super::series::holds_bars(series, "set_change_markers") { self.change_marks = marks; + } else { + return false; } + true } } @@ -539,4 +587,77 @@ mod tests { } } } + + /// A host keeps updating a chart that egui's frames do not show, as in an inactive tab. The + /// fade of a mark starts at the frame of its update, not at the chart's next frame; an + /// update with no frame between it and the chart's next frame still starts its fade there. + /// The 5 s default fade leaves the update of the first row 31 s old at 61 s. + #[test] + fn marks_recorded_while_the_chart_is_not_shown_age_from_their_update() { + let screen = |time| egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + Pos2::ZERO, + egui::Vec2::new(800.0, 600.0), + )), + time: Some(time), + ..Default::default() + }; + for (placement, shown, expected) in [ + ("in a frame that skips the chart", 61.0, 0), + ("between frames", 100.0, 1), + ("after the chart in its frame", 100.0, 1), + ] { + for main in [true, false] { + let mut chart = chart(&[100.0], &[110.0]); + let id = if main { + SeriesId::MAIN + } else { + let id = chart.add_series(Default::default()); + chart.set_data(id, chart.bars(SeriesId::MAIN).to_vec()); + id + }; + chart.set_change_markers(id, Some(ChangeMarkers::default())); + let time = chart.bars(id).last().unwrap().time; + let fall = || Bar::new(time, 100.0, 110.0, 100.0, 108.0, 1.0); + let ctx = egui::Context::default(); + crate::widget::test_frames::shapes(&ctx, &mut chart, 0.0, Vec::new()); + match placement { + "in a frame that skips the chart" => { + for second in 1..=60 { + ctx.run_ui( + egui::RawInput { + time: Some(f64::from(second)), + ..Default::default() + }, + |_| {}, + ) + .drop_without_applying_deltas(); + if second == 30 { + chart.update(id, fall()); + } + } + } + "between frames" => { + chart.update(id, fall()); + } + _ => ctx + .run_ui(screen(1.0), |ui| { + egui::CentralPanel::default().show(ui, |ui| { + chart.show(ui); + }); + chart.update(id, fall()); + }) + .drop_without_applying_deltas(), + } + assert_eq!(marks(&chart, main).marks.borrow().len(), 1); + crate::widget::test_frames::shapes(&ctx, &mut chart, shown, Vec::new()); + let stored = marks(&chart, main).marks.borrow(); + assert_eq!(stored.len(), expected, "main {main}, {placement}"); + assert!( + stored.iter().all(|mark| mark.at == Some(shown)), + "main {main}, {placement}" + ); + } + } + } } diff --git a/vendor/egui-charts/src/widget/clipboard.rs b/vendor/egui-charts/src/widget/clipboard.rs index e21be85..b39fed5 100644 --- a/vendor/egui-charts/src/widget/clipboard.rs +++ b/vendor/egui-charts/src/widget/clipboard.rs @@ -99,7 +99,10 @@ impl Chart { /// Paste study clipboard text from [`Self::copy_indicator`], on this chart or another, as /// one undoable addition, and return the new study's id. `factory` creates the study by its - /// name. Hands a study pasted beyond the [study cap](Self::set_study_limit) back in + /// name. Text copied on an earlier release is restored as a + /// [`StudyTemplate`](crate::studies::StudyTemplate) with the same name, inputs and styles is, + /// so the study draws what it drew when it was copied. Hands a study pasted beyond the + /// [study cap](Self::set_study_limit) back in /// [`crate::studies::StudyError::StudyLimitReached`]. Rejects other text, a name /// `factory` does not know, and inputs or styles the study does not accept, before changing /// the chart. Study output references need host remapping and are rejected; hosts restore @@ -127,15 +130,18 @@ impl Chart { reason: "reads another study's output, which needs remapping before paste".into(), }); } - let mut study = crate::studies::ConfiguredStudy::new( - factory - .create_registered(&copied.name) - .ok_or_else(|| StudyError::UnknownStudy(copied.name.clone()))?, - ); - study.apply_settings(&copied.inputs, copied.settings)?; + // Built as a saved template is, so text copied on an earlier release draws what it drew. + let mut study = crate::studies::StudyTemplate { + name: copied.name, + inputs: copied.inputs, + settings: copied.settings, + visible: true, + scale: Some(copied.scale), + } + .create_with(factory)?; study.set_overlay(copied.overlay); study.set_scale(copied.scale); - let study: Box = Box::new(study); + let study: Box = study; self.user_action(|chart| chart.try_add_indicator(study)) } } @@ -146,7 +152,8 @@ mod tests { use crate::widget::test_frames; /// A copied study pastes onto another chart with its inputs, styles, interval visibility, - /// placement and scale, as one undoable addition. + /// placement and scale, as one undoable addition, and text copied on an earlier release is + /// upgraded as a saved template is. #[test] fn copied_studies_paste_with_their_settings() { let mut source = test_frames::chart(&[100.0], &[110.0]); @@ -207,6 +214,24 @@ mod tests { target.indicators().map(|(id, _)| id).collect::>(), before ); + // Copied before its output could be chosen, a majority rule drew the signed direction, + // and pastes drawing it, as a template saved then restores. + let rule = source.add_indicator(Box::new(crate::studies::MajorityRule::new(10))); + let text = source.copy_indicator(rule).unwrap(); + let mut copied: serde_json::Value = + serde_json::from_str(text.strip_prefix(super::STUDY_PREFIX).unwrap()).unwrap(); + copied["inputs"] + .as_array_mut() + .unwrap() + .retain(|input| input[0] != "mode"); + let older = format!("{}{copied}", super::STUDY_PREFIX); + let pasted = target.paste_indicator(&older, &factory).unwrap(); + let mode = find(&target, pasted) + .inputs() + .into_iter() + .find(|input| input.id == "mode") + .map(|input| input.value); + assert_eq!(mode, Some(crate::studies::InputValue::Choice(1))); } /// Clipboard paste maps times into the destination before offsetting, keeps properties, diff --git a/vendor/egui-charts/src/widget/drawing_api.rs b/vendor/egui-charts/src/widget/drawing_api.rs index 358d677..0067ab3 100644 --- a/vendor/egui-charts/src/widget/drawing_api.rs +++ b/vendor/egui-charts/src/widget/drawing_api.rs @@ -191,6 +191,39 @@ impl Chart { Ok(()) } + /// Replace an anchored VWAP's settings (source, bands and their unit, fills, line plot, + /// latest-value tracking and its precision) as one undoable edit. Unknown ids, locked + /// drawings, other tools and invalid settings change nothing. + pub fn set_vwap_config( + &mut self, + id: usize, + config: crate::drawings::VwapConfig, + ) -> Result<(), DrawingError> { + let drawing = self + .drawings() + .drawings + .iter() + .find(|drawing| drawing.id == id) + .ok_or(DrawingError::UnknownDrawing(id))?; + if drawing.locked { + return Err(DrawingError::Locked(id)); + } + if drawing.tool_type != crate::drawings::DrawingToolType::AnchoredVWAP { + return Err(DrawingError::Invalid("Drawing is not an anchored VWAP")); + } + if !config.is_valid() { + return Err(DrawingError::Invalid("Invalid anchored VWAP settings")); + } + if drawing.vwap.unwrap_or_default() != config { + self.user_action(|chart| { + chart + .drawings_mut() + .edit_drawing(id, |drawing| drawing.vwap = Some(config)); + }); + } + Ok(()) + } + /// Replace a position drawing's statistics, account currency and quantity precision in /// one undoable edit. A different currency needs a host-supplied conversion rate before /// monetary statistics can be calculated. Invalid settings and locked drawings change nothing. @@ -907,6 +940,70 @@ mod tests { } } + /// Hosts set an anchored VWAP's source, band unit, fills, line plot and tracking in one + /// history entry, which templates and saved drawings carry; invalid settings, locked, missing + /// and other drawings change nothing. + #[test] + fn anchored_vwap_settings_are_validated_and_undoable() { + use crate::drawings::{DrawingTemplate, VwapBandMode, VwapConfig, VwapFill}; + let mut chart = crate::widget::test_frames::chart(&[90.0; 20], &[210.0; 20]); + let mut drawing = Drawing::new(7, DrawingToolType::AnchoredVWAP); + drawing.completed = true; + drawing.chart_points = vec![ChartPoint::new(2.0, 100.0)]; + chart.drawings_mut().drawings.push(drawing); + let edited = VwapConfig { + source: crate::model::PriceSource::OHLC4, + band_mode: VwapBandMode::Percentage, + show_line: false, + plot_type: crate::drawings::VwapPlotType::StepLine, + track_price: true, + precision: Some(3), + band_fill: VwapFill::new(false, Some([1, 2, 3, 255]), 0.4).unwrap(), + background: VwapFill::new(true, None, 0.2).unwrap(), + ..VwapConfig::default() + }; + chart.set_vwap_config(7, edited).unwrap(); + assert_eq!(chart.drawings().drawings[0].vwap, Some(edited)); + assert!(chart.undo()); + assert_eq!(chart.drawings().drawings[0].vwap, None); + assert!(!chart.can_undo()); + assert!(chart.redo()); + // An unchanged assignment does not create a second history entry. + chart.set_vwap_config(7, edited).unwrap(); + assert!(chart.undo()); + assert!(!chart.can_undo()); + assert!(chart.redo()); + let template = DrawingTemplate::from_drawing(&chart.drawings().drawings[0]); + let mut peer = Drawing::new(8, DrawingToolType::AnchoredVWAP); + template.apply_to(&mut peer).unwrap(); + assert_eq!(peer.vwap, Some(edited)); + let saved = chart.save_drawings().unwrap().to_json().unwrap(); + let mut restored = Chart::new(BarData::default()); + restored.load_drawings(&saved).unwrap(); + assert_eq!(restored.drawings().drawings[0].vwap, Some(edited)); + let invalid = VwapConfig { + precision: Some(9), + ..edited + }; + assert!(chart.set_vwap_config(7, invalid).is_err()); + chart.drawings_mut().drawings[0].locked = true; + assert_eq!( + chart.set_vwap_config(7, VwapConfig::default()), + Err(DrawingError::Locked(7)) + ); + assert_eq!( + chart.set_vwap_config(77, VwapConfig::default()), + Err(DrawingError::UnknownDrawing(77)) + ); + chart.drawings_mut().drawings[0].locked = false; + chart.drawings_mut().drawings[0].tool_type = DrawingToolType::TrendLine; + assert!(chart.set_vwap_config(7, VwapConfig::default()).is_err()); + chart.drawings_mut().drawings[0].tool_type = DrawingToolType::AnchoredVWAP; + assert_eq!(chart.drawings().drawings[0].vwap, Some(edited)); + assert!(chart.undo()); + assert!(!chart.can_undo()); + } + /// Readout edits and reversal each undo in one step, preserve times and identity, and /// round-trip through saved records and templates. Legacy records retain visible statistics. #[test] diff --git a/vendor/egui-charts/src/widget/export.rs b/vendor/egui-charts/src/widget/export.rs index b43e7a0..b740d36 100644 --- a/vendor/egui-charts/src/widget/export.rs +++ b/vendor/egui-charts/src/widget/export.rs @@ -63,6 +63,7 @@ impl Default for ImageExportOptions { /// bind any user textures referenced by their image sources whose pixels were not supplied in /// [`ImageExportOptions::textures`] before drawing. #[must_use = "Render the frame and apply its texture deltas, or clear them before dropping"] +#[derive(Debug)] #[non_exhaustive] pub struct ChartImage { /// Exact output dimensions in pixels. @@ -73,17 +74,25 @@ pub struct ChartImage { pub textures_delta: egui::TexturesDelta, } -/// A column of a [`DataTable`]: the original id and title of its study, `None` for the main -/// series, then its plot or main series column. The title keeps a choice off a study of another -/// title that a restore adds under the id the choice was made for. -pub(crate) type ColumnId = (Option<(usize, String)>, usize); +/// A column of a [`DataTable`]. A study column carries the original id and title of its study +/// and its plot; the title keeps a choice off a study of another title that a restore adds under +/// the id the choice was made for. An added series column carries its title and its place among +/// the visible series of that title, which a restore, adding the series again under new ids, +/// keeps. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum ColumnId { + Main(usize), + Series(String, usize), + Study(usize, String, usize), +} -/// The loaded bars and visible study plots as text, aligned by chart time: what -/// `Chart::export_csv` (with `csv`) writes and the chart data table lists. +/// The loaded bars, the closes of visible added series and visible study plots as text, aligned +/// by chart time: what `Chart::export_csv` (with `csv`) writes and the chart data table lists. #[derive(Debug, Clone, PartialEq)] #[non_exhaustive] pub struct DataTable { - /// Column titles: time, open, high, low, close and volume, then one per visible study plot. + /// Column titles: time, open, high, low, close and volume, then one per visible added series, + /// titled as its legend shows it, and one per visible study plot. pub headers: Vec, /// One row per loaded bar, oldest first. A missing or non-finite value is an empty cell. pub rows: Vec>, @@ -203,7 +212,9 @@ impl Chart { } } - /// Exports all loaded source bars and visible study plots as UTF-8 CSV. + /// Exports all loaded source bars, the close of each visible added series and visible study + /// plots as UTF-8 CSV. An added series fills the rows whose time matches one of its bars and + /// leaves the others empty. /// Recalculates copies of the studies so streaming updates and pending refreshes are included /// without altering the live chart. Price-based charts export source-bar calculations, aligned /// by source index and plot displacement, rather than mixing element values with source bars. @@ -219,9 +230,10 @@ impl Chart { table.csv(&(0..table.headers.len()).collect::>()) } - /// The cells of `Self::export_csv` (with `csv`) as a table, with the same bars, study plots, - /// times and precision. During replay it holds the bars the replay cutoff has completed, - /// and on price-based chart types still the source bars. Loads nothing: only loaded bars are listed. + /// The cells of `Self::export_csv` (with `csv`) as a table, with the same bars, added series + /// closes, study plots, times and precision. During replay it holds the bars the replay + /// cutoff has completed, and on price-based chart types still the source bars. Loads + /// nothing: only loaded bars are listed. pub fn data_table(&self) -> DataTable { self.data_table_with_columns().0 } @@ -238,6 +250,24 @@ impl Chart { .map(|(_, study)| study.clone_box()) .collect(); let mut columns = Vec::new(); + // Each visible added series with its legend title, which falls back to "Series" as the + // pane menu does, its place among series of that title and the decimals of its closes. + let mut series: Vec<(&[crate::model::Bar], String, usize, usize)> = Vec::new(); + for item in self.price_series.iter().filter(|item| item.visible) { + let title = match item.options.name.as_str() { + "" => "Series".to_owned(), + name => name.to_owned(), + }; + let place = series.iter().filter(|other| other.1 == title).count(); + // A series of another scale keeps four significant digits of its smallest close. + let precision = item + .bars + .iter() + .filter(|bar| !bar.is_whitespace() && bar.close.is_finite() && bar.close != 0.0) + .map(|bar| (3.0 - bar.close.abs().log10().floor()).clamp(0.0, 12.0) as usize) + .fold(price_precision, usize::max); + series.push((item.bars.as_slice(), title, place, precision)); + } let mut header = vec![ "time".into(), "open".into(), @@ -246,6 +276,7 @@ impl Chart { "close".into(), "volume".into(), ]; + header.extend(series.iter().map(|item| item.1.clone())); let clock = self.bar_clock(); for study in &mut studies { study.set_instrument(self.instrument()); @@ -306,6 +337,13 @@ impl Chart { } else { String::new() }); + row.extend(series.iter().map(|&(bars, _, _, precision)| { + bars.binary_search_by_key(&bar.time, |other| other.time) + .ok() + .map(|at| &bars[at]) + .filter(|other| !other.is_whitespace()) + .map_or_else(String::new, |other| number(other.close, precision)) + })); row.extend(columns.iter().map(|&(study, line, precision)| { studies[study] .plot_value(line, index) @@ -314,12 +352,17 @@ impl Chart { rows.push(row); } let column_ids = (0..6) - .map(|column| (None, column)) + .map(ColumnId::Main) + .chain( + series + .iter() + .map(|item| ColumnId::Series(item.1.clone(), item.2)), + ) .chain(columns.iter().map(|&(study, line, _)| { let id = self.study_ids[study].0; #[cfg(feature = "drawings")] let id = self.study_column_ids.get(&id).copied().unwrap_or(id); - (Some((id, studies[study].name().to_owned())), line) + ColumnId::Study(id, studies[study].name().to_owned(), line) })) .collect(); ( @@ -569,6 +612,9 @@ impl Chart { .unwrap_or_else(|| ctx.active_theme()); if options.transparent_background { theme.chart.bg = egui::Color32::TRANSPARENT; + // The fills that repeat the background behind text have nothing to repeat. + chart.config.background_color = egui::Color32::TRANSPARENT; + chart.config.background_style = crate::config::BackgroundStyle::Solid; } chart.theme_override = Some(theme); if let Some((time, price)) = self.last_crosshair.filter(|_| options.include_crosshair) { @@ -827,6 +873,44 @@ mod tests { last.close = 22.0; last.high = 23.0; chart.update(SeriesId::MAIN, last); + // A visible added series lists its closes at the bars it holds, by exact time; a + // hidden one has no column. + let peer = chart.add_series(crate::widget::SeriesOptions { + name: "Peer".into(), + ..Default::default() + }); + chart.set_data( + peer, + vec![ + Bar::new(times[0], 5.0, 6.0, 4.0, 5.5, 1.0), + Bar::new(times[2], 7.0, 8.0, 6.0, 7.25, 1.0), + Bar::new( + times[2] + chrono::Duration::hours(1), + 7.0, + 8.0, + 6.0, + 9.0, + 1.0, + ), + ], + ); + let tiny = chart.add_series(crate::widget::SeriesOptions { + name: "Tiny".into(), + ..Default::default() + }); + chart.set_data( + tiny, + vec![Bar::new(times[1], 0.0002, 0.0003, 0.0001, 0.000123, 1.0)], + ); + let hidden_series = chart.add_series(crate::widget::SeriesOptions { + name: "Off".into(), + ..Default::default() + }); + chart.set_data( + hidden_series, + vec![Bar::new(times[1], 1.0, 1.0, 1.0, 1.0, 1.0)], + ); + chart.set_series_visible(hidden_series, false); let csv = chart.export_csv(); fn assert_send_sync(_: &T) {} assert_send_sync(&csv); @@ -841,6 +925,8 @@ mod tests { "low", "close", "volume", + "Peer", + "Tiny", "Average, pair: mean", "Average, pair: shifted", "Fixed: Fixed", @@ -857,14 +943,23 @@ mod tests { // Two-bar means are 12 and (14 + 22) / 2 = 18; displacement -1 moves them left. assert_eq!( rows.iter().map(|row| &row[6]).collect::>(), - ["", "12.000", "18.000"] + ["5.500", "", "7.250"] ); + // A series of another scale keeps its digits instead of rounding to the main decimals. assert_eq!( rows.iter().map(|row| &row[7]).collect::>(), + ["", "0.0001230", ""] + ); + assert_eq!( + rows.iter().map(|row| &row[8]).collect::>(), + ["", "12.000", "18.000"] + ); + assert_eq!( + rows.iter().map(|row| &row[9]).collect::>(), ["12.000", "18.000", ""] ); - assert_eq!(&rows[0][8], "1.2346"); - assert_eq!(&rows[0][9], "9.9"); + assert_eq!(&rows[0][10], "1.2346"); + assert_eq!(&rows[0][11], "9.9"); // Export must not refresh or mutate the chart's scheduled study results. assert!(chart.pending_from[0].is_some()); } @@ -1249,6 +1344,8 @@ mod tests { chart.config.show_watermark = true; chart.config.watermark_text = Some("WATERMARK".into()); frame(&ctx, &mut chart, 0.0, vec![]); + // A colour of the chart's own, which no theme supplies. + chart.config.background_color = egui::Color32::from_rgb(120, 10, 10); let base = ImageExportOptions { size: [480, 320], include_title: false, diff --git a/vendor/egui-charts/src/widget/feed/mod.rs b/vendor/egui-charts/src/widget/feed/mod.rs index 9207b70..4f4d8c3 100644 --- a/vendor/egui-charts/src/widget/feed/mod.rs +++ b/vendor/egui-charts/src/widget/feed/mod.rs @@ -208,9 +208,11 @@ impl FeedLink { /// older than the one before it is left out, as it is when it arrives live. The bar of the /// oldest held trade is incomplete until a trade page reports the start of trade history. /// On a trade-based interval, paged trades fill only the bars of `history`, the chart's, that - /// open before the live executions, or without them before the oldest pushed bar the history - /// lacks or holds with other values, and that they rebuild ([`Footprint::push_history`]). With - /// `before`, includes only executions strictly before that replay cutoff. + /// open before the live executions, held ones or those the store kept apart at the first + /// instant a page covers while the chart holds a bar at or before the oldest of them, or + /// without them before the oldest pushed bar the history lacks or holds with other values, + /// and that they rebuild ([`Footprint::push_history`]). With `before`, includes only + /// executions strictly before that replay cutoff. pub(super) fn footprint( &self, before: Option>, @@ -245,7 +247,18 @@ impl FeedLink { if live.is_some_and(|live| self.trades.left_out_at() == Some(live)) { paged_bars = paged_bars.saturating_sub(1); } - flow.push_history(&paged, &history[..paged_bars], before); + // Until a trade page fills the time after the retained executions, some that traded + // after them may be missing: their end is not the page's and proves nothing. + let ended = self.trades.retained_until().is_none(); + // The sink opened the bars from the oldest live execution the store kept apart, where + // the page may hold executions the stream never sent: its allocations fill those + // bars, as `OrderFlowInput::chart_run` rebuilds them. A chart that starts after it + // holds no bar with the page's executions of that instant. + let stream_from = (self.trades.unheld_live()) + .and_then(|(_, kept)| kept.first()) + .map(|trade| trade.ts) + .filter(|at| history.first().is_some_and(|bar| bar.time <= *at)); + flow.push_history(&paged, &history[..paged_bars], before, ended, stream_from); } else if !trade_based || lost.is_none() || self.trades.live().next().is_none() { for trade in trades() { let _ = flow.push(trade); @@ -918,11 +931,14 @@ impl Chart { } /// Calendar boundaries selected by the chart, including the resolved exchange or local zone. + /// Its days are those that date the bars: bars of a day or longer given without a feed run + /// on UTC days under a display zone behind UTC unless they sit at its midnight, as + /// [`format_time`](Self::format_time) reads them. pub fn bar_clock(&self) -> BarClock { let clock = BarClock::new(self.timeframe.unwrap_or_default()); - let clock = match self.display_timezone() { - crate::scales::TimezoneMode::Local => clock.with_local_timezone(), - zone => clock.with_timezone(zone.to_tz().unwrap_or(crate::model::TimezoneId::utc())), + let clock = match self.calendar_timezone() { + Some(zone) => clock.with_timezone(zone), + None => clock.with_local_timezone(), }; match self.instrument().and_then(|instrument| { Some(( diff --git a/vendor/egui-charts/src/widget/feed/pump.rs b/vendor/egui-charts/src/widget/feed/pump.rs index 38c7599..a5efe16 100644 --- a/vendor/egui-charts/src/widget/feed/pump.rs +++ b/vendor/egui-charts/src/widget/feed/pump.rs @@ -799,7 +799,7 @@ impl Chart { // The oldest held trade's bar is complete once nothing is left before it. let reached_start = end && !link.trades_from_start; link.trades_from_start |= end; - let left_out = link.trades.left_out_at(); + let unproven = (link.trades.left_out_at(), link.trades.retained_until()); let bubbles = &mut link.bubbles; let mut changed = false; let fold = &mut |trade: &Tick, added| { @@ -812,8 +812,9 @@ impl Chart { input.replace_trades(&link.clock, &link.trades, &self.state.data().bars); } } - // A page that only leaves executions out adds none, yet the held ones then prove less. - let cut = link.trades.left_out_at() != left_out; + // A page that only leaves executions out, or fills the time after the retained ones with + // none, adds none, yet the held ones then prove less or more. + let cut = (link.trades.left_out_at(), link.trades.retained_until()) != unproven; if (changed || reached_start || cut) && link.footprint.is_some() { link.footprint = link.footprint(None, &self.state.data().bars); } diff --git a/vendor/egui-charts/src/widget/feed/tests.rs b/vendor/egui-charts/src/widget/feed/tests.rs index 10a0c2d..d15a45b 100644 --- a/vendor/egui-charts/src/widget/feed/tests.rs +++ b/vendor/egui-charts/src/widget/feed/tests.rs @@ -817,7 +817,9 @@ fn an_eviction_drops_the_scroll_back_page_in_flight_and_its_continuation() { assert_eq!(feed.pages.lock().unwrap().len(), 1, "{name}: in flight"); feed.calls(); match name { - "lowered limit" => chart.set_bar_limit(SeriesId::MAIN, NonZeroUsize::new(16)), + "lowered limit" => { + chart.set_bar_limit(SeriesId::MAIN, NonZeroUsize::new(16)); + } "live bars" => { let sink = feed.sink(); for minute in 23..27 { @@ -1379,6 +1381,138 @@ fn paged_trades_without_history_leave_their_first_bar_incomplete() { assert_eq!(flow.complete_from(), Some(start + TimeDelta::seconds(2))); } +/// Hand counts on 2t at price 100, executions of 1 without ids. A trade page answered in the drain +/// that streams the first executions holds a sell at 0 s, traded before the subscription, and its +/// copy of the stream's first buy; the stream buys twice at 0 s, then at 1 s and 2 s. The sink's +/// bars are the two buys at 0 s and those at 1 s and 2 s, each bid 0 and ask 2: the sell is in +/// neither. A footprint turned on after that drain, and again after it is turned off, shows both +/// bars as the sink allocated them. The footprint a bar replay builds for profile drawings, with +/// its cutoff after the last execution, shows the 0 s bar that way or without cells, never with +/// the sell. +#[test] +fn footprint_turned_on_later_counts_the_stream_at_the_first_instant() { + use crate::model::OrderSide::{Buy, Sell}; + let feed = Arc::new(Script::default()); + let mut chart = fed(&feed, Some("A")); + chart.set_timeframe("2t".parse().unwrap()); + let mut frames = Frames::new(); + frames.run(&mut chart); + feed.resolve() + .send(Ok(Instrument::new("A").with_tick_size(1.0))); + feed.page().send(page(Vec::new(), true)); + frames.run(&mut chart); + let start = bars(1)[0].time; + let fill = + |second: i64, side| Tick::new(start + TimeDelta::seconds(second), 100.0, 1.0, Some(side)); + // The chart applies the page before the executions it drains with. + (feed.trades.lock().unwrap().remove(0)) + .send(Ok(TradePage::new(vec![fill(0, Sell), fill(0, Buy)], false))); + let sink = feed.sink(); + for second in [0, 0, 1, 2] { + sink.push_tick(fill(second, Buy)); + } + frames.run(&mut chart); + let opens = [start, start + TimeDelta::seconds(1)]; + // The bid and ask of each bar drawn with cells; `None` draws a candle. + let cells = |flow: &Footprint| { + let complete = flow.complete_from(); + (opens.iter()) + .map(|open| { + flow.bar_at(*open) + .filter(|_| complete.is_some_and(|from| *open >= from)) + .map(|bar| (bar.bid, bar.ask)) + }) + .collect::>() + }; + for turned in ["on", "on again"] { + chart.set_chart_type(ChartType::VolumeFootprint); + for _ in 0..4 { + frames.run(&mut chart); + } + let drawn: Vec<_> = (chart.bars(SeriesId::MAIN).iter()) + .map(|bar| bar.time) + .collect(); + assert_eq!(drawn, opens, "turned {turned}"); + let flow = (chart.feed_link.as_ref().unwrap().footprint.as_ref()).unwrap(); + assert_eq!(cells(flow), [Some((0.0, 2.0)); 2], "turned {turned}"); + chart.set_chart_type(ChartType::Candles); + frames.run(&mut chart); + } + let link = chart.feed_link.as_ref().unwrap(); + let cutoff = start + TimeDelta::seconds(3); + let replay = link.footprint(Some(cutoff), chart.bars(SeriesId::MAIN)); + let replayed = cells(&replay.unwrap()); + assert_eq!(replayed[1], Some((0.0, 2.0)), "replay"); + assert!( + replayed[0].is_none() || replayed[0] == Some((0.0, 2.0)), + "replay {:?}", + replayed[0] + ); +} + +/// Hand counts on 2t, executions of 1 without ids, the page applied as in the test above. The page +/// holds copies of the stream's buys at 0 s and 1 s and a sell at 0.5 s that the stream sends after +/// the buy at 1 s, so the sink leaves it out as late; the stream goes on with a buy at 2 s, a sell +/// and a buy at 3 s, and buys at 4 s and 5 s, all at 100. The sink's bars open at 0 s (bid 0, ask +/// 2), 1 s (0, 2), 3 s (1, 1) and 4 s (0, 2). A footprint turned on afterwards never counts the +/// sell, whether it is at 99 or at 100: the 0 s bar shows its cells or none, and the later bars +/// show theirs. +#[test] +fn footprint_turned_on_later_leaves_out_a_paged_execution_the_sink_dropped() { + use crate::model::OrderSide::{Buy, Sell}; + let start = bars(1)[0].time; + let fill = + |ms, price, side| Tick::new(start + TimeDelta::milliseconds(ms), price, 1.0, Some(side)); + let buy = |ms| fill(ms, 100.0, Buy); + let opens = [0, 1000, 3000, 4000].map(|ms| start + TimeDelta::milliseconds(ms)); + for price in [99.0, 100.0] { + let feed = Arc::new(Script::default()); + let mut chart = fed(&feed, Some("A")); + chart.set_timeframe("2t".parse().unwrap()); + let mut frames = Frames::new(); + frames.run(&mut chart); + feed.resolve() + .send(Ok(Instrument::new("A").with_tick_size(1.0))); + feed.page().send(page(Vec::new(), true)); + frames.run(&mut chart); + let late = fill(500, price, Sell); + let paged = vec![buy(0), buy(0), late.clone(), buy(1000)]; + (feed.trades.lock().unwrap().remove(0)).send(Ok(TradePage::new(paged, false))); + let sink = feed.sink(); + let sell = fill(3000, 100.0, Sell); + for trade in [buy(0), buy(0), buy(1000), late, buy(2000), sell, buy(3000)] { + sink.push_tick(trade); + } + for ms in [4000, 5000] { + sink.push_tick(buy(ms)); + } + frames.run(&mut chart); + chart.set_chart_type(ChartType::VolumeFootprint); + for _ in 0..4 { + frames.run(&mut chart); + } + let drawn: Vec<_> = (chart.bars(SeriesId::MAIN).iter()) + .map(|bar| bar.time) + .collect(); + assert_eq!(drawn, opens, "sell at {price}"); + let flow = (chart.feed_link.as_ref().unwrap().footprint.as_ref()).unwrap(); + let complete = flow.complete_from(); + let cells: Vec<_> = (opens.iter()) + .map(|open| { + flow.bar_at(*open) + .filter(|_| complete.is_some_and(|from| *open >= from)) + .map(|bar| (bar.bid, bar.ask)) + }) + .collect(); + assert!( + cells[0].is_none_or(|cell| cell == (0.0, 2.0)), + "sell at {price}: {cells:?}" + ); + let later = [Some((0.0, 2.0)), Some((1.0, 1.0)), Some((0.0, 2.0))]; + assert_eq!(cells[1..], later, "sell at {price}"); + } +} + /// Hand counts on two-trade bars of buys at 100, one a second: 1 and 2 (volume 3), 3 and 4 (7), /// 5 and 6 (11), and the live 7 and 8 (15). A store of seven leaves out the buy of 1 in both /// orders, and a store of six the buys of 1 and 2, so that the oldest held execution opens the @@ -1657,7 +1791,10 @@ fn restored_order_flow_study_keeps_the_chart_bars() { /// buys of 1 to 8, which leaves no live execution in the first two bars, or for the buys of 1 to /// 4 on a chart limited to two bars, which keeps the 2 s and 4 s bars while the study's source /// keeps the 0 s one. The replay cutoff at 3 s is exclusive and falls in the 2 s bar, before -/// which only the buy of 4 came. +/// which only the buy of 4 came. With the buys of 1, 2 and 4 at 0 s, 8 at 1 s and 16 at 2 s, the +/// bars are 1 and 2 at 0 s, 4 and 8 (12) at 0 s + 1 ns, opened a nanosecond after it, and 16 at +/// 2 s; a page of the three at 0 s on a chart limited to two bars drops the 0 s bar the source +/// keeps, and the cutoff at 0.5 s falls in the 0 s + 1 ns bar, before which only the buy of 4 came. #[cfg(feature = "studies")] #[test] fn replay_after_a_trade_page_repeats_a_live_execution_stops_at_the_cutoff() { @@ -1665,22 +1802,23 @@ fn replay_after_a_trade_page_repeats_a_live_execution_stops_at_the_cutoff() { use crate::studies::OrderFlowStudy; use std::num::NonZeroUsize; let start = bars(1)[0].time; - let tape: Vec<_> = [1.0, 2.0, 4.0, 8.0, 16.0] - .iter() - .enumerate() - .map(|(second, size)| { - let at = start + TimeDelta::seconds(second as i64); - Tick::new(at, 100.0, *size, Some(Buy)) - }) - .collect(); - // The executions the page holds, the bar limit (none for 0), and the deltas before and during - // the replay. - let rows: [(usize, usize, &[f64], &[f64]); 3] = [ - (1, 0, &[3.0, 12.0, 16.0], &[3.0, 4.0]), - (4, 0, &[3.0, 12.0, 16.0], &[3.0, 4.0]), - (3, 2, &[12.0, 16.0], &[4.0]), + let apart = [0, 1000, 2000, 3000, 4000]; + // The buys' times and the replay cutoff in milliseconds, the executions the page holds, the + // bar limit (none for 0), and the deltas before and during the replay. + type Row = ([i64; 5], i64, usize, usize, &'static [f64], &'static [f64]); + let rows: [Row; 4] = [ + (apart, 3000, 1, 0, &[3.0, 12.0, 16.0], &[3.0, 4.0]), + (apart, 3000, 4, 0, &[3.0, 12.0, 16.0], &[3.0, 4.0]), + (apart, 3000, 3, 2, &[12.0, 16.0], &[4.0]), + ([0, 0, 0, 1000, 2000], 500, 3, 2, &[12.0, 16.0], &[4.0]), ]; - for (paged, limit, live, replayed) in rows { + for (times, cutoff, paged, limit, live, replayed) in rows { + let tape: Vec<_> = (times.iter().zip([1.0, 2.0, 4.0, 8.0, 16.0])) + .map(|(at, size)| { + let at = start + TimeDelta::milliseconds(*at); + Tick::new(at, 100.0, size, Some(Buy)) + }) + .collect(); let feed = Arc::new(Script::default()); let mut chart = fed(&feed, Some("A")); chart.set_timeframe("2t".parse().unwrap()); @@ -1703,12 +1841,20 @@ fn replay_after_a_trade_page_repeats_a_live_execution_stops_at_the_cutoff() { let study = chart.indicators().next().unwrap().1; study.values().line(0).to_vec() }; - assert_eq!(deltas(&mut chart), live, "{paged} paged"); + assert_eq!(deltas(&mut chart), live, "{paged} paged, cutoff {cutoff}"); chart.set_feed_paused(true); - chart.set_replay_time(Some(start + TimeDelta::seconds(3))); - assert_eq!(deltas(&mut chart), replayed, "{paged} paged, replay"); + chart.set_replay_time(Some(start + TimeDelta::milliseconds(cutoff))); + assert_eq!( + deltas(&mut chart), + replayed, + "{paged} paged, cutoff {cutoff}, replay" + ); chart.set_replay_time(None); - assert_eq!(deltas(&mut chart), live, "{paged} paged, left"); + assert_eq!( + deltas(&mut chart), + live, + "{paged} paged, cutoff {cutoff}, left" + ); } } @@ -2169,59 +2315,195 @@ fn an_interval_change_page_fills_the_retained_tape() { /// Counting the buy of 2 whole instead matches every bar's prices and volume and gives the bars /// at 00:00:01, 00:00:03 and 00:00:05 part of their neighbours' fills, as (level, bid, ask): /// (101, 0, 2), (102, 5, 0), (103, 3, 0); (103, 3, 0), (104, 0, 5), (105, 0, 2); and -/// (105, 0, 4), (106, 6, 0). +/// (105, 0, 4), (106, 6, 0). That grouping ends with the retained executions at 00:00:06, which +/// lack the sell of 4, so their end proves nothing either while the trade page is outstanding or +/// after a feed without trade history fails it. +/// +/// Nor does it on a tick interval, where a bar in the history page opens between the two streams. +/// Executions of 1 at 100: two buys at 00:00:00, a sell and then a buy at 00:00:01, and a buy each +/// second through 00:00:06. The 3 tick bars open at 00:00:00, at 00:00:01 with the buy, and at +/// 00:00:04. The 2 tick stream delivers the two executions at 00:00:01 and the buy at 00:00:02, +/// and the 3 tick stream opens at 00:00:09. Grouped from the sell, the three retained executions +/// match the prices and volume of the bar at 00:00:01 and end there, as (100, 1, 2). The bar's own +/// are (100, 0, 3), its buy at 00:00:03 is not held, and it draws a candle. +/// +/// What a second bar proves stays drawn meanwhile, and a trade page that adds nothing proves the +/// rest. Buys of 1 at 100: nine a second apart from 00:00:01 and three at 00:00:10, all delivered +/// by the 2 tick stream. The 3 tick bars open at 00:00:01, 00:00:04, 00:00:07 and 00:00:10, and +/// the 3 tick stream opens at 00:00:12. While the trade page is outstanding the bars at 00:00:01, +/// 00:00:04 and 00:00:07 draw their own (100, 0, 3), each proven by the bar that opens after it, +/// also at the instant the retained executions end, and the bar at 00:00:10, which only their end +/// could prove, draws a candle. The trade page then repeats the retained executions: nothing +/// traded between the two streams, their end is the page's, and the bar at 00:00:10 draws its +/// (100, 0, 3) as well. #[test] fn an_interval_change_page_draws_only_a_bars_own_executions() { - use crate::model::OrderSide::{Buy, Sell}; + use crate::model::OrderSide::{self, Buy, Sell}; let start = bars(1)[0].time; - let fills = [ - (100.0, 9.0, Buy), - (101.0, 2.0, Buy), - (102.0, 5.0, Sell), - (103.0, 6.0, Sell), - (104.0, 5.0, Buy), - (105.0, 6.0, Buy), - (106.0, 6.0, Sell), - (106.0, 4.0, Sell), - ]; - let rows: [(&str, bool, bool, &[f64]); 3] = [ + type Fill = (i64, f64, f64, OrderSide); + // The intervals before and after the change, the executions by second, those the first + // stream delivers, the first of the second stream, and the bars of the history page. + type Tape<'a> = ( + [&'a str; 2], + &'a [Fill], + std::ops::Range, + Fill, + usize, + ); + let volume: Tape = ( + ["20v", "10v"], + &[ + (0, 100.0, 9.0, Buy), + (1, 101.0, 2.0, Buy), + (2, 102.0, 5.0, Sell), + (3, 103.0, 6.0, Sell), + (4, 104.0, 5.0, Buy), + (5, 105.0, 6.0, Buy), + (6, 106.0, 6.0, Sell), + (7, 106.0, 4.0, Sell), + ], + 1..7, + (7, 106.0, 1.0, Sell), + 4, + ); + let ticks: Tape = ( + ["2t", "3t"], + &[ + (0, 100.0, 1.0, Buy), + (0, 100.0, 1.0, Buy), + (1, 100.0, 1.0, Sell), + (1, 100.0, 1.0, Buy), + (2, 100.0, 1.0, Buy), + (3, 100.0, 1.0, Buy), + (4, 100.0, 1.0, Buy), + (5, 100.0, 1.0, Buy), + (6, 100.0, 1.0, Buy), + ], + 2..5, + (9, 100.0, 1.0, Buy), + 3, + ); + let quiet: Tape = ( + ["2t", "3t"], + &[ + (1, 100.0, 1.0, Buy), + (2, 100.0, 1.0, Buy), + (3, 100.0, 1.0, Buy), + (4, 100.0, 1.0, Buy), + (5, 100.0, 1.0, Buy), + (6, 100.0, 1.0, Buy), + (7, 100.0, 1.0, Buy), + (8, 100.0, 1.0, Buy), + (9, 100.0, 1.0, Buy), + (10, 100.0, 1.0, Buy), + (10, 100.0, 1.0, Buy), + (10, 100.0, 1.0, Buy), + ], + 0..12, + (12, 100.0, 1.0, Buy), + 4, + ); + enum Answer { + Bars, + Executions, + NoExecutions, + } + use Answer::{Bars, Executions, NoExecutions}; + // The cells of the bars drawn, as (level, bid, ask). + type Drawn<'a> = &'a [&'a [(i64, f64, f64)]]; + let buys: &[(i64, f64, f64)] = &[(100, 0.0, 3.0)]; + // The answers in order; the held executions and the bars drawn are checked after each one + // from the history page on. + type Row<'a> = ( + &'a str, + bool, + &'a Tape<'a>, + [Answer; 2], + &'a [f64], + [Drawn<'a>; 2], + ); + let rows: [Row; 7] = [ ( "ids", true, - false, + &volume, + [Executions, Bars], &[2.0, 5.0, 6.0, 5.0, 6.0, 6.0, 4.0, 1.0], + [&[], &[]], + ), + ( + "no ids", + false, + &volume, + [Executions, Bars], + &[2.0, 5.0, 6.0, 5.0, 6.0, 6.0, 1.0], + [&[], &[]], ), - ("no ids", false, false, &[2.0, 5.0, 6.0, 5.0, 6.0, 6.0, 1.0]), ( "no ids, history page first", false, + &volume, + [Bars, Executions], + &[2.0, 5.0, 6.0, 5.0, 6.0, 6.0, 1.0], + [&[], &[]], + ), + ( + "ids, no trade history", true, + &volume, + [Bars, NoExecutions], &[2.0, 5.0, 6.0, 5.0, 6.0, 6.0, 1.0], + [&[], &[]], + ), + ( + "no ids, no trade history", + false, + &volume, + [Bars, NoExecutions], + &[2.0, 5.0, 6.0, 5.0, 6.0, 6.0, 1.0], + [&[], &[]], + ), + ( + "ticks, a bar opens between the streams, no trade history", + false, + &ticks, + [Bars, NoExecutions], + &[1.0, 1.0, 1.0, 1.0], + [&[], &[]], + ), + ( + "ticks, nothing traded between the streams, a trade page that adds nothing", + true, + &quiet, + [Bars, Executions], + &[1.0; 13], + [&[buys, buys, buys], &[buys, buys, buys, buys]], ), ]; let mut failures = Vec::new(); - for (label, ids, history_first, held) in rows { - let identified = |trade: Tick, id| if ids { trade.with_id(id) } else { trade }; - let tape: Vec = (fills.iter().enumerate()) - .map(|(second, &(price, size, side))| { - let at = start + TimeDelta::seconds(second as i64); - identified(Tick::new(at, price, size, Some(side)), second as u64 + 1) - }) + for (label, ids, (intervals, fills, streamed, live, paged), answers, held, cells) in rows { + let execution = |&(second, price, size, side): &Fill, id| { + let trade = Tick::new(start + TimeDelta::seconds(second), price, size, Some(side)); + if ids { trade.with_id(id) } else { trade } + }; + let tape: Vec = (fills.iter().zip(1..)) + .map(|(fill, id)| execution(fill, id)) .collect(); - let live = identified(Tick::new(tape[7].ts, 106.0, 1.0, Some(Sell)), 100); - let timeframe: Timeframe = "10v".parse().unwrap(); + let live = execution(live, 100); + let paged = *paged; + let timeframe: Timeframe = intervals[1].parse().unwrap(); let candles = crate::data::aggregate_trades_with_tick_size(&tape, timeframe, Some(1.0)).unwrap(); let feed = Arc::new(Script::default()); let mut chart = fed(&feed, Some("A")); - chart.set_timeframe("20v".parse().unwrap()); + chart.set_timeframe(intervals[0].parse().unwrap()); chart.set_chart_type(ChartType::VolumeFootprint); let mut frames = Frames::new(); frames.run(&mut chart); feed.resolve() .send(Ok(Instrument::new("A").with_tick_size(1.0))); frames.run(&mut chart); - (tape[1..7].iter()).for_each(|trade| feed.sink().push_tick(trade.clone())); + (tape[streamed.clone()].iter()).for_each(|trade| feed.sink().push_tick(trade.clone())); frames.run(&mut chart); chart.set_timeframe(timeframe); frames.run(&mut chart); @@ -2231,39 +2513,45 @@ fn an_interval_change_page_draws_only_a_bars_own_executions() { feed.sink().push_tick(live); frames.run(&mut chart); // Each subscription asked for its own pages; the newest are the new interval's. - let trades = feed.trades.lock().unwrap().pop().unwrap(); - let history = feed.pages.lock().unwrap().pop().unwrap(); - let trade_page = Ok(TradePage::new(tape[1..].to_vec(), false)); - let history_page = page(candles[..4].to_vec(), true); - if history_first { - history.send(history_page); - frames.run(&mut chart); - trades.send(trade_page); - } else { - trades.send(trade_page); + let mut trades = feed.trades.lock().unwrap().pop(); + let mut history = feed.pages.lock().unwrap().pop(); + for (at, answer) in answers.into_iter().enumerate() { + match answer { + Bars => (history.take().unwrap()).send(page(candles[..paged].to_vec(), true)), + Executions => { + (trades.take().unwrap()).send(Ok(TradePage::new(tape[1..].to_vec(), false))) + } + NoExecutions => trades.take().unwrap().send(Err(FeedError::NotSupported)), + } frames.run(&mut chart); - history.send(history_page); - } - frames.run(&mut chart); - assert_eq!(chart.bars(SeriesId::MAIN)[..4], candles[..4], "{label}"); - let sizes: Vec<_> = (chart.trades(SeriesId::MAIN).map(|trade| trade.size)).collect(); - if sizes != held { - failures.push(format!("{label}: held {sizes:?}")); - } - let link = chart.feed_link.as_ref().unwrap(); - let flow = link.footprint.as_ref().unwrap(); - let complete = flow.complete_from(); - let drawn: Vec> = (candles[..4].iter()) - .filter(|bar| complete.is_some_and(|from| bar.time >= from)) - .filter_map(|bar| flow.bar_at(bar.time)) - .map(|cells| { - (cells.levels.values()) - .map(|level| (level.level, level.bid, level.ask)) - .collect() - }) - .collect(); - if !drawn.is_empty() { - failures.push(format!("{label}: drawn {drawn:?}")); + if history.is_some() { + continue; + } + let label = format!("{label}, after answer {at}"); + assert_eq!( + chart.bars(SeriesId::MAIN)[..paged], + candles[..paged], + "{label}" + ); + let sizes: Vec<_> = (chart.trades(SeriesId::MAIN).map(|trade| trade.size)).collect(); + if sizes != held { + failures.push(format!("{label}: held {sizes:?}")); + } + let link = chart.feed_link.as_ref().unwrap(); + let flow = link.footprint.as_ref().unwrap(); + let complete = flow.complete_from(); + let drawn: Vec> = (candles[..paged].iter()) + .filter(|bar| complete.is_some_and(|from| bar.time >= from)) + .filter_map(|bar| flow.bar_at(bar.time)) + .map(|cells| { + (cells.levels.values()) + .map(|level| (level.level, level.bid, level.ask)) + .collect() + }) + .collect(); + if drawn != cells[at] { + failures.push(format!("{label}: drawn {drawn:?}")); + } } } assert!(failures.is_empty(), "{failures:?}"); @@ -2483,6 +2771,66 @@ fn range_bars_are_built_from_the_held_trades() { ); } +/// Trades that arrive after OHLC history keep the range bars approximated before the bar that +/// holds the first trade, on either side of a replay cursor at that trade. +#[test] +fn range_bars_keep_the_approximated_history_before_the_first_trade() { + use crate::model::RangeBarSource::{OhlcApproximation, OhlcThenExecutions}; + let feed = Arc::new(Script::default()); + let mut chart = fed(&feed, Some("A")); + chart.set_chart_type(crate::model::ChartType::Range); + chart.set_chart_type_params(crate::model::ChartTypeParams { + range_size: 1.0, + ..Default::default() + }); + let mut frames = Frames::new(); + frames.run(&mut chart); + feed.resolve().send(Ok(Instrument::new("A"))); + // Flat minute bars at 100 to 105: range bars closing at 101 to 105, then one at 105 in + // progress. + feed.page().send(page(bars(6), true)); + frames.run(&mut chart); + let closes = |chart: &Chart| { + chart + .state + .shown() + .iter() + .map(|bar| bar.close) + .collect::>() + }; + assert_eq!(closes(&chart), [101.0, 102.0, 103.0, 104.0, 105.0, 105.0]); + let history = chart.state.shown()[..4].to_vec(); + // Trades at 105 and 106 in the last bar's minute replace that bar: the bars before it give + // the range bars closing at 101 to 104, and the trades one from 105 to 106. + let minute = bars(6)[5].time; + let sink = feed.sink(); + for (seconds, price) in [(10, 105.0), (20, 106.0)] { + sink.push_tick(Tick::new( + minute + TimeDelta::seconds(seconds), + price, + 1.0, + None, + )); + } + frames.run(&mut chart); + assert_eq!(chart.range_bar_source(), Some(OhlcThenExecutions)); + assert_eq!(closes(&chart), [101.0, 102.0, 103.0, 104.0, 106.0]); + assert_eq!(chart.state.shown()[..4], history); + // Replay keeps the five completed bars: their approximation before the first trade, the + // approximated range bars and that trade's range bar after it. + for (seconds, source, last) in [ + (5, OhlcApproximation, 104.0), + (15, OhlcThenExecutions, 105.0), + ] { + chart.set_replay_time(Some(minute + TimeDelta::seconds(seconds))); + frames.run(&mut chart); + assert_eq!(chart.range_bar_source(), Some(source), "{seconds} s"); + assert_eq!(chart.state.shown()[..4], history, "{seconds} s"); + assert_eq!(chart.state.shown()[4].close, last, "{seconds} s"); + assert_eq!(chart.state.shown().len(), 5, "{seconds} s"); + } +} + #[test] fn replay_reset_removes_future_data_from_the_chart() { let feed = Arc::new(Script::default()); diff --git a/vendor/egui-charts/src/widget/format.rs b/vendor/egui-charts/src/widget/format.rs index 7278695..ab4fd7c 100644 --- a/vendor/egui-charts/src/widget/format.rs +++ b/vendor/egui-charts/src/widget/format.rs @@ -36,6 +36,9 @@ impl PriceFormatter for DisplayFormatLabels { impl Chart { /// Formats a timestamp with the chart's zone, clock visibility and interval, or the median /// spacing of the source bars in or nearest the view for inferred and trade-based intervals. + /// Bars of a day or longer given without a feed read in UTC, where they carry their trading + /// date, under a display zone behind UTC unless they sit at its midnight; see the time zones + /// guide. /// On a [horizontal scale](Self::set_horizontal_scale), formats its key as the crosshair does. /// Hosts can use this for data windows and other readouts beside the chart. pub fn format_time(&self, time: chrono::DateTime) -> String { @@ -154,7 +157,7 @@ impl Chart { crate::scales::median_bar_duration(bars[at..end].iter().map(|bar| bar.time)).num_seconds() } - pub(super) fn display_timezone(&self) -> crate::scales::TimezoneMode { + pub(crate) fn display_timezone(&self) -> crate::scales::TimezoneMode { match &self.chart_options.time_scale.timezone { crate::scales::TimezoneMode::Exchange(fallback) => { crate::scales::TimezoneMode::Exchange( @@ -168,12 +171,56 @@ impl Chart { } } + /// The zone that dates the bars. Supplied bars of a day or longer carry their trading date at + /// 00:00 UTC. A display zone behind UTC shows that stamp as the evening before, so there they + /// read in UTC unless they sit at its midnight; UTC gives a bar at that midnight the same + /// date. Other zones keep the date of the stamp and of their own midnight, so they read in + /// the display zone, as intraday bars and the bars of the chart's feed always do. Bar replay + /// decides on the history it retains, since its window is cut on this zone's calendar. + /// `bar_seconds` gives [`time_label_seconds`](Self::time_label_seconds), read only for + /// supplied bars on a time interval. + pub(crate) fn label_timezone( + &self, + bar_seconds: impl FnOnce() -> i64, + ) -> crate::scales::TimezoneMode { + let zone = self.display_timezone(); + let wall = |bar: &crate::model::Bar| match &zone { + crate::scales::TimezoneMode::Local => crate::model::local_time(chrono::Local, bar.time), + zone => crate::model::local_time(zone.to_tz().unwrap_or_default(), bar.time), + }; + let bars = (self.replay.as_ref()) + .and_then(|replay| replay.bars.get(&super::SeriesId::MAIN)) + .unwrap_or(&self.state.data().bars); + let edges = || bars.first().into_iter().chain(bars.last()); + let utc_dates = self.feed_link.is_none() + && !self + .timeframe + .is_some_and(crate::model::Timeframe::is_trade_based) + && bar_seconds() >= 86_400 + && edges().any(|bar| wall(bar) < bar.time.naive_utc()) + && !edges().all(|bar| wall(bar).time() == chrono::NaiveTime::MIN); + if utc_dates { + crate::scales::TimezoneMode::Utc + } else { + self.display_timezone() + } + } + + /// Dates and the axis marks read in [`label_timezone`](Self::label_timezone). pub(crate) fn build_time_formatter(&self) -> Box { + self.time_formatter_in(self.label_timezone(|| self.time_label_seconds())) + } + + /// Formats in `timezone`, for instants with a clock such as fills, on any interval. + pub(crate) fn time_formatter_in( + &self, + timezone: crate::scales::TimezoneMode, + ) -> Box { let mut builder = TimeFormatterBuilder::new() .with_24_hour(true) .with_seconds(self.chart_options.time_scale.seconds_visible) .with_time_visible(self.chart_options.time_scale.time_visible) - .with_timezone(self.display_timezone()); + .with_timezone(timezone); if let Some(locale) = &self.locale { builder = builder.with_locale(locale.clone()); } @@ -211,8 +258,9 @@ impl Chart { /// [`TickMarkContext`](crate::scales::TickMarkContext) and can return `None` to use the /// built-in locale-aware text for that tick. Otherwise the /// formatter replaces the built-in one, the locale and the date format. It receives - /// wall-clock times in the chart's time zone, and the time scale's - /// [`time_visible`](crate::config::TimeScaleOptions::time_visible) option still applies. + /// wall-clock times in the zone [`format_time`](Self::format_time) reads them in, and the + /// time scale's [`time_visible`](crate::config::TimeScaleOptions::time_visible) option + /// still applies. /// `None` restores the built-in formatter. /// /// [`TimeFormatter::format`]: crate::scales::TimeFormatter::format @@ -827,6 +875,181 @@ mod tests { } } + /// Bars supplied at 00:00 UTC on their trading date keep that date in every display zone, + /// in the readout and in the day, month and year marks of the axis; intraday bars keep the + /// clock of the display zone. + #[cfg(feature = "timezones")] + #[test] + fn supplied_calendar_bars_keep_their_date_in_every_display_zone() { + use crate::model::{Bar, BarData, LogicalRange, Timeframe}; + use crate::scales::TimezoneMode; + use chrono::{Datelike, Duration, Months, NaiveDate, TimeZone, Utc}; + let day = |y, m, d| Utc.with_ymd_and_hms(y, m, d, 0, 0, 0).unwrap(); + let months = [ + "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", + ]; + // (interval, first bar, bar read, its label, marks that must be painted) + for (timeframe, first, at, expected, required) in [ + ( + Timeframe::Day1, + day(2024, 1, 1), + 95, + "Apr 05, 2024", + &["Feb", "Mar", "Apr"][..], + ), + ( + Timeframe::Week1, + day(2023, 1, 2), + 95, + "Oct 28, 2024", + &["2024"][..], + ), + ( + Timeframe::Month1, + day(2016, 1, 1), + 95, + "Dec 01, 2023", + &["2020"][..], + ), + ] { + let times: Vec<_> = (0..100) + .map(|i| match timeframe { + Timeframe::Month1 => first.checked_add_months(Months::new(i)).unwrap(), + Timeframe::Week1 => first + Duration::weeks(i.into()), + _ => first + Duration::days(i.into()), + }) + .collect(); + for zone in [ + TimezoneMode::Utc, + TimezoneMode::Timezone("America/New_York".parse().unwrap()), + TimezoneMode::Timezone("Asia/Tokyo".parse().unwrap()), + ] { + let ctx = egui::Context::default(); + let bars = times + .iter() + .map(|&time| Bar::new(time, 100.0, 110.0, 100.0, 110.0, 1.0)) + .collect(); + let mut chart = crate::widget::Chart::new(BarData::from_bars(bars)); + chart.set_timeframe(timeframe); + chart.chart_options.time_scale.timezone = zone.clone(); + frame(&ctx, &mut chart, 0.0, vec![]); + assert!(chart.set_visible_logical_range(LogicalRange::new(-0.5, 99.5))); + assert_eq!( + chart.format_time(times[at]), + expected, + "{timeframe:?} {zone:?}" + ); + let painted = shapes(&ctx, &mut chart, 0.1, vec![]); + let map = chart.get_chart_mapping(); + let mut seen = Vec::new(); + for text in painted.iter().filter_map(|shape| match shape { + Shape::Text(text) if text.pos.y > map.rect.bottom() => Some(text), + _ => None, + }) { + let label = text.galley.text(); + let index = map.x_to_idx(text.pos.x + text.galley.size().x / 2.0); + let date = times[index].date_naive(); + let starts_month = + index == 0 || times[index - 1].date_naive().month() != date.month(); + let fits = match label.parse::() { + Ok(year) if year > 31 => { + starts_month && date.month() == 1 && date.year() == year + } + Ok(day) => date.day() as i32 == day, + Err(_) => { + starts_month + && months.iter().position(|name| *name == label) + == Some(date.month0() as usize) + } + }; + assert!(fits, "{timeframe:?} {zone:?}: {label} on {date}"); + seen.push(label.to_owned()); + } + for label in required { + assert!( + seen.iter().any(|seen| seen == label), + "{timeframe:?} {zone:?}: {label} missing from {seen:?}" + ); + } + } + } + // Hourly bars keep the New York clock and date. + let first = NaiveDate::from_ymd_opt(2024, 1, 5) + .unwrap() + .and_hms_opt(3, 0, 0) + .unwrap() + .and_utc(); + let bars = (0..100) + .map(|i| Bar::new(first + Duration::hours(i), 100.0, 110.0, 100.0, 110.0, 1.0)) + .collect(); + let mut chart = crate::widget::Chart::new(BarData::from_bars(bars)); + chart.set_timeframe(Timeframe::Hour1); + chart.chart_options.time_scale.timezone = TimezoneMode::nyse(); + assert_eq!(chart.format_time(first), "Thu 04 Jan '24 22:00"); + } + + /// Bar replay completes supplied daily bars, forms the bar of its cursor's date and lets + /// studies group weeks on the dates the labels give the bars: in the display zone east of + /// UTC, and in UTC behind it, where the history keeps its 00:00 UTC stamps. + #[cfg(feature = "timezones")] + #[test] + fn replay_follows_the_dates_of_supplied_daily_bars_in_every_zone() { + use crate::model::{Bar, BarClock, BarData, Timeframe}; + use crate::scales::TimezoneMode; + use crate::widget::SeriesId; + use chrono::{Duration, TimeZone, Utc}; + let bar = |time| Bar::new(time, 100.0, 110.0, 100.0, 110.0, 1.0); + let at = |month, day, hour| Utc.with_ymd_and_hms(2024, month, day, hour, 0, 0).unwrap(); + // The zone, a cursor on 5 February and the zone's midnight starting that date. + for (zone, cursor, midnight) in [ + ("Asia/Tokyo", at(2, 5, 12), at(2, 4, 15)), + ("America/New_York", at(2, 5, 17), at(2, 5, 5)), + ] { + let mut chart = crate::widget::Chart::new(BarData::from_bars( + (0..40) + .map(|i| bar(at(1, 1, 0) + Duration::days(i))) + .collect(), + )); + chart.set_timeframe(Timeframe::Day1); + chart.chart_options.time_scale.timezone = TimezoneMode::Timezone(zone.parse().unwrap()); + #[cfg(feature = "studies")] + chart.add_indicator(Box::::default()); + // 1 January completes when its date ends, also after a cursor that showed no bar. + chart.set_replay_time(Some(at(1, 1, 12))); + chart.set_replay_time(Some(at(1, 2, 6))); + let early = chart.bars(SeriesId::MAIN).len(); + chart.set_replay_time(Some(cursor)); + let hours = (0..24) + .map(|i| bar(midnight + Duration::hours(i))) + .collect(); + assert!( + chart.set_replay_source(hours, BarClock::new(Timeframe::Hour1)), + "{zone}" + ); + let bars = chart.bars(SeriesId::MAIN); + let labels: Vec<_> = (bars[bars.len() - 2..].iter()) + .map(|bar| chart.format_time(bar.time)) + .collect(); + assert_eq!( + (early, bars.len(), labels), + ( + 1, + 36, + vec!["Feb 04, 2024".to_owned(), "Feb 05, 2024".to_owned()] + ), + "{zone}" + ); + #[cfg(feature = "studies")] + { + chart.refresh_studies(1.0); + let study = chart.indicators().next().unwrap().1; + // The Mondays from 1 January; the last is the bar replay forms. + let starts: Vec<_> = (study.candles().iter()).map(|c| c.bars.start).collect(); + assert_eq!(starts, [0, 7, 14, 21, 28, 35], "{zone}"); + } + } + } + #[cfg(feature = "timezones")] #[test] fn hover_times_share_the_chart_zone_through_dst() { diff --git a/vendor/egui-charts/src/widget/frame/background.rs b/vendor/egui-charts/src/widget/frame/background.rs index 373fef2..fda8cb1 100644 --- a/vendor/egui-charts/src/widget/frame/background.rs +++ b/vendor/egui-charts/src/widget/frame/background.rs @@ -1,32 +1,97 @@ use super::Chart; use crate::chart::rendering; use crate::config::{BackgroundStyle, WatermarkPos}; -use egui::{Rect, Ui}; +use egui::{Color32, Pos2, Rect, Ui}; + +/// The colour at `pos` of a background of `style` whose gradient spans `frame`; `color` when it +/// is solid. +pub(in crate::widget) fn background_at( + frame: Rect, + style: BackgroundStyle, + color: Color32, + pos: Pos2, +) -> Color32 { + match style { + BackgroundStyle::Solid => color, + BackgroundStyle::VerticalGradient { + top_color, + bottom_color, + } => top_color.lerp_to_gamma( + bottom_color, + egui::remap_clamp(pos.y, frame.y_range(), 0.0..=1.0), + ), + BackgroundStyle::HorizontalGradient { + left_color, + right_color, + } => left_color.lerp_to_gamma( + right_color, + egui::remap_clamp(pos.x, frame.x_range(), 0.0..=1.0), + ), + } +} + +/// Fills `rect` with the part behind it of a background of `style` whose gradient spans `frame`, +/// so that rects filled one by one join without a seam; `color` when it is solid. +pub(in crate::widget) fn paint_background( + painter: &egui::Painter, + frame: Rect, + rect: Rect, + style: BackgroundStyle, + color: Color32, +) { + if style == BackgroundStyle::Solid { + painter.rect_filled(rect, 0.0, color); + return; + } + let vertices = [ + rect.left_top(), + rect.right_top(), + rect.right_bottom(), + rect.left_bottom(), + ] + .map(|pos| egui::epaint::Vertex { + pos, + uv: egui::epaint::WHITE_UV, + color: background_at(frame, style, color, pos), + }); + painter.add(egui::Shape::mesh(egui::Mesh { + indices: vec![0, 1, 2, 2, 3, 0], + vertices: vertices.to_vec(), + texture_id: egui::TextureId::default(), + })); +} impl Chart { + /// The rect the background spans: `rect`, the price frame, with the other panes and the time + /// axis below them, so that a gradient runs once through the chart. + pub(in crate::widget) fn background_frame(&self, rect: Rect) -> Rect { + let mut panes = self + .pane_layout + .panes + .iter() + .fold(Rect::NOTHING, |frame, pane| frame.union(pane.rect)); + // Stacked panes share the time axis below the last of them. + if self.has_panes() { + panes.max.y += self.time_axis_height(); + } + rect.union(panes) + } + + /// The colour of the chart's background at `pos`, whether the chart or its container paints + /// it; `rect` is the price frame. + pub(in crate::widget) fn background_at(&self, rect: Rect, pos: Pos2) -> Color32 { + background_at( + self.background_frame(rect), + self.config.background_style, + self.config.background_color, + pos, + ) + } + /// The background colour at `pos` within the frame painted by [`Self::draw_background`], /// or `None` when something else paints it. - pub(super) fn plot_background(&self, rect: Rect, pos: egui::Pos2) -> Option { - if self.config.skip_background { - return None; - } - Some(match self.config.background_style { - BackgroundStyle::Solid => self.config.background_color, - BackgroundStyle::VerticalGradient { - top_color, - bottom_color, - } => top_color.lerp_to_gamma( - bottom_color, - egui::remap_clamp(pos.y, rect.y_range(), 0.0..=1.0), - ), - BackgroundStyle::HorizontalGradient { - left_color, - right_color, - } => left_color.lerp_to_gamma( - right_color, - egui::remap_clamp(pos.x, rect.x_range(), 0.0..=1.0), - ), - }) + pub(super) fn plot_background(&self, rect: Rect, pos: Pos2) -> Option { + (!self.config.skip_background).then(|| self.background_at(rect, pos)) } /// Draw the chart background (solid or gradient) @@ -35,78 +100,13 @@ impl Chart { if self.config.skip_background { return; } - - match self.config.background_style { - BackgroundStyle::Solid => { - painter.rect_filled(rect, 0.0, self.config.background_color); - } - BackgroundStyle::VerticalGradient { - top_color, - bottom_color, - } => { - // Draw vertical gradient using a mesh - let mesh = egui::Mesh { - indices: vec![0, 1, 2, 2, 3, 0], - vertices: vec![ - egui::epaint::Vertex { - pos: rect.left_top(), - uv: egui::epaint::WHITE_UV, - color: top_color, - }, - egui::epaint::Vertex { - pos: rect.right_top(), - uv: egui::epaint::WHITE_UV, - color: top_color, - }, - egui::epaint::Vertex { - pos: rect.right_bottom(), - uv: egui::epaint::WHITE_UV, - color: bottom_color, - }, - egui::epaint::Vertex { - pos: rect.left_bottom(), - uv: egui::epaint::WHITE_UV, - color: bottom_color, - }, - ], - texture_id: egui::TextureId::default(), - }; - painter.add(egui::Shape::mesh(mesh)); - } - BackgroundStyle::HorizontalGradient { - left_color, - right_color, - } => { - // Draw horizontal gradient using a mesh - let mesh = egui::Mesh { - indices: vec![0, 1, 2, 2, 3, 0], - vertices: vec![ - egui::epaint::Vertex { - pos: rect.left_top(), - uv: egui::epaint::WHITE_UV, - color: left_color, - }, - egui::epaint::Vertex { - pos: rect.right_top(), - uv: egui::epaint::WHITE_UV, - color: right_color, - }, - egui::epaint::Vertex { - pos: rect.right_bottom(), - uv: egui::epaint::WHITE_UV, - color: right_color, - }, - egui::epaint::Vertex { - pos: rect.left_bottom(), - uv: egui::epaint::WHITE_UV, - color: left_color, - }, - ], - texture_id: egui::TextureId::default(), - }; - painter.add(egui::Shape::mesh(mesh)); - } - } + paint_background( + painter, + self.background_frame(rect), + rect, + self.config.background_style, + self.config.background_color, + ); } /// Paints the symbol watermark: the custom text at the configured size, else the symbol and diff --git a/vendor/egui-charts/src/widget/frame/mod.rs b/vendor/egui-charts/src/widget/frame/mod.rs index e9f3241..c10909b 100644 --- a/vendor/egui-charts/src/widget/frame/mod.rs +++ b/vendor/egui-charts/src/widget/frame/mod.rs @@ -3,6 +3,7 @@ mod background; mod sessions; +pub(super) use background::{background_at, paint_background}; #[cfg(feature = "studies")] pub(super) use sessions::session_ranges; @@ -218,6 +219,7 @@ impl Chart { self.sync_volume_study(ui.ctx()); #[cfg(feature = "drawings")] self.sync_stored_drawings(ui.ctx()); + self.frame_clock = Some(super::change_marks::FrameClock::shown_in(ui.ctx())); self.pump(ui.ctx()); if let Some(wait) = self.refresh_studies(ui.input(|i| i.time)) { ui.ctx() @@ -359,11 +361,14 @@ impl Chart { .time_scale .lock_visible_time_range_on_resize) && previous_axis_width > 0.0 - && old_width > 0.0 - && new_width > 0.0 + && old_width >= 2.0 + && new_width >= 2.0 { - let scale = self.state.time_scale_mut(); - scale.set_bar_spacing(scale.bar_spacing() * new_width / old_width); + self.state + .time_scale_mut() + .keep_slots_on_resize(old_width, new_width); + // The rerun pass must not resize the scale again from the old width. + self.prev_width = Some(new_width); } ui.ctx().request_discard("Chart measured its axis labels"); } @@ -585,8 +590,10 @@ impl Chart { }); // A button owns the whole gesture, including a drag that leaves the row. The chart's // own response goes back to the caller; the gesture handlers see a hover-only one. - let mut shown = - shared_plot.map_or_else(|| response.clone(), |plot| response.union(plot.clone())); + // The other panes stand in for a price frame without height in what the caller gets. + let mut shown = shared_plot + .filter(|_| rect.height() == 0.0) + .map_or_else(|| response.clone(), |plot| response.union(plot.clone())); if self.pane_collapse_click(ui.ctx()) { response.flags.remove(egui::response::Flags::CLICKED); shown.flags.remove(egui::response::Flags::CLICKED); @@ -618,7 +625,7 @@ impl Chart { #[cfg(not(feature = "drawings"))] let drawing_tool_active = false; #[cfg(not(feature = "drawings"))] - let is_drawing_interaction = false; + let (is_drawing_interaction, drawing_gesture) = (false, false); #[cfg(feature = "drawings")] if self.drawings.selection_area().is_some_and(|area| { area.pane @@ -629,10 +636,12 @@ impl Chart { self.drawings.end_selection_area(); } } + // A Ctrl or Command press on empty space arms a selection area, which only a drag starts. + #[cfg(feature = "drawings")] + let box_selection = self.drawings.box_selection_input(ui); // The Magic cursor marks while the button is held, so a drag paints rather than pans. #[cfg(feature = "drawings")] - let is_drawing_interaction = self.drawings.box_selection_input(ui) - || self.drawings.active_tool.is_some() + let drawing_gesture = self.drawings.active_tool.is_some() || self.chart_options.crosshair.style == crate::config::CrosshairStyle::Magic || self.drawings.dragging_handle.is_some() || self.drawings.text_editor.is_some() @@ -650,6 +659,8 @@ impl Chart { .any(|d| d.id == id && !d.locked) }) }); + #[cfg(feature = "drawings")] + let is_drawing_interaction = box_selection || drawing_gesture; let show_price_button = self.config.show_plus_button && !eraser_mode && !is_drawing_interaction; let show_axis_settings = !self.layout_inactive || ui.rect_contains_pointer(rect); @@ -680,21 +691,16 @@ impl Chart { .or(input.pointer.hover_pos()) .is_some_and(|pos| axis_corner.contains(pos)) }))); - let hover_rect = shared_plot.map_or_else( - || { - Rect::from_min_max( - Pos2::new( - chart_rect.left(), - self.pane_layout - .panes - .iter() - .map(|pane| pane.rect.top()) - .fold(chart_rect.top(), f32::min), - ), - Pos2::new(chart_rect.right(), time_axis_top), - ) - }, - |plot| plot.rect, + let hover_rect = Rect::from_min_max( + Pos2::new( + chart_rect.left(), + self.pane_layout + .panes + .iter() + .map(|pane| pane.rect.top()) + .fold(chart_rect.top(), f32::min), + ), + Pos2::new(chart_rect.right(), time_axis_top), ); let touch_readout_interaction = self.handle_touch_crosshair( ui, @@ -743,7 +749,7 @@ impl Chart { response.rect = rect; } - // The visible pane drives time navigation even while the price pane has no height. + // The plots of the other panes drive time navigation as the price plot does. let mut time_response = shared_plot.map_or_else(|| response.clone(), |plot| response.union(plot.clone())); time_response.flags.remove(readout_flags); @@ -797,13 +803,23 @@ impl Chart { ); // Handle double-click to reset axes - self.handle_double_click(&time_response, price_axis_rect, time_axis_rect); + self.handle_double_click(&time_response, time_axis_rect); + + // The price axis: a drawing or a touch readout that owns the drag keeps it, as on the plot. + let mut axis_response = time_response.clone(); + if is_drawing_interaction || touch_readout_interaction { + axis_response.flags.remove(egui::response::Flags::DRAGGED); + } + let price_axis_gestures = self.price_axis_gestures(ui, &axis_response, price_axis_rect); + if price_axis_gestures.reset { + self.state.price_scale_mut().reset(); + } // Handle mouse wheel for zoom/scroll // Block pan/zoom when drawing tool is active OR when manipulating a drawing let time_based = !self.chart_type.is_time_independent(); let show_volume = self.shows_volume(); - let pending_price_zoom = self.handle_mouse_wheel( + self.handle_mouse_wheel( ui, &time_response, chart_width, @@ -1126,6 +1142,17 @@ impl Chart { ) .filter(|_| self.main_series_visible && time_based) .collect::>(); + // The newest close of a price-based chart can lie beyond its newest element. While that + // element is in view, the price its last price line shows is fitted with it, so that the + // line and its label are drawn. The newest element in view is among the fitted bars. + let last_price = (!time_based + && self.main_series_visible + && self.main_series_style.price_line_source == crate::model::PriceLineSource::LastBar + && start_idx < end_idx + && end_idx == self.state.shown().len()) + .then(|| crate::model::last_with_value(&self.state.data().bars)) + .flatten() + .map(|bar| bar.close); let heikin_ashi = (self.chart_type == crate::model::ChartType::Heikin && !self.state.data().is_empty()) .then(|| { @@ -1165,6 +1192,7 @@ impl Chart { .into_iter() .chain(primitive_prices) .chain(target_prices) + .chain(last_price) .chain(footprint_prices.into_iter().flatten()) .chain(profile_prices), series_values, @@ -1343,7 +1371,12 @@ impl Chart { self.fit_main_marker_scale(&painter, price_rect, main_margins); } } - self.apply_price_zoom(pending_price_zoom, &response, price_rect, transform); + // After the fit, so that a scale on automatic is zoomed from this frame's range. + price_axis_gestures.zoom( + self.state.price_scale_mut(), + price_rect.top(), + price_rect.bottom(), + ); let bar_spacing = self.state.time_scale().bar_spacing(); if self.config.lock_price_to_bar_ratio != self.last_ratio_lock { self.state.price_scale_mut().set_bar_ratio_locked( @@ -1451,14 +1484,17 @@ impl Chart { }; let timezone = self.display_timezone(); - let time_scale = self.build_time_formatter(); + // Sampled once: inferred spacing sorts the gaps of the bars in view. + let bar_seconds = self.time_label_seconds(); + let label_timezone = self.label_timezone(|| bar_seconds); + let time_scale = self.time_formatter_in(label_timezone.clone()); let host_scale = self.horizontal_scale.clone(); let scale: &dyn crate::scales::HorizontalScale = host_scale.as_deref().unwrap_or(&time_scale); // The grid and the labels share one set of marks and the merged bars' mapping. let (time_marks, time_points, axis_coords) = if time_grid || self.config.show_time_labels { // Resolved once: a fixed-offset zone allocates on every clone. - let calendar = self.calendar_timezone(); + let calendar = Self::calendar_zone(label_timezone); let numeric = time_coords.numeric_positions.is_some(); rendering::time_axis_marks( &RenderContext::new(&painter, chart_rect), @@ -2008,6 +2044,7 @@ impl Chart { if study.is_volume() && !matches!(study.scale(), crate::studies::StudyScale::Shared(_)) && self.main_series_visible + && self.chart_type.supports_volume() && !self.state.data().is_empty() { let rect = super::volume::overlay_rect(price_rect, &self.config); @@ -2235,13 +2272,23 @@ impl Chart { if let Some(table) = statistics_rect && let Some((flow, config)) = host.or_else(|| feed.zip(feed_config.as_ref())) { + // The trading days the session breaks divide intraday bars into; a bar of a + // day or longer holds one of its own. + let trading_days = config.session_cumulative_delta.then(|| { + exchange_session + .clone() + .with_timeframe(crate::model::Timeframe::Min1) + }); + let sessions = trading_days + .as_ref() + .map(|days| self.session_provider.as_deref().unwrap_or(days)); crate::chart::overlays::render_footprint_statistics_rows( &painter, &self.get_chart_mapping().with_rect(table), self.bars(super::SeriesId::MAIN), flow, - config.text_color, - statistics_rows.as_deref().unwrap(), + config, + sessions, ); } if let Some((_, Some(volume))) = &merged { @@ -2339,8 +2386,11 @@ impl Chart { // study's pane. Otherwise overlay indicators take priority over the // series beneath them; an empty-area click clears the selection. Clicks // in a study's pane are resolved where the panes are rendered, outside - // this rect. + // this rect. As there, a click with the eraser or a drawing tool keeps + // the selection. if response.clicked() + && !drawing_tool_active + && !eraser_mode && let Some(click_pos) = response.interact_pointer_pos() { #[cfg(feature = "drawings")] @@ -2786,9 +2836,12 @@ impl Chart { axis, &study_axis, None, + colors.text, + &|pos| self.background_at(rect, pos), )); } if show_price_axis && study_axis.show_study_values { + let last_in_view = rendering::axes::last_bar_in_view(&coords); for study in studies .indicators() .iter() @@ -2796,6 +2849,10 @@ impl Chart { .filter(|(idx, _)| study_indices.contains(idx)) .map(|(_, study)| study) { + // A chart type that hides volume tags no volume value. + if study.is_volume() && !self.chart_type.supports_volume() { + continue; + } if study.is_volume() && !matches!(study.scale(), crate::studies::StudyScale::Shared(_)) { @@ -2813,6 +2870,7 @@ impl Chart { price_rect, &mapping.price, study.as_ref(), + last_in_view, axis_edge, &mut tags, &study_axis, @@ -2830,6 +2888,7 @@ impl Chart { price_rect, &price_map, study.as_ref(), + last_in_view, axis_edge, &mut tags, price_formatter.as_deref(), @@ -2985,8 +3044,6 @@ impl Chart { } } - let bar_seconds = self.time_label_seconds(); - // Handle drawing tools #[cfg(feature = "drawings")] { @@ -3044,19 +3101,25 @@ impl Chart { #[cfg(feature = "drawings")] { let mut prices = Vec::new(); - for tag in self - .drawings - .axis_tags(price_rect, ui.active_theme().chart.axis_text_secondary) - { + for tag in self.drawings.axis_tags( + price_rect, + ui.active_theme().chart.axis_text_secondary, + self.state.shown(), + self.state.revision(), + ) { match tag { - crate::drawings::manager::DrawingAxisTag::Price { price, color } => { + crate::drawings::manager::DrawingAxisTag::Price { + price, + color, + decimals, + } => { if show_price_axis && price.is_finite() && price_map .range() .contains(price_map.transform().to_scale(price)) { - prices.push((price_map.price_to_y(price), price, color)); + prices.push((price_map.price_to_y(price), price, color, decimals)); } } crate::drawings::manager::DrawingAxisTag::Time { x, anchor, color } => { @@ -3085,10 +3148,18 @@ impl Chart { if !self.config.price_axis.allow_label_overlap { ys = rendering::axes::spread_axis_ys(&painter, &ys); } - for ((_, price, color), y) in prices.into_iter().zip(ys) { + for ((_, price, color, decimals), y) in prices.into_iter().zip(ys) { let label = price_map.label( price_map.transform().to_scale(price), - rendering::axes::tag_decimals(&price_map, price_map.price_to_y(price)), + decimals.map_or_else( + || { + rendering::axes::tag_decimals( + &price_map, + price_map.price_to_y(price), + ) + }, + usize::from, + ), price_formatter.as_deref(), ); tags.push(rendering::axes::render_axis_value( @@ -3282,6 +3353,8 @@ impl Chart { session_closes.filter(|_| values && self.config.show_last_day_change); legend.study_backdrop = self.config.indicator_backdrop_opacity; legend.extended_hours = (&extended_hours.0, extended_hours.1); + let background = |pos: Pos2| self.background_at(rect, pos); + legend.background = Some(&background); let inputs: Vec<_> = self.study_inputs.iter().map(String::as_str).collect(); legend.study_inputs = &inputs; legend.previous_close = @@ -3526,8 +3599,7 @@ impl Chart { point, &self.chart_type_params.styles, color, - self.plot_background(rect, point) - .unwrap_or(self.config.background_color), + self.background_at(rect, point), ); } } @@ -3538,10 +3610,7 @@ impl Chart { item, self.series_map(item, price_rect), index, - |point| { - self.plot_background(rect, point) - .unwrap_or(self.config.background_color) - }, + |point| self.background_at(rect, point), ); } } @@ -3642,8 +3711,10 @@ impl Chart { .study_rows_at(start_idx + local_idx) .into_iter() .filter(|(id, _)| { - !tooltip_options.on_long_press - || tooltip_options.show_volume_details + // A chart type that hides volume lists no volume rows. + (self.chart_type.supports_volume() + && (!tooltip_options.on_long_press + || tooltip_options.show_volume_details)) || self .study_ids .iter() @@ -3852,9 +3923,11 @@ impl Chart { self.measured_axis_width += 26.0; } self.measured_axis_width = self.measured_axis_width.max(independent_axis_width); - for tag in tags.iter().skip(usize::from(has_currency)).flatten() { - self.measured_axis_width = self.measured_axis_width.max(tag.width() + 5.0 + 6.0); - } + self.measured_axis_width = self + .measured_axis_width + .max(rendering::axes::axis_tags_width( + tags.iter().skip(usize::from(has_currency)), + )); if show_price_axis && has_currency { let currency = self @@ -3964,6 +4037,14 @@ impl Chart { if let Some(id) = overlay_remove { self.user_action(|chart| chart.remove_series(id)); } + // The pane layout reads it to maximize or restore the price pane. + self.price_plot_double_click = response.double_clicked() + && !drawing_gesture + && !eraser_mode + && self.host_events.target.is_none() + && response + .interact_pointer_pos() + .is_some_and(|pos| chart_rect.contains(pos) && pos.y > legend_bottom); self.main_pane_actions(ui, rect, chart_rect); self.record_host_click(ui, &response); shown diff --git a/vendor/egui-charts/src/widget/frame/tests/axes.rs b/vendor/egui-charts/src/widget/frame/tests/axes.rs index 161fe09..0bf7e11 100644 --- a/vendor/egui-charts/src/widget/frame/tests/axes.rs +++ b/vendor/egui-charts/src/widget/frame/tests/axes.rs @@ -258,6 +258,9 @@ fn price_labels_and_lines_are_independent_on_either_axis() { /// Line tags use the anchor, stay clear of the last price and follow this frame's drag. /// Bar 51 is 1,700,000,000 + 51 * 86,400 = Jan 4, 2024 at 22:13:20 UTC; /// bar 61 is ten days later. Yellow's contrast with white is 1.22, so its text is black. +/// An anchored VWAP tags its latest value only while it tracks it, at its own precision: the +/// typical prices of bars 98 and 99 are 320 / 3 and 340 / 3, so from bar 98 it is 110 and from +/// bar 99 it is 113.33. #[cfg(feature = "drawings")] #[test] fn line_drawings_tag_their_price_and_time_on_the_axes() { @@ -278,6 +281,8 @@ fn line_drawings_tag_their_price_and_time_on_the_axes() { (9, T::CrossLine, 81.0, 103.59, [9, 9, 9, 255]), (10, T::HorizontalRay, 1000.0, 114.71, [200, 0, 0, 255]), (11, T::HorizontalLine, 90.0, 120.0, [140, 70, 20, 255]), + (12, T::AnchoredVWAP, 98.0, 110.0, [0, 150, 136, 255]), + (13, T::AnchoredVWAP, 99.0, 113.0, [0, 150, 136, 255]), ] { let mut drawing = Drawing::with_color(id, tool, color); drawing.chart_points = vec![ChartPoint::new(bar, price)]; @@ -286,6 +291,13 @@ fn line_drawings_tag_their_price_and_time_on_the_axes() { 8 => drawing.time_axis_label = false, 6 => drawing.visible = false, 7 => drawing.timeframe_visibility = TimeframeVisibility::specific(&["1h"]), + 12 => { + drawing.vwap = Some(crate::drawings::VwapConfig { + track_price: true, + precision: Some(4), + ..Default::default() + }) + } _ => {} } chart.drawings_mut().drawings.push(drawing); @@ -309,6 +321,8 @@ fn line_drawings_tag_their_price_and_time_on_the_axes() { ("118.13", false), ("103.59", false), ("114.71", false), + ("110.0000", true), + ("113.33", false), ] { assert_eq!(price_texts.contains(&label), shown, "price {label}"); } @@ -988,7 +1002,7 @@ fn views_past_the_bars_keep_the_chart_readable() { self.formatter.as_ref().format_crosshair(time, bar_seconds) } } - for (left, right) in [(2427.0, 3854.0), (28131.0, 29558.0)] { + for (left, right) in [(2427.0, 3852.0), (28131.0, 29556.0)] { let mut control = None; for count in [1000, 1001] { let start = Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap(); @@ -1047,56 +1061,97 @@ fn views_past_the_bars_keep_the_chart_readable() { } } +/// Startup label measurements keep the configured zoom of an unlocked chart, and a later one +/// keeps the visible range: the slots the plot spans and both edges, also in a locked chart, +/// which must not scale a second time from the old width, and at the fixed left edge's stop, +/// which must not clamp against the old width. #[test] fn initial_axis_passes_keep_zoom_and_later_measurements_keep_range() { use crate::model::Instrument; - let ctx = egui::Context::default(); - let mut chart = chart(&[100.0], &[110.0]); - chart.config.show_volume = false; - chart.set_instrument(Some(Instrument::new("TEST").with_price_decimals(2))); - let initial_view = chart.get_time_scale_state(); - let input = || egui::RawInput { - screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(800.0, 600.0))), - ..Default::default() - }; - ctx.run_ui( - egui::RawInput { - screen_rect: Some(Rect::ZERO), + for (lock, fix_left) in [(false, false), (true, false), (false, true), (true, true)] { + let row = format!("lock {lock}, fix_left_edge {fix_left}"); + let ctx = egui::Context::default(); + let mut chart = chart(&[100.0], &[110.0]); + chart.config.show_volume = false; + let mut options = chart.chart_options().clone(); + options.time_scale.bar_spacing = 20.0; + options.time_scale.lock_visible_time_range_on_resize = lock; + options.time_scale.fix_left_edge = fix_left; + chart.set_chart_options(options); + chart.set_instrument(Some(Instrument::new("TEST").with_price_decimals(2))); + let initial_view = chart.get_time_scale_state(); + let input = || egui::RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() - }, - |ui| { + }; + ctx.run_ui( + egui::RawInput { + screen_rect: Some(Rect::ZERO), + ..Default::default() + }, + |ui| { + chart.show(ui); + }, + ) + .drop_without_applying_deltas(); + let mut passes = 0; + ctx.run_ui(input(), |ui| { chart.show(ui); - }, - ) - .drop_without_applying_deltas(); - let mut passes = 0; - ctx.run_ui(input(), |ui| { - chart.show(ui); - passes += 1; - if ui.ctx().current_pass_index() == 0 { - // Metadata arriving during startup can widen labels on the discarded pass. - chart.set_instrument(Some(Instrument::new("TEST").with_price_decimals(6))); - ui.ctx().request_discard("instrument metadata arrived"); + passes += 1; + if ui.ctx().current_pass_index() == 0 { + // Metadata arriving during startup can widen labels on the discarded pass. + chart.set_instrument(Some(Instrument::new("TEST").with_price_decimals(6))); + ui.ctx().request_discard("instrument metadata arrived"); + } + }) + .drop_without_applying_deltas(); + assert!(passes > 1, "{row}"); + // A locked chart treats the startup measurement as a resize and keeps its slots. + if !lock { + assert_eq!(chart.get_time_scale_state(), initial_view, "{row}"); } - }) - .drop_without_applying_deltas(); - assert!(passes > 1); - assert_eq!(chart.get_time_scale_state(), initial_view); - ctx.run_ui(input(), |ui| { - chart.show(ui); - }) - .drop_without_applying_deltas(); - let width = chart.get_rendered_price_rect().width(); - let spacing = chart.state.time_scale().bar_spacing(); - chart.set_instrument(Some(Instrument::new("TEST").with_price_decimals(10))); - ctx.run_ui(input(), |ui| { - chart.show(ui); - }) - .drop_without_applying_deltas(); - let new_width = chart.get_rendered_price_rect().width(); - assert!(new_width < width, "later labels must widen the axis"); - assert!((new_width / chart.state.time_scale().bar_spacing() - width / spacing).abs() < 1e-4); + let settle = |chart: &mut crate::widget::Chart| { + ctx.run_ui(input(), |ui| { + chart.show(ui); + }) + .drop_without_applying_deltas(); + }; + settle(&mut chart); + if fix_left { + chart.scroll_to_position(-1000.0, false); + settle(&mut chart); + } + let width = chart.get_rendered_price_rect().width(); + let spacing = chart.state.time_scale().bar_spacing(); + let range = chart.state.time_scale().visible_logical_range(); + if fix_left { + assert_eq!( + range.left, 0.0, + "{row}: the view starts at the left edge's stop" + ); + } + chart.set_instrument(Some(Instrument::new("TEST").with_price_decimals(10))); + ctx.run_ui(input(), |ui| { + chart.show(ui); + }) + .drop_without_applying_deltas(); + let new_width = chart.get_rendered_price_rect().width(); + assert!(new_width < width, "{row}: later labels must widen the axis"); + // The plot spans `width - 1` pixels of slots, so both edges stay on the same times. + let slots = |width: f32, spacing: f32| f64::from(width - 1.0) / f64::from(spacing); + let new_spacing = chart.state.time_scale().bar_spacing(); + assert!( + (slots(new_width, new_spacing) - slots(width, spacing)).abs() < 1e-4, + "{row}: spacing {spacing} to {new_spacing}" + ); + let new_range = chart.state.time_scale().visible_logical_range(); + assert!( + (new_range.left - range.left).abs() < 1e-3 + && (new_range.right - range.right).abs() < 1e-3, + "{row}: {range:?} to {new_range:?}" + ); + } } /// Extra columns share at most half of a narrow widget on either edge. Four 70-point columns @@ -1209,3 +1264,52 @@ fn heikin_last_visible_price_line_without_main_bars() { ); } } + +/// Study value tags read their plot at the last bar in view, in the price pane, in a study pane +/// and on the volume overlay, and read the newest values again at the latest bars. Bar `i` has +/// its low at 100 + i, closes 10 above it except on every third bar and trades i + 1 lots; the +/// SMA(3) and MACD(12, 26, 9) values are worked out by hand from those closes. +#[cfg(feature = "studies")] +#[test] +fn study_value_tags_read_the_last_bar_in_view() { + use crate::model::{Bar, BarData}; + let start = chrono::DateTime::UNIX_EPOCH; + let bars = (0..100) + .map(|i| { + let low = 100.0 + i as f64; + let close = if i % 3 == 0 { low } else { low + 10.0 }; + let time = start + chrono::Duration::days(i); + Bar::new(time, low, close, low, close, (i + 1) as f64) + }) + .collect(); + let mut chart = crate::widget::Chart::new(BarData::from_bars(bars)); + chart.add_indicator(Box::new(crate::studies::SMA::new(3))); + chart.add_indicator(Box::new(crate::studies::MACD::new(12, 26, 9))); + let ctx = egui::Context::default(); + frame(&ctx, &mut chart, 0.0, vec![]); + // Scrolled back 40 bars the view ends at bar 59. + for (offset, expected) in [ + (-40.0, ["164.67", "7.22", "60"]), + (0.0, ["204.67", "6.69", "100"]), + ] { + let scale = chart.state.time_scale_mut(); + scale.set_bar_spacing(12.0); + scale.set_right_offset(offset); + frame(&ctx, &mut chart, 0.1, vec![]); + let painted = shapes(&ctx, &mut chart, 0.2, vec![]); + let plot = chart.last_rendered_price_rect; + let labels: Vec<_> = painted + .iter() + .filter_map(|shape| match shape { + Shape::Text(text) if text.pos.x >= plot.right() => Some(text.galley.text()), + _ => None, + }) + .collect(); + for expected in expected { + assert!( + labels.contains(&expected), + "offset {offset}: missing {expected}: {labels:?}" + ); + } + } +} diff --git a/vendor/egui-charts/src/widget/frame/tests/crosshair.rs b/vendor/egui-charts/src/widget/frame/tests/crosshair.rs index 3387c99..d0c3a87 100644 --- a/vendor/egui-charts/src/widget/frame/tests/crosshair.rs +++ b/vendor/egui-charts/src/widget/frame/tests/crosshair.rs @@ -877,49 +877,39 @@ fn crosshair_marker_styles_follow_each_series_and_scale() { use egui::{Color32, Stroke}; let ring = crate::tokens::DESIGN_TOKENS.stroke.thick; - // Each row: main and added styles, then the expected main, added and separate-pane - // circles. Hidden markers are `None`; default rings match the plot or pane fill. - let rows: [(MarkerStyle, MarkerStyle, _, _, _); 5] = [ + // Each row: main and added styles, then the expected main and added circles, the added + // one the same in the price pane and in a pane of its own. Hidden markers are `None`; + // default rings match the chart background, which covers every pane. + let rows: [(MarkerStyle, MarkerStyle, _, _); 5] = [ ( (5.0, None, None, ring), (7.0, None, None, ring), Some((Color32::BLUE, Stroke::new(ring, Color32::LIGHT_GRAY))), Some((Color32::GREEN, Stroke::new(ring, Color32::LIGHT_GRAY))), - Some(( - Color32::GREEN, - Stroke::new(ring, crate::theme::Theme::default().chart.bg), - )), ), ( (5.0, Some(Color32::GOLD), Some(Color32::MAGENTA), 3.0), (7.0, None, Some(Color32::CYAN), 0.0), Some((Color32::GOLD, Stroke::new(3.0, Color32::MAGENTA))), Some((Color32::GREEN, Stroke::NONE)), - Some((Color32::GREEN, Stroke::NONE)), ), ( (5.0, Some(Color32::TRANSPARENT), Some(Color32::RED), 1.0), (7.0, Some(Color32::YELLOW), None, 4.0), Some((Color32::TRANSPARENT, Stroke::new(1.0, Color32::RED))), Some((Color32::YELLOW, Stroke::new(4.0, Color32::LIGHT_GRAY))), - Some(( - Color32::YELLOW, - Stroke::new(4.0, crate::theme::Theme::default().chart.bg), - )), ), ( (5.0, None, None, -1.0), (7.0, None, None, f32::NAN), Some((Color32::BLUE, Stroke::NONE)), Some((Color32::GREEN, Stroke::NONE)), - Some((Color32::GREEN, Stroke::NONE)), ), ( (0.0, None, None, ring), (f32::NAN, None, None, ring), None, None, - None, ), ]; for kind in [ @@ -930,17 +920,12 @@ fn crosshair_marker_styles_follow_each_series_and_scale() { ChartType::Baseline, ] { for pane in [false, true] { - for (main, added, expect_main, expect_added, expect_pane) in rows { + for (main, added, expect_main, expect_added) in rows { let (circles, x, main_rect, added_rect) = hover_markers(kind, pane, (main, added), |_, _| {}); for (radius, rect, fraction, expected) in [ (5.0, main_rect, 0.25, expect_main), - ( - 7.0, - added_rect, - 0.75, - if pane { expect_pane } else { expect_added }, - ), + (7.0, added_rect, 0.75, expect_added), ] { let found = circles.iter().find(|circle| circle.radius == radius); let case = format!("{kind:?}, pane {pane}, {main:?} {added:?}"); @@ -2001,7 +1986,6 @@ fn default_marker_ring_matches_the_background_behind_it() { left_color, right_color, } => left_color.lerp_to_gamma(right_color, (circle.center.x - 8.0) / 784.0), - BackgroundStyle::Solid if circle.radius == 7.0 => theme.chart.bg, BackgroundStyle::Solid => Color32::LIGHT_GRAY, }; assert_eq!( @@ -2156,8 +2140,9 @@ fn touch_hold_released_before_the_click_limit_is_not_a_click() { #[test] fn moving_a_touch_readout_keeps_live_edge_following() { + use crate::config::TrackingModeExitMode::{OnNextTap, OnTouchEnd}; use egui::TouchPhase::{End, Move, Start}; - for pane in [false, true] { + for (pane, exit_mode) in [(false, OnNextTap), (true, OnNextTap), (false, OnTouchEnd)] { for move_time in [0.1, 0.7, 1.0] .into_iter() .filter(|time| !pane || *time > 0.5) @@ -2166,6 +2151,7 @@ fn moving_a_touch_readout_keeps_live_edge_following() { let mut chart = chart(&[100.0], &[110.0, 120.0]); chart.config.show_volume = false; chart.chart_options.tooltip.on_long_press = true; + chart.chart_options.tracking_mode.exit_mode = exit_mode; if pane { let id = chart.add_series(Default::default()); chart.set_data(id, chart.bars(crate::widget::SeriesId::MAIN).to_vec()); @@ -2191,10 +2177,14 @@ fn moving_a_touch_readout_keeps_live_edge_following() { assert_eq!( chart.is_tracking_mode_active(), move_time > 0.5, - "pane={pane}, move={move_time}" + "pane={pane}, {exit_mode:?}, move={move_time}" ); frame(&ctx, &mut chart, 3.2, touch_events(End, end)); - assert_eq!(chart.is_tracking_mode_active(), move_time > 0.5); + assert_eq!( + chart.is_tracking_mode_active(), + move_time > 0.5, + "pane={pane}, {exit_mode:?}, move={move_time}: after the release" + ); } } } diff --git a/vendor/egui-charts/src/widget/history.rs b/vendor/egui-charts/src/widget/history.rs index 18e6c1b..ab2fe21 100644 --- a/vendor/egui-charts/src/widget/history.rs +++ b/vendor/egui-charts/src/widget/history.rs @@ -38,6 +38,8 @@ struct Pending { study_order: Vec, /// Added series removed during the action, with their bars, price formatters and bar limits. removed_series: Vec, + /// The palette the chart's unedited colours followed when the action began. + palette: ChartConfig, } #[derive(Default)] @@ -49,6 +51,8 @@ struct Action { symbol: Option, series: Option, config: Option, + /// The palette that the unedited colours of `config` and `chart_type` follow. + palette: Option, /// The main series of the other state, when the action removed it. main_series: Option, main_series_visible: Option, @@ -63,6 +67,7 @@ struct Action { panes: Option, chart_type: Option<(ChartType, ChartTypeParams)>, interval: Option>, + extended_hours: Option, studies: Vec, #[cfg(feature = "drawings")] drawings: HistoryService, @@ -73,6 +78,15 @@ struct Action { impl Action { fn is_empty(&self) -> bool { + self.view.is_none() && self.keeps_all_but_the_view() + } + + /// Whether the action is a navigation step: it only moved the view. + fn is_navigation(&self) -> bool { + self.view.is_some() && self.keeps_all_but_the_view() + } + + fn keeps_all_but_the_view(&self) -> bool { #[cfg(feature = "drawings")] let drawings_changed = self.drawings.can_undo() || self.unshown.is_some(); #[cfg(not(feature = "drawings"))] @@ -82,7 +96,6 @@ impl Action { && self.layout_edit.is_none() && self.symbol.is_none() && self.series.is_none() - && self.view.is_none() && self.config.is_none() && self.main_series.is_none() && self.main_series_visible.is_none() @@ -95,6 +108,7 @@ impl Action { && self.panes.is_none() && self.chart_type.is_none() && self.interval.is_none() + && self.extended_hours.is_none() && self.studies.is_empty() && !drawings_changed } @@ -145,7 +159,8 @@ struct SeriesSet { other: Vec, main_scale: SeriesScale, main_alerts: SeriesAlerts, - main_price_line: Option, + /// The colour of the main series' price line and the bar it follows. + main_price_line: (Option, crate::model::PriceLineSource), held: Vec, } @@ -160,7 +175,10 @@ impl SeriesSet { other: Vec::new(), main_scale: chart.main_series_scale, main_alerts: chart.main_series_style.alerts, - main_price_line: chart.main_series_style.price_line_color, + main_price_line: ( + chart.main_series_style.price_line_color, + chart.main_series_style.price_line_source, + ), held: Vec::new(), } } @@ -212,7 +230,7 @@ struct Study { } impl ChartHistory { - pub(super) fn blocked(&self) -> bool { + fn blocked(&self) -> bool { self.pending.is_some() || self.resizing.strong_count() > 0 } @@ -307,7 +325,14 @@ impl ChartHistory { if action.drawings.can_undo() { self.drawing_edits += 1; } - self.redo.clear(); + // Moving the view costs the user neither the edits they could undo nor those they could + // redo: a navigation step keeps redo, and the one under it already restores the view + // from before both. + if !action.is_navigation() { + self.redo.clear(); + } else if self.undo.last().is_some_and(Action::is_navigation) { + return; + } if self.undo.len() == 100 { self.undo.remove(0); } @@ -396,6 +421,11 @@ impl Chart { /// Apply one user action from a host toolbar, menu, dialog or intent as one undo step. /// Nested actions belong to the outer action. Unchanged chart/study settings add no history. /// + /// An action that only moves the view, such as an arrow-key pan or a navigation button, is a + /// navigation step. Consecutive navigation steps are one undo step, which restores the view + /// from before the first of them, and a navigation step leaves redo available. Any other + /// action is a step of its own and clears redo. + /// /// Chart-owned drawing interactions and shortcuts record themselves. Ordinary host calls /// (including data/feed updates, setters and `drawings_mut`) do not enter chart history; /// wrap only edits originating from a user action in this method. Drawing commands and @@ -444,12 +474,14 @@ impl Chart { panes: Some(self.pane_layout.clone()), chart_type: Some((self.chart_type, self.chart_type_params.clone())), interval: Some(self.timeframe), + extended_hours: Some(self.extended_hours), ..Action::default() }, #[cfg(feature = "drawings")] standalone_drawings, study_order: self.study_ids.clone(), removed_series: Vec::new(), + palette: self.followed_palette(), }); } @@ -499,6 +531,18 @@ impl Chart { if action.symbol.is_none() && action.view == Some(self.get_time_scale_state()) { action.view = None; } + // A theme change during the action is not an edit: the colours recorded before it + // follow it, as the chart's did. + let palette = self.followed_palette(); + if pending.palette != palette { + let old = std::slice::from_ref(&pending.palette); + if let Some(config) = &mut action.config { + super::palette::follow_palette(config, old, &palette); + } + if let Some((_, params)) = &mut action.chart_type { + super::palette::follow_candle_colors(&mut params.styles, old, &palette); + } + } if action.config.as_ref() == Some(&self.config) { action.config = None; } @@ -523,6 +567,12 @@ impl Chart { if action.interval == Some(self.timeframe) { action.interval = None; } + if action.extended_hours == Some(self.extended_hours) { + action.extended_hours = None; + } + if action.config.is_some() || action.chart_type.is_some() { + action.palette = Some(palette); + } if let Some(scale) = &action.scale && same_scale(scale, self.state.price_scale()) { @@ -801,7 +851,10 @@ impl Chart { } self.main_series_scale = set.main_scale; self.main_series_style.alerts = set.main_alerts; - self.main_series_style.price_line_color = set.main_price_line; + ( + self.main_series_style.price_line_color, + self.main_series_style.price_line_source, + ) = set.main_price_line; // `now.props` lists the series shown before the exchange, in draw order. for (id, ..) in &now.props { if self.price_series.iter().all(|item| item.id != *id) { @@ -839,19 +892,22 @@ impl Chart { } /// Undo the most recent chart user action, across drawings, studies and settings. - /// Returns false while a user action is in progress; finish that action first. + /// Returns false while a user action, a drawing drag or a divider drag is in progress; + /// finish it first. pub fn undo(&mut self) -> bool { self.step_chart_history(false) } /// Redo the most recently undone chart user action. - /// Returns false while a user action is in progress; finish that action first. + /// Returns false while a user action, a drawing drag or a divider drag is in progress; + /// finish it first. pub fn redo(&mut self) -> bool { self.step_chart_history(true) } /// Drain a notification that undo/redo changed chart state. Hosts that own the data must - /// reload it if [`Self::timeframe`] or [`Self::bar_clock`] changed, and synchronize their UI. + /// reload it if [`Self::timeframe`], [`Self::bar_clock`] or [`Self::extended_hours`] changed, + /// and synchronize their UI. /// Added series that the step removed or brought back are reported by /// [`drain_events`](Self::drain_events) as [`ChartEvent::SeriesRemoved`] and /// [`ChartEvent::SeriesAdded`]. @@ -887,8 +943,19 @@ impl Chart { } } + /// Whether undo and redo wait for a user action, a divider drag or a drawing drag to end. The + /// end of a drawing drag records the drawing as the drag found it, which a step taken + /// meanwhile would no longer lead back to. + pub(super) fn history_blocked(&self) -> bool { + #[cfg(feature = "drawings")] + if self.drawings.drag_in_progress() { + return true; + } + self.history.blocked() + } + fn step_chart_history(&mut self, redo: bool) -> bool { - if self.history.blocked() { + if self.history_blocked() { return false; } let stack = if redo { @@ -979,9 +1046,20 @@ impl Chart { } *interval = current; } + if let Some(extended_hours) = &mut action.extended_hours { + let current = self.extended_hours; + // The setter reloads the history and the subscription of the restored session. + self.set_extended_hours(*extended_hours); + *extended_hours = current; + } if let Some(config) = &mut action.config { std::mem::swap(&mut self.config, config); } + // The theme is not part of an action: the colours brought back follow the chart's. + if let Some(palette) = &mut action.palette { + let recorded = std::mem::replace(palette, self.followed_palette()); + self.follow_recorded_palette(recorded); + } if let Some(visible) = &mut action.price_targets_visible { std::mem::swap(&mut self.show_price_targets, visible); } @@ -1569,6 +1647,50 @@ mod tests { assert_eq!(chart.get_time_scale_state(), (15.0, -11.0)); } + /// Undo and redo restore what the user edited and leave the colours that follow the theme on + /// the active one: the grid hidden under the dark theme comes back under the light theme on + /// its white background with its light lines, and axis text set to blue before the switch + /// comes back blue. + #[test] + fn undo_after_a_theme_change_keeps_the_active_theme_colours() { + use crate::theme::{Theme, apply_to_egui}; + use crate::widget::test_frames::frame; + const LIGHT_GRID: Color32 = Color32::from_rgb(229, 229, 229); + for edited in [false, true] { + let ctx = egui::Context::default(); + apply_to_egui(&ctx, &Theme::dark()); + let mut chart = chart(&[10.0], &[20.0]); + frame(&ctx, &mut chart, 0.0, vec![]); + assert_eq!(chart.config().background_color, Color32::BLACK); + if edited { + chart.user_action(|chart| chart.config_mut().text_color = Color32::BLUE); + } + chart.user_action(|chart| chart.config_mut().show_grid = false); + apply_to_egui(&ctx, &Theme::light()); + frame(&ctx, &mut chart, 1.0, vec![]); + let text = if edited { + Color32::BLUE + } else { + Color32::BLACK + }; + for (redo, grid) in [(false, true), (true, false)] { + assert!(if redo { chart.redo() } else { chart.undo() }); + let config = chart.config(); + assert_eq!(config.show_grid, grid, "edited {edited}, redo {redo}"); + assert_eq!(config.background_color, Color32::WHITE); + assert_eq!(config.grid_color, LIGHT_GRID); + assert_eq!(config.text_color, text); + } + if edited { + // The colour edit is undone to the colour the text has under the active theme. + assert!(chart.undo()); + assert!(chart.undo()); + assert_eq!(chart.config().text_color, Color32::BLACK); + assert_eq!(chart.config().background_color, Color32::WHITE); + } + } + } + #[test] #[cfg(feature = "drawings")] fn host_updates_and_unchanged_actions_do_not_enter_or_clear_history() { @@ -1745,6 +1867,75 @@ mod tests { } } + /// Undo waits for a drawing drag to end, and the release records the drag as one step: a + /// line added at 15.0 and dragged 20 px down with Ctrl+Z pressed before the release goes + /// back to 15.0 on the first undo and leaves the chart on the second. + #[test] + #[cfg(feature = "drawings")] + fn undo_waits_for_a_drawing_drag_to_end() { + use crate::widget::test_frames::frame; + let ctx = Context::default(); + let mut chart = chart(&[10.0], &[20.0]); + frame(&ctx, &mut chart, 0.0, vec![]); + chart.user_action(|chart| { + let mut line = host_line(); + line.chart_points = vec![ChartPoint::new(30.0, 15.0), ChartPoint::new(60.0, 15.0)]; + chart.drawings_mut().add_synced_drawing(line).unwrap(); + }); + frame(&ctx, &mut chart, 0.1, vec![]); + let prices = |chart: &Chart| -> Vec { + let drawings = &chart.drawings().drawings; + drawings + .iter() + .flat_map(|drawing| &drawing.chart_points) + .map(|point| point.price) + .collect() + }; + let start = egui::pos2( + chart.get_chart_mapping().idx_to_x(45), + chart.last_price_map.price_to_y(15.0), + ); + let end = start + egui::vec2(0.0, 20.0); + let button = |pos, pressed| Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }; + let command = Modifiers::COMMAND | Modifiers::CTRL; + for (step, events) in [ + vec![Event::PointerMoved(start), button(start, true)], + vec![Event::PointerMoved(end)], + vec![Event::Key { + key: Key::Z, + physical_key: None, + pressed: true, + repeat: false, + modifiers: command, + }], + ] + .into_iter() + .enumerate() + { + frame(&ctx, &mut chart, 0.2 + step as f64 * 0.1, events); + } + assert!(!chart.undo(), "a toolbar button follows the same rule"); + frame(&ctx, &mut chart, 0.5, vec![button(end, false)]); + let moved = prices(&chart); + assert_eq!(moved.len(), 2, "the line is still on the chart"); + assert!(moved.iter().all(|price| *price < 15.0), "{moved:?}"); + assert!(chart.undo()); + assert_eq!(prices(&chart), [15.0, 15.0]); + assert!(chart.undo()); + assert!(prices(&chart).is_empty()); + assert!(!chart.can_undo()); + assert!(chart.redo()); + assert_eq!(prices(&chart), [15.0, 15.0]); + assert!(chart.redo()); + assert_eq!(prices(&chart), moved); + assert!(!chart.can_redo()); + } + #[test] fn symbol_navigation_restores_the_view_after_later_feed_updates() { let mut chart = chart(&[10.0, 11.0], &[20.0, 21.0]); diff --git a/vendor/egui-charts/src/widget/interaction.rs b/vendor/egui-charts/src/widget/interaction.rs index 92a35fb..8f4268b 100644 --- a/vendor/egui-charts/src/widget/interaction.rs +++ b/vendor/egui-charts/src/widget/interaction.rs @@ -226,18 +226,14 @@ impl Chart { self.tracking_mode_active = false; } } - TrackingModeExitMode::OnNextTap => { - // Exit on any click + // A click or tap is both the next tap and a touch that ended. A press that + // moved has ended tracking as a drag, below, and a contact that a touch + // readout owns is not the chart's to end on. + TrackingModeExitMode::OnNextTap | TrackingModeExitMode::OnTouchEnd => { if response.clicked() { self.tracking_mode_active = false; } } - TrackingModeExitMode::OnTouchEnd => { - // Exit when drag/touch ends - if !response.dragged() && self.scroll_start_pos.is_some() { - self.tracking_mode_active = false; - } - } } // Exit tracking mode on any manual interaction (scroll, zoom, drag) @@ -306,8 +302,70 @@ impl Chart { #[cfg(test)] mod tests { - use crate::widget::test_frames::chart; - use egui::{Context, Event, Key, Modifiers, RawInput, Rect, Vec2}; + use crate::widget::test_frames::{chart, frame}; + use egui::{Context, Event, Key, Modifiers, PointerButton, RawInput, Rect, Vec2}; + + /// Live-edge following ends on the gesture its exit mode names, and on a drag or the wheel + /// under every mode; a press that is still held ends it under none. + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] + #[cfg_attr(not(target_arch = "wasm32"), test)] + fn tracking_exit_modes_follow_their_documented_gesture() { + use crate::config::TrackingModeExitMode::{OnMouseLeave, OnNextTap, OnTouchEnd}; + // Whether following survives a press, a click, a drag, the pointer leaving and the wheel. + for (mode, survives) in [ + (OnTouchEnd, [true, false, false, true, false]), + (OnMouseLeave, [true, true, false, false, false]), + (OnNextTap, [true, false, false, true, false]), + ] { + for (gesture, survives) in ["press", "click", "drag", "leave", "wheel"] + .into_iter() + .zip(survives) + { + let ctx = Context::default(); + let mut chart = chart(&[100.0], &[101.0]); + chart.chart_options.tracking_mode.exit_mode = mode; + frame(&ctx, &mut chart, 0.0, vec![]); + let pos = chart.last_rendered_price_rect.center(); + let end = pos + egui::vec2(40.0, 0.0); + frame(&ctx, &mut chart, 0.02, vec![Event::PointerMoved(pos)]); + chart.enable_tracking_mode(); + let button = |pos, pressed| Event::PointerButton { + pos, + button: PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }; + let steps = match gesture { + "press" => vec![button(pos, true)], + "click" => vec![button(pos, true), button(pos, false)], + "drag" => vec![ + button(pos, true), + Event::PointerMoved(end), + button(end, false), + ], + "leave" => vec![Event::PointerGone], + _ => vec![Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -240.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: Modifiers::NONE, + }], + }; + let settled = 0.04 + steps.len() as f64 * 0.02; + for (step, event) in steps.into_iter().enumerate() { + frame(&ctx, &mut chart, 0.04 + step as f64 * 0.02, vec![event]); + } + // A pointer that has gone stops hovering the chart in the following frame. + frame(&ctx, &mut chart, settled, vec![]); + assert_eq!( + chart.is_tracking_mode_active(), + survives, + "{mode:?}, {gesture}" + ); + } + } + } #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[cfg_attr(not(target_arch = "wasm32"), test)] @@ -409,9 +467,9 @@ mod tests { let expected = if !enabled { 0.0 } else if key == Some(Key::ArrowLeft) { - -chart.chart_options.keyboard.pan_amount - } else { chart.chart_options.keyboard.pan_amount + } else { + -chart.chart_options.keyboard.pan_amount }; assert_eq!( chart.state.time_scale().right_offset(), diff --git a/vendor/egui-charts/src/widget/keyboard.rs b/vendor/egui-charts/src/widget/keyboard.rs index b64e5b2..05e976e 100644 --- a/vendor/egui-charts/src/widget/keyboard.rs +++ b/vendor/egui-charts/src/widget/keyboard.rs @@ -7,6 +7,9 @@ use egui::{Context, Event, KeyboardShortcut}; /// /// Remove a binding to disable it, or replace its key or action to rebind it. /// The first binding wins if several actions use the same key combination. +/// A binding on a punctuation key also runs when the press differs from it only by Shift and +/// types that key's character, as some layouts need, unless another binding names that exact +/// combination. #[derive(Clone, Debug)] pub struct ShortcutMap { /// Key combinations and their actions, in precedence order. @@ -47,7 +50,36 @@ impl ShortcutMap { }) } - /// Consume the first bound key press, leaving other input for its owner. + /// The binding a key press that typed `typed` runs. Layouts differ in which punctuation + /// needs Shift, so a key named by a punctuation character matches with Shift ignored when no + /// binding names the exact modifiers and the press typed that character or nothing. + fn binding( + &self, + key: egui::Key, + modifiers: egui::Modifiers, + typed: Option<&str>, + ) -> Option<(KeyboardShortcut, KeyboardAction)> { + let find = |ignore_shift: bool| { + let held = |modifiers: egui::Modifiers| egui::Modifiers { + shift: modifiers.shift && !ignore_shift, + ..modifiers + }; + self.bindings.iter().copied().find(|(shortcut, _)| { + key == shortcut.logical_key + && held(modifiers).matches_exact(held(shortcut.modifiers)) + }) + }; + find(false).or_else(|| { + typed_char(key) + .filter(|c| !c.is_alphanumeric()) + // Shift+Period typing `>` on a US layout is not the period. + .filter(|_| typed.is_none_or(|text| egui::Key::from_name(text) == Some(key))) + .and_then(|_| find(true)) + }) + } + + /// Consume the first bound key press with the text it typed, leaving other input for its + /// owner. pub(crate) fn consume( &self, ctx: &Context, @@ -55,45 +87,51 @@ impl ShortcutMap { accepts: impl Fn(KeyboardAction, KeyboardShortcut) -> bool, ) -> Option<(KeyboardAction, Event)> { ctx.input_mut(|input| { + let pairs = typed_pairs(&input.events); + let bound = |index: usize| { + let (key, modifiers) = match &input.events[index] { + Event::Key { + key, + pressed: true, + modifiers, + .. + } => (*key, *modifiers), + Event::Copy => (egui::Key::C, egui::Modifiers::COMMAND), + Event::Paste(_) => (egui::Key::V, egui::Modifiers::COMMAND), + _ => return None, + }; + let typed = pairs[index].and_then(|text| match &input.events[text] { + Event::Text(text) => Some(text.as_str()), + _ => None, + }); + let (shortcut, action) = self.binding(key, modifiers, typed)?; + accepts(action, shortcut).then_some(action) + }; let (index, action) = input .events .iter() .enumerate() - .take_while(|(_, event)| { - !stop_at_text || !matches!(event, Event::Text(text) if starts_entry(text)) + .take_while(|(index, event)| { + // Typed text ends the search, unless the bound key that typed it follows. + !stop_at_text + || !matches!(event, Event::Text(text) if starts_entry(text)) + || (pairs[*index] == Some(index + 1) && bound(index + 1).is_some()) }) - .find_map(|(index, event)| { - let (key, modifiers) = match event { - Event::Key { - key, - pressed: true, - modifiers, - .. - } => (*key, *modifiers), - Event::Copy => (egui::Key::C, egui::Modifiers::COMMAND), - Event::Paste(_) => (egui::Key::V, egui::Modifiers::COMMAND), - _ => return None, - }; - let (shortcut, action) = self.bindings.iter().find(|(shortcut, _)| { - let matches = modifiers.matches_exact(shortcut.modifiers) - || (matches!(key, egui::Key::Plus | egui::Key::Questionmark) - && modifiers.matches_logically(shortcut.modifiers) - && modifiers.alt == shortcut.modifiers.alt); - key == shortcut.logical_key && matches - })?; - accepts(*action, *shortcut).then_some((index, *action)) - })?; - let event = input.events.remove(index); - if let Event::Key { key, .. } = &event { - let symbol = key.symbol_or_name(); - if symbol.len() == 1 - && input - .events - .get(index) - .is_some_and(|next| matches!(next, Event::Text(text) if text.eq_ignore_ascii_case(symbol))) - { - input.events.remove(index); - } + .find_map(|(index, _)| Some((index, bound(index)?)))?; + let mut event = input.events.remove(index); + // The press ran a binding, so its text is dropped whatever character it carries. + if let Some(text) = pairs[index] { + input.events.remove(text.min(index)); + } + // A browser reports the paste key and then the clipboard text: one paste, with it. + if action == KeyboardAction::PasteDrawing + && matches!(event, Event::Key { .. }) + && let Some(paste) = input + .events + .iter() + .position(|event| matches!(event, Event::Paste(_))) + { + event = input.events.remove(paste); } Some((action, event)) }) @@ -130,6 +168,42 @@ fn starts_entry(text: &str) -> bool { .is_some_and(|c| !c.is_control() && !c.is_whitespace()) } +/// The character naming a letter, digit or punctuation key, the keys whose press types text. +fn typed_char(key: egui::Key) -> Option { + let mut symbol = key.symbol_or_name().chars(); + let c = symbol.next()?; + // The arrows are named by a glyph and type nothing; the minus key by the minus sign. + (symbol.next().is_none() && (c.is_ascii() || key == egui::Key::Minus)).then_some(c) +} + +/// For each event, the index of the other half of its key press: the text a key typed, or the +/// key that typed a text. +/// +/// The two are adjacent, the key first on the desktop and the text first in a browser. A +/// press types at most one text and none with Ctrl or Command held, so a text belongs to the +/// press before it unless that press already has its text, and otherwise to the press after. +fn typed_pairs(events: &[Event]) -> Vec> { + let types = |event: &Event| { + matches!(event, Event::Key { key, pressed: true, modifiers, .. } + if typed_char(*key).is_some() && !modifiers.ctrl && !modifiers.command) + }; + let mut pairs = vec![None; events.len()]; + for (text, event) in events.iter().enumerate() { + if !matches!(event, Event::Text(_)) { + continue; + } + let key = [text.checked_sub(1), Some(text + 1)] + .into_iter() + .flatten() + .find(|&key| pairs.get(key) == Some(&None) && types(&events[key])); + if let Some(key) = key { + pairs[text] = Some(key); + pairs[key] = Some(text); + } + } + pairs +} + /// A shortcut that needs the host's dialogs, layout or clipboard. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -382,10 +456,7 @@ impl super::Chart { input.events.remove(index); return Some(key); } - if self.keyboard.map.bindings.iter().any(|(shortcut, _)| { - shortcut.logical_key == *key - && modifiers.matches_exact(shortcut.modifiers) - }) { + if self.keyboard.map.binding(*key, *modifiers, None).is_some() { return None; } } @@ -468,6 +539,7 @@ impl super::Chart { A::PanLeft | A::PanRight | A::PanLeftFast | A::PanRightFast => { self.pending_scroll_time = None; self.tracking_mode_active = false; + self.kinetic_scroll.is_active = false; let amount = if matches!(action, A::PanLeftFast | A::PanRightFast) { self.state .time_scale() @@ -477,17 +549,19 @@ impl super::Chart { } else { self.chart_options.keyboard.pan_amount }; + // Left shows earlier bars, as the Scroll left button does. self.state.time_scale_mut().scroll_bars( if matches!(action, A::PanLeft | A::PanLeftFast) { - -amount - } else { amount + } else { + -amount }, ); } A::ZoomIn | A::ZoomOut | A::PageUp | A::PageDown => { self.pending_scroll_time = None; self.tracking_mode_active = false; + self.kinetic_scroll.is_active = false; let step = self.chart_options.keyboard.zoom_step; let delta = match action { A::ZoomIn => step, @@ -740,6 +814,89 @@ mod tests { } } + #[cfg(feature = "drawings")] + fn press(key: Key, modifiers: Modifiers) -> Event { + Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers, + } + } + + /// Ctrl+Alt+H hides every drawing unless all are hidden, and then shows them all. + #[cfg(feature = "drawings")] + #[test] + fn hide_drawings_key_hides_all_unless_all_are_hidden() { + use crate::drawings::{ChartPoint, Drawing, DrawingToolType}; + use crate::widget::test_frames::frame; + for (hidden, shown) in [ + ([false, false, false], false), + ([false, true, false], false), + ([true, true, true], true), + ] { + let ctx = Context::default(); + let mut chart = chart(&[10.0], &[20.0]); + for (id, hidden) in hidden.into_iter().enumerate() { + let mut drawing = Drawing::new(id, DrawingToolType::HorizontalLine); + drawing.chart_points = vec![ChartPoint::new(30.0, 14.0 + id as f64)]; + drawing.completed = true; + drawing.visible = !hidden; + chart.drawings_mut().drawings.push(drawing); + } + frame(&ctx, &mut chart, 0.0, vec![]); + let hide = press(Key::H, Modifiers::COMMAND.plus(Modifiers::ALT)); + frame(&ctx, &mut chart, 1.0, vec![hide]); + let visible: Vec<_> = chart + .drawings() + .drawings + .iter() + .map(|d| d.visible) + .collect(); + assert_eq!(visible, [shown; 3], "{hidden:?}"); + } + } + + /// Drawings hidden by Ctrl+Alt+H or by undoing a show are deselected, so Delete and the + /// arrows leave them alone. + #[cfg(feature = "drawings")] + #[test] + fn hidden_drawings_ignore_delete_and_arrow_keys() { + use crate::drawings::{ChartPoint, Drawing, DrawingToolType}; + use crate::widget::test_frames::frame; + let ctx = Context::default(); + let mut chart = chart(&[10.0], &[20.0]); + let mut drawing = Drawing::new(7, DrawingToolType::TrendLine); + drawing.chart_points = vec![ChartPoint::new(30.0, 14.0), ChartPoint::new(70.0, 17.0)]; + drawing.completed = true; + chart.drawings_mut().drawings.push(drawing.clone()); + chart.drawings_mut().select(7); + frame(&ctx, &mut chart, 0.0, vec![]); + let hide = press(Key::H, Modifiers::COMMAND.plus(Modifiers::ALT)); + for (i, event) in [ + hide.clone(), + press(Key::Delete, Modifiers::NONE), + press(Key::ArrowRight, Modifiers::NONE), + hide, + ] + .into_iter() + .enumerate() + { + frame(&ctx, &mut chart, 1.0 + i as f64, vec![event]); + } + let drawings = &chart.drawings().drawings; + assert_eq!(drawings.len(), 1); + assert!(drawings[0].visible); + assert_eq!(drawings[0].chart_points, drawing.chart_points); + // Undoing the show hides the drawing again and deselects it too. + chart.drawings_mut().select(7); + assert!(chart.undo()); + let delete = press(Key::Delete, Modifiers::NONE); + frame(&ctx, &mut chart, 5.0, vec![delete]); + assert_eq!(chart.drawings().drawings.len(), 1); + } + #[test] fn reset_chart_restores_time_and_every_price_scale() { use crate::model::SeriesScale; @@ -820,18 +977,52 @@ mod tests { fn navigation_and_panel_keys_follow_the_shared_action_map() { use KeyboardAction as A; let alt_shift = Modifiers::ALT.plus(Modifiers::SHIFT); - for (key, modifiers, expected) in [ - (Key::ArrowLeft, Modifiers::NONE, Some(A::PanLeft)), - (Key::ArrowLeft, Modifiers::ALT, None), - (Key::ArrowRight, Modifiers::COMMAND, Some(A::PanRightFast)), - (Key::ArrowUp, Modifiers::COMMAND, Some(A::ZoomIn)), - (Key::ArrowLeft, alt_shift, Some(A::ScrollToFirstBar)), - (Key::Home, Modifiers::NONE, Some(A::ScrollToFirstBar)), - (Key::ArrowRight, alt_shift, Some(A::ScrollToRealTime)), - (Key::End, Modifiers::NONE, Some(A::ScrollToRealTime)), - (Key::Period, Modifiers::NONE, Some(A::OpenLayout)), - (Key::D, Modifiers::ALT, Some(A::OpenDataWindow)), - (Key::E, alt_shift, Some(A::ToggleSession)), + // The third field is the text the press types and whether it arrives before the key, + // as a browser reports it, or after it, as the desktop does. + for (key, modifiers, typed, expected) in [ + (Key::ArrowLeft, Modifiers::NONE, None, Some(A::PanLeft)), + (Key::ArrowRight, Modifiers::NONE, None, Some(A::PanRight)), + (Key::ArrowLeft, Modifiers::ALT, None, None), + ( + Key::ArrowLeft, + Modifiers::COMMAND, + None, + Some(A::PanLeftFast), + ), + ( + Key::ArrowRight, + Modifiers::COMMAND, + None, + Some(A::PanRightFast), + ), + (Key::ArrowUp, Modifiers::COMMAND, None, Some(A::ZoomIn)), + (Key::ArrowLeft, alt_shift, None, Some(A::ScrollToFirstBar)), + (Key::Home, Modifiers::NONE, None, Some(A::ScrollToFirstBar)), + (Key::ArrowRight, alt_shift, None, Some(A::ScrollToRealTime)), + (Key::End, Modifiers::NONE, None, Some(A::ScrollToRealTime)), + (Key::Period, Modifiers::NONE, None, Some(A::OpenLayout)), + ( + Key::Period, + Modifiers::SHIFT, + Some((".", false)), + Some(A::OpenLayout), + ), + ( + Key::Slash, + Modifiers::SHIFT, + Some(("/", false)), + Some(A::OpenIndicatorSearch), + ), + // The key typed another character, so it is not the period. + (Key::Period, Modifiers::SHIFT, Some((">", false)), None), + (Key::D, Modifiers::ALT, None, Some(A::OpenDataWindow)), + ( + Key::D, + Modifiers::ALT, + Some(("d", true)), + Some(A::OpenDataWindow), + ), + (Key::E, alt_shift, None, Some(A::ToggleSession)), ] { let ctx = Context::default(); let mut chart = chart(&[10.0], &[20.0]); @@ -861,13 +1052,17 @@ mod tests { )), time: Some(time), events: if pass == 2 { - vec![Event::Key { + let mut events = vec![Event::Key { key, modifiers, physical_key: None, pressed: true, repeat: false, - }] + }]; + if let Some((text, first)) = typed { + events.insert(usize::from(!first), Event::Text(text.into())); + } + events } else { vec![] }, @@ -886,18 +1081,31 @@ mod tests { let offset = chart.state.time_scale().right_offset(); let spacing = chart.state.time_scale().bar_spacing(); match expected { - Some(A::PanLeft) => assert_eq!(offset, before_offset + 1.0), - Some(A::PanRightFast) => assert_eq!(offset, before_offset - page), + // Left lowers the index of the first visible bar and Right raises it. + Some(A::PanLeft) => assert_eq!(offset, before_offset - 1.0), + Some(A::PanRight) => assert_eq!(offset, before_offset + 1.0), + Some(A::PanLeftFast) => assert_eq!(offset, before_offset - page), + Some(A::PanRightFast) => assert_eq!(offset, before_offset + page), Some(A::ZoomIn) => assert!(spacing > before_spacing), Some(A::ScrollToFirstBar) => { let left = chart.visible_logical_range().unwrap().left; assert!(left.abs() < 1e-3, "{key:?}: left edge at bar {left}"); } Some(A::ScrollToRealTime) => assert_eq!(offset, latest, "{key:?}"), - Some(action) => { - assert_eq!(requests, vec![ShortcutRequest::Action(action)], "{key:?}") + Some(action) => assert_eq!( + requests, + vec![ShortcutRequest::Action(action)], + "{key:?} typing {typed:?}" + ), + None => { + assert_eq!(offset, before_offset); + assert!( + !requests + .iter() + .any(|request| matches!(request, ShortcutRequest::Action(_))), + "{key:?} typing {typed:?}: {requests:?}" + ); } - None => assert_eq!(offset, before_offset), } if expected != Some(A::ZoomIn) { assert_eq!(spacing, before_spacing, "{key:?} keeps the zoom"); @@ -970,29 +1178,83 @@ mod tests { KeyboardShortcut::new(Modifiers::NONE, Key::F), KeyboardAction::FitContent, )); - ctx.run_ui( - RawInput { - events: vec![ + // A press that ran a binding types nothing, whatever character its text carries. + for (key, modifiers, text) in [ + (Key::F, Modifiers::NONE, "f"), + (Key::L, Modifiers::ALT, "¬"), + (Key::Minus, Modifiers::NONE, "-"), + ] { + ctx.run_ui( + RawInput { + events: vec![ + Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers, + }, + Event::Text(text.into()), + ], + ..Default::default() + }, + |ui| { + chart.show(ui); + }, + ) + .drop_without_applying_deltas(); + assert!( + chart.take_shortcut_requests().is_empty(), + "{key:?} is bound and must not also open symbol search" + ); + assert!( + !ctx.input(|input| input.events.contains(&Event::Text(text.into()))), + "{key:?} leaves no text for a host dialog" + ); + } + assert_eq!( + chart.state.price_scale().options().mode, + PriceScaleMode::Normal, + "Alt+L switched the logarithmic scale back" + ); + } + + /// The desktop reports a paste as the paste event alone, a browser as the key press and + /// then the paste event: either way the host gets one request carrying the text. + #[test] + fn a_paste_reported_with_its_key_press_is_one_request_with_the_text() { + for with_key in [true, false] { + let ctx = Context::default(); + let mut chart = chart(&[10.0], &[20.0]); + let mut events = vec![Event::Paste("clip".into())]; + if with_key { + events.insert( + 0, Event::Key { - key: Key::F, + key: Key::V, physical_key: None, pressed: true, repeat: false, - modifiers: Modifiers::NONE, + modifiers: Modifiers::COMMAND, }, - Event::Text("f".into()), - ], - ..Default::default() - }, - |ui| { - chart.show(ui); - }, - ) - .drop_without_applying_deltas(); - assert!( - chart.take_shortcut_requests().is_empty(), - "a bound character must not also open symbol search" - ); + ); + } + ctx.run_ui( + RawInput { + events, + ..Default::default() + }, + |ui| { + chart.show(ui); + }, + ) + .drop_without_applying_deltas(); + assert_eq!( + chart.take_shortcut_requests(), + vec![ShortcutRequest::PasteDrawing("clip".into())], + "key press reported: {with_key}" + ); + } } #[test] diff --git a/vendor/egui-charts/src/widget/layout.rs b/vendor/egui-charts/src/widget/layout.rs index 7f78a71..588c249 100644 --- a/vendor/egui-charts/src/widget/layout.rs +++ b/vendor/egui-charts/src/widget/layout.rs @@ -25,6 +25,19 @@ const LINK_MARKERS: [(&str, egui::Color32); 5] = [ ("💩", egui::Color32::from_rgb(160, 105, 90)), ]; +/// Paints `chart`'s background over `rect`, the container a chart with `skip_background` set +/// leaves its background to. +fn slot_background(ui: &Ui, rect: Rect, chart: &Chart) { + let config = chart.config(); + super::frame::paint_background( + ui.painter(), + rect, + rect, + config.background_style, + config.background_color, + ); +} + // These markers must also work in hosts without emoji fonts. fn paint_link_marker(ui: &Ui, rect: Rect, marker: &str) { let Some(index) = LINK_MARKERS.iter().position(|(name, _)| *name == marker) else { @@ -109,6 +122,7 @@ pub use drawings::{SymbolDrawing, SymbolDrawings}; #[derive( Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize, )] +#[non_exhaustive] pub enum ChartLayoutMode { /// One chart. #[default] @@ -903,12 +917,16 @@ impl LayoutEditLink { /// Independent synchronization switches within each layout group. #[derive(Debug, Clone, PartialEq)] +#[non_exhaustive] pub struct ChartSyncOptions { /// Synchronize scrolling and zooming using UTC plot edges. pub sync_time_axis: bool, /// Synchronize the hovered timestamp. pub sync_crosshair: bool, /// Synchronize completed main-pane drawings between charts of the same symbol. + /// A chart that comes to a symbol receives the drawings mirrored there. Turning this on links + /// equal drawings of the charts of a symbol and mirrors the others both ways, without replaying + /// what was done while it was off. /// Study-owned drawings stay local because study ids and scales belong to each chart. /// Charts that keep their drawings in the same storage are left to it: they read each other's /// stored drawings whether this is on or off, so a drawing reaches them once a chart history @@ -993,6 +1011,18 @@ pub struct ChartLayout { edits: LayoutEdits, } +impl std::fmt::Debug for ChartLayout { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ChartLayout") + .field("mode", &self.mode) + .field("sync", &self.sync) + .field("text_sync_groups", &self.text_sync_groups) + .field("active", &self.active) + .field("maximized", &self.maximized) + .finish_non_exhaustive() + } +} + /// Identifies a chart's bars: it changes when they are replaced, not when they stream. type BarsKey = (u64, Option>); @@ -1181,7 +1211,7 @@ impl ChartLayout { .iter() .filter(|chart| chart.history.holds_layout_edit(*id)) { - if chart.history.blocked() { + if chart.history_blocked() { return false; } belongs = true; @@ -1543,8 +1573,16 @@ impl ChartLayout { self.active = index; } // A chart supplied or restored in a slot starts a new baseline: nothing changed in it. + #[cfg(feature = "drawings")] + let known = self.previous_charts; for (index, chart) in charts.iter().enumerate() { if self.previous_charts[index] != chart.layout_identity { + // A chart new to the layout brings drawings new to it, while one that + // `swap_slots` moved keeps its links. + #[cfg(feature = "drawings")] + if !known.contains(&chart.layout_identity) { + self.drawings.forget_slot(index); + } self.previous_charts[index] = chart.layout_identity; self.previous[index] = None; self.previous_ranges[index] = None; @@ -1688,6 +1726,7 @@ impl ChartLayout { .horizontal(|ui| self.link_controls(ui, index, false)) .inner; egui::CentralPanel::default().show(ui, |ui| { + slot_background(ui, ui.max_rect(), chart); let response = render(ui, index, chart); if focus { response.request_focus(); @@ -1719,8 +1758,7 @@ impl ChartLayout { continue; } let rect = rects[index]; - ui.painter() - .rect_filled(rect, 0.0, charts[index].config().background_color); + slot_background(ui, rect, charts[index]); ui.scope_builder( egui::UiBuilder::new() .max_rect(rect) @@ -1871,23 +1909,28 @@ impl ChartLayout { ui.ctx().request_repaint(); } #[cfg(feature = "drawings")] - if (self.sync.sync_drawings - || charts.iter().take(total).any(|chart| { - chart - .drawings() - .drawings - .iter() - .any(|d| d.folder_sync_mode().is_some()) - })) - && self.drawings.sync( + { + let tracking = self.sync.sync_drawings + || charts.iter().take(total).any(|chart| { + chart + .drawings() + .drawings + .iter() + .any(|d| d.folder_sync_mode().is_some()) + }); + if !tracking { + // Turning the switch on is the first time for the drawings it mirrors, while + // those that their folder mirrors stay linked on the charts away from them. + self.drawings.forget_switched(charts, total); + } else if self.drawings.sync( charts, total, &self.groups, pointer_down, self.sync.sync_drawings, - ) - { - ui.ctx().request_repaint(); + ) { + ui.ctx().request_repaint(); + } } #[cfg(feature = "drawings")] if Chart::share_stored_drawings(charts) { @@ -2235,6 +2278,55 @@ mod tests { chart } + /// A chart that leaves its background to the layout gets its gradient over its slot. + #[test] + fn layout_paints_a_gradient_background() { + use crate::config::BackgroundStyle; + use egui::Color32; + let (top, bottom) = (Color32::from_rgb(200, 0, 0), Color32::from_rgb(0, 0, 200)); + let mut chart = chart(60); + chart.config_mut().skip_background = true; + chart.config_mut().background_style = BackgroundStyle::VerticalGradient { + top_color: top, + bottom_color: bottom, + }; + let size = vec2(800.0, 600.0); + let output = egui::Context::default().run_ui( + RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size)), + ..Default::default() + }, + |ui| { + ChartLayout::default().show(ui, &mut [&mut chart]); + }, + ); + let slot = ChartLayout::default().rects(Rect::from_min_size(Pos2::ZERO, size), 1)[0]; + let meshes: Vec> = output + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Mesh(mesh) => Some( + mesh.vertices + .iter() + .map(|vertex| (vertex.pos, vertex.color)) + .collect(), + ), + _ => None, + }) + .collect(); + output.drop_without_applying_deltas(); + // The slot's fill is painted before the chart, so it is the first mesh. + assert_eq!( + meshes.first(), + Some(&vec![ + (slot.left_top(), top), + (slot.right_top(), top), + (slot.right_bottom(), bottom), + (slot.left_bottom(), bottom), + ]) + ); + } + /// Split size and link membership steps follow the layout value that shows their chart: a host /// that replaces its layout with a clone undoes and redoes them on the clone, including the /// changes still waiting for a show, and the replaced layout keeps its own. Steps undone or diff --git a/vendor/egui-charts/src/widget/layout/copy.rs b/vendor/egui-charts/src/widget/layout/copy.rs index 90aa45d..baae402 100644 --- a/vendor/egui-charts/src/widget/layout/copy.rs +++ b/vendor/egui-charts/src/widget/layout/copy.rs @@ -260,8 +260,9 @@ fn apply_to_other_chart( let mut own = chart.chart_type_params().clone(); own.styles = params.styles; own.footprint_colors = params.footprint_colors; + own.footprint_imbalance_colors = params.footprint_imbalance_colors; if &own != chart.chart_type_params() { - chart.set_chart_type_params(own); + chart.apply_chart_type_params(own); } } let own = ChartSettingsState::from_chart(chart).order_flow; diff --git a/vendor/egui-charts/src/widget/layout/drawings.rs b/vendor/egui-charts/src/widget/layout/drawings.rs index 4d1e9e4..101cbdd 100644 --- a/vendor/egui-charts/src/widget/layout/drawings.rs +++ b/vendor/egui-charts/src/widget/layout/drawings.rs @@ -20,6 +20,9 @@ struct Snapshot { notes: Option, symbol: String, sync: Option, + /// The [`DrawingLinks::frame`] in which the layout last saw the drawing change, or wrote the + /// change of another drawing to it. + seen: u64, } /// Whether a drawing with this folder synchronization is mirrored to the other charts. @@ -44,6 +47,13 @@ fn timed_points( .collect() } +/// What a drawing and its copies have in common: [`live_key`] and the notes. +fn content(chart: &Chart, drawing: &Drawing) -> String { + format!("{}{:?}", live_key(chart, drawing), drawing.notes) +} + +type Change = (Key, Option, Option); + #[derive(Clone, Default)] pub(super) struct DrawingLinks { previous: HashMap, @@ -52,6 +62,19 @@ pub(super) struct DrawingLinks { /// Stored drawings that a gesture in progress changed through a linked drawing on another /// chart, whose charts write them once it ends. unwritten: HashSet, + /// Drawings a chart put aside with a symbol, by slot, symbol and id, with their + /// [`Snapshot::seen`] and the keys of the drawings of that symbol they are linked to: the + /// chart takes them up again when it returns. + aside: HashMap<(usize, String, usize), (u64, Vec)>, + /// The symbol each chart showed at the last frame, to see a chart come to a symbol. + shown: Vec>, + /// Charts that came to a symbol and still wait for the mirrored drawings of it. + arriving: HashSet, + /// Whether the layout-wide switch was on at the last frame. + wide: bool, + /// The frames `sync` ran in, which order the changes it sees: edit times cannot, as an undo + /// puts back the time of the state it restores and a copy is stamped when it is written. + frame: u64, } impl DrawingLinks { @@ -72,6 +95,175 @@ impl DrawingLinks { .collect(); self.retry = self.retry.drain().map(moved).collect(); self.unwritten = self.unwritten.drain().map(moved).collect(); + self.aside = self + .aside + .drain() + .map(|((slot, symbol, id), (seen, partners))| { + let partners = partners.into_iter().map(moved).collect(); + ((moved((slot, id)).0, symbol, id), (seen, partners)) + }) + .collect(); + if a.max(b) < self.shown.len() { + self.shown.swap(a, b); + } + self.arriving = self + .arriving + .drain() + .map(|slot| moved((slot, 0)).0) + .collect(); + } + + /// Forgets the drawings that the layout-wide switch mirrors, as when it is first turned on. + /// Drawings whose folder mirrors them stay linked, on show or put aside. + pub(super) fn forget_switched(&mut self, charts: &[&mut Chart], count: usize) { + self.previous.retain(|_, old| old.sync.is_some()); + self.origins + .retain(|key, _| self.previous.contains_key(key)); + self.retry.retain(|key| self.previous.contains_key(key)); + self.unwritten.retain(|key| self.previous.contains_key(key)); + self.aside.retain(|(slot, symbol, id), _| { + *slot < count && { + let chart = &charts[*slot]; + let manager = if chart.symbol() == symbol { + Some(chart.drawings()) + } else { + chart + .symbol_drawings + .get(symbol) + .map(|(manager, _)| manager) + }; + manager.is_some_and(|manager| { + manager + .drawings + .iter() + .any(|d| d.id == *id && d.folder_sync_mode().is_some()) + }) + } + }); + } + + /// Forgets the drawings of the chart in `slot`, supplied or restored there anew: its ids may + /// name other drawings now. They are new to the layout, and the chart receives the mirrored + /// drawings of its symbol as a chart that comes to it does. + pub(super) fn forget_slot(&mut self, slot: usize) { + self.previous.retain(|key, _| key.0 != slot); + self.origins.retain(|key, _| key.0 != slot); + self.retry.retain(|key| key.0 != slot); + self.unwritten.retain(|key| key.0 != slot); + self.aside.retain(|entry, _| entry.0 != slot); + for (_, partners) in self.aside.values_mut() { + partners.retain(|key| key.0 != slot); + } + self.arriving.insert(slot); + self.rename_links(|origin, _| origin.0 == slot); + } + + /// Gives each link that `gone` picks by name and symbol the name of one of its drawings on + /// show: the drawing it is named after is gone, and a new drawing that takes its id starts a + /// link of its own. A link keeps the name of a drawing deleted on its chart, which an undo + /// there brings back. + fn rename_links(&mut self, gone: impl Fn(Key, &str) -> bool) { + // Links of different symbols may have one name. + let mut names: HashMap<(Key, &str), Key> = HashMap::new(); + for (&key, &origin) in &self.origins { + if let Some(old) = self.previous.get(&key) + && gone(origin, &old.symbol) + { + let name = names.entry((origin, &old.symbol)).or_insert(key); + *name = (*name).min(key); + } + } + for (key, origin) in &mut self.origins { + if let Some(&name) = self + .previous + .get(key) + .and_then(|old| names.get(&(*origin, old.symbol.as_str()))) + { + *origin = name; + } + } + } + + fn origin_of(&self, key: Key) -> Key { + self.origins.get(&key).copied().unwrap_or(key) + } + + /// The id of the drawing on show in `slot` that is linked under `origin`. + fn linked_on(&self, charts: &[&mut Chart], slot: usize, origin: Key) -> Option { + self.origins + .iter() + .find_map(|(&(target_slot, id), &value)| { + (target_slot == slot + && value == origin + && charts[slot].drawings().drawings.iter().any(|d| d.id == id)) + .then_some(id) + }) + } + + /// Links `key` to the first of `candidates`, linked ones first, on a chart with no drawing in + /// its link yet, and to the others that fit that link. Returns the keys it linked. + fn join(&mut self, charts: &[&mut Chart], key: Key, mut candidates: Vec) -> Vec { + // A drawing taken up again in the same frame then joins the link on show instead of + // starting another beside it. + candidates.sort_by_key(|candidate| !self.origins.contains_key(candidate)); + let mut origin = None; + let mut linked = Vec::new(); + for candidate in candidates { + let theirs = self.origin_of(candidate); + let fits = match origin { + None => self.linked_on(charts, key.0, theirs).is_none(), + Some(origin) => theirs == origin || !self.origins.contains_key(&candidate), + }; + if fits { + let origin = *origin.get_or_insert(theirs); + self.origins.entry(candidate).or_insert(origin); + linked.push(candidate); + } + } + if let Some(origin) = origin { + self.origins.insert(key, origin); + } + linked + } + + /// The drawings on other charts of the symbol and group of `key` that are not linked to a + /// drawing of its chart and equal `drawing` in content, one per chart: what a restored + /// original and its restored copy are. + fn equal_drawings( + &self, + charts: &[&mut Chart], + count: usize, + groups: &[Option; 16], + key: Key, + drawing: &Drawing, + layout_wide: bool, + ) -> Vec { + if drawing.pane.is_some() { + return Vec::new(); + } + let own = content(charts[key.0], drawing); + (0..count) + .filter(|&slot| { + slot != key.0 + && groups[slot] == groups[key.0] + && charts[slot].symbol() == charts[key.0].symbol() + // Charts on one storage read each other's drawings from it. + && !(drawing.saveable && charts[slot].shares_stored_drawings(charts[key.0])) + }) + .filter_map(|slot| { + let other = charts[slot].drawings().drawings.iter().find(|d| { + d.pane.is_none() + && d.tool_type == drawing.tool_type + && d.chart_points.len() == drawing.chart_points.len() + && mirrored(d.folder_sync_mode(), layout_wide) + && self + .linked_on(charts, key.0, self.origin_of((slot, d.id))) + .is_none() + && content(charts[slot], d) == own + })?; + Some((slot, other.id)) + }) + .collect() } pub(super) fn sync( @@ -83,8 +275,94 @@ impl DrawingLinks { layout_wide: bool, ) -> bool { let mut changed = false; - let mut changes = Vec::new(); - let mut current = HashSet::new(); + self.frame += 1; + // Turning the switch on is the first time for the drawings it mirrors: nothing made while + // it was off is a change. + if layout_wide != self.wide { + if layout_wide { + self.forget_switched(charts, count); + } + self.wide = layout_wide; + } + self.shown.resize(count, None); + for (slot, chart) in charts.iter().take(count).enumerate() { + let before = self.shown[slot].replace(chart.symbol().to_owned()); + if before.is_some_and(|before| before != chart.symbol()) { + self.arriving.insert(slot); + } + } + // A drawing a chart put aside with its symbol keeps the drawings of that symbol it was + // linked to: those on show, and those put aside that keep it. + let put_aside: Vec<_> = self + .previous + .iter() + .filter(|(key, old)| key.0 < count && old.symbol != charts[key.0].symbol()) + .map(|(&key, old)| { + // An edit made before the symbol change in this frame is seen now. + let chart = &charts[key.0]; + let edited = chart + .symbol_drawings + .get(&old.symbol) + .and_then(|(manager, _)| manager.drawings.iter().find(|d| d.id == key.1)) + .is_some_and(|d| { + serde_json::to_string(d).is_ok_and(|style| style != old.style) + || timed_points(chart, d) != old.points + || d.notes != old.notes + }); + let seen = if edited { self.frame } else { old.seen }; + (key, old.symbol.clone(), seen) + }) + .collect(); + for (key, symbol, seen) in &put_aside { + let mut partners: Vec = self + .aside + .iter() + .filter(|((_, aside_symbol, _), (_, linked))| { + aside_symbol == symbol && linked.contains(key) + }) + .map(|((slot, _, id), _)| (*slot, *id)) + .collect(); + if let Some(origin) = self.origins.get(key) { + for (other, value) in &self.origins { + if value == origin + && other.0 != key.0 + && self + .previous + .get(other) + .is_some_and(|old| old.symbol == *symbol) + && !partners.contains(other) + { + partners.push(*other); + } + } + } + // A chart that put a copy aside earlier also takes the drawings this one is linked + // to, such as the copy of a chart that came to the symbol after it left. + for ((slot, aside_symbol, id), (_, linked)) in &mut self.aside { + if aside_symbol == symbol && linked.contains(key) { + for partner in &partners { + if *partner != (*slot, *id) && !linked.contains(partner) { + linked.push(*partner); + } + } + } + } + if !partners.is_empty() { + self.aside + .insert((key.0, symbol.clone(), key.1), (*seen, partners)); + } + } + // Ids belong to a symbol's drawings, so the records of a symbol a chart left go before + // anything is matched by key. + for (key, ..) in &put_aside { + self.origins.remove(key); + self.previous.remove(key); + self.retry.remove(key); + self.unwritten.remove(key); + } + let mut changes: Vec = Vec::new(); + // The `Snapshot::seen` of each drawing on show. + let mut seen = HashMap::new(); for (slot, chart) in charts.iter().take(count).enumerate() { for drawing in &chart.drawings().drawings { let Ok(style) = serde_json::to_string(drawing) else { @@ -94,26 +372,50 @@ impl DrawingLinks { let old = self.previous.get(&key); let retry = self.retry.remove(&key); let points = timed_points(chart, drawing); - if (old.is_none_or(|old| { + let edited = old.is_none_or(|old| { old.style != style || old.points != points || old.notes != drawing.notes - }) || retry) - && old.is_none_or(|old| old.symbol == chart.symbol()) - { - changes.push((key, Some(drawing.clone()))); + }); + if edited || retry { + changes.push((key, Some(drawing.clone()), None)); } - current.insert(key); + let frame = match old { + Some(old) if !edited => old.seen, + Some(_) => self.frame, + // A drawing taken up again keeps the frame it was put aside with. + None => self + .aside + .get(&(slot, chart.symbol().to_owned(), drawing.id)) + .map_or(self.frame, |(seen, _)| *seen), + }; + seen.insert(key, frame); } } for (&key, old) in &self.previous { - if key.0 < count && !current.contains(&key) && old.symbol == charts[key.0].symbol() { - changes.push((key, None)); + if key.0 < count && !seen.contains_key(&key) && old.symbol == charts[key.0].symbol() { + changes.push((key, None, None)); } } - let joined = self.join_read_drawings(charts, count, groups, &changes); - for (key, drawing) in changes { - if joined.contains(&key) { - continue; - } + let mut joined = self.join_read_drawings(charts, count, groups, &changes); + let mut extra = self.join_new_drawings( + charts, + count, + groups, + &changes, + &seen, + layout_wide, + &mut joined, + ); + let arrived = self.arrived_drawings(charts, count, groups, &changes, &joined, layout_wide); + let arrived: Vec<_> = arrived + .into_iter() + .filter(|a| !extra.iter().any(|e| e.0 == a.0 && e.2 == a.2)) + .collect(); + extra.extend(arrived); + let changes = changes + .into_iter() + .filter(|(key, ..)| !joined.contains(key)) + .chain(extra); + for (key, drawing, only) in changes { // A drawing that stops being mirrored leaves the charts its copies are on. let was_mirrored = self .previous @@ -126,31 +428,35 @@ impl DrawingLinks { continue; } let origin = *self.origins.entry(key).or_insert(key); + // A copy carries the change it copies, not one of its own. + let frame = seen.get(&key).copied().unwrap_or(self.frame); let symbol = charts[key.0].symbol().to_owned(); let mut saveable = false; let mut writers: Vec = Vec::new(); + let mut deleted = vec![key]; for slot in 0..count { // Charts on one storage read each other's stored drawings instead. let stored = drawing.as_ref().is_some_and(|drawing| drawing.saveable); if slot == key.0 + || only.is_some_and(|only| only != slot) || groups[slot] != groups[key.0] || charts[slot].symbol() != symbol || (stored && charts[slot].shares_stored_drawings(charts[key.0])) { continue; } - let linked = self - .origins - .iter() - .find_map(|(&(target_slot, id), &value)| { - (target_slot == slot - && value == origin - && charts[slot].drawings().drawings.iter().any(|d| d.id == id)) - .then_some(id) - }); + let linked = self.linked_on(charts, slot, origin); if let Some(drawing) = drawing.as_ref().filter(|_| mirror) { - let Some(mut copy) = map_drawing(drawing, charts[key.0], charts[slot]) else { - self.retry.insert(key); + let Some(mut copy) = + map_drawing(drawing, charts[key.0], charts[slot], linked.is_some()) + else { + // A new copy without bars yet: a change tries again, an arrival waits + // for them. + if only.is_some() { + self.arriving.insert(slot); + } else { + self.retry.insert(key); + } continue; }; changed = true; @@ -181,6 +487,7 @@ impl DrawingLinks { copy.saveable = target.saveable && !copy_only; *target = copy; }); + seen.insert((slot, id), frame); } else { copy.stored_id = None; copy.created_at = None; @@ -189,6 +496,7 @@ impl DrawingLinks { copy.saveable &= !charts[slot].keeps_stored_drawings(); if let Ok(added) = charts[slot].drawings_mut().add_synced_drawing(copy) { self.origins.insert((slot, added), origin); + seen.insert((slot, added), frame); } } } else if let Some(id) = linked { @@ -200,6 +508,14 @@ impl DrawingLinks { charts[slot].history.drawing_edits += 1; } charts[slot].drawings_mut().delete_drawing(id); + deleted.push((slot, id)); + } + } + if !mirror { + // A drawing deleted, or confined to its chart, also leaves the charts that put a + // copy aside, which may be linked to any of the drawings removed here. + for gone in deleted { + self.delete_aside_copies(charts, count, gone); } } // The copy that stays, or the one deleted, is now the only instance, so it is stored @@ -228,6 +544,33 @@ impl DrawingLinks { chart.drawings_mut().end_drag_handle(); } } + let gone: Vec<_> = self + .aside + .keys() + .filter(|(slot, symbol, _)| { + *slot >= count || !charts[*slot].symbol_drawings.contains_key(symbol) + }) + .cloned() + .collect(); + let mut forgotten: Vec<(usize, String)> = Vec::new(); + for (slot, symbol, id) in gone { + self.aside.remove(&(slot, symbol.clone(), id)); + // A chart away from the symbol that holds it no more forgot its drawings there, whose + // ids a new drawing of the symbol may take. + if slot < count + && charts[slot].symbol() != symbol + && !forgotten.contains(&(slot, symbol.clone())) + { + forgotten.push((slot, symbol)); + } + } + for ((_, symbol, _), (_, partners)) in &mut self.aside { + partners.retain(|key| { + !forgotten + .iter() + .any(|(slot, gone)| *slot == key.0 && gone == symbol) + }); + } // Cache the propagated state too, so receiver updates cannot echo back next frame. self.previous.clear(); for (slot, chart) in charts.iter().take(count).enumerate() { @@ -241,6 +584,7 @@ impl DrawingLinks { notes: drawing.notes.clone(), symbol: chart.symbol().to_owned(), sync: drawing.folder_sync_mode(), + seen: seen.get(&(slot, drawing.id)).copied().unwrap_or(self.frame), }, ); } @@ -248,11 +592,198 @@ impl DrawingLinks { } self.origins .retain(|key, _| self.previous.contains_key(key)); + for (slot, symbol) in forgotten { + self.rename_links(|origin, shown| origin.0 == slot && shown == symbol); + } self.retry.retain(|key| self.previous.contains_key(key)); self.unwritten.retain(|key| self.previous.contains_key(key)); changed } + /// Links each drawing new to the layout that a chart took up again, or that equals one on + /// another chart, to that drawing instead of mirroring it. Returns the changes that give each + /// chart of the symbol of a returning drawing the version of its link that the layout saw + /// change last, by the `seen` frame of each drawing on show. + fn join_new_drawings( + &mut self, + charts: &[&mut Chart], + count: usize, + groups: &[Option; 16], + changes: &[Change], + seen: &HashMap, + layout_wide: bool, + joined: &mut HashSet, + ) -> Vec { + let mut returned = Vec::new(); + for (key, drawing, _) in changes { + let Some(drawing) = drawing else { continue }; + let symbol = charts[key.0].symbol().to_owned(); + if joined.contains(key) + || self.origins.get(key).is_some_and(|origin| origin != key) + || self.previous.contains_key(key) + || !mirrored(drawing.folder_sync_mode(), layout_wide) + { + continue; + } + let kept: Vec = self + .aside + .remove(&(key.0, symbol.clone(), key.1)) + .map(|(_, partners)| partners) + .unwrap_or_default() + .into_iter() + .filter(|&(slot, _)| { + slot < count + && slot != key.0 + && groups[slot] == groups[key.0] + && charts[slot].symbol() == symbol + }) + .collect(); + // A drawing it is linked to and that is deleted in this frame takes it along. + if let Some(&gone) = kept.iter().find(|&&partner| { + changes + .iter() + .any(|(changed, drawing, _)| *changed == partner && drawing.is_none()) + }) { + self.origins.insert(*key, self.origin_of(gone)); + joined.insert(*key); + continue; + } + let kept = kept + .into_iter() + .filter(|&(slot, id)| charts[slot].drawings().drawings.iter().any(|d| d.id == id)); + let mut linked = self.join(charts, *key, kept.collect()); + if linked.is_empty() { + let equal = self.equal_drawings(charts, count, groups, *key, drawing, layout_wide); + linked = self.join(charts, *key, equal); + } + if linked.is_empty() { + continue; + } + joined.insert(*key); + joined.extend(linked); + returned.push(*key); + } + // Once every drawing that came back in this frame is linked, the version of each link + // that the layout saw change last wins, the one on show on a tie: a chart may have left + // again after its change. It goes as one change to each chart of the symbol whose drawing + // of the link differs from it, or that has none yet, as a new drawing's copies do. + let mut extra = Vec::new(); + let mut done = HashSet::new(); + for key in returned { + if done.contains(&key) { + continue; + } + let symbol = charts[key.0].symbol(); + let origin = self.origin_of(key); + let held: Vec<(usize, Option<&Drawing>)> = (0..count) + .filter(|&slot| groups[slot] == groups[key.0] && charts[slot].symbol() == symbol) + .map(|slot| { + let id = if slot == key.0 { + Some(key.1) + } else { + self.linked_on(charts, slot, origin) + }; + let drawings = &charts[slot].drawings().drawings; + (slot, id.and_then(|id| drawings.iter().find(|d| d.id == id))) + }) + .collect(); + done.extend( + held.iter() + .filter_map(|&(slot, held)| held.map(|d| (slot, d.id))), + ); + let newest = held + .iter() + .filter_map(|&(slot, held)| held.map(|d| ((slot, d.id), d))) + .max_by_key(|(member, _)| (seen.get(member), self.previous.contains_key(member))); + if let Some((winner, version)) = newest { + let won = content(charts[winner.0], version); + for &(slot, held) in &held { + if slot != winner.0 && held.is_none_or(|d| content(charts[slot], d) != won) { + extra.push((winner, Some(version.clone()), Some(slot))); + } + } + } + } + extra + } + + /// The mirrored drawings of its symbol that other charts hold, for each chart that came to the + /// symbol and has no copy of them: each goes to that chart alone, once. A drawing on a chart + /// that is equal to one of them is linked to it instead. + fn arrived_drawings( + &mut self, + charts: &[&mut Chart], + count: usize, + groups: &[Option; 16], + changes: &[Change], + joined: &HashSet, + layout_wide: bool, + ) -> Vec { + let sending: HashSet = changes + .iter() + .filter(|(key, ..)| !joined.contains(key)) + .map(|(key, ..)| *key) + .collect(); + let mut arrivals = Vec::new(); + let mut slots: Vec = std::mem::take(&mut self.arriving).into_iter().collect(); + slots.sort_unstable(); + for slot in slots.into_iter().filter(|&slot| slot < count) { + for source in (0..count).filter(|&source| { + source != slot + && groups[source] == groups[slot] + && charts[source].symbol() == charts[slot].symbol() + }) { + for drawing in &charts[source].drawings().drawings { + let key = (source, drawing.id); + if drawing.pane.is_some() + || sending.contains(&key) + || !mirrored(drawing.folder_sync_mode(), layout_wide) + || self.linked_on(charts, slot, self.origin_of(key)).is_some() + { + continue; + } + let equal = + self.equal_drawings(charts, count, groups, key, drawing, layout_wide); + let equal: Vec = + equal.into_iter().filter(|other| other.0 == slot).collect(); + if self.join(charts, key, equal).is_empty() { + arrivals.push((key, Some(drawing.clone()), Some(slot))); + } + } + } + } + arrivals + } + + /// Takes the copies of a drawing deleted or confined to its chart out of the charts that put + /// them aside with their symbol, so that they do not come back with the chart. + fn delete_aside_copies(&mut self, charts: &mut [&mut Chart], count: usize, key: Key) { + let gone: Vec<_> = self + .aside + .iter() + .filter(|((_, symbol, _), (_, partners))| { + symbol == charts[key.0].symbol() && partners.contains(&key) + }) + .map(|(entry, _)| entry.clone()) + .collect(); + for (slot, symbol, id) in gone { + self.aside.remove(&(slot, symbol.clone(), id)); + if slot >= count { + continue; + } + // A drawing the chart stores comes back from its storage, which this does not write. + let stores = charts[slot].keeps_stored_drawings(); + if let Some((manager, _)) = charts[slot].symbol_drawings.get_mut(&symbol) + && manager + .drawings + .iter() + .any(|d| d.id == id && !(stores && d.saveable)) + { + manager.remove_drawings(&[id]); + } + } + } + /// Links each drawing that a chart has just read from storage to the drawing stored under the /// same id on another chart of that storage, group and symbol, and returns their keys: the /// read drawing is that drawing, whose copies exist or are made from it. A read drawing @@ -262,10 +793,10 @@ impl DrawingLinks { charts: &[&mut Chart], count: usize, groups: &[Option; 16], - changes: &[(Key, Option)], + changes: &[Change], ) -> HashSet { let mut joined = HashSet::new(); - for (key, drawing) in changes { + for (key, drawing, _) in changes { let Some(drawing) = drawing else { continue }; if !drawing.saveable || drawing.stored_id.is_none() || self.origins.contains_key(key) { continue; @@ -699,7 +1230,15 @@ fn writes(charts: &[&mut Chart], writers: &[usize], from: usize, slot: usize, id .any(|d| d.id == id && d.saveable) } -fn map_drawing(drawing: &Drawing, source: &Chart, target: &Chart) -> Option { +/// `drawing` as a drawing of `target`, at the times its points have on `source`. Without bars on +/// `target`, a copy that `replaces` a drawing there keeps those times, at which the chart puts its +/// points once the bars load; a new copy waits for them. +fn map_drawing( + drawing: &Drawing, + source: &Chart, + target: &Chart, + replaces: bool, +) -> Option { let mut copy = drawing.clone(); if drawing.pane.is_some() { // Study ids are local to each chart, so the copy goes to the corresponding pane. @@ -714,7 +1253,12 @@ fn map_drawing(drawing: &Drawing, source: &Chart, target: &Chart) -> Option>()?; copy.points.clear(); @@ -1413,7 +1957,7 @@ mod tests { ); source.project_drawing_points(); let drawing = source.drawings().drawings.last().unwrap(); - let mapped = map_drawing(drawing, &source, &target).unwrap(); + let mapped = map_drawing(drawing, &source, &target, false).unwrap(); assert_eq!(mapped.chart_points[0].bar_idx, 1.5); assert_eq!(mapped.chart_points[1].bar_idx, 3.5); // A drawing of a study pane without a counterpart is not mirrored. @@ -1853,6 +2397,687 @@ mod tests { assert!(failures.is_empty(), "{failures:#?}"); } + /// Two charts of one symbol in a layout with drawing sync on, each holding a line at 104. + fn mirrored_pair(sync_symbol: bool) -> (ChartLayout, [Chart; 2]) { + let mut charts = [bars(60), bars(60)]; + for chart in &mut charts { + chart.set_symbol("SAMPLE"); + } + let mut layout = ChartLayout { + mode: super::super::ChartLayoutMode::TwoHorizontal, + ..Default::default() + }; + layout.sync.sync_drawings = true; + layout.sync.sync_symbol = sync_symbol; + draw(&mut charts[0], 104.0); + let mut pair = (layout, charts); + frames(&mut pair.0, &mut pair.1); + assert_eq!(prices(&pair.1), [vec![104.0], vec![104.0]]); + pair + } + + /// Adds a horizontal trend line at `price` and returns its id. + fn draw(chart: &mut Chart, price: f64) -> usize { + let mut drawing = line(""); + drawing.chart_points = vec![ChartPoint::new(2.0, price), ChartPoint::new(4.0, price)]; + chart.drawings_mut().add_drawing(drawing).unwrap() + } + + fn frames(layout: &mut ChartLayout, charts: &mut [Chart; N]) { + let ctx = egui::Context::default(); + for _ in 0..4 { + ctx.run_ui(egui::RawInput::default(), |ui| { + layout.show(ui, &mut charts.each_mut()); + }) + .drop_without_applying_deltas(); + } + } + + /// The first price of each drawing of each chart, in order. + fn prices(charts: &[Chart; N]) -> [Vec; N] { + charts.each_ref().map(|chart| { + let mut prices: Vec = chart + .drawings() + .drawings + .iter() + .map(|d| d.chart_points[0].price) + .collect(); + prices.sort_by(f64::total_cmp); + prices + }) + } + + fn move_first(chart: &mut Chart, price: f64) { + let id = chart.drawings().drawings[0].id; + chart.drawings_mut().edit_drawing(id, |drawing| { + drawing.chart_points[0].price = price; + drawing.chart_points[1].price = price; + }); + } + + /// Puts the first drawing of `chart` in a folder synchronized as `sync`. + fn into_folder(chart: &mut Chart, sync: FolderSync) { + let folder = ["Folder".to_owned()]; + let id = chart.drawings().drawings[0].id; + assert!(chart.drawings_mut().move_to_folder(&[id], &[], &folder)); + assert!(chart.drawings_mut().set_folder_sync(&folder, Some(sync))); + } + + /// Three charts on `symbols` in a layout with drawing sync on, the first holding a line at + /// 104 that the others of its symbol hold too. + fn three_charts(symbols: [&str; 3]) -> (ChartLayout, [Chart; 3]) { + let mut charts = [bars(60), bars(60), bars(60)]; + for (chart, symbol) in charts.iter_mut().zip(symbols) { + chart.set_symbol(symbol); + } + let mut layout = ChartLayout { + mode: super::super::ChartLayoutMode::ThreeHorizontal, + ..Default::default() + }; + layout.sync.sync_drawings = true; + draw(&mut charts[0], 104.0); + frames(&mut layout, &mut charts); + (layout, charts) + } + + /// A chart that leaves a symbol and returns takes its mirrored drawings up again: each chart + /// holds one line however often it happens, also when the chart that stayed changed the line + /// meanwhile. A line deleted on another chart of the symbol, also in the frame of the return, + /// or confined to that chart by its folder, does not come back, and a chart that forgot the + /// drawings of the symbol draws lines of its own there. + #[test] + fn mirrored_drawings_stay_single_through_a_symbol_round_trip() { + for sync_symbol in [true, false] { + let (mut layout, mut charts) = mirrored_pair(sync_symbol); + // With the symbol synced the active chart takes the second along, otherwise only the + // second leaves. + let leaver = usize::from(!sync_symbol); + for trip in 1..=3 { + charts[leaver].set_symbol("OTHER"); + if !sync_symbol { + // The first chart edits the line while the second is away. + move_first(&mut charts[0], 104.0 - f64::from(trip)); + } + frames(&mut layout, &mut charts); + charts[leaver].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + let price = if sync_symbol { + 104.0 + } else { + 104.0 - f64::from(trip) + }; + assert_eq!( + prices(&charts), + [vec![price], vec![price]], + "sync_symbol {sync_symbol}, round trip {trip}" + ); + } + } + let delete: fn(&mut Chart) = |chart| { + let id = chart.drawings().drawings[0].id; + chart.drawings_mut().delete_drawing(id); + }; + let confine: fn(&mut Chart) = |chart| into_folder(chart, FolderSync::Chart); + for (name, edit, kept, at_return) in [ + ("deleted while away", delete, vec![], false), + ( + "confined to its chart while away", + confine, + vec![104.0], + false, + ), + ("deleted in the frame of the return", delete, vec![], true), + ] { + let (mut layout, mut charts) = mirrored_pair(false); + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + edit(&mut charts[0]); + if !at_return { + frames(&mut layout, &mut charts); + } + charts[1].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + assert_eq!(prices(&charts), [kept, vec![]], "{name}"); + } + + // Ids belong to a symbol's drawings: a drawing made on the other symbol meanwhile may + // have the id of the copy, and the link of the copy still follows its line. + let (mut layout, mut charts) = mirrored_pair(false); + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + draw(&mut charts[1], 70.0); + frames(&mut layout, &mut charts); + charts[1].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + move_first(&mut charts[0], 95.0); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![95.0], vec![95.0]], + "after the return" + ); + let id = charts[0].drawings().drawings[0].id; + charts[0].drawings_mut().delete_drawing(id); + frames(&mut layout, &mut charts); + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + assert_eq!(prices(&charts), [vec![], vec![70.0]], "other symbol kept"); + + // Each chart draws a line on the other symbol while the other chart shows the first, each + // under the id of its line on the first symbol: they stay two lines, each once on each + // chart. + let (mut layout, mut charts) = mirrored_pair(false); + charts[0].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + draw(&mut charts[0], 70.0); + frames(&mut layout, &mut charts); + charts[0].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + draw(&mut charts[1], 60.0); + frames(&mut layout, &mut charts); + charts[0].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![60.0, 70.0], vec![60.0, 70.0]], + "two lines on the other symbol" + ); + + // A chart that forgot the symbol while away draws a line there under the id of the line it + // had: the line of the other chart stays a line of its own. + let (mut layout, mut charts) = mirrored_pair(false); + let old = charts[0].drawings().drawings[0].id; + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + charts[0].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + assert!(charts[0].forget_symbol("SAMPLE")); + frames(&mut layout, &mut charts); + charts[0].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + assert_eq!(draw(&mut charts[0], 70.0), old, "the id comes back"); + frames(&mut layout, &mut charts); + charts[1].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![70.0, 104.0], vec![70.0, 104.0]], + "symbol forgotten" + ); + // Also while the other chart shows the symbol: the new line takes the id of a line whose + // copy the other chart still shows, and that copy stays. + let (mut layout, mut charts) = mirrored_pair(false); + let kept = draw(&mut charts[0], 70.0); + frames(&mut layout, &mut charts); + let id = charts[0].drawings().drawings[0].id; + charts[0].drawings_mut().delete_drawing(id); + frames(&mut layout, &mut charts); + charts[0].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + assert!(charts[0].forget_symbol("SAMPLE")); + frames(&mut layout, &mut charts); + charts[0].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + assert_eq!(draw(&mut charts[0], 60.0), kept, "the id comes back"); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![60.0, 70.0], vec![60.0, 70.0]], + "symbol forgotten, other chart on it" + ); + + // Three charts: the third comes to the symbol after the second left, the first stays or + // leaves too, and the copy of the third is deleted or moved. The charts that were away + // keep the line from coming back and take the move. + let lower: fn(&mut Chart) = |chart| move_first(chart, 95.0); + for (name, away, edit, line) in [ + ("deleted through a later copy", false, delete, vec![]), + ("deleted with the first away", true, delete, vec![]), + ("moved with the first away", true, lower, vec![95.0]), + ] { + let (mut layout, mut charts) = three_charts(["SAMPLE", "SAMPLE", "OTHER"]); + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + charts[2].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![104.0], vec![], vec![104.0]], + "{name}: copy on arrival" + ); + if away { + charts[0].set_symbol("THIRD"); + frames(&mut layout, &mut charts); + } + edit(&mut charts[2]); + frames(&mut layout, &mut charts); + for slot in [1, 0] { + charts[slot].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + } + assert_eq!( + prices(&charts), + [line.clone(), line.clone(), line], + "{name}" + ); + } + + // A line deleted on another symbol under the key of the line here leaves the copy that the + // second chart put aside. + let (mut layout, mut charts) = mirrored_pair(false); + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + charts[0].set_symbol("THIRD"); + frames(&mut layout, &mut charts); + let id = draw(&mut charts[0], 70.0); + frames(&mut layout, &mut charts); + charts[0].drawings_mut().delete_drawing(id); + frames(&mut layout, &mut charts); + charts[1].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [Vec::::new(), vec![104.0]], + "deleted on another symbol" + ); + } + + /// A chart that comes back to a symbol takes the last change made to its mirrored line while + /// it was away: by the chart that stayed, by one that came back and left again or by one that + /// came to the symbol meanwhile, also when the change is an undo or was made in the frame in + /// which its chart left, when the returning chart still waits for its bars, and when several + /// charts come back in one frame. + #[test] + fn mirrored_drawings_take_the_last_change_on_return() { + // A move made on the chart that leaves, in the frame it leaves in, is the last change. + let (mut layout, mut charts) = mirrored_pair(false); + move_first(&mut charts[1], 95.0); + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + charts[1].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![95.0], vec![95.0]], + "moved in the frame it left" + ); + // A move undone while the other chart is away, on either chart, is the last change, also + // when the undo gives the line back the edit time it had before the move. + for undo_on in [0, 1] { + let (mut layout, mut charts) = mirrored_pair(false); + move_first(&mut charts[0], 95.0); + frames(&mut layout, &mut charts); + let away = 1 - undo_on; + charts[away].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + assert!( + charts[undo_on].drawings_mut().undo(), + "undo on chart {undo_on}" + ); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts)[undo_on], + vec![104.0], + "undone on chart {undo_on}" + ); + charts[away].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![104.0], vec![104.0]], + "move undone on chart {undo_on} while the other was away" + ); + } + + // Both charts away: the one that comes back first changes the line, and the other takes + // that version when it comes back, whichever left first, also when the first left again + // before the other came back, and for a line its folder mirrors with the switch off. + for first in [0, 1] { + for (again, by_folder) in [(false, false), (true, false), (false, true)] { + let (mut layout, mut charts) = mirrored_pair(false); + if by_folder { + into_folder(&mut charts[0], FolderSync::Layout); + layout.sync.sync_drawings = false; + frames(&mut layout, &mut charts); + } + charts[first].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + charts[1 - first].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + charts[first].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + move_first(&mut charts[first], 95.0); + frames(&mut layout, &mut charts); + if again { + charts[first].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + } + charts[1 - first].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + if again { + charts[first].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + } + assert_eq!( + prices(&charts), + [vec![95.0], vec![95.0]], + "both away, chart {first} first, again {again}, by folder {by_folder}" + ); + } + } + // A chart that came to the symbol while the line was moved away from it takes the move. + let (mut layout, mut charts) = three_charts(["SAMPLE", "SAMPLE", "OTHER"]); + for chart in &mut charts[..2] { + chart.set_symbol("OTHER"); + } + frames(&mut layout, &mut charts); + charts[0].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + move_first(&mut charts[0], 95.0); + frames(&mut layout, &mut charts); + charts[0].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + for chart in &mut charts[1..] { + chart.set_symbol("SAMPLE"); + } + frames(&mut layout, &mut charts); + charts[0].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![95.0], vec![95.0], vec![95.0]], + "a chart came meanwhile" + ); + // Three charts leave in turn, the second and the third each moving the line before it + // leaves, and come back in the same order: each return takes the last move, also over + // the copy that the layout wrote to the first chart when the second came back. + let (mut layout, mut charts) = three_charts(["SAMPLE"; 3]); + charts[0].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + for (slot, price) in [(1, 95.0), (2, 80.0)] { + move_first(&mut charts[slot], price); + frames(&mut layout, &mut charts); + charts[slot].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + } + for (slot, expected) in [ + (0, [vec![104.0], vec![], vec![]]), + (1, [vec![95.0], vec![95.0], vec![]]), + (2, [vec![80.0], vec![80.0], vec![80.0]]), + ] { + charts[slot].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + expected, + "chart {slot} back after two moves" + ); + } + + // The chart that comes back waits for its bars, as with a feed, and the chart that moved + // the line leaves meanwhile: the first takes the move once its bars are in, and the other + // finds the line moved when it returns. + let (mut layout, mut charts) = mirrored_pair(false); + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + move_first(&mut charts[0], 95.0); + frames(&mut layout, &mut charts); + let data = charts[1].bars(SeriesId::MAIN).to_vec(); + charts[1].set_symbol("SAMPLE"); + charts[1].set_data(SeriesId::MAIN, Vec::new()); + frames(&mut layout, &mut charts); + charts[0].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + charts[1].set_data(SeriesId::MAIN, data); + frames(&mut layout, &mut charts); + assert_eq!(prices(&charts), [vec![], vec![95.0]], "bars in, mover away"); + charts[0].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + assert_eq!(prices(&charts), [vec![95.0], vec![95.0]], "mover back"); + + // The second of three charts comes back to the line the first moved, which the third took, + // with its bars in place, or waiting for them while the first leaves. The second takes the + // move, and the third gets no edit for it. + for later in [false, true] { + let (mut layout, mut charts) = three_charts(["SAMPLE", "SAMPLE", "OTHER"]); + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + charts[2].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + move_first(&mut charts[0], 95.0); + frames(&mut layout, &mut charts); + let data = charts[1].bars(SeriesId::MAIN).to_vec(); + charts[1].set_symbol("SAMPLE"); + if later { + charts[1].set_data(SeriesId::MAIN, Vec::new()); + frames(&mut layout, &mut charts); + charts[0].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + charts[1].set_data(SeriesId::MAIN, data); + } + frames(&mut layout, &mut charts); + let first = if later { vec![] } else { vec![95.0] }; + assert_eq!( + prices(&charts), + [first, vec![95.0], vec![95.0]], + "bars later {later}" + ); + // The copy it received on its arrival, and the move. + let mut edits = 0; + while charts[2].drawings_mut().undo() { + edits += 1; + } + assert_eq!(edits, 2, "edits of the third chart, bars later {later}"); + } + + // Two charts that left one after the other come back in one frame while the third, which + // stayed, moved the line: both take the move into the link of the third. + let (mut layout, mut charts) = three_charts(["SAMPLE"; 3]); + assert_eq!( + prices(&charts), + [vec![104.0], vec![104.0], vec![104.0]], + "mirrored" + ); + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + charts[0].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + move_first(&mut charts[2], 95.0); + frames(&mut layout, &mut charts); + for chart in &mut charts[..2] { + chart.set_symbol("SAMPLE"); + } + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![95.0], vec![95.0], vec![95.0]], + "back in one frame" + ); + // The third chart comes to the symbol after the second left, and moves the line in the + // frame in which it leaves again. Both come back in one frame, neither knowing the copy of + // the other: all three take the move. + let (mut layout, mut charts) = three_charts(["SAMPLE", "SAMPLE", "OTHER"]); + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + charts[2].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + move_first(&mut charts[2], 95.0); + charts[2].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + for chart in &mut charts[1..] { + chart.set_symbol("SAMPLE"); + } + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![95.0], vec![95.0], vec![95.0]], + "moved in the frame it left, back in one frame" + ); + } + + /// A chart that comes to a symbol receives the mirrored drawings its group holds for it, those + /// made while it showed another symbol too, once its bars are in place, and not the ones local + /// to their chart. + #[test] + fn chart_arriving_at_a_symbol_receives_its_mirrored_drawings() { + let (mut layout, mut charts) = mirrored_pair(false); + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![104.0], vec![]], + "second chart on OTHER" + ); + // Made in its absence, one mirrored and one local to its folder. + let id = draw(&mut charts[0], 90.0); + let local = draw(&mut charts[0], 80.0); + let folder = ["Local".to_owned()]; + assert!( + charts[0] + .drawings_mut() + .move_to_folder(&[local], &[], &folder) + ); + assert!( + charts[0] + .drawings_mut() + .set_folder_sync(&folder, Some(FolderSync::Chart)) + ); + assert_ne!(id, local); + frames(&mut layout, &mut charts); + // As with a feed, the bars go with the symbol change until those of the new one load. + let data = charts[1].bars(SeriesId::MAIN).to_vec(); + charts[1].set_symbol("SAMPLE"); + charts[1].set_data(SeriesId::MAIN, Vec::new()); + frames(&mut layout, &mut charts); + assert_eq!(prices(&charts)[1], vec![104.0], "before its bars"); + charts[1].set_data(SeriesId::MAIN, data); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![80.0, 90.0, 104.0], vec![90.0, 104.0]], + "second chart back on SAMPLE" + ); + } + + /// What was done to the drawings of a chart while the switch was off stays on that chart when + /// it is turned on, and the charts end with the same drawings. + #[test] + fn turning_drawing_sync_on_keeps_changes_made_while_off() { + type Edit = fn(&mut [Chart; 2]); + let rows: [(&str, Edit, [Vec; 2]); 3] = [ + ( + "copy deleted", + |charts| { + let id = charts[1].drawings().drawings[0].id; + charts[1].drawings_mut().delete_drawing(id); + }, + [vec![104.0], vec![104.0]], + ), + ( + "copy moved", + |charts| move_first(&mut charts[1], 95.0), + [vec![95.0, 104.0], vec![95.0, 104.0]], + ), + ( + "both moved", + |charts| { + move_first(&mut charts[0], 108.0); + move_first(&mut charts[1], 95.0); + }, + [vec![95.0, 108.0], vec![95.0, 108.0]], + ), + ]; + for (name, edit, expected) in rows { + let (mut layout, mut charts) = mirrored_pair(false); + layout.sync.sync_drawings = false; + frames(&mut layout, &mut charts); + edit(&mut charts); + frames(&mut layout, &mut charts); + layout.sync.sync_drawings = true; + frames(&mut layout, &mut charts); + assert_eq!(prices(&charts), expected, "{name}"); + } + + // A line its folder mirrors stays linked when the switch is turned on: the chart that was + // away takes the move made meanwhile. + let (mut layout, mut charts) = mirrored_pair(false); + into_folder(&mut charts[0], FolderSync::Layout); + layout.sync.sync_drawings = false; + frames(&mut layout, &mut charts); + charts[1].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + move_first(&mut charts[0], 95.0); + frames(&mut layout, &mut charts); + layout.sync.sync_drawings = true; + frames(&mut layout, &mut charts); + charts[1].set_symbol("SAMPLE"); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![95.0], vec![95.0]], + "mirrored by its folder" + ); + } + + /// Charts saved as snapshots and restored into a new layout show each mirrored drawing once, + /// still linked, however often that happens. + #[cfg(feature = "ui")] + #[test] + fn mirrored_drawings_restored_from_snapshots_stay_single_and_linked() { + let (mut layout, mut charts) = mirrored_pair(false); + for restart in 1..=3 { + let saved = charts.each_ref().map(|chart| chart.snapshot().unwrap()); + charts = [bars(60), bars(60)]; + for (chart, saved) in charts.iter_mut().zip(&saved) { + chart.set_symbol("SAMPLE"); + chart.restore(saved).unwrap(); + } + layout = ChartLayout { + mode: super::super::ChartLayoutMode::TwoHorizontal, + ..Default::default() + }; + layout.sync.sync_drawings = true; + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![104.0], vec![104.0]], + "restart {restart}" + ); + } + move_first(&mut charts[0], 95.0); + frames(&mut layout, &mut charts); + assert_eq!(prices(&charts), [vec![95.0], vec![95.0]], "still linked"); + + // One chart restored from a snapshot of the symbol holding another line, whether it + // shows the symbol or is away from it, and whether it drew the line here or holds its + // copy: both lines end on both charts. + let saved = { + let mut chart = bars(60); + chart.set_symbol("SAMPLE"); + draw(&mut chart, 70.0); + chart.snapshot().unwrap() + }; + for (restored, away) in [(1, false), (1, true), (0, false), (0, true)] { + let (mut layout, mut charts) = mirrored_pair(false); + if away { + charts[restored].set_symbol("OTHER"); + frames(&mut layout, &mut charts); + } + let data = charts[restored].bars(SeriesId::MAIN).to_vec(); + charts[restored].restore(&saved).unwrap(); + // Restoring another symbol empties the bars until the new ones load. + charts[restored].set_data(SeriesId::MAIN, data); + frames(&mut layout, &mut charts); + assert_eq!( + prices(&charts), + [vec![70.0, 104.0], vec![70.0, 104.0]], + "chart {restored} restored, away {away}" + ); + } + } + /// Two charts keep their drawings in one storage that keeps revisions, a third in its own. /// Keeping or editing a mirrored drawing on the third chart writes the shared storage once, /// which the other chart there reads: a second write would be refused as a conflict for the diff --git a/vendor/egui-charts/src/widget/marks.rs b/vendor/egui-charts/src/widget/marks.rs index e9b6d2f..cda2b9f 100644 --- a/vendor/egui-charts/src/widget/marks.rs +++ b/vendor/egui-charts/src/widget/marks.rs @@ -119,13 +119,12 @@ impl Chart { ) { if layer == MarkerZOrder::Normal { // Marks age on the frame clock even while their series is not drawn. - let now = ctx.painter.ctx().input(|input| input.time); for marks in self.change_marks.iter().chain( self.price_series .iter() .filter_map(|item| item.change_marks.as_ref()), ) { - marks.expire(now); + marks.expire(ctx.painter.ctx()); } } // Normal markers of added series, and all markers in other panes, are painted with @@ -1489,8 +1488,11 @@ mod tests { "top", "eraser", "moved", + "tool", ] { - if !cfg!(feature = "drawings") && matches!(cover, "drawing" | "top" | "eraser") { + if !cfg!(feature = "drawings") + && matches!(cover, "drawing" | "top" | "eraser" | "tool") + { continue; } let ctx = Context::default(); @@ -1512,6 +1514,12 @@ mod tests { if cover == "eraser" { chart.drawings_mut().eraser_mode = true; } + #[cfg(feature = "drawings")] + if cover == "tool" { + chart + .drawings_mut() + .set_active_tool(Some(crate::drawings::DrawingToolType::HorizontalLine)); + } let time = chart.bars(id)[70].time; chart.set_marker_options( id, @@ -1589,9 +1597,11 @@ mod tests { _ => None, }) .unwrap_or_else(|| panic!("secondary={secondary}, cover={cover}: {events:?}")); - let marked = !matches!(cover, "primitive" | "drawing" | "eraser" | "moved"); + let marked = + !matches!(cover, "primitive" | "drawing" | "eraser" | "moved" | "tool"); // Bar 70 spans 95 to 105, so without the marker the click selects its series; a - // click on a drawing clears the selection. + // click on a drawing clears the selection, and with the eraser on or a drawing tool + // armed it selects nothing. let unmarked = matches!(cover, "primitive" | "moved").then_some(ChartElementId::Series(id)); if let Some(primitive) = primitive { @@ -1615,13 +1625,11 @@ mod tests { usize::from(marked), "secondary={secondary}, cover={cover}: {events:?}" ); - if cover != "eraser" { - assert_eq!( - chart.selected_element(), - unmarked, - "secondary={secondary}, cover={cover}" - ); - } + assert_eq!( + chart.selected_element(), + unmarked, + "secondary={secondary}, cover={cover}" + ); #[cfg(feature = "drawings")] if cover == "top" { assert_eq!(chart.drawings.selected_ids().count(), 0); @@ -1630,10 +1638,76 @@ mod tests { if cover == "drawing" { assert!(chart.drawings.is_selected(77), "secondary={secondary}"); } + // The tool still places its line with the click. + #[cfg(feature = "drawings")] + if cover == "tool" { + assert_eq!(chart.drawings.drawings.len(), 1, "secondary={secondary}"); + } } } } + /// With the eraser on, a click erases the drawing under it and leaves the element selection + /// as it was, in the price pane as in a secondary pane. + #[cfg(feature = "drawings")] + #[test] + fn eraser_click_keeps_the_element_selection() { + use crate::widget::{ChartElementId, SeriesOptions}; + for secondary in [false, true] { + let ctx = Context::default(); + let mut chart = test_frames::chart(&[95.0], &[105.0]); + chart.config.show_volume = false; + let id = if secondary { + let id = chart.add_series(SeriesOptions { + chart_type: crate::model::ChartType::Candles, + ..Default::default() + }); + chart.set_data(id, chart.bars(SeriesId::MAIN).to_vec()); + let pane = chart.add_pane(); + chart.move_series_to_pane(id, pane); + id + } else { + SeriesId::MAIN + }; + chart.drawings_mut().eraser_mode = true; + test_frames::frame(&ctx, &mut chart, 0.0, vec![]); + let pos = egui::pos2( + chart.get_chart_mapping().idx_to_x(70), + chart.series_price_map(id).unwrap().price_to_y(100.0), + ); + let click = |pressed| egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: Default::default(), + }; + test_frames::frame(&ctx, &mut chart, 0.1, vec![egui::Event::PointerMoved(pos)]); + + // A click on a bar that erases nothing selects nothing. + test_frames::frame(&ctx, &mut chart, 0.2, vec![click(true), click(false)]); + assert_eq!(chart.selected_element(), None, "secondary={secondary}"); + + // A click on a drawing erases it and keeps the series selected. + let mut drawing = crate::drawings::Drawing::with_color( + 77, + crate::drawings::DrawingToolType::HorizontalLine, + [0, 0, 255, 255], + ); + drawing.chart_points = vec![crate::drawings::ChartPoint::new(70.0, 100.0)]; + drawing.pane = secondary.then_some(id.0); + chart.drawings_mut().drawings.push(drawing); + chart.selection.select(ChartElementId::Series(id), None); + test_frames::frame(&ctx, &mut chart, 0.3, vec![egui::Event::PointerMoved(pos)]); + test_frames::frame(&ctx, &mut chart, 0.4, vec![click(true), click(false)]); + assert!(chart.drawings.drawings.is_empty(), "secondary={secondary}"); + assert_eq!( + chart.selected_element(), + Some(ChartElementId::Series(id)), + "secondary={secondary}" + ); + } + } + /// A primary click reports only the top mark's host ID, if it has one, and selects nothing. #[test] fn clicking_overlapping_marks_reports_the_top_one_and_selects_nothing() { diff --git a/vendor/egui-charts/src/widget/mod.rs b/vendor/egui-charts/src/widget/mod.rs index 5cef326..706c478 100644 --- a/vendor/egui-charts/src/widget/mod.rs +++ b/vendor/egui-charts/src/widget/mod.rs @@ -59,6 +59,8 @@ use egui::{Pos2, Rect, Vec2}; pub(crate) use export::ColumnId; pub use export::{ChartImage, DataTable, ExportError, ImageExportOptions}; pub use pane::{IndicatorCoordParams, IndicatorPane, IndicatorPaneConfig, PaneInteraction}; +#[cfg(feature = "ui")] +pub(crate) use readout::SeriesFingerprint; use std::collections::BTreeMap; // Re-export from logic layer @@ -259,8 +261,8 @@ pub struct Chart { pub(crate) scroll_start_offset: Option, /// Previous widget width for resize handling (UI state only) pub(crate) prev_width: Option, - /// Price-axis drag this frame: anchor y where the drag began, and the y movement (UI state only) - pub(crate) price_axis_drag: Option<(f32, f32)>, + /// Bar spacing when a time-axis drag began or was last rebased (UI state only) + pub(crate) scroll_start_spacing: Option, /// Apply external start-index once to time scale (UI state only) pub(crate) pending_start_idx: Option, /// Timestamp to centre, retained while older history is loading. @@ -269,6 +271,9 @@ pub struct Chart { scroll_animation: Option, /// Time axis below the plots in the last frame; zero height while its labels are hidden time_axis_rect: Rect, + /// Whether the last price frame took a double-click on its plot, below its status line and + /// away from the drawings, series and primitives there + price_plot_double_click: bool, /// Chart type (candlestick, line, area, bar, Renko, Kagi) pub(crate) chart_type: ChartType, /// Parameters of the price-based chart types and the baseline @@ -464,6 +469,9 @@ pub struct Chart { marker_options: crate::model::MarkerOptions, /// Marks of the main series' recent changes; see [`Chart::set_change_markers`]. change_marks: Option, + /// Clock of the last frame that showed the chart, which dates change marks recorded while no + /// frame shows it. + frame_clock: Option, /// Horizontal lines on the main series; see [`Chart::set_price_lines`]. price_lines: Vec<(PriceLineId, crate::model::PriceLine)>, /// The number of price line handles issued. @@ -504,6 +512,16 @@ pub struct Chart { merge_groups: merge::Groups, } +impl std::fmt::Debug for Chart { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Chart") + .field("symbol", &self.symbol()) + .field("timeframe", &self.timeframe()) + .field("bars", &self.bars(SeriesId::MAIN).len()) + .finish_non_exhaustive() + } +} + /// The object a right-click landed on, with the data needed to position and /// populate a context menu. /// @@ -767,8 +785,9 @@ impl Chart { /// candle colors in that chart type's style instead, a `None` border or wick meaning the /// body color, and these colors win over the same colors in `chart_type_params`. A new /// scale mode returns the scale to auto-scaling and clears the zoom history, whose ranges - /// are in the old mode's units. Call this when the user changes series appearance in a - /// settings dialog. + /// are in the old mode's units. An ATR or percentage size whose method is unchanged keeps + /// its resolved value. Call this when the user changes series appearance in a settings + /// dialog. pub fn apply_series_settings(&mut self, settings: &SeriesSettings) { let mut params = settings.chart_type_params.clone(); if let Some( @@ -800,7 +819,7 @@ impl Chart { self.config.show_price_line = settings.show_price_line; self.config.show_prev_close_line = settings.show_prev_close_line; self.main_series_style.alerts = settings.alerts; - self.set_chart_type_params(params); + self.apply_chart_type_params(params); if self.state.price_scale().options().mode != settings.price_scale_mode { self.state.price_scale_mut().reset(); self.state.clear_zoom_history(); diff --git a/vendor/egui-charts/src/widget/navigation.rs b/vendor/egui-charts/src/widget/navigation.rs index 4fe6d73..b5c6e7a 100644 --- a/vendor/egui-charts/src/widget/navigation.rs +++ b/vendor/egui-charts/src/widget/navigation.rs @@ -357,6 +357,41 @@ pub(super) mod tests { assert_eq!(chart.state.price_scale().is_manual(), manual); assert_eq!(chart.state.price_scale().options().mode, mode); } + // View movements are one undo step that keeps redo, here Left arrow presses after the + // grid was hidden: (presses, whether the grid edit is undone before them) + for (presses, undone) in [(120, false), (1, true)] { + let ctx = egui::Context::default(); + let mut chart = chart(&[100.0], &[200.0]); + frame(&ctx, &mut chart, 0.0, Vec::new()); + chart.state.time_scale_mut().set_bar_spacing(20.0); + chart.state.time_scale_mut().set_right_offset(-20.0); + chart.user_action(|chart| chart.config.show_grid = false); + if undone { + assert!(chart.undo()); + } + for press in 0..presses { + let key = Event::Key { + key: egui::Key::ArrowLeft, + physical_key: None, + pressed: true, + repeat: press > 0, + modifiers: egui::Modifiers::NONE, + }; + frame(&ctx, &mut chart, 1.0 + f64::from(press) * 0.02, vec![key]); + } + assert_ne!(chart.get_time_scale_state(), (20.0, -20.0)); + if undone { + assert!(chart.redo(), "a view movement keeps redo"); + assert!(!chart.config.show_grid); + } else { + assert!(chart.undo()); + assert_eq!(chart.get_time_scale_state(), (20.0, -20.0)); + assert!(!chart.config.show_grid); + assert!(chart.undo(), "{presses} presses are one step"); + assert!(chart.config.show_grid); + assert!(!chart.can_undo()); + } + } } /// The selected fill follows price-axis scaling/reset and series settings on the next frame, diff --git a/vendor/egui-charts/src/widget/palette.rs b/vendor/egui-charts/src/widget/palette.rs index 0d16f7c..cb856d2 100644 --- a/vendor/egui-charts/src/widget/palette.rs +++ b/vendor/egui-charts/src/widget/palette.rs @@ -1,7 +1,7 @@ //! Active palette propagation for chart configuration colours. use super::Chart; -use crate::config::ChartConfig; +use crate::config::{BackgroundStyle, ChartConfig}; use crate::model::{ChartTypeStyles, HlcAreaStyle}; use crate::theme::Theme; @@ -29,6 +29,16 @@ impl Chart { }) } + /// Lets the colours that undo or redo brought back, where they still match the palette + /// `recorded` with them, follow the theme the chart follows, or the active theme on the next + /// frame of a chart that follows none yet. The others were edited and stay. + pub(super) fn follow_recorded_palette(&mut self, recorded: ChartConfig) { + self.restored_palettes.push(recorded); + if let Some(theme) = self.inherited_theme.clone() { + self.follow_chart_theme(&theme); + } + } + /// Lets the colours of a restored configuration that still match the palette they were saved /// with follow a per-chart theme immediately, or the active theme on the next frame. Layouts /// saved without that palette are compared with both built-in themes. @@ -108,8 +118,24 @@ pub(crate) fn follow_candle_colors( } /// Replaces every colour of `config` equal to the same colour of one of the `old` palettes by -/// the one of `new`; the others were edited and stay. -fn follow_palette(config: &mut ChartConfig, old: &[ChartConfig], new: &ChartConfig) { +/// the one of `new`; the others were edited and stay. A gradient's endpoints start as copies of +/// the background colour and follow it in the same way. +pub(super) fn follow_palette(config: &mut ChartConfig, old: &[ChartConfig], new: &ChartConfig) { + if let BackgroundStyle::VerticalGradient { + top_color: first, + bottom_color: second, + } + | BackgroundStyle::HorizontalGradient { + left_color: first, + right_color: second, + } = &mut config.background_style + { + for color in [first, second] { + if old.iter().any(|old| *color == old.background_color) { + *color = new.background_color; + } + } + } macro_rules! follow { ($($field:ident),+ $(,)?) => { $(if old.iter().any(|old| config.$field == old.$field) { config.$field = new.$field; })+ }; } @@ -276,6 +302,43 @@ mod tests { } } + /// A gradient chosen under the light preset without picking colours holds two copies of its + /// white background. Both follow a change to the dark preset, whose background is black, + /// through the chart's own theme and through the context; an endpoint the user picked stays. + #[test] + fn unedited_gradient_endpoints_follow_the_theme() { + use crate::config::BackgroundStyle; + use egui::Color32; + const EDITED: Color32 = Color32::from_rgb(1, 2, 3); + for via_override in [false, true] { + for edited in [false, true] { + let ctx = egui::Context::default(); + apply_to_egui(&ctx, &Theme::light()); + let mut chart = chart(&[100.0], &[110.0]); + frame(&ctx, &mut chart, 0.0, vec![]); + chart.config_mut().background_style = BackgroundStyle::VerticalGradient { + top_color: Color32::WHITE, + bottom_color: if edited { EDITED } else { Color32::WHITE }, + }; + if via_override { + chart.set_theme_override(Some(Theme::dark())); + } else { + apply_to_egui(&ctx, &Theme::dark()); + } + frame(&ctx, &mut chart, 1.0, vec![]); + assert_eq!( + chart.config().background_style, + BackgroundStyle::VerticalGradient { + top_color: Color32::BLACK, + bottom_color: if edited { EDITED } else { Color32::BLACK }, + }, + "override {via_override}" + ); + assert_eq!(chart.config().text_color, Color32::WHITE); + } + } + } + /// Both calls follow unedited chart type style colours as a theme change through the context /// does, and keep edited ones. The light preset's colours go to the high contrast preset's. #[test] diff --git a/vendor/egui-charts/src/widget/pan_zoom/mod.rs b/vendor/egui-charts/src/widget/pan_zoom/mod.rs index 83c089b..887b44f 100644 --- a/vendor/egui-charts/src/widget/pan_zoom/mod.rs +++ b/vendor/egui-charts/src/widget/pan_zoom/mod.rs @@ -20,9 +20,8 @@ pub(super) mod state; pub(super) use box_zoom::render_box_zoom; use egui::{Event, MouseWheelUnit, Pos2, Rect, Response, Ui, Vec2, vec2}; -use web_time::Instant; -use crate::scales::PriceTransform; +use crate::scales::PriceScale; use crate::widget::Chart; /// This frame's wheel scroll in points before egui smooths it: line and page units converted, and @@ -60,11 +59,98 @@ pub(super) fn raw_wheel_delta(ui: &Ui) -> Vec2 { }) } +/// What the pointer asks of one price axis in a frame, read by [`Chart::price_axis_gestures`]. +#[derive(Default)] +pub(in crate::widget) struct PriceAxisGestures { + /// The wheel and the drag: the points each moved and the height whose price stays in place. + zooms: [Option<(f32, f32)>; 2], + /// Whether a double-click returns the scale to automatic. + pub(in crate::widget) reset: bool, +} + +impl PriceAxisGestures { + /// Zooms `scale`, drawn from `top` down to `bottom`, and returns whether there was a zoom. + /// + /// A movement of `dy` points scales the range by `exp(dy / height)`, so a gesture zooms by + /// the same amount however many frames it spans. + pub(in crate::widget) fn zoom(&self, scale: &mut PriceScale, top: f32, bottom: f32) -> bool { + let mut zoomed = false; + for (dy, anchor_y) in self.zooms.into_iter().flatten().filter(|_| bottom > top) { + let anchor = scale + .map(scale.transform(), top, bottom) + .y_to_scale(anchor_y); + scale.zoom((f64::from(dy) / f64::from(bottom - top)).exp(), anchor); + zoomed = true; + } + zoomed + } +} + impl Chart { - /// Handle mouse wheel events for time-axis zoom, price-axis zoom, and horizontal pan. + /// Reads the gestures of a price axis from `response`, which may cover more than the axis: + /// only what the pointer does within `axis` counts. /// - /// Returns `Some(delta_y)` when the wheel was over the price axis, signaling - /// that price zoom should be applied downstream (deferred to avoid borrow conflicts). + /// A drag that began on the axis zooms around the price where it began, the wheel zooms + /// around the pointer, and a double-click returns the scale to automatic. Each obeys its + /// `handle_scale` permission and the group switch. Positive wheel points and an upward drag + /// narrow the range; Shift leaves the wheel to horizontal scrolling. + pub(in crate::widget) fn price_axis_gestures( + &self, + ui: &Ui, + response: &Response, + axis: Rect, + ) -> PriceAxisGestures { + let options = self.chart_options.handle_scale; + let mut gestures = PriceAxisGestures::default(); + if !options.enabled { + return gestures; + } + let on_axis = |pos: Option| pos.filter(|pos| axis.contains(*pos)); + let (origin, hover, shift, contacts) = ui.input(|i| { + ( + on_axis(i.pointer.press_origin()), + on_axis(i.pointer.hover_pos()), + i.modifiers.shift, + i.multi_touch().is_some(), + ) + }); + let wheel = raw_wheel_delta(ui).y; + if options.mouse_wheel + && response.hovered() + && !shift + && wheel.is_finite() + && wheel.abs() > 0.1 + && let Some(pos) = hover + { + gestures.zooms[0] = Some((-wheel, pos.y)); + } + // Two contacts are a pinch, whichever of them began on the axis. + if options.axis_pressed_mouse_move.price + && response.dragged() + && !contacts + && let Some(origin) = origin + { + gestures.zooms[1] = Some((response.drag_delta().y, origin.y)); + } + gestures.reset = options.axis_double_click_reset.price + && response.double_clicked() + && !self.pane_collapse_click(ui.ctx()) + && on_axis(response.interact_pointer_pos()).is_some(); + gestures + } + + /// Whether `pos` is in a pane other than the price pane. A gesture there moves the shared + /// time scale and leaves the prices of the price pane alone. + fn in_other_pane(&self, pos: Pos2) -> bool { + let main = self.main_series_pane(); + self.pane_layout + .panes + .iter() + .any(|pane| pane.id != main && pane.rect.contains(pos)) + } + + /// Handle mouse wheel events for time-axis zoom and horizontal pan. The wheel over the + /// price axis is left to [`Self::price_axis_gestures`]. pub(crate) fn handle_mouse_wheel( &mut self, ui: &Ui, @@ -72,19 +158,22 @@ impl Chart { chart_width: f32, chart_rect_min_x: f32, price_axis_rect: Rect, - ) -> Option { - let mut pending_price_zoom = None; + ) { let scale = self.chart_options.handle_scale; let scroll = self.chart_options.handle_scroll; let scale_wheel = scale.enabled && scale.mouse_wheel; let scroll_wheel = scroll.enabled && scroll.mouse_wheel; if !response.hovered() || (!scale_wheel && !scroll_wheel) { - return pending_price_zoom; + return; } // Apply this frame's wheel events; smoothing can outlive the pointer's axis or modifiers. let raw = raw_wheel_delta(ui); + if raw != Vec2::ZERO { + // The wheel takes over from the momentum of an earlier flick. + self.kinetic_scroll.is_active = false; + } let scroll_input = ui.input(|i| { let mut dx = raw.x; let mut dy = raw.y; @@ -105,38 +194,37 @@ impl Chart { if shift_held && scroll_wheel { let pan_amount = -delta_y * 2.0; self.state.time_scale_mut().scroll_pixels(pan_amount); - } else if scale_wheel && let Some(hp) = hover_pos.or_else(|| response.hover_pos()) { - if price_axis_rect.contains(hp) { - pending_price_zoom = Some(delta_y); - } else { - // Integrate raw points multiplicatively, independently of frame batching. - let zoom_scale = (delta_y / 1000.0).min(80.0).exp_m1() * 10.0; - // Zoom around the pointer, or the right edge while the right bar stays on scroll - let zoom_point_x = self.zoom_anchor(hp.x - chart_rect_min_x, chart_width); - - log::debug!( - "[ZOOM INPUT] mouse_x={:.1}, chart_min_x={:.1}, anchor_x={:.1}, chart_width={:.1}", - hp.x, - chart_rect_min_x, - zoom_point_x, - chart_width - ); + } else if scale_wheel + && let Some(hp) = hover_pos.or_else(|| response.hover_pos()) + && !price_axis_rect.contains(hp) + { + // Integrate raw points multiplicatively, independently of frame batching. + let zoom_scale = (delta_y / 1000.0).min(80.0).exp_m1() * 10.0; + // Zoom around the pointer, or the right edge while the right bar stays on scroll + let zoom_point_x = self.zoom_anchor(hp.x - chart_rect_min_x, chart_width); - self.state.time_scale_mut().zoom( - zoom_scale, - zoom_point_x, - chart_rect_min_x, - chart_width, - ); - did_zoom = true; - - // CRITICAL: Reset drag state after zoom to prevent jump - // If user was dragging while zooming, the old start_offset is now invalid - if self.scroll_start_offset.is_some() { - self.scroll_start_offset = - Some(self.state.time_scale().right_offset_precise()); - self.scroll_start_pos = response.interact_pointer_pos(); - } + log::debug!( + "[ZOOM INPUT] mouse_x={:.1}, chart_min_x={:.1}, anchor_x={:.1}, chart_width={:.1}", + hp.x, + chart_rect_min_x, + zoom_point_x, + chart_width + ); + + self.state.time_scale_mut().zoom( + zoom_scale, + zoom_point_x, + chart_rect_min_x, + chart_width, + ); + did_zoom = true; + + // CRITICAL: Reset drag state after zoom to prevent jump + // If user was dragging while zooming, the old start_offset is now invalid + if self.scroll_start_offset.is_some() { + self.scroll_start_offset = Some(self.state.time_scale().right_offset_precise()); + self.scroll_start_pos = response.interact_pointer_pos(); + self.scroll_start_spacing = None; } } } @@ -144,14 +232,13 @@ impl Chart { if !did_zoom && delta_y.abs() < 0.1 && delta_x.abs() > 0.1 && scroll_wheel { self.state.time_scale_mut().scroll_pixels(delta_x); } - - pending_price_zoom } /// Handles pinch-to-zoom for touch/trackpad gestures /// - /// Native zoom events and contact-based pinches share the pointer anchor. - /// Contact gestures take precedence when a backend reports both. + /// A contact pinch zooms around the midpoint between the fingers and pans by its movement, + /// so the bars under the fingers stay under them; a native zoom event zooms around the + /// pointer. Contact gestures take precedence when a backend reports both. pub(crate) fn handle_pinch_zoom( &mut self, ui: &Ui, @@ -166,7 +253,8 @@ impl Chart { // Get multi-touch zoom delta (1.0 = no zoom, >1.0 = zoom in, <1.0 = zoom out) let zoom_info = ui.input(|i| { i.multi_touch() - .map(|mt| (mt.zoom_delta, mt.translation_delta, i.pointer.hover_pos())) + // The pointer follows the first finger; the gesture turns about their midpoint. + .map(|mt| (mt.zoom_delta, mt.translation_delta, Some(mt.center_pos))) .or_else(|| { // Wheel zoom is handled separately, including its Ctrl/Cmd variant. let native_zoom: f32 = i @@ -187,7 +275,19 @@ impl Chart { }) }); - if let Some((zoom_delta, translation_delta, hover_pos)) = zoom_info { + if let Some((zoom_delta, translation_delta, anchor)) = zoom_info { + // Handle two-finger pan (translation during pinch) first: the zoom below then keeps + // the bar under the midpoint where the fingers have taken it. + if self.chart_options.handle_scroll.enabled + && self.chart_options.handle_scroll.horz_touch_drag + && translation_delta.x != 0.0 + { + self.pending_scroll_time = None; + self.state + .time_scale_mut() + .scroll_pixels(translation_delta.x); + } + // Handle pinch zoom if self.chart_options.handle_scale.enabled && self.chart_options.handle_scale.pinch @@ -201,9 +301,9 @@ impl Chart { self.tracking_mode_active = false; self.kinetic_scroll.is_active = false; - // Use hover position or center of chart as zoom anchor + // Use the gesture's anchor or center of chart as zoom anchor let zoom_point_x = self.zoom_anchor( - hover_pos.map_or(chart_width / 2.0, |p| p.x - chart_rect_min_x), + anchor.map_or(chart_width / 2.0, |p| p.x - chart_rect_min_x), chart_width, ); @@ -222,26 +322,19 @@ impl Chart { if self.scroll_start_offset.is_some() { self.scroll_start_offset = Some(self.state.time_scale().right_offset_precise()); self.scroll_start_pos = response.interact_pointer_pos(); + self.scroll_start_spacing = None; } } - // Handle two-finger pan (translation during pinch) - if self.chart_options.handle_scroll.enabled - && self.chart_options.handle_scroll.horz_touch_drag - && translation_delta.x.abs() > 0.5 - { - self.pending_scroll_time = None; - self.state - .time_scale_mut() - .scroll_pixels(translation_delta.x); - } + // The vertical part of the two-finger pan moves a manual price range. if self.chart_options.handle_scroll.enabled && self.chart_options.handle_scroll.vert_touch_drag && self.last_rendered_price_rect.height() > 0.0 && self.state.price_scale().is_manual() - && translation_delta.y.abs() > 0.5 + && translation_delta.y != 0.0 + && anchor.is_none_or(|pos| !self.in_other_pane(pos)) { - let y = hover_pos.map_or(0.0, |pos| pos.y); + let y = anchor.map_or(0.0, |pos| pos.y); let map = self.last_price_map; let shift = map.y_to_scale(y - translation_delta.y) - map.y_to_scale(y); let range = self.state.price_scale().range(); @@ -252,7 +345,7 @@ impl Chart { } } - /// Handle drag-to-pan, price-axis scaling, and time-axis drag-zoom. + /// Handle drag-to-pan and time-axis drag-zoom. /// /// When the drag starts on the main chart area, horizontal movement pans the /// time axis and vertical movement pans the price axis, switching it to manual @@ -270,13 +363,15 @@ impl Chart { ) { // CRITICAL: Skip panning if box zoom is active (right-click drag) let box_zoom_active = self.box_zoom.active; - let (is_touch, multi_touch) = ui.input(|i| { + // The frame clock times the samples, as it times the input they come from. + let (is_touch, multi_touch, now) = ui.input(|i| { ( i.any_touches() || i.events .iter() .any(|event| matches!(event, Event::Touch { .. })), i.multi_touch().is_some(), + i.time, ) }); @@ -290,6 +385,11 @@ impl Chart { && self.chart_options.kinetic_scroll.mouse }; + // A press, a click or a touch on the chart stops the momentum of an earlier flick. + if response.is_pointer_button_down_on() || response.clicked() { + self.kinetic_scroll.is_active = false; + } + if !response.dragged() || multi_touch || has_active_drawing_tool || box_zoom_active { // Drag ended - handle kinetic scrolling if response.drag_stopped() @@ -298,6 +398,16 @@ impl Chart { && kinetic && self.scroll_start_pos.is_some() { + // A pointer that came to rest before the release throws nothing. + let moving = |last: Option| last.is_some_and(|last| now - last <= 0.05); + // Frames slower than that rest leave the release to carry the pointer's last + // movement itself. Faster frames have measured the speed over a whole frame, + // which a release that arrives part way through its own would understate. + if !moving(self.kinetic_scroll.last_time) + && let Some(pos) = response.interact_pointer_pos() + { + self.sample_kinetic_speed(pos, now); + } let move_distance = self .kinetic_scroll .last_pos @@ -307,13 +417,14 @@ impl Chart { let min_v_px_s = self.chart_options.kinetic_scroll.min_scroll_speed * 60.0; let max_v_px_s = self.chart_options.kinetic_scroll.max_scroll_speed * 60.0; - if move_distance >= self.chart_options.kinetic_scroll.scroll_min_move + if moving(self.kinetic_scroll.last_time) + && move_distance >= self.chart_options.kinetic_scroll.scroll_min_move && self.kinetic_scroll.velocity.abs() >= min_v_px_s { self.kinetic_scroll.is_active = true; self.kinetic_scroll.velocity = self.kinetic_scroll.velocity.clamp(-max_v_px_s, max_v_px_s); - self.kinetic_scroll.anim_last_time = Some(Instant::now()); + self.kinetic_scroll.anim_last_time = Some(now); } } @@ -326,8 +437,13 @@ impl Chart { self.scroll_start_pos = None; self.scroll_start_offset = None; } + self.scroll_start_spacing = None; self.kinetic_scroll.last_pos = None; self.kinetic_scroll.last_time = None; + if !self.kinetic_scroll.is_active { + // Only a coast carries the speed of a drag past its release. + self.kinetic_scroll.velocity = 0.0; + } return; } @@ -346,36 +462,32 @@ impl Chart { ) { let origin = ui.input(|i| i.pointer.press_origin()).unwrap_or(start_pos); if price_axis_rect.contains(origin) { - if self.chart_options.handle_scale.enabled - && self - .chart_options - .handle_scale - .axis_pressed_mouse_move - .price - { - // Zoom by this frame's movement around the point where the drag began. - self.price_axis_drag = Some((origin.y, response.drag_delta().y)); - } + // The price axis reads its own drag. } else if time_axis_rect.contains(origin) { - if !self.chart_options.handle_scale.enabled { + let scale = self.chart_options.handle_scale; + if !scale.enabled || !scale.axis_pressed_mouse_move.time { + // Rebase while disabled so re-enabling does not replay the blocked movement. self.scroll_start_pos = Some(curr_pos); + self.scroll_start_offset = Some(self.state.time_scale().right_offset_precise()); + self.scroll_start_spacing = None; return; } - if self.chart_options.handle_scale.axis_pressed_mouse_move.time { - let dx = curr_pos.x - start_pos.x; - if dx.abs() > 0.1 { - let zoom_point_x = curr_pos.x - chart_rect_min_x; - let zoom_scale = (dx / 100.0).signum() * (dx / 100.0).abs().min(1.0); - let chart_width = time_axis_rect.width(); - self.state.time_scale_mut().zoom( - zoom_scale, - zoom_point_x, - chart_rect_min_x, - chart_width, - ); - self.scroll_start_pos = Some(curr_pos); - } - } + // Zoom the view the drag began with by the whole movement since, around the bar + // that was pressed: the spacing grows e times per 1000 points whatever frames + // the drag spans, and coming back restores the view. + let time_scale = self.state.time_scale_mut(); + let spacing = *self + .scroll_start_spacing + .get_or_insert(time_scale.bar_spacing()); + time_scale.set_bar_spacing(spacing); + time_scale.set_right_offset(start_offset); + // TimeScale::zoom applies one tenth of its delta. + time_scale.zoom( + ((curr_pos.x - start_pos.x) / 1000.0).min(80.0).exp_m1() * 10.0, + origin.x - chart_rect_min_x, + chart_rect_min_x, + time_axis_rect.width(), + ); } else { let scroll = self.chart_options.handle_scroll; if !scroll.enabled { @@ -402,17 +514,7 @@ impl Chart { self.state.time_scale_mut().set_right_offset(new_offset); if kinetic { - let now = Instant::now(); - if let (Some(last_pos), Some(last_time)) = - (self.kinetic_scroll.last_pos, self.kinetic_scroll.last_time) - { - let dt = now.duration_since(last_time).as_secs_f32(); - if dt > 0.0 { - self.kinetic_scroll.velocity = (curr_pos.x - last_pos.x) / dt; - } - } - self.kinetic_scroll.last_pos = Some(curr_pos); - self.kinetic_scroll.last_time = Some(now); + self.sample_kinetic_speed(curr_pos, now); } } @@ -441,6 +543,24 @@ impl Chart { } } + /// Measures the drag speed from the pointer at `pos` at frame time `now`. A resting pointer + /// adds no sample, so the age of the last one tells a release how long ago it moved. + fn sample_kinetic_speed(&mut self, pos: Pos2, now: f64) { + if self.kinetic_scroll.last_pos == Some(pos) { + return; + } + if let (Some(last_pos), Some(last_time)) = + (self.kinetic_scroll.last_pos, self.kinetic_scroll.last_time) + { + let dt = (now - last_time) as f32; + if dt > 0.0 { + self.kinetic_scroll.velocity = (pos.x - last_pos.x) / dt; + } + } + self.kinetic_scroll.last_pos = Some(pos); + self.kinetic_scroll.last_time = Some(now); + } + /// Advance the kinetic scrolling animation by one frame. /// /// Applies the current velocity to the right-offset, then damps the velocity @@ -461,13 +581,11 @@ impl Chart { return; } - let now = Instant::now(); - let dt = if let Some(t0) = self.kinetic_scroll.anim_last_time { - now.duration_since(t0).as_secs_f32().max(0.0) - } else { - self.kinetic_scroll.anim_last_time = Some(now); - 0.0 - }; + let now = ui.input(|i| i.time); + let dt = self + .kinetic_scroll + .anim_last_time + .map_or(0.0, |t0| (now - t0).max(0.0) as f32); self.kinetic_scroll.anim_last_time = Some(now); if dt > 0.0 { @@ -497,37 +615,23 @@ impl Chart { ui.ctx().request_repaint(); } - /// Reset axes on double-click: time axis jumps to latest, price axis re-enables auto-scale. - pub(crate) fn handle_double_click( - &mut self, - response: &Response, - price_axis_rect: Rect, - time_axis_rect: Rect, - ) { + /// Reset the time axis on double-click: it returns to the configured spacing at the latest + /// bar. The price axis is left to [`Self::price_axis_gestures`]. + pub(crate) fn handle_double_click(&mut self, response: &Response, time_axis_rect: Rect) { if !self.chart_options.handle_scale.enabled || !response.double_clicked() { return; } - if let Some(pos) = response.interact_pointer_pos() { - if self.chart_options.handle_scale.axis_double_click_reset.time - && time_axis_rect.contains(pos) - { - // Spacing first: a pixel right offset is converted at the restored spacing. - self.state - .time_scale_mut() - .set_bar_spacing(self.chart_options.time_scale.bar_spacing); - self.state.time_scale_mut().jump_to_latest(); - self.pending_scroll_time = None; - } - if self - .chart_options - .handle_scale - .axis_double_click_reset - .price - && price_axis_rect.contains(pos) - { - self.state.price_scale_mut().reset(); - } + if let Some(pos) = response.interact_pointer_pos() + && self.chart_options.handle_scale.axis_double_click_reset.time + && time_axis_rect.contains(pos) + { + // Spacing first: a pixel right offset is converted at the restored spacing. + self.state + .time_scale_mut() + .set_bar_spacing(self.chart_options.time_scale.bar_spacing); + self.state.time_scale_mut().jump_to_latest(); + self.pending_scroll_time = None; } } @@ -611,12 +715,14 @@ impl Chart { time_scale.coord_to_idx_precise((min_x + max_x) / 2.0, chart_rect.min.x, chart_width); let center = time_scale.position(center_idx); let old = time_scale.bar_spacing(); - time_scale.set_bar_spacing((old * chart_width / (max_x - min_x)).min(chart_width.max(old))); - // The inverse of `coord_to_idx` at the middle of the width. + time_scale.set_bar_spacing( + (old * (chart_width - 1.0) / (max_x - min_x)).min((chart_width - 1.0).max(old)), + ); + // The inverse of `coord_to_idx` at the middle of the plot's pixel span. let spacing = time_scale.bar_spacing(); let base_idx = time_scale.base_idx() as f64; time_scale.set_right_offset( - center - base_idx + (f64::from(chart_width) / 2.0 - 1.0) / f64::from(spacing) - 0.5, + center - base_idx + (f64::from(chart_width) - 1.0) / 2.0 / f64::from(spacing) - 0.5, ); // Vertical zoom: the box's prices, in the units of the window it selects, whose first @@ -643,43 +749,15 @@ impl Chart { true // Zoom successfully applied } - /// Apply deferred price-axis zoom from mouse wheel or price-axis drag. - /// - /// Called after all input processing to avoid mutable borrow conflicts. A - /// drag movement of `dy` points scales the range by `exp(dy / height)`, so a - /// drag zooms by the same amount however many frames it spans. Wheel input - /// uses the opposite sign so positive points narrow the price range. - pub(crate) fn apply_price_zoom( - &mut self, - pending_price_zoom: Option, - response: &Response, - price_rect: Rect, - transform: PriceTransform, - ) { - let wheel = pending_price_zoom - .map(|dy| -dy) - .zip(response.hover_pos().map(|p| p.y)); - let drag = self.price_axis_drag.take().map(|(y, dy)| (dy, y)); - for (dy, anchor_y) in wheel.into_iter().chain(drag) { - let scale = self.state.price_scale(); - let anchor = scale - .map(transform, price_rect.min.y, price_rect.max.y) - .y_to_scale(anchor_y); - let factor = (dy as f64 / price_rect.height() as f64).exp(); - self.state.price_scale_mut().zoom(factor, anchor); - } - } - /// Apply pending timescale configuration: width, initial visible bars, /// lock-on-resize behavior, and pending start-index jumps. pub(crate) fn apply_timescale_config(&mut self, chart_width: f32) { // Hidden or collapsed layouts cannot establish a zoom or a resize baseline. - if !chart_width.is_finite() || chart_width <= 1.0 { + if !chart_width.is_finite() || chart_width < 2.0 { return; } - self.state.time_scale_mut().set_width(chart_width); - if self.apply_visible_bars_once { + self.state.time_scale_mut().set_width(chart_width); if let Some(desired) = self.desired_visible_bars && desired > 0 { @@ -695,10 +773,15 @@ impl Chart { .time_scale .lock_visible_time_range_on_resize && let Some(prev_width) = self.prev_width - && (chart_width - prev_width).abs() > 1.0 + && chart_width != prev_width { - let spacing = self.state.time_scale().bar_spacing() * chart_width / prev_width; - self.state.time_scale_mut().set_bar_spacing(spacing); + // Sets the new width with the rescaled spacing, so a fixed edge never clamps + // against the new width at the old spacing. + self.state + .time_scale_mut() + .keep_slots_on_resize(prev_width, chart_width); + } else { + self.state.time_scale_mut().set_width(chart_width); } self.prev_width = Some(chart_width); @@ -722,7 +805,7 @@ impl Chart { .as_ref() .is_some_and(|link| !link.paging_stopped); let scale = self.state.time_scale_mut(); - let half_window = (chart_width / scale.bar_spacing() - 1.0) / 2.0; + let half_window = ((chart_width - 1.0) / scale.bar_spacing() - 1.0) / 2.0; scale.set_right_offset( scale.position(index as f64) - scale.base_idx() as f64 + f64::from(half_window), ); @@ -735,7 +818,7 @@ impl Chart { if let Some(target_start) = self.pending_start_idx.take() { let bar_spacing = self.state.time_scale().bar_spacing(); if bar_spacing > 0.0 { - let visible_len = chart_width / bar_spacing; + let visible_len = (chart_width - 1.0) / bar_spacing; let base_idx = self.state.time_scale().base_idx() as f64; let desired_right_border = self.state.time_scale().position(target_start as f64) + f64::from(visible_len) @@ -755,17 +838,18 @@ mod tests { use crate::widget::test_frames::{chart, frame}; use egui::{Event, Modifiers, PointerButton, Pos2, Rect}; - /// Invalid damping falls back at both option entry points and the animation still ends. + /// Invalid damping falls back at both option entry points and the animation still ends; + /// under the defaults a flick keeps its speed and settles in under two seconds. #[test] fn kinetic_damping_options_decay_to_a_stop() { for runtime in [false, true] { for (coefficient, expected) in [ - (f32::NAN, 0.997), - (f32::INFINITY, 0.997), - (f32::NEG_INFINITY, 0.997), - (-0.5, 0.997), - (1.0, 0.997), - (1.5, 0.997), + (f32::NAN, 0.95), + (f32::INFINITY, 0.95), + (f32::NEG_INFINITY, 0.95), + (-0.5, 0.95), + (1.0, 0.95), + (1.5, 0.95), (0.0, 0.0), (0.5, 0.5), (0.997, 0.997), @@ -783,10 +867,9 @@ mod tests { frame(&ctx, &mut chart, 0.0, vec![]); chart.kinetic_scroll.is_active = true; chart.kinetic_scroll.velocity = 600.0; - // At the default damping, 600 * 0.997^(40 * 60) < 12 px/s. + chart.kinetic_scroll.anim_last_time = Some(0.0); + // At the slowest damping here, 600 * 0.997^(40 * 60) < 12 points per second. for i in 1..=40 { - chart.kinetic_scroll.anim_last_time = - Some(web_time::Instant::now() - std::time::Duration::from_secs(1)); frame(&ctx, &mut chart, f64::from(i), vec![]); assert!(chart.state.time_scale().right_offset_precise().is_finite()); } @@ -798,6 +881,38 @@ mod tests { assert_eq!(chart.chart_options().kinetic_scroll.damping_coeff, expected); } } + + // A drag of 20 points every 10 ms is released at 2000 points per second, under the + // default limit of 3000. At 60 frames per second each frame keeps 0.95 of the speed, + // and 2000 * 0.95^100 = 11.8 is the first below the minimum of 12 points per second. + let ctx = egui::Context::default(); + let mut chart = chart(&[95.0], &[105.0]); + chart.chart_options.kinetic_scroll.mouse = true; + frame(&ctx, &mut chart, 0.0, vec![]); + let start = chart.last_rendered_price_rect.center(); + let button = |pos, pressed| Event::PointerButton { + pos, + button: PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }; + frame(&ctx, &mut chart, 0.01, vec![Event::PointerMoved(start)]); + frame(&ctx, &mut chart, 0.02, vec![button(start, true)]); + let mut end = start; + for i in 1..=4 { + end.x = start.x + 20.0 * i as f32; + let time = 0.02 + f64::from(i) * 0.01; + frame(&ctx, &mut chart, time, vec![Event::PointerMoved(end)]); + } + frame(&ctx, &mut chart, 0.07, vec![button(end, false)]); + assert!(chart.kinetic_scroll.is_active); + let speed = chart.kinetic_scroll.velocity; + assert!((speed - 2000.0).abs() < 1.0, "released at {speed}"); + let frames = (1..=1200).find(|&i| { + frame(&ctx, &mut chart, 0.07 + f64::from(i) / 60.0, vec![]); + !chart.kinetic_scroll.is_active + }); + assert_eq!(frames, Some(100)); } /// Invalid motion and a disabled scroll group stop momentum without changing the viewport. @@ -818,9 +933,7 @@ mod tests { let offset = chart.state.time_scale().right_offset_precise(); chart.kinetic_scroll.is_active = true; chart.kinetic_scroll.velocity = velocity; - chart.kinetic_scroll.anim_last_time = elapsed.map(|seconds| { - web_time::Instant::now() - std::time::Duration::from_secs_f32(seconds) - }); + chart.kinetic_scroll.anim_last_time = elapsed.map(|seconds| 0.05 - seconds); chart.chart_options.handle_scroll.enabled = enabled; frame(&ctx, &mut chart, 0.05, vec![]); assert!(!chart.kinetic_scroll.is_active, "velocity={velocity}"); @@ -833,21 +946,27 @@ mod tests { } } - /// Native zoom and contact pinch each scale once, retaining the bar under the pointer. + /// Native zoom and contact pinch each scale once: a native zoom keeps the bar under the + /// pointer, and a pinch keeps the bars under both fingers. #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[cfg_attr(not(target_arch = "wasm32"), test)] fn native_and_contact_pinch_keep_the_zoom_anchor() { + // Contacts are how far each finger moves while they spread from 100 to 150 points + // apart: the first rests, both move or the second rests. + let (first_rests, both_move, second_rests) = ([0.0, 50.0], [-25.0, 25.0], [-50.0, 0.0]); for (contacts, native, enabled, tracking, kinetic, maximized, group_enabled) in [ - (false, true, true, false, false, false, true), - (true, false, true, false, false, false, true), - (true, true, true, false, false, false, true), - (false, true, false, false, false, false, true), - (false, true, true, true, false, false, true), - (false, true, true, false, true, false, true), - (false, true, true, false, false, true, true), - (true, false, true, false, false, true, true), - (false, true, true, false, false, false, false), - (true, false, true, false, false, false, false), + (None, true, true, false, false, false, true), + (Some(first_rests), false, true, false, false, false, true), + (Some(both_move), false, true, false, false, false, true), + (Some(second_rests), false, true, false, false, false, true), + (Some(both_move), true, true, false, false, false, true), + (None, true, false, false, false, false, true), + (None, true, true, true, false, false, true), + (None, true, true, false, true, false, true), + (None, true, true, false, false, true, true), + (Some(first_rests), false, true, false, false, true, true), + (None, true, true, false, false, false, false), + (Some(second_rests), false, true, false, false, false, false), ] { let ctx = egui::Context::default(); let mut chart = chart(&[95.0, 100.0], &[105.0, 110.0]); @@ -879,14 +998,21 @@ mod tests { pos: Pos2::new(x, pointer.y), force: None, }; - if contacts { + // A backend keeps the pointer on the first finger. + if contacts.is_some() { frame( &ctx, &mut chart, 0.04, vec![ - touch(1, egui::TouchPhase::Start, pointer.x - 50.0), - touch(2, egui::TouchPhase::Start, pointer.x + 50.0), + Event::PointerButton { + pos: pointer, + button: PointerButton::Primary, + pressed: true, + modifiers: Modifiers::NONE, + }, + touch(1, egui::TouchPhase::Start, pointer.x), + touch(2, egui::TouchPhase::Start, pointer.x + 100.0), ], ); } @@ -897,14 +1023,15 @@ mod tests { chart.chart_options.kinetic_scroll.enabled = true; chart.kinetic_scroll.is_active = true; chart.kinetic_scroll.velocity = 120.0; - chart.kinetic_scroll.anim_last_time = Some(web_time::Instant::now()); + chart.kinetic_scroll.anim_last_time = Some(0.04); } let (spacing, offset) = chart.get_time_scale_state(); let mut events = Vec::new(); - if contacts { + if let Some([first, second]) = contacts { events.extend([ - touch(1, egui::TouchPhase::Move, pointer.x - 75.0), - touch(2, egui::TouchPhase::Move, pointer.x + 75.0), + Event::PointerMoved(Pos2::new(pointer.x + first, pointer.y)), + touch(1, egui::TouchPhase::Move, pointer.x + first), + touch(2, egui::TouchPhase::Move, pointer.x + 100.0 + second), ]); } if native { @@ -917,11 +1044,20 @@ mod tests { let expected_spacing = if enabled { spacing * 1.5 } else { spacing }; assert!( (zoomed - expected_spacing).abs() < 1e-5, - "contacts={contacts}, native={native}, enabled={enabled}: {zoomed}" + "contacts={contacts:?}, native={native}, enabled={enabled}: {zoomed}" ); + // The bar under the fingers' midpoint follows it, and the other bars spread around + // it by the pinch ratio; a native zoom turns about the pointer, which stays. + let (from, to) = contacts.map_or((pointer.x, pointer.x), |[first, second]| { + (pointer.x + 50.0, pointer.x + 50.0 + (first + second) / 2.0) + }); let expected_offset = - offset + (rect.right() - pointer.x - 1.0) * (1.0 / zoomed - 1.0 / spacing); - assert!((moved - expected_offset).abs() < 1e-4); + offset + (rect.right() - to - 1.0) / zoomed - (rect.right() - from - 1.0) / spacing; + assert!( + (moved - expected_offset).abs() < 1e-4, + "contacts={contacts:?}, native={native}, enabled={enabled}: {moved}, expected \ + {expected_offset}" + ); frame(&ctx, &mut chart, 0.08, vec![]); assert_eq!(chart.get_time_scale_state(), (zoomed, moved)); if tracking { @@ -1192,7 +1328,7 @@ mod tests { show(&mut chart, 1064.0); let width = chart.last_rendered_price_rect.width(); let scale = chart.state.time_scale(); - let spacing = width / 100.0; + let spacing = (width - 1.0) / 100.0; assert!((scale.bar_spacing() - spacing).abs() < 1e-5); let offset = pixels.map_or(2.5, |px| px / spacing); assert!((scale.right_offset() - offset).abs() < 1e-5); @@ -1202,19 +1338,24 @@ mod tests { show(&mut chart, 1064.0); assert!((chart.state.time_scale().bar_spacing() - spacing).abs() < 1e-5); assert_eq!(chart.state.time_scale().right_offset(), -20.0); - show(&mut chart, 1564.0); - let expected = if lock { - chart.last_rendered_price_rect.width() / 100.0 - } else { - spacing - }; - assert!((chart.state.time_scale().bar_spacing() - expected).abs() < 1e-5); - assert_eq!(chart.state.time_scale().right_offset(), -20.0); + // A locked resize keeps the `width - 1` pixels of slots the plot spans, also when + // the window grows by less than a pixel per frame. + for step in 0..=20 { + show(&mut chart, 1564.0 + 0.5 * step as f32); + let expected = if lock { + (chart.last_rendered_price_rect.width() - 1.0) / 100.0 + } else { + spacing + }; + let actual = chart.state.time_scale().bar_spacing(); + assert!((actual - expected).abs() < 1e-5, "step={step}"); + assert_eq!(chart.state.time_scale().right_offset(), -20.0); + } chart.set_visible_bars(80); show(&mut chart, 1264.0); assert!( (chart.state.time_scale().bar_spacing() - - chart.last_rendered_price_rect.width() / 80.0) + - (chart.last_rendered_price_rect.width() - 1.0) / 80.0) .abs() < 1e-5, "a pending view must take precedence over a locked resize" @@ -1223,6 +1364,43 @@ mod tests { } } + /// A locked resize at the fixed left edge's stop keeps the first bar at the left edge. + #[test] + fn locked_resize_at_the_left_edge_stop_keeps_the_first_bar() { + let ctx = egui::Context::default(); + let mut chart = chart(&[95.0], &[105.0]).visible_bars(50); + let options = &mut chart.chart_options.time_scale; + options.lock_visible_time_range_on_resize = true; + options.fix_left_edge = true; + let options = chart.chart_options.clone(); + chart = chart.with_chart_options(options); + let show = |chart: &mut Chart, width| { + ctx.run_ui( + egui::RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(width, 600.0))), + ..Default::default() + }, + |ui| { + chart.show(ui); + }, + ) + .drop_without_applying_deltas(); + }; + show(&mut chart, 1064.0); + chart.scroll_to_position(-1000.0, false); + for width in [1064.0, 1364.0, 1364.5, 864.0] { + show(&mut chart, width); + let scale = chart.state.time_scale(); + let left = scale.visible_logical_range().left; + assert!(left.abs() < 1e-4, "width={width}: left={left}"); + let spacing = (chart.last_rendered_price_rect.width() - 1.0) / 50.0; + assert!( + (scale.bar_spacing() - spacing).abs() < 1e-4, + "width={width}" + ); + } + } + /// Drags down by 100 points in `steps` frames from the point `start` picks given the price pane. fn drag_down(chart: &mut Chart, start: fn(Rect) -> Pos2, steps: usize, touch: bool) { let ctx = egui::Context::default(); @@ -1287,7 +1465,8 @@ mod tests { (range.min, range.max) } - /// Positive wheel input zooms in on either axis, retaining its anchor and permissions. + /// Positive wheel input zooms in on the time scale or on the price axis under the pointer, + /// retaining its anchor and permissions and leaving every other scale alone. /// Ctrl/Cmd wheel and point-based trackpad input follow the same direction. #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[cfg_attr(not(target_arch = "wasm32"), test)] @@ -1318,15 +1497,20 @@ mod tests { ) .drop_without_applying_deltas(); }; - for (modifiers, right_bar_stays, fraction, group_enabled) in [ - (Modifiers::NONE, false, 0.25, true), - (Modifiers::NONE, false, 0.25, false), - (Modifiers::CTRL, false, 0.75, true), - (Modifiers::COMMAND, false, 0.75, true), - (Modifiers::COMMAND, false, 0.75, false), - (Modifiers::NONE, true, 0.25, true), + for (modifiers, right_bar_stays, fraction, group_enabled, wheel_enabled) in [ + (Modifiers::NONE, false, 0.25, true, true), + (Modifiers::NONE, false, 0.25, false, true), + (Modifiers::NONE, false, 0.25, true, false), + (Modifiers::CTRL, false, 0.75, true, true), + (Modifiers::COMMAND, false, 0.75, true, true), + (Modifiers::COMMAND, false, 0.75, false, true), + (Modifiers::NONE, true, 0.25, true, true), ] { - for price in [false, true] { + // The plot, the main price axis, a study pane's axis and an added series' axis. + for target in ["plot", "price", "pane", "series"] { + let price = target != "plot"; + let enabled = group_enabled && wheel_enabled; + let key = crate::model::SeriesScale::Separate(1); for delta in [-1.0_f32, 1.0] { for (unit, source) in [ (egui::MouseWheelUnit::Line, egui::MouseWheelSource::Wheel), @@ -1336,26 +1520,72 @@ mod tests { ), ] { let case = format!( - "{modifiers:?}, price={price}, delta={delta}, unit={unit:?}, enabled={group_enabled}, width={width}" + "{modifiers:?}, target={target}, delta={delta}, unit={unit:?}, enabled={enabled}, width={width}" ); let time = ctx.input(|input| input.time) + 1.0; let mut chart = chart(&[95.0, 100.0], &[105.0, 110.0]); + match target { + "pane" => { + chart.add_indicator(Box::new( + crate::studies::CustomIndicator::new("Pane", |bars| { + vec![ + crate::studies::IndicatorValue::Single(50.0); + bars.len() + ] + }) + .with_overlay(false), + )); + } + "series" => { + let series = chart.add_series(crate::widget::SeriesOptions { + scale: key, + ..Default::default() + }); + chart.set_data(series, chart.state.data().bars.clone()); + } + _ => {} + } chart.set_theme(&ctx, &theme); chart.chart_options.handle_scale.enabled = group_enabled; + chart.chart_options.handle_scale.mouse_wheel = wheel_enabled; chart.chart_options.handle_scroll.enabled = !group_enabled; chart.chart_options.time_scale.right_bar_stays_on_scroll = right_bar_stays; chart.state.price_scale_mut().set_range(90.0, 110.0); frame(&ctx, &mut chart, time, Vec::new()); + // The pointed scale shows a manual range 20 wide from `low`. + let low = match target { + "pane" => { + chart.pane_layout.panes[1].scale.set_range(40.0, 60.0); + 40.0 + } + "series" => { + let pane = chart.main_series_pane(); + chart.pane_price_scale_mut(pane, key).set_range(90.0, 110.0); + 90.0 + } + _ => 90.0, + }; + let pointed = |chart: &Chart| match target { + "pane" => chart.pane_layout.panes[1].scale.range(), + "series" => chart.series_scales[&key].range(), + _ => chart.state.price_scale().range(), + }; let (spacing, offset) = chart.get_time_scale_state(); let rect = chart.last_rendered_price_rect; + // The height the pointed scale is drawn over. + let axis = if target == "pane" { + chart.pane_layout.panes[1].rect + } else { + rect + }; let pointer = Pos2::new( - if price { - rect.right() + 10.0 - } else { - rect.left() + rect.width() * fraction + match target { + "plot" => rect.left() + rect.width() * fraction, + "series" => rect.left() - 10.0, + _ => rect.right() + 10.0, }, - rect.top() + rect.height() * fraction, + axis.top() + axis.height() * fraction, ); frame( &ctx, @@ -1363,8 +1593,8 @@ mod tests { time + 0.02, vec![Event::PointerMoved(pointer)], ); - let anchor_price = - 110.0 - 20.0 * f64::from((pointer.y - rect.top()) / rect.height()); + let anchor_price = low + 20.0 + - 20.0 * f64::from((pointer.y - axis.top()) / axis.height()); let wheel = Event::MouseWheel { unit, delta: egui::vec2(0.0, delta), @@ -1377,22 +1607,27 @@ mod tests { frame(&ctx, &mut chart, time + i as f64 * 0.02, Vec::new()); } let (zoomed, moved) = chart.get_time_scale_state(); - let range = chart.state.price_scale().range(); - if price && group_enabled { + let range = pointed(&chart); + let main = chart.state.price_scale().range(); + if price && enabled { let span = range.max - range.min; assert_eq!(span < 20.0, delta > 0.0, "{case}: {range:?}"); assert!((span - 20.0).abs() > 1e-6, "{case}"); // Affine range scaling keeps the pointed value at its original fraction. let anchored = range.max - - span * f64::from((pointer.y - rect.top()) / rect.height()); + - span * f64::from((pointer.y - axis.top()) / axis.height()); assert!( - (anchored - anchor_price).abs() < 1e-6, + (anchored - anchor_price).abs() < 1e-5, "{case}: anchor {anchored}, expected {anchor_price}" ); assert_eq!((zoomed, moved), (spacing, offset), "{case}"); + if target != "price" { + assert_eq!((main.min, main.max), (90.0, 110.0), "{case}"); + } } else { - assert_eq!((range.min, range.max), (90.0, 110.0), "{case}"); - if group_enabled { + assert_eq!((range.min, range.max), (low, low + 20.0), "{case}"); + assert_eq!((main.min, main.max), (90.0, 110.0), "{case}"); + if enabled { assert_eq!( zoomed > spacing, delta > 0.0, @@ -1402,11 +1637,7 @@ mod tests { } else { assert_eq!((zoomed, moved), (spacing, offset), "{case}"); } - assert_eq!( - moved == offset, - right_bar_stays || !group_enabled, - "{case}" - ); + assert_eq!(moved == offset, right_bar_stays || !enabled, "{case}"); let anchor = if right_bar_stays { rect.right() - 1.0 } else { @@ -1514,7 +1745,9 @@ mod tests { /// Axis resets follow both permissions; the time reset restores spacing and a pixel offset. #[test] fn axis_resets_respect_permissions_and_configured_right_offset() { - for target in ["time", "price", "pane"] { + let key = crate::model::SeriesScale::Separate(1); + // The time axis, the main price axis, a study pane's axis and an added series' axis. + for target in ["time", "price", "pane", "series"] { for individual in [false, true] { let ctx = egui::Context::default(); let options = crate::config::ChartOptions { @@ -1534,6 +1767,13 @@ mod tests { .with_overlay(false), )); } + if target == "series" { + let series = chart.add_series(crate::widget::SeriesOptions { + scale: key, + ..Default::default() + }); + chart.set_data(series, chart.state.data().bars.clone()); + } chart.chart_options.handle_scroll.enabled = false; chart .chart_options @@ -1556,6 +1796,11 @@ mod tests { rect.bottom().max(chart.last_rendered_volume_rect.bottom()) + 5.0, ), "price" => Pos2::new(rect.right() + 10.0, rect.center().y), + "series" => { + let pane = chart.main_series_pane(); + chart.pane_price_scale_mut(pane, key).set_range(90.0, 110.0); + Pos2::new(rect.left() - 10.0, rect.center().y) + } _ => { chart.pane_layout.panes[1].scale.set_range(40.0, 60.0); let pane = &chart.get_rendered_indicator_panes()[0]; @@ -1595,6 +1840,7 @@ mod tests { ); } "price" => assert_eq!(chart.state.price_scale().is_manual(), !reset), + "series" => assert_eq!(chart.series_scales[&key].is_manual(), !reset), _ => assert_eq!(chart.pane_layout.panes[1].scale.is_manual(), !reset), } let reset = chart.chart_options.handle_scale.axis_double_click_reset; @@ -1723,8 +1969,8 @@ mod tests { ); let after = chart.get_time_scale_state(); if time_axis { - // The time-axis sensitivity scales spacing by 1 + (dx/100)*0.1. - assert!((after.0 - before.0 * 1.01).abs() < 1e-5); + // Ten points on the time axis scale the spacing by e^0.01 = 1.010050. + assert!((after.0 - before.0 * 1.010_05).abs() < 1e-5); } else { assert_eq!(after.0, before.0); assert!((after.1 - (before.1 - 10.0 / before.0)).abs() < 1e-5); @@ -1732,7 +1978,8 @@ mod tests { } } - /// Zoom speed must not depend on how many frames a drag spans. + /// Zoom speed must not depend on how many frames a drag spans, and the price that was + /// grabbed stays at its height. #[test] fn price_axis_drag_zoom_is_frame_independent() { for left in [false, true] { @@ -1745,6 +1992,91 @@ mod tests { "1 frame: {one:?}, 10 frames: {ten:?}" ); } + // The axis of an added series showing 90..110, grabbed a quarter of the way down at 105: + // 100 points down widen the range by e^(100 / height), a quarter of it above 105. + let key = crate::model::SeriesScale::Separate(1); + for steps in [1, 10] { + let mut chart = chart(&[95.0, 100.0], &[105.0, 110.0]); + let series = chart.add_series(crate::widget::SeriesOptions { + scale: key, + ..Default::default() + }); + chart.set_data(series, chart.state.data().bars.clone()); + let pane = chart.main_series_pane(); + chart.pane_price_scale_mut(pane, key).set_range(90.0, 110.0); + drag_down( + &mut chart, + |rect| Pos2::new(rect.left() - 10.0, rect.top() + rect.height() * 0.25), + steps, + false, + ); + let range = chart.series_scales[&key].range(); + let span = 20.0 * (100.0 / f64::from(chart.last_rendered_price_rect.height())).exp(); + assert!( + (range.max - range.min - span).abs() < 1e-4 + && (range.max - 105.0 - span * 0.25).abs() < 1e-4, + "{steps} frames: {range:?}, expected a span of {span}" + ); + } + } + + /// A drag on the time axis scales the bar spacing by e per 1000 points of its whole movement + /// around the bar that was pressed, however many frames it spans, and returning restores the view. + #[test] + fn time_axis_drag_zoom_is_frame_independent() { + // 300 points to the right in one frame and in ten, then out and back. + let mut views = Vec::new(); + for (steps, back) in [(1, false), (10, false), (10, true)] { + let ctx = egui::Context::default(); + let mut chart = chart(&[95.0, 100.0], &[105.0, 110.0]); + frame(&ctx, &mut chart, 0.0, vec![]); + let rect = chart.last_rendered_price_rect; + let start = Pos2::new( + rect.left() + rect.width() * 0.25, + rect.bottom().max(chart.last_rendered_volume_rect.bottom()) + 5.0, + ); + let (spacing, offset) = chart.get_time_scale_state(); + let button = |pos, pressed| Event::PointerButton { + pos, + button: PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }; + let out = (1..=steps).map(|step| 300.0 * step as f32 / steps as f32); + let path: Vec<_> = if back { + out.clone().chain(out.rev().skip(1)).chain([0.0]).collect() + } else { + out.collect() + }; + let mut events = vec![vec![Event::PointerMoved(start)], vec![button(start, true)]]; + events.extend( + path.iter() + .map(|dx| vec![Event::PointerMoved(start + egui::vec2(*dx, 0.0))]), + ); + let end = start + egui::vec2(*path.last().unwrap(), 0.0); + events.push(vec![button(end, false)]); + for (at, events) in events.into_iter().enumerate() { + frame(&ctx, &mut chart, 0.02 * (at + 1) as f64, events); + } + let (zoomed, moved) = chart.get_time_scale_state(); + if back { + assert_eq!((zoomed, moved), (spacing, offset)); + } else { + // e^0.3 = 1.349859. + assert!( + (zoomed - spacing * 1.349_859).abs() < 1e-5, + "{steps} frames: spacing {spacing} -> {zoomed}" + ); + let expected = + offset + (rect.right() - start.x - 1.0) * (1.0 / zoomed - 1.0 / spacing); + assert!( + (moved - expected).abs() < 1e-4, + "{steps} frames: offset {moved}, expected {expected}" + ); + views.push((zoomed, moved)); + } + } + assert_eq!(views[0], views[1], "1 frame against 10"); } /// With auto-scale off, the prices follow a drag on the chart: 100 points down moves the @@ -1893,12 +2225,26 @@ mod tests { } } - /// A fast horizontal drag continues after release only when inertia is enabled for its - /// device, and a new drag stops it. + /// A fast horizontal drag continues after release, at its speed, only when inertia is + /// enabled for its device and the pointer was still moving, and a new drag stops it. #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[cfg_attr(not(target_arch = "wasm32"), test)] fn released_drag_continues_under_its_device_inertia() { - for touch in [false, true] { + // The seconds from the last movement frame to the release, whether frames are drawn + // meanwhile, and how far the pointer has moved on when the release arrives. + for (touch, rest, frames, slide) in [ + (false, 0.02, false, 0.0), + (true, 0.02, false, 0.0), + (false, 0.04, true, 0.0), + (true, 0.04, true, 0.0), + (false, 0.5, false, 0.0), + (true, 0.5, false, 0.0), + (false, 0.5, true, 0.0), + (true, 0.5, true, 0.0), + (false, 0.1, false, 15.0), + (true, 0.1, false, 15.0), + (true, 0.02, false, 2.0), + ] { for (touch_inertia, mouse_inertia) in [(false, false), (true, false), (false, true), (true, true)] { @@ -1937,24 +2283,128 @@ mod tests { let events = input(Event::PointerMoved(end), egui::TouchPhase::Move, end); frame(&ctx, &mut chart, 0.04 + i as f64 * 0.02, events); } + let released = 0.12 + rest; + if frames { + for time in (1..).map(|i| 0.12 + f64::from(i) * 0.02) { + if time > released - 0.01 { + break; + } + frame(&ctx, &mut chart, time, vec![]); + } + } + end.x -= slide; let release = input(button(end, false), egui::TouchPhase::End, end); - frame(&ctx, &mut chart, 0.2, release); - let expected = if touch { touch_inertia } else { mouse_inertia }; + frame(&ctx, &mut chart, released, release); + let inertia = if touch { touch_inertia } else { mouse_inertia }; + // Only a rest of more than 50 ms ends the motion, whether or not frames were + // drawn, and a release that brings movement with it is no rest, however slow + // the frames. assert_eq!( - chart.kinetic_scroll.is_active, expected, - "touch={touch}, touch inertia={touch_inertia}, mouse inertia={mouse_inertia}" + chart.kinetic_scroll.is_active, + inertia && (rest <= 0.05 || slide > 0.0), + "touch={touch}, rest={rest}, frames={frames}, slide={slide}, touch \ + inertia={touch_inertia}, mouse inertia={mouse_inertia}" + ); + // The drag moved 15 points every 20 ms. A release within 50 ms continues at that + // speed, whatever part of its own frame's movement it brings, and a later one + // at the speed of the movement it brings. + let speed = if rest <= 0.05 { + -750.0 + } else { + -slide / rest as f32 + }; + assert!( + !chart.kinetic_scroll.is_active + || (chart.kinetic_scroll.velocity - speed).abs() < 1.0, + "touch={touch}, rest={rest}, slide={slide}: {}", + chart.kinetic_scroll.velocity ); let press = input(button(end, true), egui::TouchPhase::Start, end); - frame(&ctx, &mut chart, 0.22, press); + frame(&ctx, &mut chart, released + 0.02, press); end.x += 20.0; let events = input(Event::PointerMoved(end), egui::TouchPhase::Move, end); - frame(&ctx, &mut chart, 0.24, events); + frame(&ctx, &mut chart, released + 0.04, events); assert!(!chart.kinetic_scroll.is_active); } } } + /// A press, a click, a touch, the wheel and the pan and zoom keys each end a coast in the + /// frame they arrive, before it moves the view again. + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] + #[cfg_attr(not(target_arch = "wasm32"), test)] + fn press_wheel_and_keys_stop_a_coast() { + let button = |pos, pressed| Event::PointerButton { + pos, + button: PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }; + let wheel = |delta| Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: Modifiers::NONE, + }; + let key = |key, modifiers| Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers, + }; + for (input, stops) in [ + ("none", false), + ("press", true), + ("click", true), + ("touch", true), + ("wheel zoom", true), + ("wheel scroll", true), + ("pan key", true), + ("zoom key", true), + ] { + // The same input reaches a coasting chart and one at rest. + let [(coasting, moved), (_, rest)] = [true, false].map(|coast| { + let ctx = egui::Context::default(); + let mut chart = chart(&[95.0, 100.0], &[105.0, 110.0]); + chart.chart_options.kinetic_scroll.enabled = true; + frame(&ctx, &mut chart, 0.0, vec![]); + let pos = chart.last_rendered_price_rect.center(); + frame(&ctx, &mut chart, 0.02, vec![Event::PointerMoved(pos)]); + if coast { + chart.kinetic_scroll.is_active = true; + chart.kinetic_scroll.velocity = 600.0; + chart.kinetic_scroll.anim_last_time = Some(0.02); + } + let events = match input { + "none" => vec![], + "press" => vec![button(pos, true)], + "click" => vec![button(pos, true), button(pos, false)], + "touch" => vec![ + button(pos, true), + Event::Touch { + device_id: egui::TouchDeviceId(1), + id: egui::TouchId(1), + phase: egui::TouchPhase::Start, + pos, + force: None, + }, + ], + "wheel zoom" => vec![wheel(egui::vec2(0.0, -240.0))], + "wheel scroll" => vec![wheel(egui::vec2(120.0, 0.0))], + "pan key" => vec![key(egui::Key::ArrowLeft, Modifiers::NONE)], + _ => vec![key(egui::Key::ArrowUp, Modifiers::COMMAND)], + }; + frame(&ctx, &mut chart, 0.04, events); + (chart.kinetic_scroll.is_active, chart.get_time_scale_state()) + }); + assert_eq!(coasting, !stops, "{input}"); + assert_eq!(moved == rest, stops, "{input}: {moved:?}, at rest {rest:?}"); + } + } + /// Two contacts translate each enabled axis once, independently of pinch scaling. #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[cfg_attr(not(target_arch = "wasm32"), test)] @@ -2002,12 +2452,14 @@ mod tests { contact(2, egui::TouchPhase::Start, start + egui::vec2(100.0, 0.0)), ], ); - for step in 1..=2 { - let pos = start + egui::vec2(30.0, 30.0) * step as f32; + // The second step is under half a point: the fingers are followed however + // slowly they move. + for (step, moved) in [(1, 30.0), (2, 30.4)] { + let pos = start + egui::vec2(moved, moved); frame( &ctx, &mut chart, - 0.02 + step as f64 * 0.02, + 0.02 + f64::from(step) * 0.02, vec![ Event::PointerMoved(pos), contact(1, egui::TouchPhase::Move, pos), @@ -2015,7 +2467,7 @@ mod tests { ], ); } - let pos = start + egui::vec2(60.0, 60.0); + let pos = start + egui::vec2(30.4, 30.4); frame( &ctx, &mut chart, @@ -2026,7 +2478,7 @@ mod tests { pos + egui::vec2(100.0, 0.0), )], ); - let pos = start + egui::vec2(90.0, 90.0); + let pos = start + egui::vec2(60.4, 60.4); frame( &ctx, &mut chart, @@ -2036,9 +2488,9 @@ mod tests { contact(1, egui::TouchPhase::Move, pos), ], ); - let expected_offset = offset - if horizontal { 90.0 / spacing } else { 0.0 }; + let expected_offset = offset - if horizontal { 60.4 / spacing } else { 0.0 }; let shift = if vertical { - 20.0 * 90.0 / rect.height() as f64 + 20.0 * 60.4 / rect.height() as f64 } else { 0.0 }; @@ -2158,8 +2610,9 @@ mod tests { } else { before }; + // 100 points on the time axis scale the spacing by e^0.1 = 1.105171. let expected_spacing = if !price && axis { - spacing * 1.05 * 1.05 + spacing * 1.105_171 } else { spacing }; @@ -2219,7 +2672,8 @@ mod tests { let x = |idx| ts.idx_to_coord_precise(idx, rect.left(), rect.width()); let (x_left, x_right) = (x(left), x(right)); assert!( - (x_left - rect.left()).abs() < 0.5 && (x_right - rect.right()).abs() < 0.5, + (x_left - rect.left()).abs() < 0.01 + && (x_right - (rect.right() - 1.0)).abs() < 0.01, "{mode:?}: bars {left}..{right} at x {x_left}..{x_right}, pane {rect:?}" ); let after = chart.get_chart_mapping().price; @@ -2240,7 +2694,7 @@ mod tests { let (x, y) = (rect.center().x, rect.top() + 100.0); let (start, end) = (Pos2::new(x, y), Pos2::new(x + 25.0, y + 100.0)); assert!(one_bar.execute_box_zoom(start, end, rect, rect.width())); - assert_eq!(one_bar.state.time_scale().bar_spacing(), rect.width()); + assert_eq!(one_bar.state.time_scale().bar_spacing(), rect.width() - 1.0); // Invalid corners or width must leave both scales and zoom history unchanged. let view = one_bar.get_time_scale_state(); diff --git a/vendor/egui-charts/src/widget/pan_zoom/state.rs b/vendor/egui-charts/src/widget/pan_zoom/state.rs index 3c9ba84..9a5d54a 100644 --- a/vendor/egui-charts/src/widget/pan_zoom/state.rs +++ b/vendor/egui-charts/src/widget/pan_zoom/state.rs @@ -19,12 +19,12 @@ pub struct KineticScrollState { pub velocity: f32, /// Last pointer position during drag (for velocity calculation). pub last_pos: Option, - /// Timestamp of the last pointer sample. - pub last_time: Option, + /// Frame time of the last pointer sample, in seconds. + pub last_time: Option, /// Whether kinetic animation is currently running. pub is_active: bool, - /// Last animation frame time (for delta-time calculation). - pub anim_last_time: Option, + /// Frame time of the last animation step, in seconds (for delta-time calculation). + pub anim_last_time: Option, } impl Default for KineticScrollState { diff --git a/vendor/egui-charts/src/widget/pane/controls.rs b/vendor/egui-charts/src/widget/pane/controls.rs index dff16d9..01afffa 100644 --- a/vendor/egui-charts/src/widget/pane/controls.rs +++ b/vendor/egui-charts/src/widget/pane/controls.rs @@ -96,131 +96,19 @@ impl Chart { Sense::click_and_drag(), ) .on_hover_cursor(egui::CursorIcon::ResizeVertical); - if response.dragged() - && self.chart_options.handle_scale.enabled - && self - .chart_options - .handle_scale - .axis_pressed_mouse_move - .price - { - let anchor_y = ui - .input(|input| input.pointer.press_origin()) - .map_or(rect.center().y, |pos| pos.y); - let scale = self.pane_price_scale_mut(pane_id, key); - let map = scale.map(scale.transform(), rect.top(), rect.bottom()); - let anchor = map.transform().to_scale(map.y_to_price(anchor_y)); - scale.zoom( - (f64::from(response.drag_delta().y) / f64::from(rect.height())).exp(), - anchor, - ); + let gestures = self.price_axis_gestures(ui, &response, Rect::EVERYTHING); + if gestures.reset { + self.user_action(|chart| chart.pane_price_scale_mut(pane_id, key).reset()); ui.ctx().request_repaint(); } - if response.double_clicked() - && !self.pane_collapse_click(ui.ctx()) - && self.chart_options.handle_scale.enabled - && self - .chart_options - .handle_scale - .axis_double_click_reset - .price - { - self.user_action(|chart| chart.pane_price_scale_mut(pane_id, key).reset()); + // The pane is already painted: show the zoomed scale on the next frame. + if gestures.zoom( + self.pane_price_scale_mut(pane_id, key), + rect.top(), + rect.bottom(), + ) { ui.ctx().request_repaint(); } - response.context_menu(|ui| { - self.user_action(|chart| { - let scale = chart.pane_price_scale_mut(pane_id, key); - if ui - .selectable_label(!scale.is_manual(), l10n::text(ui.ctx(), "Auto scale")) - .clicked() - { - scale.reset(); - ui.close(); - } - ui.separator(); - use crate::scales::PriceScaleMode; - for mode in [ - PriceScaleMode::Normal, - PriceScaleMode::Logarithmic, - PriceScaleMode::Percentage, - PriceScaleMode::IndexedTo100, - ] { - if ui - .selectable_label( - scale.options().mode == mode, - l10n::text(ui.ctx(), mode.to_string()), - ) - .clicked() - { - scale.options_mut().mode = mode; - scale.reset(); - ui.close(); - } - } - ui.separator(); - if ui - .checkbox( - &mut scale.options_mut().invert_scale, - l10n::text(ui.ctx(), "Invert scale"), - ) - .changed() - { - ui.close(); - } - ui.separator(); - let options = chart.pane_axis_options(pane_id).expect("present pane"); - for (label, side) in [ - ("Axes on left", crate::model::AxisSide::Left), - ("Axes on right", crate::model::AxisSide::Right), - ] { - if ui - .selectable_label( - options.side == Some(side), - l10n::text(ui.ctx(), label), - ) - .clicked() - { - chart.set_pane_axis_options( - pane_id, - crate::model::PaneAxisOptions { - side: (options.side != Some(side)).then_some(side), - ..options - }, - ); - ui.close(); - } - } - ui.menu_button(l10n::text(ui.ctx(), "Join price scales"), |ui| { - for (label, side) in [ - ("At left edge", crate::model::AxisSide::Left), - ("At right edge", crate::model::AxisSide::Right), - ] { - if ui - .selectable_label(false, l10n::text(ui.ctx(), label)) - .clicked() - { - chart.merge_pane_scales(pane_id, side); - ui.close(); - } - } - }); - let mut hide_unused = options.hide_unused; - if ui - .checkbox(&mut hide_unused, l10n::text(ui.ctx(), "Hide unused axes")) - .changed() - { - chart.set_pane_axis_options( - pane_id, - crate::model::PaneAxisOptions { - hide_unused, - ..options - }, - ); - ui.close(); - } - }); - }); } } @@ -392,14 +280,16 @@ impl Chart { .or_else(|| self.series_pane(SeriesId::MAIN)); let above = pane_idx.checked_sub(1).map(|at| panes[at].id); let below = panes.get(pane_idx + 1).map(|pane| pane.id); + let [drawn_above, drawn_below] = + [false, true].map(|down| self.drawn_neighbour(pane_idx, down)); child.menu_button("...", |ui| { let members = self.pane_series(id); let editable = members.iter().all(|member| { !self.study_ids.contains(member) || self.indicator_user_edit_enabled(*member) }); for (label, enabled, command) in [ - ("Move pane up", above.is_some(), 0), - ("Move pane down", below.is_some(), 1), + ("Move pane up", drawn_above.is_some(), 0), + ("Move pane down", drawn_below.is_some(), 1), ( if collapsed { "Expand pane" @@ -465,8 +355,9 @@ impl Chart { self.begin_user_action(); } match action { - Some(0) => self.pane_layout.panes.swap(pane_idx, pane_idx - 1), - Some(1) => self.pane_layout.panes.swap(pane_idx, pane_idx + 1), + // Hidden panes in between keep their place next to the panes not moved. + Some(0) => self.pane_layout.panes[drawn_above.unwrap()..=pane_idx].rotate_right(1), + Some(1) => self.pane_layout.panes[pane_idx..=drawn_below.unwrap()].rotate_left(1), Some(2) => self.pane_layout.panes[pane_idx].collapsed = Some(!collapsed), Some(3 | 4) => { let target = if action == Some(3) { @@ -498,6 +389,17 @@ impl Chart { } } + /// The index of the nearest pane drawn below or above the pane at `at`. + fn drawn_neighbour(&self, at: usize, down: bool) -> Option { + let panes = &self.pane_layout.panes; + let drawn = |idx: &usize| self.pane_drawn(&panes[*idx]); + if down { + (at + 1..panes.len()).find(drawn) + } else { + (0..at).rev().find(drawn) + } + } + /// Separators between consecutive drawn panes, given top to bottom as the pane index, its /// panel rect and whether it is collapsed. pub(super) fn pane_separators(&mut self, ui: &mut Ui, panes: &[(usize, Rect, bool)]) { @@ -536,14 +438,24 @@ impl Chart { continue; } let response = response.on_hover_cursor(egui::CursorIcon::ResizeVertical); - if response.dragged() && !collapsed && !upper_collapsed { - let delta = response.drag_delta().y.clamp( - 40.0 - upper.height(), - (rect.height() - 40.0).max(40.0 - upper.height()), + // Heights follow the whole drag from the press, so movement past a limit is kept. + if response.drag_started() { + ui.data_mut(|data| data.insert_temp(response.id, (upper.height(), rect.height()))); + } + if response.dragged() + && !collapsed + && !upper_collapsed + && let Some(((upper_height, height), total)) = ui + .data(|data| data.get_temp::<(f32, f32)>(response.id)) + .zip(response.total_drag_delta()) + { + let delta = total.y.clamp( + 40.0 - upper_height, + (height - 40.0).max(40.0 - upper_height), ); // The other panes keep their heights: these two exchange pixels. - self.pane_layout.panes[upper_idx].height = Some(upper.height() + delta); - self.pane_layout.panes[idx].height = Some(rect.height() - delta); + self.pane_layout.panes[upper_idx].height = Some(upper_height + delta); + self.pane_layout.panes[idx].height = Some(height - delta); ui.ctx().request_repaint(); } if response.double_clicked() && !self.pane_collapse_click(ui.ctx()) { @@ -668,7 +580,16 @@ mod tests { #[test] fn pointer_command_double_click_collapses_and_restores_the_pointed_pane() { - for location in ["plot", "header", "axis", "price", "moved-price", "disabled"] { + for location in [ + "plot", + "header", + "axis", + "price", + "moved-price", + "disabled", + "maximized", + "maximized-price", + ] { for modifiers in [ Modifiers::CTRL.plus(Modifiers::COMMAND), Modifiers::MAC_CMD.plus(Modifiers::COMMAND), @@ -677,6 +598,9 @@ mod tests { let mut chart = crate::widget::test_frames::chart(&[100.0; 100], &[110.0; 100]); let study = chart.add_indicator(Box::new(crate::studies::RSI::new(14))); let study_pane = chart.series_pane(study).unwrap(); + if location.starts_with("maximized") { + chart.add_indicator(Box::new(crate::studies::RSI::new(7))); + } if location == "price" { chart.add_indicator(Box::new(crate::studies::RSI::new(7))); for pane in &mut chart.pane_layout.panes { @@ -688,11 +612,14 @@ mod tests { if location == "moved-price" { chart.move_series_to_pane(SeriesId::MAIN, study_pane); } - let id = if location == "price" || location == "moved-price" { + let id = if location.ends_with("price") { chart.main_series_pane() } else { study_pane }; + if location.starts_with("maximized") { + chart.pane_layout.maximized = Some(id); + } let screen_height = std::cell::Cell::new(600.0); let mut time = 0.0; let mut frame = |chart: &mut Chart, events| { @@ -727,9 +654,14 @@ mod tests { .unwrap(); let height = chart.pane_height(id).unwrap(); let stretch = chart.pane_stretch_factor(id).unwrap(); + // Left of the first bar the price pane's plot has no series to hit. + let first_bar = chart.get_chart_mapping().idx_to_x(0); let click = |rect: Rect| match location { "header" => rect.left_top() + egui::vec2(30.0, 10.0), "axis" => rect.right_center() - egui::vec2(10.0, 0.0), + "maximized-price" => { + Pos2::new((rect.left() + first_bar) / 2.0, rect.center().y) + } _ => rect.center(), }; let pos = click(chart.pane_layout.panes[at].rect); @@ -749,6 +681,23 @@ mod tests { ); } frame(&mut chart, vec![]); + if location.starts_with("maximized") { + // There it is the plain double-click: one step that brings back every pane. + assert_eq!(chart.pane_layout.maximized, None, "{modifiers:?}"); + assert_eq!(chart.pane_layout.panes.len(), 3, "{location}"); + assert!( + chart + .pane_layout + .panes + .iter() + .all(|pane| pane.rect.height() > 24.0), + "{modifiers:?}" + ); + assert!(chart.undo()); + assert_eq!(chart.pane_layout.maximized, Some(id)); + assert!(!chart.can_undo()); + continue; + } if location == "disabled" { assert_eq!(chart.pane_height(id), Some(height)); assert_eq!(chart.pane_layout.maximized, None); @@ -828,6 +777,47 @@ mod tests { } } + /// The move entries of a pane's menu pass the hidden panes next to it. + #[test] + fn move_pane_entries_skip_hidden_panes() { + use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, + }; + + for hide_rsi in [false, true] { + let mut chart = crate::widget::test_frames::chart(&[100.0; 20], &[110.0; 20]); + let rsi = chart.add_indicator(Box::new(crate::studies::RSI::new(14))); + let macd = chart.add_indicator(Box::new(crate::studies::MACD::new(12, 26, 9))); + let [rsi_pane, macd_pane] = [rsi, macd].map(|id| chart.series_pane(id).unwrap()); + let (hidden, pane, expected) = if hide_rsi { + (rsi, macd_pane, [macd_pane, PaneId::MAIN, rsi_pane]) + } else { + (macd, rsi_pane, [rsi_pane, PaneId::MAIN, macd_pane]) + }; + chart.set_series_visible(hidden, false); + let mut harness = Harness::builder() + .with_size(egui::vec2(800.0, 600.0)) + .build_ui_state( + |ui, chart: &mut Chart| { + let rect = ui.max_rect(); + let at = chart.pane_layout.panes.iter().position(|p| p.id == pane); + chart.pane_actions(ui, at.unwrap(), pane, rect, rect, false); + }, + chart, + ); + harness.hover_at(egui::pos2(400.0, 300.0)); + harness.run(); + harness.get_by_label("...").click(); + harness.run(); + let down = harness.get_by_label("Move pane down"); + assert!(down.accesskit_node().is_disabled(), "{hide_rsi}"); + harness.get_by_label("Move pane up").click(); + harness.run(); + assert_eq!(harness.state().panes(), expected, "{hide_rsi}"); + } + } + #[test] fn command_double_click_outside_every_pane_keeps_the_time_axis_reset() { for modifiers in [ diff --git a/vendor/egui-charts/src/widget/pane/indicator/config.rs b/vendor/egui-charts/src/widget/pane/indicator/config.rs index 9f6d95c..5a0b34b 100644 --- a/vendor/egui-charts/src/widget/pane/indicator/config.rs +++ b/vendor/egui-charts/src/widget/pane/indicator/config.rs @@ -11,6 +11,7 @@ use egui::{Color32, Pos2, Rect, Response}; /// for common indicators via [`IndicatorPaneConfig::rsi`], /// [`IndicatorPaneConfig::macd`], and [`IndicatorPaneConfig::stochastic`]. #[derive(Debug, Clone)] +#[non_exhaustive] pub struct IndicatorPaneConfig { /// Panel height in egui logical points. pub height: f32, @@ -211,6 +212,7 @@ impl IndicatorCoordParams { /// Returned by [`super::IndicatorPane::show_aligned_interactive`]. Besides the rects /// and y-axis range used for click hit-testing, it carries the [`Response`] for /// the legend's close "x" so the host can offer one-click pane removal. +#[derive(Debug)] #[non_exhaustive] pub struct PaneInteraction { /// Full panel rect, including the y-axis label gutter. diff --git a/vendor/egui-charts/src/widget/pane/indicator/mod.rs b/vendor/egui-charts/src/widget/pane/indicator/mod.rs index d22a10a..5e75bb3 100644 --- a/vendor/egui-charts/src/widget/pane/indicator/mod.rs +++ b/vendor/egui-charts/src/widget/pane/indicator/mod.rs @@ -92,6 +92,21 @@ pub struct IndicatorPane { pub(super) primitive_axis_labels: Vec<(crate::chart::primitives::PriceAxisLabel, PriceMap)>, pub(super) axis_options: crate::config::PriceAxisOptions, pub(super) legend_backdrop: f32, + /// The background of the chart showing the pane: the rect its gradient spans, its style and + /// its solid colour. A pane shown on its own has the theme's chart background. + pub(super) background: Option<(Rect, crate::config::BackgroundStyle, egui::Color32)>, + /// Colour of the legend text and the axis labels, the scale text colour of the chart showing + /// the pane. A pane shown on its own takes them from the egui style and the theme. + pub(super) text_color: Option, +} + +impl std::fmt::Debug for IndicatorPane { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("IndicatorPane") + .field("config", &self.config) + .field("overlay", &self.overlay) + .finish_non_exhaustive() + } } impl IndicatorPane { @@ -117,9 +132,19 @@ impl IndicatorPane { primitive_axis_labels: Vec::new(), axis_options, legend_backdrop: 0.6, + background: None, + text_color: None, } } + /// The colour of the background behind `pos`. + pub(super) fn background_at(&self, ctx: &egui::Context, pos: Pos2) -> egui::Color32 { + self.background.map_or_else( + || ctx.active_theme().chart.bg, + |(frame, style, color)| crate::widget::frame::background_at(frame, style, color, pos), + ) + } + /// Render the indicator panel with proper x-axis alignment pub fn show( &mut self, @@ -197,6 +222,7 @@ impl IndicatorPane { y_min, y_max, indicator, + visible_range.end.checked_sub(1), Some(crate::scales::PriceScaleId::Right), None, ); @@ -293,6 +319,7 @@ impl IndicatorPane { y_min, y_max, indicator, + crate::chart::rendering::axes::last_bar_in_view(&horizontal), Some(crate::scales::PriceScaleId::Right), None, ); @@ -376,7 +403,9 @@ impl IndicatorPane { // Get chart background and text colors from theme let colors = ui.active_theme().chart; let chart_bg = colors.bg; - let text_color = ui.style().visuals.text_color(); + let text_color = self + .text_color + .unwrap_or_else(|| ui.style().visuals.text_color()); let grid_color = colors.grid_line; // Get live theme colors for zones @@ -401,9 +430,17 @@ impl IndicatorPane { let painter = &ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); - // Fill background + // Fill background: the part of the chart's that lies behind the pane, also when a container + // paints the chart's: the fill hides the crosshair line the price frame draws through panes. if !self.overlay { - painter.rect_filled(rect, 0.0, chart_bg); + match self.background { + Some((frame, style, color)) => { + crate::widget::frame::paint_background(painter, frame, rect, style, color); + } + None => { + painter.rect_filled(rect, 0.0, chart_bg); + } + } } // Calculate drawing area to match main chart layout @@ -629,7 +666,15 @@ impl IndicatorPane { axis_foregrounds.extend(crate::widget::primitives::take_shapes(painter, start)); // Draw y-axis labels self.measured_axis_width = self.draw_y_axis_labels( - painter, rect, chart_rect, y_min, y_max, indicator, axis, tag, + painter, + rect, + chart_rect, + y_min, + y_max, + indicator, + crate::chart::rendering::axes::last_bar_in_view(&mapping), + axis, + tag, ); } @@ -652,7 +697,7 @@ impl IndicatorPane { ui, row, controls, - true, + Some(self.background_at(ui.ctx(), controls.center())), response.id.with("study_controls"), indicator, ) @@ -880,7 +925,8 @@ mod tests { } /// A fitted pane keeps a study's levels in view when its values lie between them, and a - /// hidden level holds the scale open only when its value line is visible. + /// hidden level holds the scale open only when its value line is visible. Williams %R fits a + /// source that reads past -100 to 0 rather than clipping it. #[test] fn fitted_panes_keep_visible_levels_in_view() { let bars: Vec<_> = [(10.0, 8.0, 9.0), (12.0, 9.0, 11.0), (11.0, 7.0, 8.0)] @@ -916,5 +962,15 @@ mod tests { assert!(low < 38.2, "{low}..{high}"); assert_eq!(high > 61.8, shown, "{low}..{high}"); } + + // Williams %R fits a source past its bounds. With the same bars and a two-bar window, a + // source of 14 on bar 1 gives (12 - 14) / (12 - 8) * -100 = 50 and 9 on bar 2 gives + // (12 - 9) / (12 - 7) * -100 = -60, so with its levels at -20 and -80 the values and + // levels span -80 to 50. + let mut study = + crate::studies::ConfiguredStudy::new(Box::new(crate::studies::WilliamsR::new(2))); + study.update_source(&bars, 0, &[f64::NAN, 14.0, 9.0]); + let (low, high) = fit(&study); + assert!(low < -80.0 && high > 50.0, "{low}..{high}"); } } diff --git a/vendor/egui-charts/src/widget/pane/indicator/paint.rs b/vendor/egui-charts/src/widget/pane/indicator/paint.rs index a11fb2d..3f824be 100644 --- a/vendor/egui-charts/src/widget/pane/indicator/paint.rs +++ b/vendor/egui-charts/src/widget/pane/indicator/paint.rs @@ -244,7 +244,7 @@ impl IndicatorPane { if count == 0 { return; } - let spacing = rect.width() / count as f32; + let spacing = (rect.width() - 1.0) / count as f32; let coords = IndicatorCoordParams::new( spacing, 0.0, @@ -267,7 +267,7 @@ impl IndicatorPane { if count == 0 { return; } - let spacing = rect.width() / count as f32; + let spacing = (rect.width() - 1.0) / count as f32; let coords = IndicatorCoordParams::new( spacing, 0.0, @@ -317,6 +317,7 @@ impl IndicatorPane { y_min: f64, y_max: f64, indicator: &dyn Indicator, + last_in_view: Option, axis: Option, crosshair_tag: Option, ) -> f32 { @@ -342,7 +343,9 @@ impl IndicatorPane { }, |axis| axis.right(), ); - let text_color = painter.ctx().active_theme().chart.axis_text; + let text_color = self + .text_color + .unwrap_or_else(|| painter.ctx().active_theme().chart.axis_text); let map = self .price_map .unwrap_or_else(|| { @@ -369,6 +372,7 @@ impl IndicatorPane { label_rect, &map, indicator, + last_in_view, axis_edge, &mut tags, &self.axis_options, @@ -379,6 +383,7 @@ impl IndicatorPane { label_rect, &map, indicator, + last_in_view, axis_edge, &mut tags, None, @@ -398,9 +403,9 @@ impl IndicatorPane { self.price_formatter.as_deref(), ) }; - for tag in tags.iter().chain(&self.fixed_axis_tags).flatten() { - width = width.max(tag.width() + 5.0 + 6.0); - } + width = width.max(crate::chart::rendering::axes::axis_tags_width( + tags.iter().chain(&self.fixed_axis_tags), + )); self.axis_tags = tags.clone(); tags.extend(self.fixed_axis_tags.iter().copied()); if !self.draw_axis { @@ -586,14 +591,13 @@ impl IndicatorPane { rect.left() + theme.spacing.sm, rect.top() + self.legend_offset + theme.spacing.sm.min(rect.height() / 2.0), ); + let backdrop = Rect::from_min_size(pos, galley.size()) + .expand(2.0) + .intersect(rect); painter.rect_filled( - Rect::from_min_size(pos, galley.size()) - .expand(2.0) - .intersect(rect), + backdrop, 0.0, - theme - .chart - .bg + self.background_at(painter.ctx(), backdrop.center()) .gamma_multiply(self.legend_backdrop.clamp(0.0, 1.0)), ); painter.galley(pos, galley, text_color); @@ -611,7 +615,10 @@ impl IndicatorPane { indicator, text_color, theme.ui.text_muted, - theme.chart.bg, + self.background_at( + painter.ctx(), + rect.min + egui::vec2(0.0, self.legend_offset), + ), theme.text.ohlc, ); let controls_width = crate::chart::rendering::controls_width(indicator); @@ -1005,6 +1012,7 @@ mod tests { 0.0, 3_000_000.0, studies[0].as_ref(), + Some(usize::MAX), Some(crate::scales::PriceScaleId::Right), None, ); @@ -1190,6 +1198,8 @@ mod tests { rect, &Default::default(), None, + egui::Color32::WHITE, + &|_| egui::Color32::BLACK, ); } else { crate::chart::rendering::axes::render_study_tags( @@ -1197,6 +1207,7 @@ mod tests { rect, &map, &study, + Some(usize::MAX), 450.0, &mut Vec::new(), None, diff --git a/vendor/egui-charts/src/widget/pane/mod.rs b/vendor/egui-charts/src/widget/pane/mod.rs index e1ef268..8a946cd 100644 --- a/vendor/egui-charts/src/widget/pane/mod.rs +++ b/vendor/egui-charts/src/widget/pane/mod.rs @@ -281,6 +281,11 @@ impl Chart { .any(|id| self.pane_member(*id) && self.is_series_visible(*id))) } + /// Whether `pane` is drawn when no pane is maximized: the price panes always are. + pub(super) fn pane_drawn(&self, pane: &Pane) -> bool { + pane.id == PaneId::MAIN || pane.id == self.main_series_pane() || self.pane_shown(pane) + } + /// Whether rendering needs the shared layout for panes other than the original price pane. pub(super) fn has_panes(&self) -> bool { self.pane_index(PaneId::MAIN).is_none() @@ -373,12 +378,14 @@ impl Chart { } let main = std::mem::take(&mut self.pane_layout.main); self.pane_layout.main = self.main_pane_order(main); + // A maximized pane needs a drawn pane to hide, also when undo brings the state back. if self.pane_layout.maximized.is_some_and(|id| { - !self + let mut drawn = self .pane_layout .panes .iter() - .any(|pane| pane.id == id && (id == PaneId::MAIN || self.pane_shown(pane))) + .filter(|pane| self.pane_drawn(pane)); + !drawn.clone().any(|pane| pane.id == id) || drawn.nth(1).is_none() }) { self.pane_layout.maximized = None; } @@ -455,11 +462,12 @@ impl Chart { /// Adds an empty pane at the bottom and returns its id. Fill it with /// [`move_series_to_pane`](Self::move_series_to_pane). Once its last series or study leaves /// it the pane is removed, unless [`set_preserve_empty_pane`](Self::set_preserve_empty_pane) - /// keeps it. + /// keeps it. A maximized pane is restored, so that the new pane is drawn. pub fn add_pane(&mut self) -> PaneId { let id = PaneId(self.next_series); self.next_series += 1; self.pane_layout.panes.push(Pane::new(id)); + self.pane_layout.maximized = None; id } diff --git a/vendor/egui-charts/src/widget/pane/render/mod.rs b/vendor/egui-charts/src/widget/pane/render/mod.rs index 9da8065..a535527 100644 --- a/vendor/egui-charts/src/widget/pane/render/mod.rs +++ b/vendor/egui-charts/src/widget/pane/render/mod.rs @@ -124,8 +124,7 @@ impl Chart { .enumerate() .filter(|(_, pane)| { pane.id == main_pane - || (pane.id == PaneId::MAIN || self.pane_shown(pane)) - && maximized.is_none_or(|id| id == pane.id) + || self.pane_drawn(pane) && maximized.is_none_or(|id| id == pane.id) }) .map(|(idx, pane)| (idx, pane.id, false)) .collect(); @@ -262,19 +261,26 @@ impl Chart { Pos2::new(plot.left(), available.bottom() - axis_height), Pos2::new(plot.right(), available.bottom()), ); - // The price frame has no height for time navigation in these layouts. - let shared_plot = - (main_at.is_none() || main_collapsed || maximized.is_some_and(|id| id != main_pane)) - .then(|| { - ui.interact( - Rect::from_min_max( - Pos2::new(plot.left(), available.top()), - Pos2::new(plot.right(), time_axis.top()), - ), - ui.scope_id().with((maximized, "plot")), - Sense::click_and_drag(), - ) - }); + // The plot of every row but the expanded price frame, made before that frame so that + // time navigation reads their drags, wheel and pinch with its own. A row's own response + // lies above its plot and keeps the clicks and the keyboard focus. + let pane_plots: Vec<_> = panes + .iter() + .zip(&rects) + .filter(|((_, id, collapsed), _)| *id != main_pane || *collapsed) + .map(|((_, id, _), rect)| { + let response = ui.interact( + Rect::from_x_y_ranges(plot.x_range(), rect.y_range()), + ui.scope_id().with((*id, "plot")), + Sense::CLICK | Sense::DRAG, + ); + (*id, response) + }) + .collect(); + let shared_plot = pane_plots + .iter() + .map(|(_, plot)| plot.clone()) + .reduce(|plots, plot| plots.union(plot)); let price_frame = if main_collapsed { Rect::from_min_size(main_rect.min, egui::vec2(main_rect.width(), 0.0)) } else { @@ -380,7 +386,10 @@ impl Chart { // A host series whose legend asked to remove it, hide it, or open its settings. let mut pending_series_action = None; let mut pending_pane_collapse = None; - let mut pending_pane_maximize = None; + // A chart without another pane has nothing to hide behind the price pane. + let mut pending_pane_maximize = (self.price_plot_double_click + && (maximized.is_some() || panes.len() > 1)) + .then_some(main_pane); let current_selection = self.selection.selected_id(); // Draws the background, grid, axis and crosshair of a pane without a visible study. let frame = CustomIndicator::new("", |_| Vec::new()) @@ -575,6 +584,12 @@ impl Chart { config.show_grid &= Some(entry) == first; let mut panel = IndicatorPane::with_config(config); panel.legend_backdrop = self.config.indicator_backdrop_opacity; + panel.background = Some(( + self.background_frame(panel_rect), + self.config.background_style, + self.config.background_color, + )); + panel.text_color = Some(self.config.text_color); panel.axis_options = crate::config::PriceAxisOptions { show_study_values: self.config.price_axis.show_study_values, ..self.config.price_axis @@ -932,15 +947,11 @@ impl Chart { menu, } = interaction; - let mut pane_response = match shared_plot.as_ref().filter(|_| { - maximized.is_some() - || ui - .input(|input| input.pointer.interact_pos()) - .is_some_and(|pos| chart_rect.contains(pos)) - }) { - Some(plot) => pane_response.union(plot.clone()), - None => pane_response.interact(Sense::click_and_drag()), - }; + // A drag belongs to the pane it began in, wherever the pointer goes. + let mut pane_response = pane_plots + .iter() + .filter(|(id, _)| *id == pane_id) + .fold(pane_response, |pane, (_, plot)| pane.union(plot.clone())); if self.chart_options.tooltip.enabled && self.chart_options.tooltip.on_long_press && touch_readout.touch_input @@ -1300,7 +1311,7 @@ impl Chart { item, self.series_map(item, chart_rect), index, - |_| ui.active_theme().chart.bg, + |point| self.background_at(panel_rect, point), ); } } @@ -1431,7 +1442,10 @@ impl Chart { let mut cursors = std::mem::take(&mut self.cursor_modes); let timescale = self.state.time_scale().clone(); let painter = ui.painter().clone(); - let time_formatter = self.build_time_formatter(); + // Sampled once: inferred spacing sorts the gaps of the bars in view. + let bar_seconds = self.time_label_seconds(); + let time_formatter = + self.time_formatter_in(self.label_timezone(|| bar_seconds)); self.handle_pane_drawings( ui, &mut drawings, @@ -1441,7 +1455,7 @@ impl Chart { &drawing_map, &painter, ×cale, - (time_formatter.as_ref(), self.time_label_seconds()), + (time_formatter.as_ref(), bar_seconds), Some(pane_id), ); let drawing_hit = pane_response @@ -1540,7 +1554,7 @@ impl Chart { } } if !collapsed { - let mut table_rect = plot; + let mut table_rect = pane_plot; for id in &members { if let Some(idx) = self.study_ids.iter().position(|study| study == id) { let study = &studies.indicators()[idx]; @@ -1628,7 +1642,10 @@ impl Chart { if main_collapsed { self.collapsed_price_header(ui, main_rect); } - self.pane_collapse_shortcut(ui); + // On a pane maximized when the frame began, the gesture was the plain double-click. + if maximized.is_none() { + self.pane_collapse_shortcut(ui); + } ui.advance_cursor_after_rect(available); ui.spacing_mut().item_spacing = host_spacing; diff --git a/vendor/egui-charts/src/widget/pane/render/tests.rs b/vendor/egui-charts/src/widget/pane/render/tests.rs index 380bd2a..fbd51b2 100644 --- a/vendor/egui-charts/src/widget/pane/render/tests.rs +++ b/vendor/egui-charts/src/widget/pane/render/tests.rs @@ -1,6 +1,4 @@ use crate::studies::{MACD, RSI}; -#[cfg(all(test, feature = "ui"))] -use crate::ui::context_menu::ChartMenus; use crate::widget::test_frames::chart; use egui::{Context, Event, Modifiers, PointerButton, Pos2, RawInput, Rect, Vec2}; @@ -406,6 +404,31 @@ fn pane_separators_resize_neighbors_and_maximize_restores_the_layout() { let main = chart.get_rendered_price_rect(); let before = chart.get_rendered_indicator_panes().to_vec(); let separator = Pos2::new(main.center().x, before[1].panel_rect.top() - 0.5); + // Past the 40 point minimum the separator waits at it until the pointer comes back. + let [upper, lower] = [0, 1].map(|at| before[at].panel_rect.height()); + pointer(&ctx, &mut chart, separator, None); + pointer(&ctx, &mut chart, separator, Some(true)); + for (moved, expected) in [ + (400.0, lower - 40.0), + (300.0, lower - 40.0), + (-25.0, -25.0), + (0.0, 0.0), + ] { + for _ in 0..2 { + pointer(&ctx, &mut chart, separator + egui::vec2(0.0, moved), None); + } + let panes = chart.get_rendered_indicator_panes(); + assert!( + (panes[0].panel_rect.height() - upper - expected).abs() < 0.1, + "{moved}" + ); + assert!( + (panes[1].panel_rect.height() - lower + expected).abs() < 0.1, + "{moved}" + ); + assert_eq!(chart.get_rendered_price_rect(), main); + } + pointer(&ctx, &mut chart, separator, Some(false)); drag( &ctx, &mut chart, @@ -449,6 +472,56 @@ fn pane_separators_resize_neighbors_and_maximize_restores_the_layout() { ); assert_eq!(chart.take_indicator_settings_request(), None); } + // The price pane takes the gesture on its plot, away from its series, axis and status line. + let mapping = chart.get_chart_mapping(); + let empty = Pos2::new(main.left() + 20.0, main.center().y); + assert!(mapping.idx_to_x(0) > empty.x + 10.0); + for (at, toggles) in [ + (empty, true), + ( + Pos2::new(mapping.idx_to_x(70), mapping.price_to_y(107.0)), + false, + ), + (Pos2::new(main.right() + 20.0, main.center().y), false), + (main.left_top() + egui::vec2(20.0, 12.0), false), + ] { + for maximized in [true, false] { + for pressed in [None, Some(true), Some(false), Some(true), Some(false), None] { + pointer(&ctx, &mut chart, at, pressed); + } + let shown = chart.get_rendered_indicator_panes().len(); + assert_eq!(shown, if toggles && maximized { 0 } else { 2 }, "{at:?}"); + assert_eq!( + chart.get_rendered_price_rect().height() > 500.0, + toggles && maximized + ); + } + } + // Each toggle of the price pane is one undo step. + assert!(chart.undo()); + assert_eq!(chart.pane_layout.maximized, Some(chart.main_series_pane())); + assert!(chart.redo()); + // A double-click that finishes a drawing only finishes it. + #[cfg(feature = "drawings")] + { + use crate::drawings::DrawingToolType; + chart + .drawings_mut() + .set_active_tool(Some(DrawingToolType::Path)); + click(&ctx, &mut chart, empty - egui::vec2(0.0, 40.0)); + for pressed in [None, Some(true), Some(false), Some(true), Some(false), None] { + pointer(&ctx, &mut chart, empty, pressed); + } + assert_eq!(chart.get_rendered_indicator_panes().len(), 2); + assert!( + chart + .drawings_mut() + .drawings + .iter() + .any(|drawing| drawing.completed) + ); + chart.drawings_mut().set_active_tool(None); + } let separator = Pos2::new(main.center().x, resized[0].panel_rect.top() - 0.5); drag( &ctx, @@ -520,6 +593,42 @@ fn pane_separators_resize_neighbors_and_maximize_restores_the_layout() { } } +/// A study added while a pane is maximized is drawn, also after the maximized price pane became +/// the only pane, and undo does not maximize a chart left with one pane. +#[test] +fn study_added_while_a_pane_is_maximized_is_drawn() { + use crate::widget::PaneId; + for remove_others in [true, false] { + let ctx = Context::default(); + let mut chart = chart(&[100.0], &[110.0]); + let rsi = chart.add_indicator(Box::new(RSI::new(14))); + let macd = chart.add_indicator(Box::new(MACD::new(12, 26, 9))); + let maximized = if remove_others { + PaneId::MAIN + } else { + chart.series_pane(rsi).unwrap() + }; + chart.user_action(|chart| chart.pane_layout.maximized = Some(maximized)); + if remove_others { + for id in [rsi, macd] { + chart.user_action(|chart| chart.remove_series(id)); + } + } + let added = chart.user_action(|chart| chart.add_indicator(Box::new(RSI::new(7)))); + for time in [0.0, 0.1] { + crate::widget::test_frames::frame(&ctx, &mut chart, time, Vec::new()); + } + let pane = chart.series_pane(added).unwrap(); + assert!(chart.pane_height(pane) > Some(40.0), "{remove_others}"); + if remove_others { + assert!(chart.undo()); + crate::widget::test_frames::frame(&ctx, &mut chart, 0.2, Vec::new()); + assert_eq!(chart.panes(), [PaneId::MAIN]); + assert_eq!(chart.pane_layout.maximized, None); + } + } +} + /// The Hide and Remove controls in an added series' legend are one undo step each, and undo /// brings the series back with its price formatter and bar limit. #[test] @@ -633,53 +742,6 @@ fn merged_panes_share_scales_and_studies_can_return_to_the_main_pane() { } assert_eq!(chart.pane_layout.panes[1].scale.is_manual(), !enabled); } - #[cfg(feature = "ui")] - { - let mut menus = ChartMenus::default(); - let mut shapes = Vec::new(); - for clicked in [true, false] { - let mut output = ctx.run_ui( - RawInput { - screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(800.0, 600.0))), - time: Some(ctx.input(|input| input.time) + 0.1), - events: if clicked { - vec![ - Event::PointerMoved(axis), - Event::PointerButton { - pos: axis, - button: PointerButton::Secondary, - pressed: true, - modifiers: Modifiers::NONE, - }, - Event::PointerButton { - pos: axis, - button: PointerButton::Secondary, - pressed: false, - modifiers: Modifiers::NONE, - }, - ] - } else { - Vec::new() - }, - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - chart.show(ui); - }); - menus.show(&ctx, &mut chart); - }, - ); - shapes = std::mem::take(&mut output.shapes); - output.drop_without_applying_deltas(); - } - assert!( - !shapes.iter().any(|shape| matches!(&shape.shape, - egui::Shape::Text(text) if text.galley.text() == "Lock price to bar ratio")), - "the main-axis menu must not open over a study axis" - ); - egui::Popup::close_all(&ctx); - } // The same engine maps 10 and 1000 around 100 at the midpoint in logarithmic units. let scale = &mut chart.pane_layout.panes[1].scale; scale.options_mut().mode = PriceScaleMode::Logarithmic; @@ -1307,20 +1369,23 @@ fn merged_pane_legends_reserve_their_wrapped_height() { } } +/// The plot of a study pane pans and zooms the shared time scale beside the price pane as it +/// does alone, and leaves the prices of the price pane where they are. #[test] fn collapsed_price_pane_keeps_pointer_navigation_in_the_visible_pane() { use crate::widget::PaneId; let mut results = Vec::new(); - for layout in ["maximized", "collapsed"] { + for layout in ["ordinary", "maximized", "collapsed"] { let ctx = Context::default(); let mut chart = chart(&[100.0, 105.0], &[110.0, 115.0]); let study = chart.add_indicator(Box::new(RSI::new(14))); let study_pane = chart.series_pane(study).unwrap(); crate::widget::test_frames::frame(&ctx, &mut chart, 0.0, Vec::new()); - // Either way the study fills the chart and the price frame has no height. + // Maximized or with the price pane collapsed, the study fills the chart and the price + // frame has no height. if layout == "maximized" { chart.pane_layout.maximized = Some(study_pane); - } else { + } else if layout == "collapsed" { for pane in &mut chart.pane_layout.panes { if pane.id == PaneId::MAIN { pane.collapsed = Some(true); @@ -1332,10 +1397,13 @@ fn collapsed_price_pane_keeps_pointer_navigation_in_the_visible_pane() { let pos = chart.get_rendered_indicator_panes()[0].chart_rect.center(); assert_eq!(chart.state.time_scale().bar_spacing(), 6.0); let before = chart.state.time_scale().right_offset_precise(); - drag(&ctx, &mut chart, pos, pos + egui::vec2(40.0, 0.0)); + chart.state.price_scale_mut().set_range(90.0, 120.0); + drag(&ctx, &mut chart, pos, pos + egui::vec2(40.0, 20.0)); let moved = chart.state.time_scale().right_offset_precise() - before; // Forty pixels at six pixels per bar move history by 6 2/3 bars. assert!((moved + 20.0 / 3.0).abs() < 1e-5, "{layout}: moved {moved}"); + let prices = chart.state.price_scale().range(); + assert_eq!((prices.min, prices.max), (90.0, 120.0), "{layout}"); let time = ctx.input(|input| input.time) + 1.0; crate::widget::test_frames::frame( &ctx, @@ -1358,7 +1426,11 @@ fn collapsed_price_pane_keeps_pointer_navigation_in_the_visible_pane() { crate::widget::test_frames::frame(&ctx, &mut chart, time, Vec::new()); } let spacing = chart.state.time_scale().bar_spacing(); - assert!(spacing > 6.0, "{layout}: spacing {spacing}"); + // Twenty wheel points scale the six pixels by e^0.02 = 1.020201, to 6.12 pixels. + assert!( + (spacing - 6.0 * 1.020_201).abs() < 1e-5, + "{layout}: spacing {spacing}" + ); let offset = chart.state.time_scale().right_offset_precise(); results.push((moved, spacing)); if layout == "collapsed" { @@ -1371,6 +1443,7 @@ fn collapsed_price_pane_keeps_pointer_navigation_in_the_visible_pane() { } } assert_eq!(results[0], results[1]); + assert_eq!(results[1], results[2]); } #[test] @@ -1411,3 +1484,125 @@ fn collapsing_the_price_pane_of_a_short_chart_leaves_no_blank_area() { } assert_eq!(heights(&chart), [90.0, 24.0]); } + +/// A chart's own background covers its study panes. Solid, neither a pane nor the fills that +/// keep legend text and the labels of a study's own axis readable paint the theme's background, +/// nor does the plate under the controls of a hovered study pane row. A gradient spans the chart +/// frame, from 8 to 592 points down the 600 point test frame, and each pane paints the part +/// behind it. A chart that leaves its background to a container paints none behind the price +/// pane and still fills its study panes, which hides the crosshair line the price frame draws +/// through them. +#[test] +fn custom_background_reaches_study_panes() { + use crate::config::BackgroundStyle; + use crate::studies::{SMA, StudyScale}; + use crate::widget::test_frames::{frame, shapes}; + use egui::{Color32, Shape}; + let solid = Color32::from_rgb(120, 10, 10); + let (top, bottom) = (Color32::from_rgb(200, 0, 0), Color32::from_rgb(0, 0, 200)); + let gradient = BackgroundStyle::VerticalGradient { + top_color: top, + bottom_color: bottom, + }; + let at = |y: f32| top.lerp_to_gamma(bottom, (y - 8.0) / 584.0); + let theme = crate::theme::Theme::dark(); + for (style, skip) in [ + (BackgroundStyle::Solid, false), + (BackgroundStyle::Solid, true), + (gradient, false), + (gradient, true), + ] { + let ctx = Context::default(); + let mut chart = chart(&[100.0, 105.0], &[110.0, 115.0]); + chart.set_theme(&ctx, &theme); + chart.add_indicator(Box::new(RSI::new(14))); + let average = chart.add_indicator(Box::new(SMA::new(5))); + assert!(chart.set_indicator_scale(average, StudyScale::Independent)); + chart.config_mut().background_color = solid; + chart.config_mut().background_style = style; + chart.config_mut().skip_background = skip; + frame(&ctx, &mut chart, 0.0, vec![]); + // The pointer rests on the study pane's legend row, which reveals the row's controls. + let row = chart.get_rendered_indicator_panes()[0].chart_rect.min + Vec2::new(20.0, 12.0); + frame(&ctx, &mut chart, 0.05, vec![Event::PointerMoved(row)]); + let painted = shapes(&ctx, &mut chart, 0.1, vec![Event::PointerMoved(row)]); + let pane = chart.get_rendered_indicator_panes()[0].panel_rect; + // A background fill is one colour, or a mesh's corner colours clockwise from the top left. + let fills = |rect: Rect| -> Vec> { + let corners = [ + rect.left_top(), + rect.right_top(), + rect.right_bottom(), + rect.left_bottom(), + ]; + painted + .iter() + .filter_map(|shape| match shape { + Shape::Rect(shape) if shape.rect == rect && shape.stroke.width == 0.0 => { + Some(vec![shape.fill]) + } + Shape::Mesh(mesh) if mesh.vertices.iter().map(|v| v.pos).eq(corners) => { + Some(mesh.vertices.iter().map(|v| v.color).collect()) + } + _ => None, + }) + .collect() + }; + let slice = |rect: Rect| { + if style == BackgroundStyle::Solid { + vec![solid] + } else { + let (top, bottom) = (at(rect.top()), at(rect.bottom())); + vec![top, top, bottom, bottom] + } + }; + let label = format!("{style:?}, skip_background {skip}"); + assert_eq!(fills(pane), [slice(pane)], "{label}"); + let price_height = chart.pane_height(crate::widget::PaneId::MAIN).unwrap(); + let price_frame = Rect::from_min_size(Pos2::new(8.0, 8.0), Vec2::new(784.0, price_height)); + let price_fills = if skip { + Vec::new() + } else { + vec![slice(price_frame)] + }; + assert_eq!(fills(price_frame), price_fills, "{label}"); + if style == BackgroundStyle::Solid { + // The theme's background, opaque and at the 60% opacity of a study's legend row. + let stale: Vec<_> = painted + .iter() + .filter_map(|shape| match shape { + Shape::Rect(shape) + if shape.stroke.width == 0.0 + && (shape.fill == Color32::BLACK + || shape.fill == Color32::from_black_alpha(153)) => + { + Some(shape.rect) + } + _ => None, + }) + .filter(|rect| *rect != Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0))) + .collect(); + assert!(stale.is_empty(), "theme background at {stale:?}"); + } + } +} + +/// A study in its own pane draws its table in that pane, not over the price pane. +#[test] +fn study_tables_sit_in_their_own_pane() { + let ctx = Context::default(); + let mut chart = chart(&[100.0, 105.0], &[110.0, 115.0]); + chart.set_size(Some(Vec2::new(800.0, 600.0))); + chart.add_indicator(Box::new(crate::studies::TechnicalRatings::default())); + crate::widget::test_frames::frame(&ctx, &mut chart, 0.0, vec![]); + let shapes = crate::widget::test_frames::shapes(&ctx, &mut chart, 1.0, vec![]); + let heading = shapes + .iter() + .find_map(|shape| match shape { + egui::Shape::Text(text) if text.galley.text() == "Coverage" => Some(text.pos), + _ => None, + }) + .expect("table painted"); + let pane = chart.get_rendered_indicator_panes()[0].chart_rect; + assert!(pane.contains(heading), "{heading:?} outside {pane:?}"); +} diff --git a/vendor/egui-charts/src/widget/readout.rs b/vendor/egui-charts/src/widget/readout.rs index 62dbda3..3f675fa 100644 --- a/vendor/egui-charts/src/widget/readout.rs +++ b/vendor/egui-charts/src/widget/readout.rs @@ -3,6 +3,11 @@ use super::{Chart, CursorDataPolicy, SeriesId}; use crate::chart::rendering::StudyValue; +/// What the data table reads of a visible added series: id, title, bar revision and last bar +/// (time in nanoseconds, close bits). +#[cfg(feature = "ui")] +pub(crate) type SeriesFingerprint = (usize, String, u64, Option<(i64, u64)>); + impl Chart { /// The table is current while this is unchanged: the history revision and a revision moved /// by edits of the last bar, study edits, host-fed study data and the instrument. @@ -11,6 +16,25 @@ impl Chart { (self.state.revision(), self.readout_revision) } + /// What the table lists of each visible added series: its id, title, bar revision and last + /// bar, which the revision leaves out. The table is current while this is unchanged too. + #[cfg(feature = "ui")] + pub(crate) fn data_table_series(&self) -> Vec { + self.price_series + .iter() + .filter(|item| item.visible) + .map(|item| { + let last = item.bars.last().map(|bar| { + ( + bar.time.timestamp_nanos_opt().unwrap_or_default(), + bar.close.to_bits(), + ) + }); + (item.id.0, item.options.name.clone(), item.revision, last) + }) + .collect() + } + /// Tells this chart from the others a host shows one data table over, through a restore of /// its saved state, which adds its studies again under new ids. #[cfg(feature = "ui")] diff --git a/vendor/egui-charts/src/widget/replay.rs b/vendor/egui-charts/src/widget/replay.rs index 0610ce7..2f2da47 100644 --- a/vendor/egui-charts/src/widget/replay.rs +++ b/vendor/egui-charts/src/widget/replay.rs @@ -165,10 +165,10 @@ impl Chart { /// Enters or seeks replay, retaining the full history inside the chart. Only bars completed /// by `time` reach rendering, studies, auto-scaling and readouts, including the histories - /// that studies request for other symbols and intervals. A bar's close is its - /// `BarClock::next_open`; without a timeframe or on numeric and custom horizontal axes, - /// keys strictly before `time` are available. Supply finer bars with `set_replay_source` - /// to build the unfinished chart bar. No future OHLC is inferred from a completed coarse bar. + /// that studies request for other symbols and intervals. A bar closes at its next open on + /// [`Self::bar_clock`]; without a timeframe or on numeric and custom horizontal axes, keys + /// strictly before `time` are available. Supply finer bars with `set_replay_source` to build + /// the unfinished chart bar. No future OHLC is inferred from a completed coarse bar. /// /// The main feed is suspended and current quotes and book views are hidden. Use /// [`Self::set_market_replay`] to replay recorded trades, quotes and depth together. @@ -236,6 +236,8 @@ impl Chart { session_quote: self.session_quote.take(), }); self.set_feed_paused(true); + // The session resolves its sizes from the bars before the cursor. + self.arm_box_sizes(); } self.apply_replay_window(); self.replay_order_flow(previous.map_or(time, |previous| previous.min(time))); @@ -385,9 +387,10 @@ impl Chart { partial.into_iter().map(|bar| (bar, Origin::Live)).collect(), ); } - let replay = self.replay.take(); + // A step keeps the sizes resolved for the session, as bars streaming in do. + let (replay, pending) = (self.replay.take(), self.pending_box_sizes); self.replace_main_data(visible); - self.replay = replay; + (self.replay, self.pending_box_sizes) = (replay, pending); } pub(super) fn replay_set_data(&mut self, id: SeriesId, bars: Vec) { @@ -398,9 +401,19 @@ impl Chart { let (bars, rejected) = super::series::clean(bars, &clock); replay.bars.insert(id, bars); self.count_replay_rejections(id, rejected); + // New history resolves the sizes again, as `set_data` does outside replay. + if id == SeriesId::MAIN { + self.arm_box_sizes(); + } self.apply_replay_window(); } + /// Resolves the sizes derived from history again, from the bars before the cursor. + fn arm_box_sizes(&mut self) { + self.pending_box_sizes = (self.chart_type_params.size_methods()) + .map(|method| method != crate::model::BoxSizeMethod::Fixed); + } + /// Merges `bar` into the retained bars of `id`; returns whether they changed. pub(super) fn replay_update(&mut self, id: SeriesId, bar: Bar) -> bool { let clock = self.clock(); @@ -819,6 +832,45 @@ mod tests { ); } + /// A session resolves ATR and percentage sizes from the bars before the cursor when it starts, + /// or once the cursor passes enough bars, and keeps them while the cursor moves, as bars + /// streaming in do; applying the parameters again recalculates. ATR(14) of 14 true ranges of + /// 2 is 2, and the 15th bar's true range of 16 makes it (13 * 2 + 16) / 14 = 3. + #[test] + fn replay_steps_keep_history_derived_sizes() { + use crate::model::{BoxSizeMethod, ChartType, ChartTypeParams}; + let mut bars: Vec<_> = (0..14) + .map(|i| bar(i, [100.0, 101.0, 99.0, 100.0, 1.0])) + .collect(); + bars.push(bar(14, [100.0, 115.0, 99.0, 100.0, 1.0])); + let mut chart = Chart::new(BarData::from_bars(bars)); + chart.set_timeframe(Timeframe::Min1); + chart.set_chart_type(ChartType::Renko); + chart.set_chart_type_params(ChartTypeParams { + renko_size_method: BoxSizeMethod::Atr { + period: 14, + multiplier: 1.0, + }, + ..Default::default() + }); + let size_at = |chart: &mut Chart, cursor: Option| { + chart.set_replay_time(cursor.map(time)); + chart.show_elements(); + chart.chart_type_params().renko_brick_size + }; + let steps = [(Some(5), 0.0), (Some(14), 2.0), (Some(15), 2.0)]; + for (cursor, size) in steps { + let got = size_at(&mut chart, cursor); + assert!((got - size).abs() < 1e-12, "{cursor:?}: {got}"); + } + chart.set_chart_type_params(chart.chart_type_params().clone()); + assert!((chart.chart_type_params().renko_brick_size - 3.0).abs() < 1e-12); + for (cursor, size) in [(None, 3.0), (Some(14), 2.0)] { + let got = size_at(&mut chart, cursor); + assert!((got - size).abs() < 1e-12, "{cursor:?}: {got}"); + } + } + /// Bar replay over recorded trades: one-trade bars build the unfinished chart bar from the /// trades before each cursor position, two trades of one timestamp are two steps, a trade in /// the next minute starts that bar, and seeking back shows the earlier bar again. The diff --git a/vendor/egui-charts/src/widget/series/mod.rs b/vendor/egui-charts/src/widget/series/mod.rs index 51a2b90..cf98911 100644 --- a/vendor/egui-charts/src/widget/series/mod.rs +++ b/vendor/egui-charts/src/widget/series/mod.rs @@ -140,18 +140,19 @@ impl Chart { /// A view scrolled back stays on its bars when older or newer bars arrive, and stops with the /// oldest bar in view once the replacement no longer holds them. /// - /// Bar series accept data; unknown ids and study ids are ignored with a warning, and so is - /// the main series while it is removed from a chart that keeps the original pane. + /// Returns `false` when `series` holds no bars, such as an unknown or removed series, a study + /// or the main series while it is removed from a chart that keeps the original pane. Unknown + /// ids and study ids also log a warning. /// See [`set_data_operation_notifications`](Self::set_data_operation_notifications) to /// observe every accepted call, including empty and unchanged replacements. - pub fn set_data(&mut self, series: SeriesId, bars: Vec) { + pub fn set_data(&mut self, series: SeriesId, bars: Vec) -> bool { if (series == SeriesId::MAIN && self.main_bars_live() || self.price_series.iter().any(|item| item.id == series)) && self.replay_retains(series) { self.replay_set_data(series, bars); self.data_set(series); - return; + return true; } if let Some(at) = self.price_series.iter().position(|item| item.id == series) { let (mut bars, rejected) = clean(bars, &self.clock()); @@ -164,13 +165,14 @@ impl Chart { } item.feed.rejected_bars += rejected; self.data_set(series); - return; + return true; } if !self.main_bars_live() || !holds_bars(series, "set_data") { - return; + return false; } self.replace_main_data(bars); self.data_set(series); + true } pub(super) fn replace_main_data(&mut self, bars: Vec) { @@ -206,10 +208,12 @@ impl Chart { /// oldest bar in view once a bar limit has evicted them. A merged bar is /// reported by [`ChartEvent::DataUpdated`](super::ChartEvent::DataUpdated). /// - /// Bar series accept data; unknown ids and study ids are ignored with a warning. + /// Returns `false` when `series` holds no bars, such as an unknown or removed series or a + /// study, and logs a warning. + /// A series that holds bars returns `true`, also when the bar is dropped as invalid. /// See [`set_data_operation_notifications`](Self::set_data_operation_notifications) to /// observe every accepted call, including unchanged updates. - pub fn update(&mut self, series: SeriesId, bar: Bar) { + pub fn update(&mut self, series: SeriesId, bar: Bar) -> bool { let operation = if self.host_events.data_operations && valid(&bar) { let clock = self.clock(); let slot = clock.bar_open(bar.time); @@ -242,7 +246,7 @@ impl Chart { let merged = merge(&mut item.bars, &mut BTreeMap::new(), &clock, incoming); item.feed.rejected_bars += merged.rejected; if let Some(marks) = &mut item.change_marks { - marks.record(&item.bars, &clock, before); + marks.record(&item.bars, &clock, before, self.frame_clock.as_ref()); } if merged.first_changed.is_some_and(|first| first + 1 < len) { item.revision = crate::model::next_revision(); @@ -255,7 +259,7 @@ impl Chart { .first_changed .is_some() } else { - return; + return false; }; if changed { self.data_updated(series); @@ -263,6 +267,7 @@ impl Chart { if let Some(operation) = operation { self.data_operation(series, operation); } + true } /// Removes the last `count` bars of `series`, or all of them for a larger count, and returns @@ -324,10 +329,11 @@ impl Chart { /// Each eviction restarts the studies on the retained window, including their warm-up, so a /// stream of new bars restarts them once per `limit / 8 + 1` bars. Drawing timestamps /// are kept, even for evicted bars; markers and raw trades have independent lifetimes. - /// Unknown ids and study ids are ignored with a warning. - pub fn set_bar_limit(&mut self, series: SeriesId, limit: Option) { + /// Returns `false` when `series` holds no bars, such as an unknown or removed series or a + /// study, and logs a warning. + pub fn set_bar_limit(&mut self, series: SeriesId, limit: Option) -> bool { if !self.bar_series_present(series, "set_bar_limit") { - return; + return false; } match limit { Some(limit) => { @@ -341,6 +347,7 @@ impl Chart { if !self.replay_windows(series) && self.enforce_bar_limit(series) > 0 { self.data_updated(series); } + true } /// The retained-bar limit of `series`, or `None` when unlimited or absent. The main bars keep @@ -578,13 +585,17 @@ impl Chart { /// Replaces the markers drawn on the bars of `series` (trade signals, events). /// - /// Bar series accept data; unknown ids and study ids are ignored with a warning. - pub fn set_markers(&mut self, series: SeriesId, markers: Vec) { + /// Returns `false` when `series` holds no bars, such as an unknown or removed series or a + /// study, and logs a warning. + pub fn set_markers(&mut self, series: SeriesId, markers: Vec) -> bool { if let Some(item) = self.price_series.iter_mut().find(|item| item.id == series) { item.markers = markers.into(); } else if self.main_series_present && holds_bars(series, "set_markers") { self.marks = markers.into(); + } else { + return false; } + true } /// The markers of `series` from [`set_markers`](Self::set_markers), without those of a @@ -613,13 +624,17 @@ impl Chart { /// Sets whether the markers of `series` widen its autoscaled price range and where they /// are painted. The main series' options also apply to the bar marks of a mark source. /// - /// Bar series accept options; unknown ids and study ids are ignored with a warning. - pub fn set_marker_options(&mut self, series: SeriesId, options: MarkerOptions) { + /// Returns `false` when `series` holds no bars, such as an unknown or removed series or a + /// study, and logs a warning. + pub fn set_marker_options(&mut self, series: SeriesId, options: MarkerOptions) -> bool { if let Some(item) = self.price_series.iter_mut().find(|item| item.id == series) { item.marker_options = options; } else if self.main_series_present && holds_bars(series, "set_marker_options") { self.marker_options = options; + } else { + return false; } + true } /// Replaces the price lines drawn on the scale of `series`. Handles of its previous lines, @@ -627,12 +642,16 @@ impl Chart { /// /// Every bar series accepts price lines. The price /// scale does not fit to them: a line whose price is off the scale or not finite is not drawn. - pub fn set_price_lines(&mut self, series: SeriesId, lines: Vec) { + /// Returns `false` when `series` holds no bars, as + /// [`add_price_line`](Self::add_price_line) returns `None`. + pub fn set_price_lines(&mut self, series: SeriesId, lines: Vec) -> bool { let first = self.next_price_line; self.next_price_line += lines.len() as u64; - if let Some(stored) = self.price_lines_mut(series, "set_price_lines") { - *stored = (first..).map(PriceLineId).zip(lines).collect(); - } + let Some(stored) = self.price_lines_mut(series, "set_price_lines") else { + return false; + }; + *stored = (first..).map(PriceLineId).zip(lines).collect(); + true } /// Adds `line` to the price lines drawn on the scale of `series` and returns its handle, @@ -750,7 +769,12 @@ impl Chart { merged.first_changed }); if let (Some(marks), Some(closes)) = (&mut self.change_marks, closes) { - marks.record(&self.state.data().bars, clock, closes); + marks.record( + &self.state.data().bars, + clock, + closes, + self.frame_clock.as_ref(), + ); } self.feed.rejected_bars += merged.rejected; #[cfg(feature = "drawings")] @@ -846,7 +870,8 @@ impl Chart { self.anchor_drawing_points(); self.chart_type_params .resolve_sizes(&self.state.data().bars, &mut self.pending_box_sizes); - // Range bars come from the held trades, as of the replay cutoff, while there are any. + // Range bars come from the held trades, as of the replay cutoff, while there are any, + // after the approximation of the bars before them. let cutoff = self.replay_time(); let ranges = &mut self.execution_ranges; let executions = self @@ -856,6 +881,9 @@ impl Chart { .and_then(|link| { ranges.bars( &self.chart_type_params, + &self.state.data().bars, + self.state.revision(), + &link.clock, link.trades.revision(), link.trades.iter(), cutoff, @@ -994,7 +1022,7 @@ impl Chart { } let right = self.right_edge().right; let scale = self.state.time_scale_mut(); - let full = f64::from(scale.width()) / f64::from(scale.bar_spacing()) - 1.0; + let full = (f64::from(scale.width()) - 1.0) / f64::from(scale.bar_spacing()) - 1.0; let last = scale.position(scale.base_idx() as f64) - scale.position(0.0); let stop = full.clamp(0.0, last); // The right edge a stop leaves at `full` can read back a rounding error short of it. diff --git a/vendor/egui-charts/src/widget/series/options.rs b/vendor/egui-charts/src/widget/series/options.rs index 01a44d0..54c8971 100644 --- a/vendor/egui-charts/src/widget/series/options.rs +++ b/vendor/egui-charts/src/widget/series/options.rs @@ -762,11 +762,15 @@ impl Chart { .remove(&scale) .expect("scale was inserted"); let old = std::mem::replace(self.state.price_scale_mut(), next); - // Joining a scale preserves its bounds in scale units, even with a new reference. + // Joining a scale preserves its bounds in scale units, even with a new reference. A + // fit in other units, such as prices on a logarithmic scale without a positive value + // in view, keeps the prices instead. if self.state.price_scale().is_manual() { - let range = self.state.price_scale().range(); - self.state.fit_price_scale(std::iter::empty()); - self.state.price_scale_mut().set_range(range.min, range.max); + let main = self.state.price_scale(); + let (range, mode) = (main.range(), main.transform().mode); + if self.state.fit_price_scale(std::iter::empty()).mode == mode { + self.state.price_scale_mut().set_range(range.min, range.max); + } } self.series_scales.insert(self.main_series_scale, old); self.main_series_scale = scale; diff --git a/vendor/egui-charts/src/widget/series/paint.rs b/vendor/egui-charts/src/widget/series/paint.rs index 178e5b2..2592af5 100644 --- a/vendor/egui-charts/src/widget/series/paint.rs +++ b/vendor/egui-charts/src/widget/series/paint.rs @@ -558,31 +558,18 @@ impl Chart { widget: Rect, rect: Rect, ) { - let interaction = self.chart_options.handle_scale; for (key, axis) in self.secondary_axes(widget, rect) { let response = ui.interact( axis, ui.scope_id().with(("series_axis", key)), - egui::Sense::drag(), + egui::Sense::click_and_drag(), ); + let gestures = self.price_axis_gestures(ui, &response, Rect::EVERYTHING); let scale = self.pane_price_scale_mut(self.main_series_pane(), key); - if response.double_clicked() - && interaction.enabled - && interaction.axis_double_click_reset.price - { + if gestures.reset { scale.reset(); - } else if response.dragged() - && interaction.enabled - && interaction.axis_pressed_mouse_move.price - { - let delta = ui.input(|input| input.pointer.delta().y); - let range = scale.range(); - let anchor = (range.min + range.max) * 0.5; - scale.zoom( - (f64::from(delta) / f64::from(rect.height().max(1.0))).exp(), - anchor, - ); } + gestures.zoom(scale, rect.top(), rect.bottom()); } } @@ -639,6 +626,8 @@ impl Chart { axis, &study_axis, self.percentage_formatter.as_deref(), + colors.text, + &|pos| self.background_at(widget, pos), )); } continue; @@ -661,6 +650,8 @@ impl Chart { )); } if study_axis.show_study_values { + let last_in_view = + crate::chart::rendering::axes::last_bar_in_view(&self.get_chart_mapping()); for study in &assigned { let mapping = study .scale_mapping() @@ -672,6 +663,7 @@ impl Chart { label_rect, &mapping, *study, + last_in_view, axis.right(), &mut tags, None, @@ -700,6 +692,8 @@ impl Chart { .edge_ticks_visible .then_some(label_rect), )); + // A tag led by a long name can be wider than the scale's tick labels. + measured = measured.max(crate::chart::rendering::axes::axis_tags_width(&tags)); ui.interact( axis, ui.scope_id().with(("series_axis", key)), diff --git a/vendor/egui-charts/src/widget/series/scales/mod.rs b/vendor/egui-charts/src/widget/series/scales/mod.rs index a2ff4d4..052869e 100644 --- a/vendor/egui-charts/src/widget/series/scales/mod.rs +++ b/vendor/egui-charts/src/widget/series/scales/mod.rs @@ -39,21 +39,32 @@ fn shared_prices( ) }) .flat_map(move |line| { - let plot = study.plot_style(line); - range + let mut values = range .clone() .filter_map(move |bar| study.plot_value(line, bar)) .filter(|value| value.is_finite()) - .chain(std::iter::once(0.0).filter(move |_| { - matches!( - plot.plot_type, - PlotType::Histogram | PlotType::Columns | PlotType::Area - ) - })) + .peekable(); + // Columns and areas reach down to zero beside a value, never in a view without one. + let base = values.peek().is_some() + && matches!( + study.plot_style(line).plot_type, + PlotType::Histogram | PlotType::Columns | PlotType::Area + ); + values.chain(base.then_some(0.0)) }) .chain(fills) } +/// `transform` as `scale` fitted it this frame: a logarithmic scale without a positive value +/// in view shows the prices as they are. +fn fitted_transform(scale: &PriceScale, transform: PriceTransform) -> PriceTransform { + if transform.mode == PriceScaleMode::Logarithmic && scale.transform().mode != transform.mode { + PriceTransform::default() + } else { + transform + } +} + impl Chart { /// The pane's saved axis layout, or `None` for an unknown pane. pub fn pane_axis_options(&self, pane: PaneId) -> Option { @@ -995,25 +1006,32 @@ impl Chart { let logarithmic = self .series_price_scale(item.id) .is_some_and(|scale| scale.options().mode == PriceScaleMode::Logarithmic); - let base = item - .options - .columns_base - .filter(|_| item.options.chart_type == ChartType::Columns && !bars.is_empty()); - let default = bars - .iter() - .flat_map(|bar| item.extremes(bar)) - .chain( - bars.iter() - .flat_map(|bar| [bar.open, bar.close]) - .filter(|_| logarithmic && item.options.chart_type.uses_ohlc()), - ) - .chain(base) - .filter(|value| value.is_finite() && (!logarithmic || *value > 0.0)) - .fold(None, |range: Option<(f64, f64)>, value| { - Some(range.map_or((value, value), |(min, max)| { - (min.min(value), max.max(value)) - })) - }); + // The base counts beside a value in view, never over whitespace alone. + let base = item.options.columns_base.filter(|_| { + item.options.chart_type == ChartType::Columns + && bars + .iter() + .flat_map(|bar| item.extremes(bar)) + .any(f64::is_finite) + }); + let range = |positive: bool| { + bars.iter() + .flat_map(|bar| item.extremes(bar)) + .chain( + bars.iter() + .flat_map(|bar| [bar.open, bar.close]) + .filter(|_| logarithmic && item.options.chart_type.uses_ohlc()), + ) + .chain(base) + .filter(|value| value.is_finite() && (!positive || *value > 0.0)) + .fold(None, |range: Option<(f64, f64)>, value| { + Some(range.map_or((value, value), |(min, max)| { + (min.min(value), max.max(value)) + })) + }) + }; + // Without a positive value a logarithmic scale fits the prices as they are. + let default = range(logarithmic).or_else(|| range(false).filter(|_| logarithmic)); match &item.options.style.autoscale { Some(provider) => provider.info(bars, default), None => default.map(Into::into), @@ -1072,7 +1090,12 @@ impl Chart { let mut margins = AutoscaleMargins::default(); let mut reference = None; let mode = self.pane_price_scale(pane, key).options().mode; + // What the regular fit would show, for a logarithmic scale without a positive value. + let mut prices = (f64::INFINITY, f64::NEG_INFINITY); let mut include = |bounds: &mut (f64, f64), value: f64, transform: PriceTransform| { + if value.is_finite() { + prices = (prices.0.min(value), prices.1.max(value)); + } if mode == PriceScaleMode::Logarithmic && value <= 0.0 { return; } @@ -1100,10 +1123,13 @@ impl Chart { include(&mut bounds, value, transform); } } - if bounds.0.is_finite() && mode != PriceScaleMode::Logarithmic { - let padding = crate::scales::auto_scale_span(bounds.0, bounds.1) * 0.1; - bounds.0 -= padding; - bounds.1 += padding; + // A tenth of the range in the scale's own units, logarithmic ones included. + let pad = |(min, max): (f64, f64), mode| { + let padding = crate::scales::fit_span(mode, min, max) * 0.1; + (min - padding, max + padding) + }; + if bounds.0.is_finite() { + bounds = pad(bounds, mode); } for (&id, study) in self .study_ids @@ -1127,8 +1153,14 @@ impl Chart { } let transform = self.shared_study_transform(id, study.as_ref(), key); if mode == PriceScaleMode::Logarithmic { + // Padded as the regular value range below is. + let mut own = (f64::INFINITY, f64::NEG_INFINITY); for value in shared_prices(study.as_ref(), visible.clone()) { - include(&mut bounds, value, transform); + include(&mut own, value, transform); + } + if own.0.is_finite() { + let own = pad(own, mode); + bounds = (bounds.0.min(own.0), bounds.1.max(own.1)); } } else if !self.is_custom_data(id) && let Some(range) = crate::widget::IndicatorPane::with_config( @@ -1147,6 +1179,11 @@ impl Chart { } } } + if reference.is_none() && mode == PriceScaleMode::Logarithmic && prices.0.is_finite() { + // No positive value in view: this frame shows the prices as they are. + reference = Some(PriceTransform::default()); + bounds = pad(prices, PriceScaleMode::Normal); + } let Some(mut transform) = reference else { continue; }; @@ -1155,7 +1192,7 @@ impl Chart { transform.base = 1.0; } let scale = self.pane_price_scale_mut(pane, key); - let manual = (scale.is_manual() && scale.transform().mode == mode) + let manual = (scale.is_manual() && scale.transform().mode == transform.mode) .then(|| (scale.range(), scale.bar_ratio())); scale.rebase(transform); if let Some((range, ratio)) = manual { @@ -1222,9 +1259,10 @@ impl Chart { for key in keys { self.ensure_series_scale(key); } + // Each scale's transform, bounds in its units, pixel margins and bounds in prices. let mut values = std::collections::HashMap::< SeriesScale, - (PriceTransform, f64, f64, AutoscaleMargins), + (PriceTransform, f64, f64, AutoscaleMargins, (f64, f64)), >::new(); for item in self.main_pane_series() { let transform = self.series_transform(item); @@ -1234,6 +1272,7 @@ impl Chart { f64::INFINITY, f64::NEG_INFINITY, AutoscaleMargins::default(), + (f64::INFINITY, f64::NEG_INFINITY), )); let markers = self.marker_prices(&item.markers, &[], item.marker_options); for value in self @@ -1246,6 +1285,9 @@ impl Chart { }) .chain(markers) { + if value.is_finite() { + entry.4 = (entry.4.0.min(value), entry.4.1.max(value)); + } let value = transform.to_scale(value); if value.is_finite() { if !entry.1.is_finite() { @@ -1279,12 +1321,16 @@ impl Chart { f64::INFINITY, f64::NEG_INFINITY, AutoscaleMargins::default(), + (f64::INFINITY, f64::NEG_INFINITY), )); let primitive_prices = self.primitive_autoscale(id).flat_map(|info| { entry.3.merge(info.margins); [info.price_range.0, info.price_range.1] }); for value in shared_prices(study.as_ref(), start..end).chain(primitive_prices) { + if value.is_finite() { + entry.4 = (entry.4.0.min(value), entry.4.1.max(value)); + } if transform.mode == PriceScaleMode::Logarithmic && value <= 0.0 { continue; } @@ -1297,7 +1343,16 @@ impl Chart { } let mut main = Vec::new(); let mut pixel_margins = std::collections::HashMap::new(); - for (key, (transform, min, max, margins)) in values { + for (key, (mut transform, mut min, mut max, margins, prices)) in values { + // No positive value in view: this frame shows the prices as they are. The main + // series' scale decides so in its own fit. + if !min.is_finite() + && transform.mode == PriceScaleMode::Logarithmic + && prices.0.is_finite() + && key != self.main_series_scale + { + (transform, min, max) = (PriceTransform::default(), prices.0, prices.1); + } // The main series also fits its scale, so the frame decides on those margins. if margins != AutoscaleMargins::default() && (min.is_finite() || key == self.main_series_scale) @@ -1361,19 +1416,18 @@ impl Chart { } _ => return None, }; + let transform = self.shared_study_transform(id, study.as_ref(), key); if pane == self.main_series_pane() { - return Some(self.secondary_scale(key).map( - self.shared_study_transform(id, study.as_ref(), key), + let scale = self.secondary_scale(key); + return Some(scale.map( + fitted_transform(scale, transform), rect.top(), rect.bottom(), )); } let pane = self.pane_layout.panes.iter().find(|item| item.id == pane)?; - Some(self.pane_price_scale(pane.id, key).map( - self.shared_study_transform(id, study.as_ref(), key), - 0.0, - 1.0, - )) + let scale = self.pane_price_scale(pane.id, key); + Some(scale.map(fitted_transform(scale, transform), 0.0, 1.0)) }) .collect(); for (at, map) in maps.into_iter().enumerate() { @@ -1385,11 +1439,14 @@ impl Chart { } pub(in crate::widget) fn series_map(&self, item: &PriceSeries, rect: Rect) -> PriceMap { + let scale = self.series_price_scale(item.id).expect("present series"); self.series_display_map( item.id, - self.series_price_scale(item.id) - .expect("present series") - .map(self.series_transform(item), rect.top(), rect.bottom()), + scale.map( + fitted_transform(scale, self.series_transform(item)), + rect.top(), + rect.bottom(), + ), ) .with_thousands_sep(self.config.thousands_sep) } diff --git a/vendor/egui-charts/src/widget/series/scales/tests.rs b/vendor/egui-charts/src/widget/series/scales/tests.rs index 3209d5c..545ac3c 100644 --- a/vendor/egui-charts/src/widget/series/scales/tests.rs +++ b/vendor/egui-charts/src/widget/series/scales/tests.rs @@ -150,11 +150,12 @@ fn fit_content_includes_added_series_across_panes() { }; let margin = if case == "fixed edges" { 0.0 } else { 3.0 }; let pixels = if case == "pixels" { 60.0 } else { 0.0 }; - let expected = - ((plot.width() - pixels) / (slots + if pixels > 0.0 { 0.0 } else { margin })).clamp( - if case == "minimum" { 100.0 } else { 0.5 }, - if case == "maximum" { 4.0 } else { f32::MAX }, - ); + let expected = ((plot.width() - 1.0 - pixels) + / (slots + if pixels > 0.0 { 0.0 } else { margin })) + .clamp( + if case == "minimum" { 100.0 } else { 0.5 }, + if case == "maximum" { 4.0 } else { f32::MAX }, + ); assert!( (chart.get_time_scale_state().0 - expected).abs() < 0.001, "{case}: spacing {:?} != {expected}", @@ -237,7 +238,7 @@ fn fit_content_includes_added_series_across_panes() { }; assert!( (chart.get_time_scale_state().0 - - chart.get_rendered_price_rect().width() / (slots + 3.0)) + - (chart.get_rendered_price_rect().width() - 1.0) / (slots + 3.0)) .abs() < 0.001, "{case}: fit after replacing the fallback domain" @@ -286,7 +287,8 @@ fn added_only_appends_keep_a_scrolled_back_view() { let next = data[201].time + TimeDelta::minutes(1); chart.update(id, Bar::new(next, 10.0, 10.0, 10.0, 10.0, 1.0)); frame(&ctx, &mut chart, 0.5, vec![]); - assert_eq!(chart.get_time_scale_state().1, 2.5, "{added_only}"); + // TradeCraft preserves the chosen near-live offset when a new bar arrives. + assert_eq!(chart.get_time_scale_state().1, -1.0, "{added_only}"); } } @@ -1810,6 +1812,8 @@ fn magnet_snaps_to_study_values_on_their_own_scale() { /// occupies 80% of the pane; a lone zero-crossing bar instead starts at ln(5). #[test] fn log_fit_includes_positive_ohlc_of_zero_crossing_bars() { + use crate::studies::{CustomIndicator, IndicatorValue, PlotType, StudyScale}; + use crate::widget::PaneScale; for secondary in [false, true] { for count in [1, 2] { let mut input = bars(&[10.0, 15.0]); @@ -1850,6 +1854,306 @@ fn log_fit_includes_positive_ohlc_of_zero_crossing_bars() { } } } + // Without a positive price in view the scale shows the regular axis, a spread from -20 to + // -10 or bars at zero, until positive prices come into view. + for secondary in [false, true] { + for (low, high) in [(-20.0, -10.0), (0.0, 0.0)] { + let mut input = bars(&[high, low]); + for bar in &mut input { + bar.low = low; + bar.high = high; + } + let fit = |mode| { + let mut chart = Chart::new(BarData::from_bars(input.clone())); + let id = if secondary { + let id = chart.add_series(SeriesOptions { + chart_type: ChartType::Candles, + scale: SeriesScale::Left, + ..Default::default() + }); + chart.set_data(id, input.clone()); + id + } else { + SeriesId::MAIN + }; + chart.series_price_scale_mut(id).unwrap().options_mut().mode = mode; + frame(&egui::Context::default(), &mut chart, 0.0, vec![]); + (chart, id) + }; + let axis = |chart: &Chart, id| { + let map = chart.series_price_map(id).unwrap(); + let labels: Vec<_> = map.marks().into_iter().map(|mark| mark.label).collect(); + (map.range(), labels) + }; + let (mut chart, id) = fit(PriceScaleMode::Logarithmic); + let regular = axis(&fit(PriceScaleMode::Normal).0, id); + assert_eq!( + axis(&chart, id), + regular, + "secondary={secondary}, {low}..{high}" + ); + chart.set_data(id, bars(&[10.0, 15.0])); + frame(&egui::Context::default(), &mut chart, 0.1, vec![]); + let map = chart.series_price_map(id).unwrap(); + assert_eq!(map.transform().mode, PriceScaleMode::Logarithmic); + let span = (15.0_f64.ln() - 10.0_f64.ln()) / 0.8; + assert!((map.range().max - (15.0_f64.ln() + span * 0.1)).abs() < 1e-10); + } + } + // A range scaled by hand keeps its prices while the scale shows prices for want of a + // positive value, on the main scale, beside it and in a pane of its own, also while no bar + // is in view. One scaled by hand to prices at or below zero leaves nothing to keep when + // positive prices return, so the scale fits them again. + for place in ["main", "left", "pane"] { + let mut input = bars(&[100.0; 20]); + for (at, bar) in input.iter_mut().enumerate() { + let (low, high) = if at < 10 { + (50.0, 150.0) + } else { + (-20.0, -10.0) + }; + (bar.open, bar.high, bar.low, bar.close) = (high, high, low, low); + } + let mut chart = Chart::new(BarData::from_bars(input.clone())); + let id = if place == "main" { + SeriesId::MAIN + } else { + let id = chart.add_series(SeriesOptions { + chart_type: ChartType::Candles, + scale: if place == "left" { + SeriesScale::Left + } else { + SeriesScale::Right + }, + ..Default::default() + }); + chart.set_data(id, input); + if place == "pane" { + let pane = chart.add_pane(); + assert!(chart.move_series_to_pane(id, pane)); + } + id + }; + chart.series_price_scale_mut(id).unwrap().options_mut().mode = PriceScaleMode::Logarithmic; + let ctx = egui::Context::default(); + let mut time = 0.0; + let mut view = |chart: &mut Chart, first: f32| { + assert!( + chart + .set_visible_logical_range(crate::model::LogicalRange::new(first, first + 9.0)) + ); + time += 0.1; + frame(&ctx, chart, time, vec![]); + chart.series_price_map(id).unwrap() + }; + let near = |range: crate::scales::PriceRange, (min, max): (f64, f64)| { + (range.min - min).abs() < 1e-9 && (range.max - max).abs() < 1e-9 + }; + view(&mut chart, 0.0); + let logarithmic = (50.0_f64.ln(), 150.0_f64.ln()); + chart + .series_price_scale_mut(id) + .unwrap() + .set_range(logarithmic.0, logarithmic.1); + let map = view(&mut chart, 10.0); + assert_eq!(map.transform().mode, PriceScaleMode::Normal, "{place}"); + assert!( + near(map.range(), (50.0, 150.0)), + "{place}: {:?}", + map.range() + ); + let map = view(&mut chart, 0.0); + assert_eq!(map.transform().mode, PriceScaleMode::Logarithmic, "{place}"); + assert!(near(map.range(), logarithmic), "{place}: {:?}", map.range()); + + view(&mut chart, 10.0); + chart + .series_price_scale_mut(id) + .unwrap() + .set_range(-25.0, -5.0); + let map = view(&mut chart, 30.0); + assert_eq!(map.transform().mode, PriceScaleMode::Normal, "{place}"); + let range = map.range(); + assert!(near(range, (-25.0, -5.0)), "{place}: {range:?}"); + let range = view(&mut chart, 0.0).range(); + assert!( + range.min.is_finite() && range.max.is_finite() && range.min < range.max, + "{place}: {range:?}" + ); + assert!( + !chart.series_price_scale_mut(id).unwrap().is_manual(), + "{place}" + ); + } + // The main series without a positive value in view joins a logarithmic scale scaled by + // hand to 50..150, which keeps those prices. + let mut chart = Chart::new(BarData::from_bars(bars(&[-15.0; 10]))); + let id = chart.add_series(SeriesOptions { + scale: SeriesScale::Left, + ..Default::default() + }); + chart.set_data(id, bars(&[50.0, 150.0])); + chart.series_price_scale_mut(id).unwrap().options_mut().mode = PriceScaleMode::Logarithmic; + let ctx = egui::Context::default(); + frame(&ctx, &mut chart, 0.0, vec![]); + let logarithmic = (50.0_f64.ln(), 150.0_f64.ln()); + chart + .series_price_scale_mut(id) + .unwrap() + .set_range(logarithmic.0, logarithmic.1); + assert!(chart.set_series_scale(SeriesId::MAIN, SeriesScale::Left)); + frame(&ctx, &mut chart, 0.1, vec![]); + let range = chart.series_price_map(id).unwrap().range(); + assert!( + (range.min - logarithmic.0).abs() < 1e-9 && (range.max - logarithmic.1).abs() < 1e-9, + "join: {range:?}" + ); + // Columns reach down to zero only beside a value in view. A study drawing them keeps the + // units and range of its scale in a view without bars, in a pane of its own, beside the main + // scale and on it, in both modes; the regular mode fits that zero beside the values. + for (place, scale) in [ + ("pane", None), + ("left", Some(StudyScale::Shared(SeriesScale::Left))), + ("main", Some(StudyScale::Main)), + ] { + for mode in [PriceScaleMode::Normal, PriceScaleMode::Logarithmic] { + let mut study = CustomIndicator::new("Columns", |bars| { + (0..bars.len()) + .map(|at| IndicatorValue::Single(100.0 + 10.0 * at as f64)) + .collect() + }) + .with_overlay(scale.is_some()) + .with_plot_types(vec![PlotType::Histogram]); + if let Some(scale) = scale { + study = study.with_scale(scale); + } + let mut chart = Chart::new(BarData::from_bars(bars(&[100.0; 10]))); + let id = chart.add_indicator(Box::new(study)); + let ctx = egui::Context::default(); + frame(&ctx, &mut chart, 0.0, vec![]); + let pane = chart.series_pane(id).unwrap(); + let axis = PaneScale::Named(match scale { + Some(StudyScale::Shared(key)) => key, + _ => SeriesScale::Right, + }); + chart.pane_scale_mut(pane, axis).unwrap().options_mut().mode = mode; + let view = |chart: &mut Chart, first: f32, time: f64| { + let range = crate::model::LogicalRange::new(first, first + 9.0); + assert!(chart.set_visible_logical_range(range)); + frame(&ctx, chart, time, vec![]); + let scale = chart.pane_scale(pane, axis).unwrap(); + (scale.transform().mode, scale.range()) + }; + let fitted = view(&mut chart, 0.0, 0.1); + assert_eq!(fitted.0, mode, "{place}"); + assert!( + mode == PriceScaleMode::Logarithmic || fitted.1.min < 0.0, + "{place}: {fitted:?}" + ); + assert_eq!(view(&mut chart, 30.0, 0.2), fitted, "{place}, {mode:?}"); + } + } + // A host's columns base counts only beside a value of its series in view: over whitespace + // bars alone the scale keeps its units and range, beside the main scale and in a pane of + // its own. + for place in ["left", "pane"] { + for mode in [PriceScaleMode::Logarithmic, PriceScaleMode::Normal] { + let mut chart = Chart::new(BarData::from_bars(bars(&[100.0; 10]))); + let id = chart.add_series(SeriesOptions { + chart_type: ChartType::Columns, + columns_base: Some(0.0), + scale: if place == "left" { + SeriesScale::Left + } else { + SeriesScale::Right + }, + ..Default::default() + }); + if place == "pane" { + let pane = chart.add_pane(); + assert!(chart.move_series_to_pane(id, pane)); + } + let mut data = bars(&[10.0, 20.0, 30.0, 40.0, 50.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + for bar in &mut data[5..] { + *bar = Bar::whitespace(bar.time); + } + chart.set_data(id, data); + let ctx = egui::Context::default(); + frame(&ctx, &mut chart, 0.0, vec![]); + chart.series_price_scale_mut(id).unwrap().options_mut().mode = mode; + let view = |chart: &mut Chart, first: f32, last: f32, time: f64| { + let range = crate::model::LogicalRange::new(first, last); + assert!(chart.set_visible_logical_range(range)); + frame(&ctx, chart, time, vec![]); + let scale = chart.series_price_scale(id).unwrap(); + (scale.transform().mode, scale.range()) + }; + let fitted = view(&mut chart, 0.0, 4.0, 0.1); + assert_eq!(fitted.0, mode, "{place}"); + assert_eq!(view(&mut chart, 6.0, 9.0, 0.2), fitted, "{place}, {mode:?}"); + } + } +} + +/// A scale other than the main one keeps a tenth of its data's range free above and below +/// the data, a twelfth of the pane, in logarithmic units as in prices: a series from 50 to +/// 150 in a pane of its own and a study pane from 10 to 990.1. A series flat at 1.01 shows +/// the same prices in both modes. +#[test] +fn secondary_scales_keep_their_margin_in_logarithmic_mode() { + use crate::studies::{CustomIndicator, IndicatorValue}; + use crate::widget::PaneScale; + for (study, low, high) in [ + (false, 50.0, 150.0), + (true, 10.0, 990.1), + (false, 1.01, 1.01), + ] { + let mut regular = None; + for mode in [PriceScaleMode::Normal, PriceScaleMode::Logarithmic] { + let mut chart = Chart::new(BarData::from_bars(bars(&[100.0, 100.0]))); + let id = if study { + chart.add_indicator(Box::new( + CustomIndicator::new("Study", move |_| { + vec![IndicatorValue::Single(low), IndicatorValue::Single(high)] + }) + .with_overlay(false), + )) + } else { + let id = chart.add_series(SeriesOptions::default()); + chart.set_data(id, bars(&[low, high])); + let pane = chart.add_pane(); + assert!(chart.move_series_to_pane(id, pane)); + id + }; + let pane = chart.series_pane(id).unwrap(); + let axis = PaneScale::Named(SeriesScale::Right); + chart.pane_scale_mut(pane, axis).unwrap().options_mut().mode = mode; + frame(&egui::Context::default(), &mut chart, 0.0, vec![]); + let scale = chart.pane_scale(pane, axis).unwrap(); + let (transform, range) = (scale.transform(), scale.range()); + assert_eq!(transform.mode, mode); + let prices = (transform.to_price(range.min), transform.to_price(range.max)); + if low == high { + let regular = *regular.get_or_insert(prices); + assert!( + (prices.0 / regular.0 - 1.0).abs() < 1e-5 + && (prices.1 / regular.1 - 1.0).abs() < 1e-5, + "{mode:?}: {prices:?}, regular {regular:?}" + ); + continue; + } + let span = range.max - range.min; + for free in [ + range.max - transform.to_scale(high), + transform.to_scale(low) - range.min, + ] { + assert!( + (free / span - 1.0 / 12.0).abs() < 1e-9, + "study={study}, {mode:?}: {range:?}" + ); + } + } + } } /// The first transformed open after the gap is (100 + 100) / 2 = 100, @@ -1992,7 +2296,9 @@ fn comparisons_share_percent_ranges_with_individual_visible_references() { "join_main" => { chart.set_series_scale(SeriesId::MAIN, SeriesScale::Left); } - _ => chart.set_data(first, Vec::new()), + _ => { + chart.set_data(first, Vec::new()); + } } frame(&ctx, &mut chart, 0.3, vec![]); let range = chart.series_price_scale(second).unwrap().range(); @@ -2443,8 +2749,9 @@ fn autoscale_contributions_reserve_pixels_per_pane_and_scale() { let plot_height = bottom - top; let transform = map.transform(); let (low, high) = (transform.to_scale(100.0), transform.to_scale(last)); - // Secondary bar panes already pad their raw span by 10% on each side. - let padding = if placement == "added" && mode != PriceScaleMode::Logarithmic { + // Secondary bar panes already pad their span by 10% on each side, in + // logarithmic units too. + let padding = if placement == "added" { (high - low) * 0.1 } else { 0.0 @@ -2545,8 +2852,9 @@ fn autoscale_contributions_reserve_pixels_per_pane_and_scale() { assert!(!chart.series_price_scale(target).unwrap().is_manual()); let transform = chart.series_price_map(target).unwrap().transform(); let (low, high) = (transform.to_scale(100.0), transform.to_scale(200.0)); - // Secondary bar panes already pad their raw span by 10% on each side. - let padding = if placement == "added" && mode != PriceScaleMode::Logarithmic { + // Secondary bar panes already pad their span by 10% on each side, in + // logarithmic units too. + let padding = if placement == "added" { (high - low) * 0.1 } else { 0.0 @@ -2758,7 +3066,8 @@ fn column_padding_searches_past_neighbours_and_single_point_times() { } /// Each added series writes its last value with its own scale's decimals, led by its own -/// name once the axis shows names, and a host formatter still replaces the decimals. +/// name once the axis shows names, and a host formatter still replaces the decimals. A +/// column on either side of the plot widens to hold a named tag whole. #[test] fn added_series_value_tags_use_their_scale_precision_and_name() { let ctx = egui::Context::default(); @@ -2776,8 +3085,8 @@ fn added_series_value_tags_use_their_scale_precision_and_name() { .set_price_precision(Some(decimals)); id }; - let alpha = add("Alpha", SeriesScale::Separate(2), 3, 200.5); - add("Beta", SeriesScale::Separate(3), 0, 300.5); + let alpha = add("Alpha Growth", SeriesScale::Separate(2), 3, 200.5); + add("Beta Industrial", SeriesScale::Separate(3), 0, 300.5); chart.config.price_axis.show_symbol_name = true; frame(&ctx, &mut chart, 0.0, vec![]); let labels = |chart: &Chart, key, rect| { @@ -2789,9 +3098,41 @@ fn added_series_value_tags_use_their_scale_precision_and_name() { let rect = chart.last_rendered_price_rect; assert_eq!( labels(&chart, SeriesScale::Separate(2), rect), - ["Alpha 200.500"] + ["Alpha Growth 200.500"] ); - assert_eq!(labels(&chart, SeriesScale::Separate(3), rect), ["Beta 300"]); + assert_eq!( + labels(&chart, SeriesScale::Separate(3), rect), + ["Beta Industrial 300"] + ); + for side in [crate::model::AxisSide::Left, crate::model::AxisSide::Right] { + assert!(chart.place_pane_scales(chart.main_series_pane(), side)); + frame(&ctx, &mut chart, 0.1, vec![]); + let painted = crate::widget::test_frames::shapes(&ctx, &mut chart, 0.2, vec![]); + // The central panel's margin around the chart. + let widget = egui::Rect::from_min_max(Pos2::new(8.0, 8.0), Pos2::new(792.0, 592.0)); + let plot = chart.last_rendered_price_rect; + assert_eq!(chart.calculate_layout_rects(widget).price_rect, plot); + let axes = chart.secondary_axes(widget, plot); + for (key, label) in [ + (SeriesScale::Separate(2), "Alpha Growth 200.500"), + (SeriesScale::Separate(3), "Beta Industrial 300"), + ] { + let column = axes.iter().find(|(axis, _)| *axis == key).unwrap().1; + let text = painted + .iter() + .find_map(|shape| match shape { + egui::Shape::Text(text) if text.galley.text() == label => { + Some(text.visual_bounding_rect()) + } + _ => None, + }) + .unwrap_or_else(|| panic!("{side:?}: {label} is painted")); + assert!( + text.left() >= column.left() && text.right() <= column.right(), + "{side:?}: {label} at {text:?} fits {column:?}" + ); + } + } chart.config.price_axis.show_symbol_name = false; assert_eq!(labels(&chart, SeriesScale::Separate(2), rect), ["200.500"]); chart.set_series_formatter( @@ -3837,11 +4178,11 @@ fn series_data_is_queried_popped_and_reported() { assert!(chart.set_visible_logical_range(LogicalRange::new(0.0, 4.0))); frame(&ctx, &mut chart, 0.1, vec![]); let plot = chart.get_rendered_price_rect(); - let spacing = plot.width() / 5.0; + let spacing = (plot.width() - 1.0) / 5.0; for index in 0..5 { let time = minute(index); let x = chart.time_to_x(time).unwrap(); - let expected = plot.left() + (index as f32 + 0.5) * spacing - 1.0; + let expected = plot.left() + (index as f32 + 0.5) * spacing; assert!( (x - expected).abs() < 0.001, "centre {index}: {x} != {expected}" @@ -4766,7 +5107,12 @@ fn study_without_values_in_view_adds_nothing_to_its_scale() { PriceScaleMode::Normal => (999.0, 1011.0), PriceScaleMode::Percentage => (-0.1, 1.1), PriceScaleMode::IndexedTo100 => (99.9, 101.1), - PriceScaleMode::Logarithmic => (1000_f64.ln(), 1010_f64.ln()), + // A tenth of the span of 1000 to 1010 in logarithmic units, as above. + PriceScaleMode::Logarithmic => { + let (low, high) = (1000_f64.ln(), 1010_f64.ln()); + let padding = (high - low) * 0.1; + (low - padding, high + padding) + } }, }; let height = f64::from(map.extent().1 - map.extent().0); diff --git a/vendor/egui-charts/src/widget/series/tests.rs b/vendor/egui-charts/src/widget/series/tests.rs index acff0e8..e7e23dd 100644 --- a/vendor/egui-charts/src/widget/series/tests.rs +++ b/vendor/egui-charts/src/widget/series/tests.rs @@ -212,6 +212,37 @@ fn window(start: i64, len: i64) -> Vec { (start..start + len).map(|i| bar(i * 60, 10.0)).collect() } +/// The bar setters report whether `series` holds bars, not whether the call changed them. +#[test] +fn bar_setters_report_whether_the_series_holds_bars() { + let mut chart = Chart::new(BarData::from_bars(vec![bar(0, 10.0), bar(60, 11.0)])); + let added = chart.add_series(SeriesOptions::default()); + let removed = chart.add_series(SeriesOptions::default()); + assert!(chart.remove_series(removed)); + let study = chart.add_indicator(Box::new(SMA::new(2))); + for (series, holds_bars) in [ + (SeriesId::MAIN, true), + (added, true), + (removed, false), + (study, false), + ] { + let results = [ + chart.set_data(series, vec![bar(0, 10.0)]), + chart.update(series, bar(60, 11.0)), + chart.set_bar_limit(series, NonZeroUsize::new(10)), + chart.set_markers(series, Vec::new()), + chart.set_marker_options(series, MarkerOptions::default()), + chart.set_price_lines(series, Vec::new()), + chart.set_change_markers(series, None), + ]; + assert_eq!(results, [holds_bars; 7], "{series:?}"); + } + // A negative volume is invalid, so the bar is dropped. + let mut dropped = bar(120, 12.0); + dropped.volume = -1.0; + assert!(chart.update(SeriesId::MAIN, dropped)); +} + /// Streaming keeps the configured live offset, or the same scrolled-back element. #[test] fn appended_bars_keep_the_view() { @@ -525,7 +556,8 @@ fn set_data_newer_window_keeps_a_scrolled_back_view_on_bars() { let expected = match minute { ..165 => -30.0 - (minute - 99) as f32, 165 => 0.0, - _ => 2.5, + // TradeCraft keeps the user's offset rather than restoring the default margin. + _ => 0.0, }; assert_eq!( chart.state.time_scale().right_offset(), @@ -540,7 +572,7 @@ fn set_data_newer_window_keeps_a_scrolled_back_view_on_bars() { // left edge, then that bar stays there as the window moves on. At 23 px a bar the right // edge of the stopped view reads back a rounding error short of a full plot. let mut chart = scrolled(23.0, -30.0); - let visible = f64::from(chart.state.time_scale().width()) / 23.0; + let visible = (f64::from(chart.state.time_scale().width()) - 1.0) / 23.0; for start in 1..=60 { chart.set_data(SeriesId::MAIN, window(start, 100)); frame(&ctx, &mut chart, start as f64, Vec::new()); @@ -556,7 +588,7 @@ fn set_data_newer_window_keeps_a_scrolled_back_view_on_bars() { // view. Indices 56, 43 and 30 at the right edge of a plot of about 35 bars, and the 88 // bars left fill the plot from its left border. let mut chart = scrolled(20.0, -30.0); - let visible = f64::from(chart.state.time_scale().width()) / 20.0; + let visible = (f64::from(chart.state.time_scale().width()) - 1.0) / 20.0; chart.set_bar_limit(SeriesId::MAIN, NonZeroUsize::new(100)); for minute in 100..=126 { chart.update(SeriesId::MAIN, bar(minute * 60, 10.0)); @@ -711,9 +743,15 @@ fn updates_reach_bars_studies_and_revision() { let revision = chart.state.revision(); for action in actions { match action { - Update(bar) => chart.update(SeriesId::MAIN, bar), - SetData(bars) => chart.set_data(SeriesId::MAIN, bars), - Limit(count) => chart.set_bar_limit(SeriesId::MAIN, NonZeroUsize::new(count)), + Update(bar) => { + chart.update(SeriesId::MAIN, bar); + } + SetData(bars) => { + chart.set_data(SeriesId::MAIN, bars); + } + Limit(count) => { + chart.set_bar_limit(SeriesId::MAIN, NonZeroUsize::new(count)); + } RemoveOldest(count) => { assert_eq!( chart.remove_oldest_bars(SeriesId::MAIN, count), diff --git a/vendor/egui-charts/src/widget/settings/apply.rs b/vendor/egui-charts/src/widget/settings/apply.rs index 8f98ab1..7f03030 100644 --- a/vendor/egui-charts/src/widget/settings/apply.rs +++ b/vendor/egui-charts/src/widget/settings/apply.rs @@ -2,7 +2,7 @@ use super::{ BackgroundType, ButtonVisibility, ChartSettingsState, GridLinesMode, PrecisionMode, - WatermarkMode, + ThousandsSeparator, WatermarkMode, }; use crate::{ Chart, @@ -33,6 +33,38 @@ fn axis_line_color(config: &ChartConfig) -> Color32 { } } +/// The right margin the dialog shows, in bars: the margin the view keeps, which for a margin set +/// in pixels is its width at the current bar spacing. +fn right_margin_bars(chart: &Chart) -> f32 { + let options = &chart.chart_options().time_scale; + options + .right_offset_pixels + .map_or(options.right_offset, |pixels| { + pixels / chart.state().time_scale().bar_spacing() + }) + .max(0.0) +} + +fn thousands_separator(separator: Option) -> ThousandsSeparator { + match separator { + None => ThousandsSeparator::Off, + Some(',') => ThousandsSeparator::Comma, + Some(' ') => ThousandsSeparator::Space, + Some('\'') => ThousandsSeparator::Apostrophe, + Some(other) => ThousandsSeparator::Other(other), + } +} + +fn thousands_sep(separator: ThousandsSeparator) -> Option { + match separator { + ThousandsSeparator::Off => None, + ThousandsSeparator::Comma => Some(','), + ThousandsSeparator::Space => Some(' '), + ThousandsSeparator::Apostrophe => Some('\''), + ThousandsSeparator::Other(other) => Some(other), + } +} + fn button_visibility(buttons: NavigationButtons) -> ButtonVisibility { match buttons { NavigationButtons::Always => ButtonVisibility::AlwaysVisible, @@ -63,6 +95,8 @@ pub enum ChartSettingsError { /// The bottom margin in percent. bottom: f32, }, + /// The right margin in bars is not finite or is negative. + RightMargin(f32), /// The crosshair line width is not finite or not above zero. CrosshairWidth(f32), /// The axis font size is zero. @@ -87,6 +121,7 @@ impl std::fmt::Display for ChartSettingsError { f.write_str(match self { Self::Timezone(_) => "Invalid timezone", Self::Margins { .. } => "Margins must leave room for prices", + Self::RightMargin(_) => "Right margin must be zero or more bars", Self::CrosshairWidth(_) => "Crosshair width must be above zero", Self::FontSize(_) => "Font sizes must be between 1 and 256", Self::PriceToBarRatio(_) => "Price-to-bar ratio must be positive and finite", @@ -124,6 +159,7 @@ impl ChartSettingsState { chart_type_params: Some(chart.chart_type_params().clone()), price_source: Some(chart.config().price_source), events: chart.event_visibility().clone(), + show_session_breaks: Some(config.show_session_breaks), order_flow: super::OrderFlowSettings { show_heatmap: chart .feed_link @@ -245,9 +281,12 @@ impl ChartSettingsState { settings.scales_and_lines.show_extended_session_price = config.show_extended_session_price; settings.scales_and_lines.extended_session_price_color = config.extended_session_price_color; - settings.scales_and_lines.symbol_price_color = chart - .series_style(crate::widget::SeriesId::MAIN) - .and_then(|style| style.price_line_color); + let main_style = chart.series_style(crate::widget::SeriesId::MAIN); + settings.scales_and_lines.symbol_price_color = + main_style.and_then(|style| style.price_line_color); + settings.scales_and_lines.price_line_source = + main_style.map(|style| style.price_line_source); + settings.scales_and_lines.thousands_sep = Some(thousands_separator(config.thousands_sep)); settings.scales_and_lines.lock_price_to_bar_ratio = chart.state().price_scale().bar_ratio_locked(); // An unlocked chart offers the ratio of the view it shows, which ticking the lock keeps; one @@ -275,7 +314,7 @@ impl ChartSettingsState { (chart.state().price_scale().options().scale_margins.top * 100.0) as f32; settings.margins.bottom_percent = (chart.state().price_scale().options().scale_margins.bottom * 100.0) as f32; - settings.margins.right_bars = chart.chart_options().time_scale.right_offset.max(0.0) as u32; + settings.margins.right_bars = right_margin_bars(chart); let scale = chart.state().price_scale(); settings.scales_and_lines.auto_scale = !scale.is_manual(); settings.scales_and_lines.log_scale = scale.options().mode == PriceScaleMode::Logarithmic; @@ -343,6 +382,7 @@ impl ChartSettingsState { settings.watermark.color = config.watermark_color; settings.scales_appearance.text_color = config.text_color; settings.scales_appearance.font_size = axis_font_size(config); + settings.scales_appearance.font_family = Some(config.axis_font_family.clone()); settings.scales_appearance.lines_color = axis_line_color(config); settings.btns.pane = button_visibility(config.pane_buttons); @@ -371,6 +411,10 @@ impl ChartSettingsState { { return Err(ChartSettingsError::Margins { top, bottom }); } + let right = self.margins.right_bars; + if !right.is_finite() || right < 0.0 { + return Err(ChartSettingsError::RightMargin(right)); + } if !self.crosshair.line_width.is_finite() || self.crosshair.line_width <= 0.0 { return Err(ChartSettingsError::CrosshairWidth( self.crosshair.line_width, @@ -410,7 +454,8 @@ impl ChartSettingsState { /// Apply the display controls offered by the dialog without rebuilding the chart or feed. /// Host-owned trading and alerts are left to their providers. Invalid timezone, - /// margins or crosshair width returns an error before changing the chart. + /// margins or crosshair width returns an error before changing the chart. The optional + /// choices that hold `None`, as in settings saved before they existed, keep the chart's. pub fn apply_to_chart(&self, chart: &mut Chart) -> Result<(), ChartSettingsError> { let timezone = self.validate()?; if let Some(params) = &self.chart_type_params { @@ -420,7 +465,7 @@ impl ChartSettingsState { reason: error, }); } - chart.set_chart_type_params(params.clone()); + chart.apply_chart_type_params(params.clone()); } if let Some(source) = self.price_source { chart.config_mut().price_source = source; @@ -559,6 +604,12 @@ impl ChartSettingsState { config.show_countdown = self.scales_and_lines.show_countdown; config.show_bid_ask = self.scales_and_lines.show_bid_ask; config.show_high_low = self.scales_and_lines.show_high_low; + if let Some(separator) = self.scales_and_lines.thousands_sep { + config.thousands_sep = thousands_sep(separator); + } + if let Some(show) = self.show_session_breaks { + config.show_session_breaks = show; + } set_unless_resolved( &mut config.vertical_grid_color, @@ -590,6 +641,9 @@ impl ChartSettingsState { if self.scales_appearance.font_size != axis_font_size(config) { config.axis_font_size = Some(f32::from(self.scales_appearance.font_size)); } + if let Some(family) = &self.scales_appearance.font_family { + config.axis_font_family.clone_from(family); + } config.show_watermark = self.watermark.mode != WatermarkMode::ReplayMode; config.watermark_color = self.watermark.color; if self.watermark.mode != WatermarkMode::Custom { @@ -601,9 +655,19 @@ impl ChartSettingsState { top: f64::from(self.margins.top_percent.clamp(0.0, 100.0)) / 100.0, bottom: f64::from(self.margins.bottom_percent.clamp(0.0, 100.0)) / 100.0, }; - if self.margins.right_bars != chart.chart_options().time_scale.right_offset.max(0.0) as u32 - { - chart.set_right_margin(self.margins.right_bars as f32); + // An unedited margin keeps the chart's, in bars or in pixels; an edited one is in bars. + // Settings saved before the margin could hold part of a bar, which hold none of the + // choices `from_chart` fills, hold the whole bars of the bar margin for an unedited one. + let whole_bars = chart + .chart_options() + .time_scale + .right_offset + .max(0.0) + .trunc(); + let saved_unedited = + self.scales_appearance.font_family.is_none() && self.margins.right_bars == whole_bars; + if self.margins.right_bars != right_margin_bars(chart) && !saved_unedited { + chart.set_right_margin(self.margins.right_bars); } let mode = if self.scales_and_lines.log_scale { PriceScaleMode::Logarithmic @@ -651,6 +715,9 @@ impl ChartSettingsState { chart.state.price_scale_mut().set_price_precision(precision); if let Some(style) = chart.series_style_mut(crate::widget::SeriesId::MAIN) { style.price_line_color = self.scales_and_lines.symbol_price_color; + if let Some(source) = self.scales_and_lines.price_line_source { + style.price_line_source = source; + } } chart.price_scale_mut().set_bar_ratio( self.scales_and_lines @@ -672,7 +739,7 @@ impl ChartSettingsState { style.wick_up = colors.wick_up; style.wick_down = colors.wick_down; if chart.chart_type_params() != ¶ms { - chart.set_chart_type_params(params); + chart.apply_chart_type_params(params); } } else if self.chart_type == crate::model::ChartType::HollowCandles { let mut params = chart.chart_type_params().clone(); @@ -688,7 +755,7 @@ impl ChartSettingsState { style.wick_up = colors.wick_up; style.wick_down = colors.wick_down; if chart.chart_type_params() != ¶ms { - chart.set_chart_type_params(params); + chart.apply_chart_type_params(params); } } else if self.chart_type == crate::model::ChartType::VolumeCandles { let mut params = chart.chart_type_params().clone(); @@ -717,7 +784,7 @@ impl ChartSettingsState { style.wick_down = colors.wick_down; } if chart.chart_type_params() != ¶ms { - chart.set_chart_type_params(params); + chart.apply_chart_type_params(params); } } else if self.chart_type != crate::model::ChartType::Bars { let candles = CandlesStyle { @@ -725,11 +792,10 @@ impl ChartSettingsState { wick_visible: self.candle_colors.show_wick, color_by_previous_close: self.candle_colors.color_by_previous_close, }; - // Other chart type parameters re-resolve their box sizes when set, so only a change is set. if chart.chart_type_params().styles.candles != candles { let mut params = chart.chart_type_params().clone(); params.styles.candles = candles; - chart.set_chart_type_params(params); + chart.apply_chart_type_params(params); } } Ok(()) @@ -1234,7 +1300,8 @@ mod tests { /// The state read from a chart applies back without changing its configuration, so pressing /// Ok without edits adds no undo step; colours that fell back to another stay unset. A colour - /// left as shown while the one it fell back to changes keeps what it showed. + /// left as shown while the one it fell back to changes keeps what it showed. A size resolved + /// from history keeps its value until its method is edited. #[test] fn unedited_settings_apply_records_no_undo() { let bars = || { @@ -1274,6 +1341,102 @@ mod tests { assert_eq!(config.grid_color, grid); assert_eq!(config.vertical_grid_color, Some(old_grid)); assert!(chart.can_undo()); + + // An ATR(14) reversal of 2 on 14 bars with a true range of 2 stays through a streamed + // bar with a true range of 16 and an unedited apply, which would make it + // (13 * 2 + 16) / 14 = 3. An edited period resolves again: ATR(15) seeds 44 / 15. + use crate::model::{BoxSizeMethod, ChartType, ChartTypeParams}; + let bar = |minute, high| { + let time = chrono::DateTime::UNIX_EPOCH + chrono::TimeDelta::minutes(minute); + Bar::new(time, 100.0, high, 99.0, 100.0, 0.0) + }; + let atr = |period| BoxSizeMethod::Atr { + period, + multiplier: 1.0, + }; + let mut chart = Chart::new(BarData::from_bars((0..14).map(|i| bar(i, 101.0)).collect())); + chart.set_chart_type(ChartType::Kagi); + chart.set_chart_type_params(ChartTypeParams { + kagi_size_method: atr(14), + ..Default::default() + }); + chart.update(crate::widget::SeriesId::MAIN, bar(14, 115.0)); + chart.user_action(|chart| { + ChartSettingsState::from_chart(chart) + .apply_to_chart(chart) + .unwrap(); + }); + assert!((chart.chart_type_params().kagi_reversal - 2.0).abs() < 1e-12); + assert!(!chart.can_undo()); + // An edited candle style and an unedited series settings apply keep it too. + let mut settings = ChartSettingsState::from_chart(&chart); + settings.candle_colors.show_wick = !settings.candle_colors.show_wick; + settings.apply_to_chart(&mut chart).unwrap(); + let series = chart.series_settings(); + chart.apply_series_settings(&series); + assert!((chart.chart_type_params().kagi_reversal - 2.0).abs() < 1e-12); + let mut settings = ChartSettingsState::from_chart(&chart); + settings + .chart_type_params + .as_mut() + .unwrap() + .kagi_size_method = atr(15); + settings.apply_to_chart(&mut chart).unwrap(); + assert!((chart.chart_type_params().kagi_reversal - 44.0 / 15.0).abs() < 1e-12); + } + + /// A size that waits for more history than is loaded is not invalid: the chart names the + /// bars it waits for and other settings apply. A fixed size of 0 is still rejected. Whitespace + /// bars do not count, so the size resolves once 14 bars with prices are loaded. + #[test] + fn settings_apply_while_a_history_derived_size_waits() { + use crate::model::{BoxSizeMethod, ChartType, ChartTypeParams}; + use crate::widget::test_frames::shapes; + let time = |minute| chrono::DateTime::UNIX_EPOCH + chrono::TimeDelta::minutes(minute); + let bar = |minute| Bar::new(time(minute), 100.0, 101.0, 99.0, 100.0, 0.0); + let bars = (-10..0) + .map(|minute| Bar::whitespace(time(minute))) + .chain((0..5).map(bar)) + .collect(); + let mut chart = Chart::new(BarData::from_bars(bars)); + chart.set_chart_type(ChartType::Renko); + chart.set_chart_type_params(ChartTypeParams { + renko_size_method: BoxSizeMethod::Atr { + period: 14, + multiplier: 1.0, + }, + ..Default::default() + }); + ChartSettingsState::from_chart(&chart) + .apply_to_chart(&mut chart) + .unwrap(); + let mut settings = ChartSettingsState::from_chart(&chart); + settings.scales_and_lines.show_price_line = !chart.config().show_price_line; + settings.apply_to_chart(&mut chart).unwrap(); + assert_eq!( + chart.config().show_price_line, + settings.scales_and_lines.show_price_line + ); + let ctx = Context::default(); + let painted = shapes(&ctx, &mut chart, 0.0, Vec::new()); + assert!(painted.iter().any(|shape| matches!(shape, Shape::Text(t) + if t.galley.text() == "Waiting for 14 bars of history to size the chart"))); + + let params = settings.chart_type_params.as_mut().unwrap(); + params.renko_size_method = BoxSizeMethod::Fixed; + params.renko_brick_size = 0.0; + assert!(matches!( + settings.apply_to_chart(&mut chart), + Err(ChartSettingsError::ChartTypeParams { + chart_type: ChartType::Renko, + .. + }) + )); + for minute in 5..14 { + chart.update(crate::widget::SeriesId::MAIN, bar(minute)); + } + chart.show_elements(); + assert!((chart.chart_type_params().renko_brick_size - 2.0).abs() < 1e-12); } /// Hollow candles colour by the close against the previous close, and are hollow when the @@ -2364,11 +2527,14 @@ mod tests { } /// The saved scale font size, axis line colour and pane button visibility render on the main, - /// study and time axes and in a maximized pane, and read back from the chart. + /// study and time axes and in a maximized pane, and read back from the chart. So does the + /// scale text colour, which also reaches the axis of a study on a scale of its own. #[test] fn scale_appearance_and_pane_button_settings_render_and_read_back() { - use crate::studies::RSI; + use crate::studies::{RSI, SMA, StudyScale}; + use crate::widget::PaneId; use crate::widget::test_frames::{chart, frame, shapes}; + const TEXT: Color32 = Color32::from_rgb(1, 2, 3); for (visibility, maximized) in [ (ButtonVisibility::AlwaysVisible, false), (ButtonVisibility::VisibleOnMouseOver, false), @@ -2379,10 +2545,13 @@ mod tests { let ctx = Context::default(); let mut chart = chart(&[100.0, 105.0], &[110.0, 115.0]); let study = chart.add_indicator(Box::new(RSI::new(14))); + let average = chart.add_indicator(Box::new(SMA::new(5))); + assert!(chart.set_indicator_scale(average, StudyScale::Independent)); frame(&ctx, &mut chart, 0.0, Vec::new()); chart.pane_layout.maximized = maximized.then(|| chart.series_pane(study).unwrap()); let mut settings = ChartSettingsState::from_chart(&chart); settings.scales_appearance.font_size = 18; + settings.scales_appearance.text_color = TEXT; settings.scales_appearance.lines_color = Color32::RED; settings.btns.pane = visibility; settings.apply_to_chart(&mut chart).unwrap(); @@ -2422,6 +2591,33 @@ mod tests { }); assert!(line, "axis line beside {rect:?}"); } + // The price axis and the average's own axis beside the price pane, the study pane's + // axis and the time axis. + let mut axes = vec![ + egui::Rect::from_x_y_ranges( + pane.chart_rect.right()..=pane.panel_rect.right(), + pane.chart_rect.y_range(), + ), + chart.time_axis_rect, + ]; + if !maximized { + let price_pane = &chart.pane_layout.panes[0]; + assert_eq!(price_pane.id, PaneId::MAIN); + let beside: Vec<_> = chart + .pane_scale_axes(PaneId::MAIN, price_pane.rect, plot) + .map(|(_, axis)| axis) + .collect(); + assert_eq!(beside.len(), 2, "{beside:?}"); + axes.extend(beside); + } + for axis in axes { + let label = painted.iter().any(|shape| { + matches!(shape, Shape::Text(text) + if axis.contains(text.pos) + && text.galley.job.sections[0].format.color == TEXT) + }); + assert!(label, "no label in the text colour on the axis at {axis:?}"); + } let button = egui::Rect::from_min_size( egui::Pos2::new(pane.chart_rect.right() - 22.0, pane.panel_rect.top() + 2.0), Vec2::splat(20.0), @@ -2529,4 +2725,107 @@ mod tests { // while one price unit per bar spans the plot's height in bar widths, about 91. assert!(range.max - range.min < 0.0875, "{range:?}"); } + + /// The session breaks switch and the bar the last price line follows reach the chart, read + /// back and are undone. Settings saved before these, the axis font family and the thousands + /// separator could be chosen hold none of them and keep the chart's. + #[test] + fn session_breaks_and_last_price_bar_apply_and_read_back() { + use crate::model::PriceLineSource::{LastBar, LastVisible}; + use crate::widget::{SeriesId, test_frames::chart}; + let read = |chart: &Chart| { + let style = chart.series_style(SeriesId::MAIN).unwrap(); + (chart.config().show_session_breaks, style.price_line_source) + }; + let mut chart = chart(&[100.0], &[110.0]); + let new_chart = ChartSettingsState::from_chart(&chart); + for (breaks, source) in [(true, LastVisible), (false, LastBar)] { + let mut settings = ChartSettingsState::from_chart(&chart); + settings.show_session_breaks = Some(breaks); + settings.scales_and_lines.price_line_source = Some(source); + chart.user_action(|chart| settings.apply_to_chart(chart).unwrap()); + assert_eq!(read(&chart), (breaks, source)); + let settings = ChartSettingsState::from_chart(&chart); + assert_eq!( + ( + settings.show_session_breaks, + settings.scales_and_lines.price_line_source + ), + (Some(breaks), Some(source)) + ); + } + assert!(chart.undo()); + assert_eq!(read(&chart), (true, LastVisible)); + + chart.config_mut().axis_font_family = egui::FontFamily::Monospace; + chart.config_mut().thousands_sep = Some('_'); + let mut saved = serde_json::to_value(new_chart).unwrap(); + for (group, choice) in [ + ("", "show_session_breaks"), + ("/scales_and_lines", "price_line_source"), + ("/scales_and_lines", "thousands_sep"), + ("/scales_appearance", "font_family"), + ] { + let group = saved.pointer_mut(group).unwrap().as_object_mut().unwrap(); + group.remove(choice).expect(choice); + } + let saved: ChartSettingsState = serde_json::from_value(saved).unwrap(); + saved.apply_to_chart(&mut chart).unwrap(); + assert_eq!(read(&chart), (true, LastVisible)); + assert_eq!(chart.config().axis_font_family, egui::FontFamily::Monospace); + assert_eq!(chart.config().thousands_sep, Some('_')); + } + + /// The right margin row shows the margin the view keeps: part of a bar as it is, and a margin + /// set in pixels as its width in bars at the bar spacing. Unedited settings leave the bar and + /// pixel margins as they were, and an edit sets the margin in bars. Settings saved before the + /// row could hold part of a bar hold the whole bars of the bar margin and keep the chart's. + #[test] + fn right_margin_row_shows_the_margin_the_view_keeps() { + use crate::widget::test_frames::chart; + // A new chart, and one keeping 60 pixels at the default bar spacing of 6 points. + for (pixels, shown) in [(None, 2.5), (Some(60.0), 10.0)] { + let mut options = crate::config::ChartOptions::default(); + options.time_scale.right_offset_pixels = pixels; + let mut chart = chart(&[100.0], &[110.0]).with_chart_options(options); + let kept = chart.chart_options().time_scale.clone(); + let mut settings = ChartSettingsState::from_chart(&chart); + assert_eq!(settings.margins.right_bars, shown, "{pixels:?}"); + settings.apply_to_chart(&mut chart).unwrap(); + assert_eq!( + chart.chart_options().time_scale, + kept, + "unedited, {pixels:?}" + ); + + // The margins a new chart saved before the change, without the later choices. + let mut saved = serde_json::to_value(&settings).unwrap(); + saved["margins"] = serde_json::from_str( + r#"{"top_percent":10.0,"bottom_percent":10.0,"right_bars":2}"#, + ) + .unwrap(); + let appearance = saved["scales_appearance"].as_object_mut().unwrap(); + appearance.remove("font_family").unwrap(); + let saved: ChartSettingsState = serde_json::from_value(saved).unwrap(); + saved.apply_to_chart(&mut chart).unwrap(); + assert_eq!(chart.chart_options().time_scale, kept, "saved, {pixels:?}"); + + // An edit, also to the whole bars of the bar margin. + for bars in [2.0, 7.5] { + settings.margins.right_bars = bars; + settings.apply_to_chart(&mut chart).unwrap(); + let time_scale = &chart.chart_options().time_scale; + assert_eq!( + (time_scale.right_offset, time_scale.right_offset_pixels), + (bars, None), + "{pixels:?}" + ); + } + settings.margins.right_bars = -1.0; + assert_eq!( + settings.apply_to_chart(&mut chart), + Err(ChartSettingsError::RightMargin(-1.0)) + ); + } + } } diff --git a/vendor/egui-charts/src/widget/settings/data.rs b/vendor/egui-charts/src/widget/settings/data.rs index 69768ee..ab6e64d 100644 --- a/vendor/egui-charts/src/widget/settings/data.rs +++ b/vendor/egui-charts/src/widget/settings/data.rs @@ -13,6 +13,7 @@ use egui::Color32; /// Saved settings without a field take its default. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(default)] +#[non_exhaustive] pub struct CandleColorConfig { /// Colour plain candles by their close against the previous close instead of their open. /// Bars, volume candles and Heikin Ashi keep their rule in `ChartSettingsState::chart_type_params`. @@ -65,6 +66,7 @@ impl Default for CandleColorConfig { /// Status line display options. Saved settings without a field take its default. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(default)] +#[non_exhaustive] pub struct StatusLineOptions { /// Whether the legend shows the symbol's logo before the title, or its initial on a neutral /// disc without one. @@ -208,11 +210,16 @@ impl Default for WatermarkSettings { /// Canvas tab: Scales appearance settings #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] pub struct ScalesAppearanceSettings { /// Text color. pub text_color: Color32, /// Font size in logical pixels. pub font_size: u8, + /// Font family of the axis labels and tags. `None` keeps the chart's family, as do settings + /// saved without this field. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub font_family: Option, /// Axis line color. pub lines_color: Color32, } @@ -222,6 +229,7 @@ impl Default for ScalesAppearanceSettings { Self { text_color: crate::theme::Theme::default().ui.text_secondary, font_size: 12, + font_family: None, lines_color: Color32::TRANSPARENT, } } @@ -252,23 +260,44 @@ pub struct MarginsSettings { pub top_percent: f32, /// Empty space below prices, as a percentage of pane height. pub bottom_percent: f32, - /// Empty space after the latest bar, in bars. - pub right_bars: u32, + /// Empty space after the latest bar, in bars; a margin set in pixels reads as its width in + /// bars at the current bar spacing. Settings without + /// [`ScalesAppearanceSettings::font_family`], as saved when this held whole bars, keep the + /// chart's margin when this equals its whole bars. + pub right_bars: f32, } impl Default for MarginsSettings { + /// The margins of a new chart, read as the settings read a chart's. fn default() -> Self { + let price = crate::scales::PriceScaleMargins::default(); Self { - top_percent: 10.0, - bottom_percent: 8.0, - right_bars: 10, + top_percent: (price.top * 100.0) as f32, + bottom_percent: (price.bottom * 100.0) as f32, + right_bars: crate::config::TimeScaleOptions::default().right_offset, } } } +/// The character that groups the thousands of the built-in price labels. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum ThousandsSeparator { + /// Plain digits: `42541.77`. + Off, + /// A comma: `42,541.77`. + Comma, + /// A space: `42 541.77`. + Space, + /// An apostrophe: `42'541.77`. + Apostrophe, + /// A character the host set as `ChartConfig::thousands_sep`. + Other(char), +} + /// Scales and lines tab settings #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(default)] +#[non_exhaustive] pub struct ScalesAndLinesSettings { /// Axis layout of the pane containing the main series. pub axis_layout: crate::model::PaneAxisOptions, @@ -320,6 +349,12 @@ pub struct ScalesAndLinesSettings { pub show_prev_close_label: bool, /// Whether to show price line. pub show_price_line: bool, + /// The bar whose close the last price line and label of the main series show. `None` keeps + /// the chart's choice, as do settings saved without this field. + pub price_line_source: Option, + /// The thousands separator of price labels. `None` keeps the chart's separator, as do + /// settings saved without this field. + pub thousands_sep: Option, /// Whether to show countdown. pub show_countdown: bool, /// Whether to show bid ask. @@ -356,6 +391,8 @@ impl Default for ScalesAndLinesSettings { show_last_price_label: true, show_prev_close_label: false, show_price_line: true, + price_line_source: None, + thousands_sep: None, show_countdown: true, show_bid_ask: false, show_high_low: false, @@ -370,6 +407,7 @@ impl Default for ScalesAndLinesSettings { /// Saved settings without a field take its default, unless the field says otherwise. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(default)] +#[non_exhaustive] pub struct TradingSettings { /// Buy and Sell place a market order of the order quantity at once instead of opening the /// order ticket. @@ -468,6 +506,7 @@ impl TradingNotifications { /// Alerts tab settings #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(default)] +#[non_exhaustive] pub struct AlertsSettings { /// Ask the host to play a local sound when an alert fires. pub play_sound: bool, @@ -522,6 +561,7 @@ pub struct OrderFlowSettings { /// Serializable display settings shared by the chart and its settings dialog. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] // The trait impls below wrap the derived ones. #[serde(remote = "Self")] pub struct ChartSettingsState { @@ -590,6 +630,10 @@ pub struct ChartSettingsState { // Events tab /// Visible event categories. pub events: crate::model::EventVisibility, + /// Whether session break lines are drawn. `None` keeps the chart's choice, as do settings + /// saved without this field. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub show_session_breaks: Option, } impl serde::Serialize for ChartSettingsState { @@ -648,6 +692,7 @@ impl Default for ChartSettingsState { alerts: AlertsSettings::default(), events: crate::model::EventVisibility::default(), + show_session_breaks: None, } } } diff --git a/vendor/egui-charts/src/widget/settings/mod.rs b/vendor/egui-charts/src/widget/settings/mod.rs index 5e7e011..d368c02 100644 --- a/vendor/egui-charts/src/widget/settings/mod.rs +++ b/vendor/egui-charts/src/widget/settings/mod.rs @@ -11,7 +11,7 @@ mod types; pub use data::{ AlertsSettings, ButtonsSettings, CandleColorConfig, ChartBasicStylesSettings, ChartSettingsState, CrosshairSettings, GridLinesSettings, MarginsSettings, OrderFlowSettings, - ScalesAndLinesSettings, ScalesAppearanceSettings, StatusLineOptions, TradingNotifications, - TradingSettings, WatermarkSettings, + ScalesAndLinesSettings, ScalesAppearanceSettings, StatusLineOptions, ThousandsSeparator, + TradingNotifications, TradingSettings, WatermarkSettings, }; pub use types::{BackgroundType, ButtonVisibility, GridLinesMode, PrecisionMode, WatermarkMode}; diff --git a/vendor/egui-charts/src/widget/stored_drawings.rs b/vendor/egui-charts/src/widget/stored_drawings.rs index 77ca4c1..85aa142 100644 --- a/vendor/egui-charts/src/widget/stored_drawings.rs +++ b/vendor/egui-charts/src/widget/stored_drawings.rs @@ -4,20 +4,12 @@ use super::Chart; use crate::data::FeedError; use crate::data::inbox::Inbox; use crate::drawings::persistence::{DrawingStorage, LoadError, StorageError, StoredPane}; -use crate::localization as l10n; +use crate::localization::format_text_or_english as message; use crate::services::document::{Received, StoredDocument, copy_number}; use crate::services::{ConflictChoice, Revision, Storage, StoreKind}; use std::collections::{HashMap, VecDeque}; use std::sync::Arc; -/// Formats a message for the chart's last context, with English before its first frame. -fn message(ctx: Option<&egui::Context>, english: &str, values: &[(&str, &str)]) -> String { - match ctx { - Some(ctx) => l10n::format_text(ctx, english, values), - None => l10n::substitute(english, values), - } -} - /// What a chart asked its storage about the kept copies of its symbols' drawings. #[derive(Default)] struct LocalCopies { diff --git a/vendor/egui-charts/src/widget/time_scale.rs b/vendor/egui-charts/src/widget/time_scale.rs index 04331b5..a3201d9 100644 --- a/vendor/egui-charts/src/widget/time_scale.rs +++ b/vendor/egui-charts/src/widget/time_scale.rs @@ -144,7 +144,7 @@ impl Chart { self.cancel_view_motion(); self.tracking_mode_active = false; let scale = self.state.time_scale_mut(); - scale.set_bar_spacing(scale.width() / bars); + scale.set_bar_spacing((scale.width() - 1.0) / bars); scale.set_right_offset(right - scale.base_idx() as f64); true } @@ -158,9 +158,21 @@ impl Chart { } } - /// Calendar zone behind the axis; `None` selects the system's local zone. + /// Calendar zone of the time conversions; `None` selects the system's local zone. pub(super) fn calendar_timezone(&self) -> Option { - let timezone = self.display_timezone(); + // Only an interval steps by calendar months; without one the zone is unread, and dating + // the bars would sample their spacing on every conversion. + Self::calendar_zone(if self.calendar_timeframe().is_some() { + self.label_timezone(|| self.time_label_seconds()) + } else { + self.display_timezone() + }) + } + + /// The calendar of `timezone`; `None` selects the system's local zone. + pub(super) fn calendar_zone( + timezone: crate::scales::TimezoneMode, + ) -> Option { match timezone { crate::scales::TimezoneMode::Local => None, _ => Some(timezone.to_tz().unwrap_or_default()), @@ -696,7 +708,8 @@ mod tests { plot, plot.width(), )); - assert!((chart.index_to_x(center).unwrap() - plot.center().x).abs() < 1e-3); + // The box centre lands mid-way between the first pixel and the last, at width - 1. + assert!((chart.index_to_x(center).unwrap() - (plot.center().x - 0.5)).abs() < 1e-3); chart.state.time_scale_mut().set_bar_spacing(200.0); chart.state.time_scale_mut().set_right_offset(-500_000.005); let x = chart.index_to_x(499_999.0).unwrap(); @@ -740,12 +753,12 @@ mod tests { // 40 bar widths across the plot, with bar 49 the last whole bar. assert!(chart.set_visible_logical_range(LogicalRange::new(10.0, 49.0))); let spacing = chart.get_time_scale_state().0; - assert_close(spacing.into(), (width / 40.0).into(), "spacing"); + assert_close(spacing.into(), ((width - 1.0) / 40.0).into(), "spacing"); assert_close(chart.get_time_scale_state().1.into(), -50.0, "offset"); assert_range(&chart, 10.0, 49.0, "set range"); - // Bar 10 is centred half a bar in from the left edge: the last pixel is width - 1. + // Bar 10 is centred half a bar in from the first pixel, as the last pixel is width - 1. let x = chart.index_to_x(10.0).unwrap(); - assert_close(x.into(), (plot.left() + spacing / 2.0 - 1.0).into(), "x"); + assert_close(x.into(), (plot.left() + spacing / 2.0).into(), "x"); assert_close(chart.x_to_index(x).unwrap(), 10.0, "index"); frame(&ctx, &mut chart, 0.2, vec![]); let range = chart.visible_logical_range(); @@ -776,7 +789,7 @@ mod tests { chart.fit_content(); assert_close( chart.get_time_scale_state().0.into(), - (width / 102.5).into(), + ((width - 1.0) / 102.5).into(), "fit", ); assert_range(&chart, 0.0, 101.5, "fit"); @@ -819,7 +832,7 @@ mod tests { chart.fit_content(); assert_close( chart.get_time_scale_state().0.into(), - ((width - 60.0) / 100.0).into(), + ((width - 1.0 - 60.0) / 100.0).into(), "fit with pixels", ); assert_range( diff --git a/vendor/egui-charts/src/widget/tool_interaction/mod.rs b/vendor/egui-charts/src/widget/tool_interaction/mod.rs index 39276bb..da36853 100644 --- a/vendor/egui-charts/src/widget/tool_interaction/mod.rs +++ b/vendor/egui-charts/src/widget/tool_interaction/mod.rs @@ -1830,7 +1830,7 @@ mod tests { assert!( chart .drawings() - .axis_tags(main, Color32::WHITE) + .axis_tags(main, Color32::WHITE, &[], 0) .any(|tag| matches!( tag, crate::drawings::manager::DrawingAxisTag::Time { x: tag_x, .. } if tag_x == x diff --git a/vendor/egui-charts/src/widget/tool_interaction/text.rs b/vendor/egui-charts/src/widget/tool_interaction/text.rs index 39a956a..630fd98 100644 --- a/vendor/egui-charts/src/widget/tool_interaction/text.rs +++ b/vendor/egui-charts/src/widget/tool_interaction/text.rs @@ -122,9 +122,38 @@ pub(super) fn begin_fibonacci_edit( } /// Open the text field of a selected rectangle, circle or ellipse on a click on its text, or on -/// the hint it shows in place of none. The click that selects the shape leaves the field closed, -/// as does a double click, which the host answers with the drawing's settings. +/// the hint it shows in place of none. The click that selects the shape leaves the field closed. +/// A click on one of the shape's handles leaves it closed too, so a circle's centre handle, where +/// its text is painted, keeps starting a move. The field opens once the double-click delay has +/// passed with no second press, since a field over the text would take the second click of a +/// double click, which the host answers with the drawing's settings. pub(super) fn begin_shape_edit(ui: &Ui, manager: &mut DrawingManager, response: &egui::Response) { + type Pending = (usize, egui::Pos2, f64); + let key = response.id.with("shape_edit_pending"); + let press_key = response.id.with("shape_edit_press"); + let now = ui.input(|input| input.time); + let delay = ui.ctx().options(|o| o.input_options.max_double_click_delay); + // A click is released at most a click distance from its press, and the drag tests the press. + if let Some(origin) = ui.input(|input| input.pointer.press_origin()) { + ui.data_mut(|data| data.insert_temp(press_key, origin)); + } + if let Some((id, pos, due)) = ui.data(|data| data.get_temp::(key)) { + // Any press ends the wait, also one in the frame the delay ends. A wait that frames + // skipped past its due time is stale and dropped. + if ui.input(|input| input.pointer.any_pressed()) || now - due > delay { + ui.data_mut(|data| data.remove_temp::(key)); + } else if now >= due { + ui.data_mut(|data| data.remove_temp::(key)); + if manager.active_tool.is_none() && manager.text_editor.is_none() { + open_shape_edit(ui, manager, id, pos); + } + return; + } else { + ui.ctx() + .request_repaint_after(std::time::Duration::from_secs_f64(due - now)); + return; + } + } if manager.active_tool.is_some() || manager.eraser_mode || manager.text_editor.is_some() @@ -138,17 +167,41 @@ pub(super) fn begin_shape_edit(ui: &Ui, manager: &mut DrawingManager, response: let Some(pos) = response.interact_pointer_pos() else { return; }; - let Some(drawing) = manager.hit_test(pos).and_then(|id| { - manager.drawings.iter().find(|drawing| { - drawing.id == id - && matches!( - drawing.tool_type, - DrawingToolType::Rect | DrawingToolType::Circle | DrawingToolType::Ellipse - ) - && !drawing.locked - && manager.is_selected(id) - }) - }) else { + let Some(id) = manager + .hit_test(pos) + .filter(|&id| editable_shape(manager, id).is_some()) + else { + return; + }; + // The same handle test as the drag in `handle_selection`, which starts it for one selection. + let origin = ui + .data(|data| data.get_temp::(press_key)) + .unwrap_or(pos); + let one = manager.selected_ids().count() == 1; + if one && manager.hit_test_handle_by_id(origin, id).is_some() { + return; + } + ui.data_mut(|data| data.insert_temp(key, (id, pos, now + delay))); + ui.ctx() + .request_repaint_after(std::time::Duration::from_secs_f64(delay)); +} + +/// The selected, unlocked rectangle, circle or ellipse `id`. +fn editable_shape(manager: &DrawingManager, id: usize) -> Option<&crate::drawings::Drawing> { + manager.drawings.iter().find(|drawing| { + drawing.id == id + && matches!( + drawing.tool_type, + DrawingToolType::Rect | DrawingToolType::Circle | DrawingToolType::Ellipse + ) + && !drawing.locked + && manager.is_selected(id) + }) +} + +/// Opens the field of shape `id` when the click at `pos` is on its painted text or hint. +fn open_shape_edit(ui: &Ui, manager: &mut DrawingManager, id: usize, pos: egui::Pos2) { + let Some(drawing) = editable_shape(manager, id) else { return; }; let text = drawing.text.clone().filter(|t| !t.trim().is_empty()); @@ -156,10 +209,9 @@ pub(super) fn begin_shape_edit(ui: &Ui, manager: &mut DrawingManager, response: .clone() .unwrap_or_else(|| l10n::text(ui.ctx(), "Add text")); if manager - .painted_text(drawing.id, &field) + .painted_text(id, &field) .is_some_and(|(min, galley)| Rect::from_min_size(min, galley.size()).contains(pos)) { - let id = drawing.id; manager.text_editor = Some(TextEditState { id, draft: text.unwrap_or_default(), @@ -584,9 +636,12 @@ mod tests { } /// A selected rectangle, circle or ellipse shows a hint where its text would be and opens its - /// text field on a click there. A double click that begins by selecting the shape does not, - /// and a locked shape has no field. A draft that starts blank keeps its field, cancels - /// without history, and confirms as one undoable edit that a saved file restores. + /// text field on a still click there, once the double-click delay has passed. A double click, + /// whether or not it begins by selecting the shape, reports the double click and leaves the + /// field closed, and a locked shape has no field. A circle's centre handle, where its text is + /// painted, opens no field and still starts a move after a click on it. A draft that starts + /// blank keeps its field, cancels without history, and confirms as one undoable edit that a + /// saved file restores. #[test] fn shape_text_field_click_edits_the_text() { use crate::drawings::{ChartPoint, Drawing}; @@ -599,8 +654,9 @@ mod tests { let ctx = Context::default(); let mut chart = chart(&[10.0; 20], &[20.0; 20]); let mut drawing = Drawing::new(7, tool); + // Wide enough that the centre is clear of the side handles. drawing.chart_points = - vec![ChartPoint::new(8.0, 15.0), ChartPoint::new(12.0, 18.0)]; + vec![ChartPoint::new(8.0, 15.0), ChartPoint::new(28.0, 18.0)]; drawing.completed = true; drawing.locked = locked; drawing.text = initial.map(String::from); @@ -632,6 +688,18 @@ mod tests { }; let hint = |chart: &crate::Chart| chart.drawings().painted_text(7, "Add text"); assert!(hint(&chart).is_none(), "{tool:?}"); + // A circle paints its text on its centre handle, so its click lands beside it. + let click_at = |chart: &crate::Chart| { + let (min, galley) = chart + .drawings() + .painted_text(7, initial.unwrap_or("Add text")) + .unwrap(); + if tool == DrawingToolType::Circle { + min + egui::vec2(galley.size().x - 2.0, galley.size().y / 2.0) + } else { + center + } + }; step(&mut chart, vec![Event::PointerMoved(center)]); for pressed in [true, false, true, false] { step(&mut chart, vec![button(center, pressed)]); @@ -644,20 +712,54 @@ mod tests { initial.is_none() && !locked, "{tool:?} {initial:?} locked {locked}" ); + if !locked { + // A double click on the selected shape's text or hint reports itself. + let click = click_at(&chart); + for _ in 0..5 { + step(&mut chart, vec![]); + } + chart.drain_events().for_each(drop); + for pressed in [true, false, true, false] { + step(&mut chart, vec![button(click, pressed)]); + } + for _ in 0..5 { + step(&mut chart, vec![]); + } + let doubles = chart + .drain_events() + .filter(|event| { + matches!(event, crate::widget::ChartEvent::DoubleClick { .. }) + }) + .count(); + assert_eq!(doubles, 1, "{tool:?} {initial:?} double click"); + assert!(chart.drawings().text_editor.is_none(), "{tool:?}"); + } for confirm in [false, true] { // Later than a double click of the last one. for _ in 0..5 { step(&mut chart, vec![]); } + let click = if locked { center } else { click_at(&chart) }; for pressed in [true, false] { - step(&mut chart, vec![button(center, pressed)]); + step(&mut chart, vec![button(click, pressed)]); } + // The field opens once a second click can no longer make it a double click. step(&mut chart, vec![]); + if !locked { + assert!(chart.drawings().text_editor.is_none(), "{tool:?} waits"); + } + for _ in 0..3 { + step(&mut chart, vec![]); + } if locked { assert!(chart.drawings().text_editor.is_none(), "{tool:?}"); break; } - assert_eq!(chart.drawings().text_editor.as_ref().unwrap().id, 7); + assert_eq!( + chart.drawings().text_editor.as_ref().map(|e| e.id), + Some(7), + "{tool:?} {initial:?}" + ); step( &mut chart, vec![key(Key::A, Modifiers::COMMAND), Event::Text(" ".into())], @@ -689,6 +791,46 @@ mod tests { assert!(!chart.can_undo()); } } + if tool == DrawingToolType::Circle && !locked { + // A press on the centre handle moves the circle, also after a still click. + // A loaded drawing has its screen points after the next frame, and a new id. + step(&mut chart, vec![]); + let id = chart.drawings().drawings[0].id; + let handle = chart.drawings().drawings[0].points[0]; + let before = chart.drawings().drawings[0].chart_points[0].bar_idx; + // Select the circle first, so the still click below lands on a selected shape. + for pressed in [true, false] { + step(&mut chart, vec![button(handle, pressed)]); + } + for _ in 0..5 { + step(&mut chart, vec![]); + } + assert!(chart.drawings().is_selected(id), "{initial:?}"); + for pressed in [true, false] { + step(&mut chart, vec![button(handle, pressed)]); + } + for _ in 0..4 { + step(&mut chart, vec![]); + } + assert!(chart.drawings().text_editor.is_none(), "{initial:?}"); + step(&mut chart, vec![button(handle, true)]); + for dx in [10.0, 20.0, 30.0, 40.0] { + step( + &mut chart, + vec![Event::PointerMoved(handle + egui::vec2(dx, 0.0))], + ); + } + step( + &mut chart, + vec![button(handle + egui::vec2(40.0, 0.0), false)], + ); + step(&mut chart, vec![]); + let after = chart.drawings().drawings[0].chart_points[0].bar_idx; + assert!( + after > before + 1.0, + "{initial:?} moved from {before} to {after}" + ); + } } } } diff --git a/vendor/egui-charts/src/widget/volume.rs b/vendor/egui-charts/src/widget/volume.rs index 9182ff7..081a650 100644 --- a/vendor/egui-charts/src/widget/volume.rs +++ b/vendor/egui-charts/src/widget/volume.rs @@ -151,16 +151,18 @@ pub(super) fn paint( crate::chart::indicators::plots::paint_price_lines(&painter, study, &map); } +/// The volume study's value tags, read at the bar `study_tag_bar` gives for `last_in_view`. pub(super) fn tags( painter: &Painter, rect: Rect, map: &crate::scales::PriceMap, study: &dyn Indicator, + last_in_view: Option, edge: f32, occupied: &mut Vec>, axis: &crate::config::PriceAxisOptions, ) { - let Some(bar) = study.values().len().checked_sub(1) else { + let Some(bar) = crate::chart::rendering::axes::study_tag_bar(study, last_in_view) else { return; }; if !axis.show_study_values @@ -248,6 +250,79 @@ mod tests { use crate::widget::test_frames::{chart, shapes}; use egui::Context; + /// The volume study adds columns, a tag on the price axis and rows in the tooltip to a candle + /// chart, and none of them on the chart types that hide volume. + #[test] + fn price_based_charts_show_no_volume_tag_or_rows() { + use crate::model::ChartType; + let mut failures = Vec::new(); + for (kind, shown) in [ + (ChartType::Candles, true), + (ChartType::Renko, false), + (ChartType::Kagi, false), + (ChartType::LineBreak, false), + (ChartType::PointAndFigure, false), + (ChartType::Range, false), + ] { + let ctx = Context::default(); + // Closes of 100, 103, 106 and 109 in turn build elements at the default sizes. + let mut chart = chart(&[100.0], &[100.0, 103.0, 106.0, 109.0]); + chart.set_chart_type(kind); + chart.config_mut().show_volume = false; + shapes(&ctx, &mut chart, 0.0, vec![]); + shapes(&ctx, &mut chart, 0.1, vec![]); + let map = chart.get_chart_mapping(); + let newest = chart.state.shown().len() - 1; + let pointer = + egui::Event::PointerMoved(egui::pos2(map.idx_to_x(newest), map.rect.center().y)); + let texts = |painted: Vec| { + Vec::from_iter(painted.into_iter().filter_map(|shape| match shape { + egui::Shape::Text(text) => Some((text.pos.x, text.galley.text().to_owned())), + _ => None, + })) + }; + // The texts on the price axis and the rectangles in the volume area without a + // pointer, and whether the tooltip over the newest element lists a row of the study. + let readouts = |chart: &mut crate::widget::Chart, time| { + shapes(&ctx, chart, time, vec![]); + let painted = shapes(&ctx, chart, time + 0.1, vec![]); + let area = super::overlay_rect(chart.last_rendered_price_rect, chart.config()); + let columns = painted + .iter() + .filter(|shape| { + matches!(shape, egui::Shape::Rect(rect) if area.contains_rect(rect.rect)) + }) + .count(); + let mut tags = texts(painted); + let axis = chart.last_rendered_price_rect.right(); + tags.retain(|(x, _)| *x >= axis); + shapes(&ctx, chart, time + 0.2, vec![pointer.clone()]); + let hovered = texts(shapes(&ctx, chart, time + 0.3, vec![pointer.clone()])); + shapes(&ctx, chart, time + 0.4, vec![egui::Event::PointerGone]); + let rows = hovered.iter().any(|(_, text)| text.starts_with("Volume:")); + (tags, columns, rows) + }; + let (tags, columns, rows) = readouts(&mut chart, 0.2); + assert!(!rows, "{kind:?}: no study, no rows"); + chart.config_mut().show_volume = true; + let (with_volume, with_columns, rows) = readouts(&mut chart, 0.7); + if (with_volume != tags) != shown { + failures.push(format!( + "{kind:?}: price axis {with_volume:?}, was {tags:?}" + )); + } + if (with_columns != columns) != shown { + failures.push(format!( + "{kind:?}: {with_columns} rectangles in the volume area, was {columns}" + )); + } + if rows != shown { + failures.push(format!("{kind:?}: volume rows in the tooltip: {rows}")); + } + } + assert!(failures.is_empty(), "{failures:#?}"); + } + #[test] fn volume_switch_and_pane_keep_volume_off_the_price_scale() { let ctx = Context::default(); diff --git a/vendor/egui-charts/terminal/Cargo.lock b/vendor/egui-charts/terminal/Cargo.lock index 8f01828..ff4ad52 100644 --- a/vendor/egui-charts/terminal/Cargo.lock +++ b/vendor/egui-charts/terminal/Cargo.lock @@ -617,6 +617,7 @@ dependencies = [ "egui-charts", "egui_extras", "iana-time-zone", + "png 0.17.16", "rand", "serde_json", ] diff --git a/vendor/egui-charts/terminal/Cargo.toml b/vendor/egui-charts/terminal/Cargo.toml index 24732e0..cb6e460 100644 --- a/vendor/egui-charts/terminal/Cargo.toml +++ b/vendor/egui-charts/terminal/Cargo.toml @@ -16,6 +16,7 @@ chrono = "0.4.43" iana-time-zone = "0.1.65" egui_extras = { version = "0.37.0", default-features = false } serde_json = "1.0.149" +png = "0.17.16" [dev-dependencies] # `examples/terminal.rs` is a standalone `eframe` app over the library's synthetic feed; the diff --git a/vendor/egui-charts/terminal/src/action.rs b/vendor/egui-charts/terminal/src/action.rs index 59bd2e0..dbf07b5 100644 --- a/vendor/egui-charts/terminal/src/action.rs +++ b/vendor/egui-charts/terminal/src/action.rs @@ -3,7 +3,7 @@ use egui_charts::model::Instrument; use egui_charts::services::ConflictChoice; use egui_charts::ui::context_menu::ChartContextAction; -use egui_charts::ui::dialogs::{AlertDialogAction, DrawingPropertiesAction}; +use egui_charts::ui::dialogs::{AlertDialogAction, DataTableAction, DrawingPropertiesAction}; use egui_charts::ui::drawing_toolbar::DrawingToolbarAction; use egui_charts::ui::export::ExportResponse; use egui_charts::ui::floating_replay_control::ReplayControlAction; @@ -28,6 +28,9 @@ use egui_charts::widget::{ImageRequest, ShortcutRequest}; #[derive(Clone, Debug)] #[non_exhaustive] pub enum Action { + /// The id of a quick search entry registered by + /// [`Terminal::add_command`](super::Terminal::add_command). + Command(String), /// The top toolbar. TopToolbar(TopToolbarAction), /// The drawing toolbar. @@ -66,6 +69,8 @@ pub enum Action { AlertDialog(AlertDialogAction), /// The alerts panel. Alerts(AlertPanelAction), + /// The loaded chart data table. + DataTable(DataTableAction), /// The export dialog. Export(ExportResponse), /// The go-to-date picker. diff --git a/vendor/egui-charts/terminal/src/commands.rs b/vendor/egui-charts/terminal/src/commands.rs index 06483ff..92a8dc4 100644 --- a/vendor/egui-charts/terminal/src/commands.rs +++ b/vendor/egui-charts/terminal/src/commands.rs @@ -2,21 +2,261 @@ use super::core::Direction; use super::layout::Region; -use super::{Action, Terminal}; +use super::{Action, ExportContents, ExportFile, Terminal}; +use egui_charts::config::KeyboardAction; +use egui_charts::drawings::DrawingToolType; +use egui_charts::scales::PriceScaleMode; use egui_charts::services::UserSettings; +use egui_charts::studies::IndicatorFactory; +use egui_charts::ui::Control; +use egui_charts::ui::context_menu::{ChartContextAction, ContextMenuAction}; +use egui_charts::ui::dialogs::{DataTableAction, DataTableDialog}; +use egui_charts::ui::drawing_toolbar::DrawingToolbarAction; +use egui_charts::ui::export::{ExportDialog, ExportFormat, ExportResponse}; +use egui_charts::ui::timeframe_toolbar::TimeframeToolbarAction; +use egui_charts::ui::top_toolbar::{LayoutAction, TopToolbarAction}; +use egui_charts::ui::widget_bar::{RightBarIcon, WidgetBarAction}; +use egui_charts::ui_kit::command_palette::{Command, CommandPaletteHandler}; +use egui_charts::widget::{ChartElementId, ImageExportOptions, ShortcutRequest}; +use std::path::PathBuf; -#[derive(Default)] -pub(super) struct State {} +const STUDY_CLIPBOARD: &str = "egui-charts-study\n"; + +pub(super) struct State { + palette: CommandPaletteHandler, + export: ExportDialog, + data_table: DataTableDialog, + host_commands: std::collections::HashSet, + /// The text last copied, for a paste key that arrives without clipboard text. + copied: Option, + /// The export dialog opens at the start of the next frame: the Enter that chose the entry + /// must not also press the dialog's Export button. + open_export: bool, +} + +impl Default for State { + fn default() -> Self { + Self { + palette: CommandPaletteHandler::new(Vec::new()), + export: ExportDialog::new(), + data_table: DataTableDialog::new(), + host_commands: Default::default(), + copied: None, + open_export: false, + } + } +} + +/// What the quick search offers: fixed entries, every drawing tool and every study. +fn quick_search_commands(factory: &IndicatorFactory) -> Vec { + let mut commands: Vec<_> = [ + ("symbols", "Symbol search", "Actions"), + ("indicators", "Indicators", "Actions"), + ("settings", "Chart settings", "Settings"), + ("export", "Export chart", "Actions"), + ("reset", "Reset chart view", "Actions"), + ("date", "Go to date", "Actions"), + ("replay", "Toggle replay", "Actions"), + ("help", "Keyboard shortcuts", "Actions"), + ("log", "Toggle logarithmic scale", "Settings"), + ("invert", "Invert price scale", "Settings"), + ("grid", "Toggle grid", "Settings"), + ] + .into_iter() + .map(|(id, label, category)| Command::new(id, label).category(category)) + .collect(); + for category in DrawingToolType::categories() { + for tool in DrawingToolType::by_category(category) { + if !tool.is_cursor() { + commands.push( + Command::new(format!("tool:{}", tool.data_name()), tool.as_str()) + .category("Drawing tools") + .keywords([*category]), + ); + } + } + } + let mut names = factory.list(); + names.sort(); + commands.extend(names.into_iter().map(|name| { + Command::new(format!("study:{name}"), format!("Add {name}")) + .category("Studies") + .keywords([factory.category(&name).unwrap_or_default()]) + })); + commands +} + +/// Where a rendered chart image is delivered. +enum ImageTarget { + /// The host's file export. + File { + open: bool, + }, + Clipboard, +} + +/// Decodes the PNG of a chart export into an image for the clipboard. +fn decode_png(png: &[u8]) -> Result { + let mut reader = png::Decoder::new(std::io::Cursor::new(png)) + .read_info() + .map_err(|error| error.to_string())?; + let mut pixels = vec![0; reader.output_buffer_size()]; + let info = reader + .next_frame(&mut pixels) + .map_err(|error| error.to_string())?; + if info.color_type != png::ColorType::Rgba || info.bit_depth != png::BitDepth::Eight { + return Err("the chart image is not 8-bit RGBA".to_owned()); + } + Ok(egui::ColorImage::from_rgba_unmultiplied( + [info.width as usize, info.height as usize], + &pixels[..info.buffer_size()], + )) +} impl Terminal { - pub(super) fn commands_init(&mut self) {} + /// Adds a quick search entry whose id is returned as [`Action::Command`] when chosen. + /// An entry with the same id replaces the previous entry, including a built-in command. + pub fn add_command(&mut self, command: Command) { + self.commands.host_commands.insert(command.id.clone()); + self.commands.palette.remove_command(&command.id); + self.commands.palette.add_command(command); + } + + pub(super) fn commands_init(&mut self) { + for command in quick_search_commands(self.studies.indicators.factory()) { + if !self.commands.host_commands.contains(&command.id) { + self.commands.palette.add_command(command); + } + } + for control in [Control::QuickSearch, Control::Snapshot, Control::ExportData] { + self.set_control_visible(control, true); + } + // Files go to the host; without it the clipboard is all an export can reach. + let mut formats = if self.services.save.is_some() { + self.services.export_formats.to_vec() + } else { + Vec::new() + }; + if !formats.contains(&ExportFormat::Clipboard) { + formats.push(ExportFormat::Clipboard); + } + self.commands.export = ExportDialog::new().with_formats(&formats); + } - pub(super) fn commands_poll(&mut self, _ctx: &egui::Context) {} + pub(super) fn commands_poll(&mut self, _ctx: &egui::Context) { + if std::mem::take(&mut self.commands.open_export) { + self.commands.export.open(); + } + } - pub(super) fn commands_show(&mut self, _ui: &mut egui::Ui, _region: Region) {} + pub(super) fn commands_show(&mut self, ui: &mut egui::Ui, region: Region) { + match region { + Region::Chart => self.open_dialogs_of_keys(), + Region::Windows => { + let ctx = ui.ctx().clone(); + if let Some(id) = self.commands.palette.show(&ctx) { + self.run_quick_command(&id); + } + match self + .commands + .data_table + .show(&ctx, &self.charts[self.active]) + { + DataTableAction::None => {} + response => self.emit(Action::DataTable(response)), + } + match self.commands.export.show(&ctx) { + ExportResponse::None => {} + response => self.emit(Action::Export(response)), + } + } + _ => {} + } + } pub(super) fn commands_perform(&mut self, action: Action) -> Option { - Some(action) + match action { + Action::Shortcut(ShortcutRequest::SymbolSearch(text)) => { + let open = Action::TopToolbar(TopToolbarAction::OpenSymbolSearch); + if !self.dispatch(open) { + return None; + } + self.studies.symbol_search.open_with_query(text); + } + // The drawings group has taken drawing text; other text is ignored. + Action::Shortcut(ShortcutRequest::PasteDrawing(text)) => { + if text.starts_with(STUDY_CLIPBOARD) { + self.paste_study(&text); + } + } + Action::Shortcut(ShortcutRequest::Action(keyboard)) => { + return self.perform_keyboard(keyboard); + } + Action::TopToolbar(TopToolbarAction::OpenQuickSearch) => { + self.commands.palette.open(); + } + Action::TopToolbar( + top @ (TopToolbarAction::TakeScreenshot + | TopToolbarAction::CopyImage + | TopToolbarAction::OpenImage), + ) => { + let file = self.services.save.is_some(); + let target = match top { + TopToolbarAction::CopyImage => ImageTarget::Clipboard, + // The library writes no files and has no viewer: without the host's file + // export a screenshot goes to the clipboard and opening is the host's. + TopToolbarAction::OpenImage if !file => { + return Some(Action::TopToolbar(top)); + } + _ if file => ImageTarget::File { + open: top == TopToolbarAction::OpenImage, + }, + _ => ImageTarget::Clipboard, + }; + let mut options = ImageExportOptions::default(); + options.include_crosshair = true; + self.export_image(target, &options, None); + } + Action::ChartMenu(ChartContextAction::Chart(ContextMenuAction::OpenDataTable)) => { + self.commands.data_table.open(); + } + Action::ChartMenu(ChartContextAction::Chart(ContextMenuAction::ExportCsv)) => { + self.export_csv(None) + } + Action::Export(ExportResponse::Export { config, save_path }) => match config.format { + ExportFormat::Png if self.services.save.is_some() => { + self.export_image(ImageTarget::File { open: false }, &config.image, save_path); + } + // The layout menu asks for a PNG download without the host's file export too. + ExportFormat::Png | ExportFormat::Clipboard => { + self.export_image(ImageTarget::Clipboard, &config.image, None); + } + ExportFormat::Csv => self.export_csv(save_path), + ExportFormat::Svg => match self.chart().export_svg(&self.ctx(), &config.image) { + Ok(svg) => { + let name = format!("{}_export.svg", self.chart().symbol()); + self.deliver_text(name, save_path, svg); + } + Err(error) => self.report_export(Err(error.to_string())), + }, + }, + Action::DataTable(DataTableAction::Export(csv)) => { + self.deliver_text("chart_data.csv".into(), None, csv); + } + // The table's symbol button stands for the toolbar's, text typed over it for the + // chart's typed symbol search. + Action::DataTable(DataTableAction::SearchSymbol(query)) => { + self.dispatch(if query.is_empty() { + Action::TopToolbar(TopToolbarAction::OpenSymbolSearch) + } else { + Action::Shortcut(ShortcutRequest::SymbolSearch(query)) + }); + } + Action::DataTable(_) => {} + Action::Export(ExportResponse::Closed | ExportResponse::None) => {} + action => return Some(action), + } + None } pub(super) fn commands_settings( @@ -27,6 +267,729 @@ impl Terminal { } pub(super) fn commands_modal(&self) -> bool { - false + self.commands.palette.is_open() + || self.commands.export.is_open() + || self.commands.data_table.is_open + } + + /// Performs the keys that open a dialog before the dialogs show, so that the keys queued + /// behind the request in the same frame reach the dialog and not the chart. + fn open_dialogs_of_keys(&mut self) { + use KeyboardAction as A; + let opens = |action: &Action| { + matches!( + action, + Action::Shortcut( + ShortcutRequest::SymbolSearch(_) + | ShortcutRequest::Action( + A::OpenQuickSearch + | A::OpenSymbolSearch + | A::OpenIndicatorSearch + | A::ShowKeyboardHelp + | A::GoToDate + | A::OpenLayout + ) + ) + ) + }; + let (opening, rest): (Vec<_>, Vec<_>) = std::mem::take(&mut self.emitted) + .into_iter() + .partition(opens); + self.emitted = rest; + for action in opening { + self.dispatch(action); + } + } + + /// Performs a key the chart hands to its host, by the action of the control that stands for + /// it. The equivalent action follows the same host intercept as its control. + fn perform_keyboard(&mut self, keyboard: KeyboardAction) -> Option { + use KeyboardAction as A; + let equivalent = match keyboard { + A::OpenQuickSearch => Action::TopToolbar(TopToolbarAction::OpenQuickSearch), + A::ShowKeyboardHelp => Action::WidgetBar(WidgetBarAction::Clicked(RightBarIcon::Help)), + A::OpenIndicatorSearch => Action::TopToolbar(TopToolbarAction::OpenIndicators), + A::OpenSymbolSearch => Action::TopToolbar(TopToolbarAction::OpenSymbolSearch), + A::Snapshot => Action::TopToolbar(TopToolbarAction::TakeScreenshot), + A::OpenLayout => Action::TopToolbar(TopToolbarAction::Layout(LayoutAction::OpenLayout)), + A::MaximizeChart => Action::TopToolbar(TopToolbarAction::ToggleFullscreen), + A::CopyDrawing => { + self.copy_selection(); + return None; + } + A::PasteDrawing => { + if let Some(text) = self.commands.copied.clone() { + self.perform(Action::Shortcut(ShortcutRequest::PasteDrawing(text))); + } + return None; + } + _ => return Some(Action::Shortcut(ShortcutRequest::Action(keyboard))), + }; + self.dispatch(equivalent); + None + } + + /// Copies the selected drawings, or else the selected study, to the system clipboard. + fn copy_selection(&mut self) { + match self.chart().copy_selected_drawings() { + Ok(Some(text)) => self.copy_text(text), + Ok(None) => { + if let Some(ChartElementId::Indicator(id)) = self.chart().selected_element() + && let Some(text) = self.chart().copy_indicator(id) + { + self.copy_text(text); + } + } + Err(error) => { + self.toasts + .error(format!("Could not copy drawings: {error}")); + } + } + } + + /// Puts `text` on the system clipboard and keeps it for a paste key that arrives without + /// clipboard text. + pub(super) fn copy_text(&mut self, text: String) { + self.ctx().copy_text(text.clone()); + self.commands.copied = Some(text); + } + + fn paste_study(&mut self, text: &str) { + if let Err(error) = + self.charts[self.active].paste_indicator(text, self.studies.indicators.factory()) + { + self.toasts + .error(format!("Could not paste the study: {error}")); + } + } + + /// Runs the quick search entry `id` by the action it stands for. + fn run_quick_command(&mut self, id: &str) { + if self.commands.host_commands.contains(id) { + self.emit(Action::Command(id.to_owned())); + return; + } + if let Some(name) = id.strip_prefix("tool:") { + if let Some(tool) = DrawingToolType::all() + .iter() + .find(|tool| tool.data_name() == name) + { + self.emit(Action::DrawingToolbar(DrawingToolbarAction::SelectTool( + *tool, + ))); + } + return; + } + if let Some(name) = id.strip_prefix("study:") { + self.emit(Action::TopToolbar(TopToolbarAction::AddIndicator( + name.to_owned(), + ))); + return; + } + let action = match id { + "symbols" => Action::TopToolbar(TopToolbarAction::OpenSymbolSearch), + "indicators" => Action::TopToolbar(TopToolbarAction::OpenIndicators), + "settings" => Action::TopToolbar(TopToolbarAction::OpenSettings), + "replay" => Action::TopToolbar(TopToolbarAction::ToggleReplay), + "help" => Action::WidgetBar(WidgetBarAction::Clicked(RightBarIcon::Help)), + "date" => Action::BottomBar(TimeframeToolbarAction::OpenDatePicker), + "reset" => Action::ChartMenu(ChartContextAction::Chart(ContextMenuAction::ResetChart)), + "export" => { + self.commands.open_export = true; + return; + } + "log" => { + self.user_action(|terminal| { + let mode = &mut terminal.chart_mut().price_scale_mut().options_mut().mode; + *mode = if *mode == PriceScaleMode::Logarithmic { + PriceScaleMode::Normal + } else { + PriceScaleMode::Logarithmic + }; + }); + return; + } + "invert" => { + self.user_action(|terminal| { + let options = terminal.chart_mut().price_scale_mut().options_mut(); + options.invert_scale = !options.invert_scale; + }); + return; + } + "grid" => { + self.user_action(|terminal| { + let config = terminal.chart_mut().config_mut(); + config.show_grid = !config.show_grid; + }); + return; + } + _ => return, + }; + self.emit(action); + } + + /// Renders the active chart as PNG and delivers it. The export dialog, if open, shows how it + /// went. + fn export_image( + &mut self, + target: ImageTarget, + options: &ImageExportOptions, + path: Option, + ) { + let ctx = self.ctx(); + let result = self + .chart() + .export_png(&ctx, options) + .map_err(|error| error.to_string()) + .and_then(|png| match target { + ImageTarget::File { open } => self.hand_over( + format!("{}_chart.png", self.chart().symbol()), + path, + ExportContents::Png(png), + open, + ), + ImageTarget::Clipboard => { + ctx.copy_image(decode_png(&png)?); + Ok("Image sent to clipboard".to_owned()) + } + }); + self.report_export(result); + } + + /// Exports loaded bars and visible study plots to the host, or the clipboard without one. + fn export_csv(&mut self, path: Option) { + match self.chart().export_csv() { + Ok(csv) => { + self.deliver_text(format!("{}_export.csv", self.chart().symbol()), path, csv) + } + Err(error) => self.report_export(Err(error.to_string())), + } + } + + fn deliver_text(&mut self, name: String, path: Option, text: String) { + let result = if self.services.save.is_some() { + self.hand_over(name, path, ExportContents::Text(text), false) + } else { + self.ctx().copy_text(text); + Ok(format!("Copied {name} to the clipboard")) + }; + self.report_export(result); + } + + /// Hands a finished file to the host and reports its delivery result. + fn hand_over( + &mut self, + name: String, + path: Option, + contents: ExportContents, + open: bool, + ) -> Result { + let save = self + .services + .save + .as_mut() + .ok_or("the host has no file export")?; + let shown = path + .as_ref() + .map_or_else(|| name.clone(), |path| path.display().to_string()); + save(ExportFile { + name, + path, + contents, + open, + })?; + Ok(if open { + "Image opened in viewer".to_owned() + } else { + format!("Export successful: {shown}") + }) + } + + /// Tells the user, and the export dialog if it is open, how an export went. + fn report_export(&mut self, result: Result) { + if self.commands.export.is_open() { + match &result { + Ok(_) => self.commands.export.mark_success(), + Err(error) => self.commands.export.mark_error(error.clone()), + } + } + match result { + Ok(message) => self.toast(message), + Err(error) => self.toasts.error(format!("Export failed: {error}")), + } + } +} + +#[cfg(test)] +mod tests { + use super::super::test_support::{SIZE, TestFeed, frame, key}; + use super::*; + use egui::{Event, Key, Modifiers, RawInput}; + use egui_charts::drawings::{ChartPoint, Drawing}; + use egui_charts::studies::IndicatorFactory; + use egui_charts::ui::dialogs::DrawingContextMenuAction; + use egui_charts::ui::export::ExportConfig; + use std::cell::RefCell; + use std::rc::Rc; + use std::sync::Arc; + + fn terminal() -> Terminal { + Terminal::new(Arc::new(TestFeed)).with_symbol("AAPL") + } + + /// Runs a frame and returns what it asked the platform to do, such as copying to the + /// clipboard, with what `show` returned. + fn frame_output( + terminal: &mut Terminal, + events: Vec, + ) -> (Vec, Vec) { + let ctx = terminal.ctx.clone().expect("a frame has run"); + let mut actions = Vec::new(); + let output = ctx.run_ui( + RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, SIZE)), + time: Some(ctx.input(|i| i.time) + 0.1), + events, + ..Default::default() + }, + |ui| actions = terminal.show(ui), + ); + let commands = output.platform_output.commands.clone(); + output.drop_without_applying_deltas(); + (commands, actions) + } + + fn trend_line(id: usize, price: f64) -> Drawing { + let mut drawing = Drawing::new(id, DrawingToolType::TrendLine); + drawing.chart_points = vec![ChartPoint::new(10.0, price), ChartPoint::new(20.0, price)]; + drawing.completed = true; + drawing + } + + /// The quick search types its entry even when the key that opens it and the text share a + /// frame, and runs the entry as the action the owner performs. + #[test] + fn quick_search_runs_the_entry_it_is_given() { + let ctrl_k = Modifiers::CTRL.plus(Modifiers::COMMAND); + // The ways to open it: the key with the text in the same frame, the key then the text, + // and the toolbar action then the text. + for open in ["same frame", "key", "toolbar"] { + for (query, expected) in [ + ( + "RSI", + Some(Action::TopToolbar(TopToolbarAction::AddIndicator( + "RSI".into(), + ))), + ), + ( + "Trend Line", + Some(Action::DrawingToolbar(DrawingToolbarAction::SelectTool( + DrawingToolType::TrendLine, + ))), + ), + ( + "Chart settings", + Some(Action::TopToolbar(TopToolbarAction::OpenSettings)), + ), + ( + "Host average", + Some(Action::TopToolbar(TopToolbarAction::AddIndicator( + "Host average".into(), + ))), + ), + ("Export chart", None), + ("Sample backtest", Some(Action::Command("backtest".into()))), + ("Host drawing", Some(Action::Command("tool:host".into()))), + ] { + // The host sees what the palette emits and leaves the keys to the terminal. + let mut terminal = terminal().with_intercept(|action| { + !matches!( + action, + Action::Shortcut(_) | Action::TopToolbar(TopToolbarAction::OpenQuickSearch) + ) + }); + let mut factory = IndicatorFactory::new(); + factory.register_in(IndicatorFactory::PERSONAL, "Host average", || { + Box::new(egui_charts::studies::SMA::new(42)) + }); + terminal = terminal.with_indicator_factory(factory); + terminal.add_command(Command::new("backtest", "Sample backtest")); + terminal.add_command(Command::new("tool:host", "Host drawing")); + frame(&mut terminal, SIZE, vec![]); + let mut seen = Vec::new(); + let typed = Event::Text(query.into()); + let opening = Event::ModifiersChanged(ctrl_k); + let mut frames = vec![match open { + "same frame" => vec![opening, key(Key::K, ctrl_k), typed.clone()], + "key" => vec![opening, key(Key::K, ctrl_k)], + _ => vec![], + }]; + if open == "toolbar" { + assert!( + terminal + .run(Action::TopToolbar(TopToolbarAction::OpenQuickSearch)) + .is_none() + ); + } + if open != "same frame" { + frames.push(vec![Event::ModifiersChanged(Modifiers::NONE), typed]); + } + // The empty frame shows the dialog that the entry opened. + frames.push(vec![key(Key::Enter, Modifiers::NONE)]); + frames.push(vec![]); + for events in frames { + seen.extend(frame(&mut terminal, SIZE, events).actions); + } + let label = format!("{query} opened by {open}"); + match expected { + Some(expected) => { + assert_eq!(format!("{seen:?}"), format!("{:?}", [expected]), "{label}"); + } + None => { + assert!(seen.is_empty(), "{label}: {seen:?}"); + assert!(terminal.commands.export.is_open(), "{label}"); + } + } + assert!(!terminal.commands.palette.is_open(), "{label}"); + } + } + // Each search edit is one undo step. + let flags = |terminal: &mut Terminal| { + let grid = terminal.chart().config().show_grid; + let scale = terminal.chart_mut().price_scale_mut().options(); + ( + grid, + scale.mode == PriceScaleMode::Logarithmic, + scale.invert_scale, + ) + }; + for command in ["grid", "log", "invert"] { + let mut terminal = terminal(); + for _ in 0..3 { + frame(&mut terminal, SIZE, vec![]); + } + let before = flags(&mut terminal); + terminal.run_quick_command(command); + assert_ne!(flags(&mut terminal), before, "{command}"); + terminal.run(Action::TopToolbar(TopToolbarAction::Undo)); + assert_eq!(flags(&mut terminal), before, "one undo restores {command}"); + } + } + + /// An open dialog of this group takes Escape before the chart does. + #[test] + fn open_dialogs_keep_the_keys_of_the_chart() { + for dialog in [ + "quick search", + "export", + "data table", + "table symbol search", + "help", + "indicators", + ] { + let mut terminal = terminal(); + frame(&mut terminal, SIZE, vec![]); + terminal + .chart_mut() + .drawings_mut() + .drawings + .push(trend_line(7, 100.0)); + terminal.chart_mut().drawings_mut().select(7); + terminal + .chart_mut() + .drawings_mut() + .set_active_tool(Some(DrawingToolType::TrendLine)); + match dialog { + "export" => terminal.commands.export.open(), + "data table" => { + terminal.run(Action::ChartMenu(ChartContextAction::Chart( + ContextMenuAction::OpenDataTable, + ))); + } + // The table's symbol button. + "table symbol search" => { + terminal.run(Action::DataTable(DataTableAction::SearchSymbol( + String::new(), + ))); + } + "indicators" => { + let slash = frame(&mut terminal, SIZE, vec![key(Key::Slash, Modifiers::NONE)]); + assert!(slash.actions.is_empty(), "{:?}", slash.actions); + assert!(terminal.keyboard_dialog_open()); + } + "help" => { + terminal.run(Action::Shortcut(ShortcutRequest::Action( + KeyboardAction::ShowKeyboardHelp, + ))); + } + _ => terminal.commands.palette.open(), + } + for events in [ + vec![], + vec![key(Key::Delete, Modifiers::NONE)], + vec![key(Key::Escape, Modifiers::NONE)], + ] { + frame(&mut terminal, SIZE, events); + } + assert!(!terminal.keyboard_dialog_open(), "{dialog}"); + assert_eq!(terminal.chart().drawings().sel_drawing(), Some(7)); + assert_eq!( + terminal.chart().drawings().active_tool(), + Some(DrawingToolType::TrendLine) + ); + } + } + + /// Copy puts the selected drawings on the system clipboard, a pasted study is one undo step, + /// and other text is ignored. + #[test] + fn clipboard_copies_drawings_and_pastes_a_study_once() { + let mut terminal = terminal(); + for _ in 0..3 { + frame(&mut terminal, SIZE, vec![]); + } + let drawings = terminal.chart_mut().drawings_mut(); + drawings.drawings.push(trend_line(7, 100.0)); + drawings.drawings.push(trend_line(8, 110.0)); + drawings.select_drawings([7, 8]); + let (commands, actions) = frame_output(&mut terminal, vec![Event::Copy]); + assert!(actions.is_empty(), "{actions:?}"); + let copied = commands.iter().find_map(|command| match command { + egui::OutputCommand::CopyText(text) => Some(text.clone()), + _ => None, + }); + let copied = copied.expect("system clipboard text"); + assert!(copied.starts_with("egui-charts-drawings\n")); + terminal.commands.copied = None; + for (events, count) in [ + (vec![Event::Paste("unrelated clipboard text".into())], 2), + (vec![Event::Paste(copied)], 4), + (vec![key(Key::Z, Modifiers::COMMAND)], 2), + ] { + let (_, actions) = frame_output(&mut terminal, events); + assert!(actions.is_empty(), "{actions:?}"); + assert_eq!(terminal.chart().drawings().drawings.len(), count); + } + // A browser sends the paste key before the clipboard text, so the key pastes what the + // terminal copied last, here from the drawing menu. + terminal.chart_mut().drawings_mut().select_drawings([7, 8]); + terminal.run(Action::ChartMenu(ChartContextAction::Drawing( + DrawingContextMenuAction::Copy, + ))); + let (_, actions) = frame_output(&mut terminal, vec![key(Key::V, Modifiers::COMMAND)]); + assert!(actions.is_empty(), "{actions:?}"); + assert_eq!(terminal.chart().drawings().drawings.len(), 4); + + let studies = |terminal: &Terminal| terminal.chart().indicators().count(); + let rsi = IndicatorFactory::new().create("RSI").unwrap(); + let id = terminal.chart_mut().add_indicator(rsi); + let text = terminal.chart().copy_indicator(id).unwrap(); + let before = studies(&terminal); + let paste = |text: &str| vec![Event::Paste(text.into())]; + for (events, count) in [ + (paste("unrelated clipboard text"), before), + (paste(&text), before + 1), + ] { + let (_, returned) = frame_output(&mut terminal, events); + assert!(returned.is_empty(), "{returned:?}"); + assert_eq!(studies(&terminal), count); + } + // One undo removes the pasted study. + assert!( + terminal + .run(Action::TopToolbar(TopToolbarAction::Undo)) + .is_none() + ); + assert_eq!(studies(&terminal), before); + } + + /// Exports reach the clipboard without a file export and the host's callback with one; + /// opening an image is the host's. + #[test] + fn exports_go_to_the_clipboard_or_the_hosts_file_export() { + let mut small = ImageExportOptions::default(); + small.size = [200, 120]; + let export = |format| { + Action::Export(ExportResponse::Export { + config: ExportConfig { + format, + image: small.clone(), + }, + save_path: Some("out".into()), + }) + }; + // Without a file export. + let mut terminal = terminal(); + frame(&mut terminal, SIZE, vec![]); + let open = Action::TopToolbar(TopToolbarAction::OpenImage); + assert!(terminal.run(open).is_some()); + // Every format reaches the clipboard: the layout menu's downloads ask for PNG and CSV + // whether or not the host saves files. + for format in [ + ExportFormat::Clipboard, + ExportFormat::Png, + ExportFormat::Csv, + ExportFormat::Svg, + ] { + assert!(terminal.run(export(format)).is_none()); + } + let (commands, _) = frame_output(&mut terminal, vec![]); + let images = commands.iter().filter(|command| { + matches!(command, egui::OutputCommand::CopyImage(image) if image.size == [200, 120]) + }); + assert_eq!(images.count(), 2); + assert!(commands.iter().any(|command| matches!(command, + egui::OutputCommand::CopyText(csv) if csv.starts_with("time,")))); + assert!(commands.iter().any(|command| matches!(command, + egui::OutputCommand::CopyText(svg) if svg.contains(" = output + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) => Some(text.galley.text().to_owned()), + _ => None, + }) + .collect(); + output.drop_without_applying_deltas(); + assert!(terminal.commands.export.is_open()); + assert_eq!(attempts.get(), attempt); + assert!( + texts.iter().any(|text| text.starts_with(message)), + "{format:?}: {texts:?}" + ); + } + } + } + + /// Text and editing keys queued behind the opening shortcut reach symbol search in order. + #[test] + fn typed_symbol_search_keeps_queued_editing_keys() { + use egui_charts::model::Instrument; + // A symbol other than the chart's, so a search that changes nothing fails. + let symbols = Arc::new(vec![Instrument::new("BTCUSD")]); + let mut terminal = terminal().with_symbol_search(symbols); + for _ in 0..3 { + frame(&mut terminal, SIZE, vec![]); + } + terminal + .chart_mut() + .drawings_mut() + .drawings + .push(trend_line(7, 100.0)); + terminal.chart_mut().drawings_mut().select(7); + frame( + &mut terminal, + SIZE, + vec![ + Event::Text("BTCUSX".into()), + key(Key::Backspace, Modifiers::NONE), + Event::Text("D".into()), + ], + ); + assert_eq!(terminal.chart().drawings().drawings.len(), 1); + frame(&mut terminal, SIZE, vec![key(Key::Enter, Modifiers::NONE)]); + assert_eq!(terminal.chart().symbol(), "BTCUSD"); + assert!(!terminal.keyboard_dialog_open()); + } + + fn terminal_with_files(sink: Rc>>) -> Terminal { + terminal().with_file_export( + &[ExportFormat::Png, ExportFormat::Csv, ExportFormat::Svg], + move |file| { + sink.borrow_mut().push(file); + Ok(()) + }, + ) } } diff --git a/vendor/egui-charts/terminal/src/drawings.rs b/vendor/egui-charts/terminal/src/drawings.rs index 26665b6..aee841e 100644 --- a/vendor/egui-charts/terminal/src/drawings.rs +++ b/vendor/egui-charts/terminal/src/drawings.rs @@ -260,6 +260,7 @@ impl Terminal { CrosshairStyle::Arrow | CrosshairStyle::Hidden => CursorType::Arrow, CrosshairStyle::Demonstration => CursorType::Demonstration, CrosshairStyle::Magic => CursorType::Magic, + _ => CursorType::Cross, }, eraser_mode_enabled: manager.is_eraser_mode(), stay_in_drawing_mode: manager.stay_in_drawing_mode, @@ -396,6 +397,12 @@ impl Terminal { { drawing.fill_color = saved.fill_color; } + if own + .border_color + .is_some_and(|border| border[..3] != own.color[..3]) + { + drawing.border_color = saved.border_color; + } if let (Some(own_levels), Some(before), Some(after)) = (&own.pitchfork, &saved.pitchfork, &mut drawing.pitchfork) { @@ -470,7 +477,7 @@ impl Terminal { DrawingContextMenuAction::Edit => self.open_drawing_properties(id), DrawingContextMenuAction::Clone => self.clone_drawing(id), DrawingContextMenuAction::Copy => match self.chart().copy_selected_drawings() { - Ok(Some(text)) => self.ctx().copy_text(text), + Ok(Some(text)) => self.copy_text(text), Ok(None) => {} Err(error) => self .toasts @@ -863,6 +870,66 @@ mod tests { } } + /// A toolbar pick keeps a text box's grey border, while a price label's border still + /// follows its line. + #[test] + fn toolbar_colours_keep_the_text_box_border() { + let mut terminal = ready(); + let grey = [112, 112, 112, 255]; + let red = [242, 54, 69, 255]; + // A grey pick first makes the saved default's line the border's grey; the next pick + // must not recolour the border with the line. + for tool in [DrawingToolType::TextLabel, DrawingToolType::AnchoredText] { + let manager = terminal.chart_mut().drawings_mut(); + manager.tool_defaults.clear(); + manager.options.default_color = None; + manager.set_active_tool(Some(tool)); + run(&mut terminal, DrawingToolbarAction::ColorChanged(grey)); + run(&mut terminal, DrawingToolbarAction::ColorChanged(red)); + let drawing = terminal.chart().drawings().new_drawing(1, tool); + assert_eq!(drawing.color, red, "{tool:?}"); + assert_eq!(drawing.border_color, Some(grey), "{tool:?}"); + } + // The same under a grey host colour: one pick recolours the line, not the border. + for tool in [DrawingToolType::TextLabel, DrawingToolType::AnchoredText] { + let manager = terminal.chart_mut().drawings_mut(); + manager.tool_defaults.clear(); + manager.options.default_color = Some(grey); + manager.set_active_tool(Some(tool)); + run(&mut terminal, DrawingToolbarAction::ColorChanged(red)); + let drawing = terminal.chart().drawings().new_drawing(1, tool); + assert_eq!(drawing.color, red, "{tool:?}"); + assert_eq!(drawing.border_color, Some(grey), "{tool:?}"); + } + // Control: a price label's border starts in the label's own colour, so a pick + // recolours it with the line, both when never chosen and from an older save. + for saved in [false, true] { + let manager = terminal.chart_mut().drawings_mut(); + manager.tool_defaults.clear(); + manager.options.default_color = None; + manager.set_active_tool(Some(DrawingToolType::PriceLabel)); + if saved { + let mut defaults = manager.new_drawing(0, DrawingToolType::PriceLabel); + defaults.border_color = Some(defaults.color); + manager.tool_defaults.insert( + DrawingToolType::PriceLabel, + DrawingTemplate::from_drawing(&defaults), + ); + } + run(&mut terminal, DrawingToolbarAction::ColorChanged(red)); + let drawing = terminal + .chart() + .drawings() + .new_drawing(1, DrawingToolType::PriceLabel); + assert_eq!(drawing.color, red, "saved={saved}"); + assert_eq!( + drawing.border_color, + if saved { Some(red) } else { None }, + "saved={saved}" + ); + } + } + /// Selecting a drawing exposes current style values, and each quick edit is undoable. #[test] fn selected_toolbar_styles_and_more_menu_reach_the_chart() { @@ -1566,7 +1633,7 @@ mod tests { let paste = |text: &str| Action::Shortcut(ShortcutRequest::PasteDrawing(text.into())); assert!(terminal.run(paste(&text)).is_none()); assert_eq!(count(&terminal), before + 1); - assert!(terminal.run(paste("egui-charts-study\n{}")).is_some()); + assert!(terminal.run(paste("egui-charts-study\n{}")).is_none()); assert_eq!(count(&terminal), before + 1); } diff --git a/vendor/egui-charts/terminal/src/layout.rs b/vendor/egui-charts/terminal/src/layout.rs index 103b98e..665d99f 100644 --- a/vendor/egui-charts/terminal/src/layout.rs +++ b/vendor/egui-charts/terminal/src/layout.rs @@ -82,11 +82,15 @@ impl Terminal { self.show_region(ui, Region::Left); self.show_region(ui, Region::Right); self.show_region(ui, Region::Bottom); + let mut financials_shown = false; egui::CentralPanel::default() .frame(panel_frame(panel_bg)) .show(ui, |ui| { - let mut slots: Vec<_> = self.charts.iter_mut().collect(); - self.layout.show_with(ui, &mut slots, &mut render); + financials_shown = self.show_financials(ui); + if !financials_shown { + let mut slots: Vec<_> = self.charts.iter_mut().collect(); + self.layout.show_with(ui, &mut slots, &mut render); + } }); if self.layout.active() != self.active { self.activate_slot(self.layout.active()); @@ -104,9 +108,11 @@ impl Terminal { self.toasts.error(error.to_string()); } } - self.show_region(ui, Region::Chart); - if let Some(action) = self.menus.show(&ctx, &mut self.charts[self.active]) { - self.emit(Action::ChartMenu(action)); + if !financials_shown { + self.show_region(ui, Region::Chart); + if let Some(action) = self.menus.show(&ctx, &mut self.charts[self.active]) { + self.emit(Action::ChartMenu(action)); + } } self.show_region(ui, Region::Windows); self.show_storage_conflict(&ctx); diff --git a/vendor/egui-charts/terminal/src/layouts.rs b/vendor/egui-charts/terminal/src/layouts.rs index 6d481ae..897e3b5 100644 --- a/vendor/egui-charts/terminal/src/layouts.rs +++ b/vendor/egui-charts/terminal/src/layouts.rs @@ -50,6 +50,23 @@ fn tab_price(price: f64) -> String { CurrencyFormatter::new("", if price.abs() < 1.0 { 4 } else { 2 }).format(price) } +fn option_tab_symbol(symbol: &str) -> Option { + if !symbol.is_ascii() || symbol.len() <= 15 { return None; } + let (root, suffix) = symbol.split_at(symbol.len() - 15); + if !root.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'/') { return None; } + chrono::NaiveDate::parse_from_str(&suffix[..6], "%y%m%d").ok()?; + let kind = &suffix[6..7]; + if kind != "C" && kind != "P" { return None; } + if !suffix[7..].bytes().all(|b| b.is_ascii_digit()) { return None; } + let strike: u32 = suffix[7..].parse().ok()?; + let whole = strike / 1000; + let fraction = strike % 1000; + let strike = if fraction == 0 { whole.to_string() } else { + format!("{whole}.{fraction:03}").trim_end_matches('0').to_owned() + }; + Some(format!("{root} {strike}{kind}")) +} + fn show_chart_tab( ui: &mut egui::Ui, symbol: &str, @@ -59,7 +76,9 @@ fn show_chart_tab( closable: bool, theme: &egui_charts::theme::Theme, ) -> (bool, bool) { - let shown_symbol = symbol.rsplit(':').next().unwrap_or(symbol); + let short_symbol = symbol.rsplit(':').next().unwrap_or(symbol); + let formatted_symbol = option_tab_symbol(short_symbol); + let shown_symbol = formatted_symbol.as_deref().unwrap_or(short_symbol); let font = egui::FontId::proportional(15.0); let text_color = theme.ui.text; let painter = ui.painter().clone(); @@ -75,6 +94,7 @@ fn show_chart_tab( + change_text.as_ref().map_or(0.0, |text| measure(text) + 6.0) + measure(&detail) + if closable { 34.0 } else { 10.0 }; let (rect, response) = ui.allocate_exact_size(egui::vec2(width, 42.0), egui::Sense::click()); + let response = if formatted_symbol.is_some() { response.on_hover_text(symbol) } else { response }; let bg = if active { if theme.dark { egui::Color32::from_rgb(15, 16, 18) } else { theme.ui.panel_bg } } else if response.hovered() { theme.ui.btn_bg_hover } else { egui::Color32::TRANSPARENT }; if bg != egui::Color32::TRANSPARENT { ui.painter().rect_filled(rect, egui::CornerRadius::same(8), bg); } @@ -596,6 +616,13 @@ impl Terminal { true } + /// Open a symbol in a new chart tab while retaining the current workspace. + pub fn open_symbol_tab(&mut self, symbol: &str) { + if self.new_layout(None) { + self.switch_symbol(symbol); + } + } + fn close_layout(&mut self, index: usize) { if self.layouts.tabs.len() == 1 { return; @@ -1037,17 +1064,14 @@ mod tests { show_economic_events: true, ..Default::default() }); + let mut hidden = ToolAvailability::default(); + hidden.visible = false; + hidden.enabled = false; terminal .chart_mut() .drawings_mut() .registry - .set_availability( - DrawingToolType::TrendLine, - ToolAvailability { - visible: false, - enabled: false, - }, - ); + .set_availability(DrawingToolType::TrendLine, hidden); let mut drawing = Drawing::new(7, DrawingToolType::HorizontalLine); drawing.completed = true; drawing.chart_points.push(ChartPoint::new(10.0, 42.0)); diff --git a/vendor/egui-charts/terminal/src/lib.rs b/vendor/egui-charts/terminal/src/lib.rs index 352a53f..88d72ea 100644 --- a/vendor/egui-charts/terminal/src/lib.rs +++ b/vendor/egui-charts/terminal/src/lib.rs @@ -120,7 +120,6 @@ pub struct Terminal { layouts: layouts::State, #[allow(dead_code, reason = "the group keeps its state here")] compare: compare::State, - #[allow(dead_code, reason = "the group keeps its state here")] commands: commands::State, } @@ -299,10 +298,12 @@ impl Terminal { self } - /// Offers `formats` in the export dialog and hands each finished export to `save`. Without - /// it, alert-log exports are returned to the host as unhandled actions. The host returns an + /// Offers `formats` in the export dialog, beside copying to the clipboard, and hands each + /// finished export to `save`. Without it, chart images and data go to the clipboard and + /// alert-log exports are returned to the host as unhandled actions. The host returns an /// error message if saving or opening fails, and opens the saved image when - /// [`ExportFile::open`] is true. Errors are shown as toasts; the action remains handled. + /// [`ExportFile::open`] is true. Errors are shown as toasts and in the open export dialog; + /// the action remains handled. pub fn with_file_export( mut self, formats: &'static [ExportFormat], @@ -418,9 +419,9 @@ impl Drop for Terminal { #[cfg(test)] mod tests { - use super::test_support::{self, MemoryStorage, SIZE, TestFeed, click, frame, key}; + use super::test_support::{self, MemoryStorage, SIZE, TestFeed, click, frame}; use super::*; - use egui::{Key, Modifiers, vec2}; + use egui::vec2; use egui_charts::drawings::{ChartPoint, Drawing, DrawingToolType}; use egui_charts::ui::top_toolbar::TopToolbarAction; use egui_charts::widget::ShortcutRequest; @@ -481,7 +482,7 @@ mod tests { ), ( Action::Shortcut(ShortcutRequest::SymbolSearch("A".into())), - false, + true, ), (menu(ContextMenuAction::MergeTradeProfilePrevious), true), (menu(ContextMenuAction::MergeTradeProfileNext), true), @@ -489,8 +490,6 @@ mod tests { ] { assert_eq!(terminal.run(action).is_none(), handled); } - let help = frame(&mut terminal, SIZE, vec![key(Key::F1, Modifiers::NONE)]).actions; - assert!(matches!(help.as_slice(), [Action::Shortcut(_)])); } #[test] diff --git a/vendor/egui-charts/terminal/src/panels.rs b/vendor/egui-charts/terminal/src/panels.rs index b6fc90b..9b5e21b 100644 --- a/vendor/egui-charts/terminal/src/panels.rs +++ b/vendor/egui-charts/terminal/src/panels.rs @@ -11,6 +11,7 @@ use egui_charts::model::Tick; use egui_charts::model::{Bar, Watchlist}; use egui_charts::services::{ProfileDirectory, ProfileId, Profiles, UserSettings}; use egui_charts::ui::context_menu::{ChartContextAction, ContextMenuAction}; +use egui_charts::ui::financials::FinancialsPanel; use egui_charts::ui::profile::ProfileCard; use egui_charts::ui::top_toolbar::TopToolbarAction; use egui_charts::ui::widget_bar::{ @@ -122,6 +123,9 @@ pub(super) struct State { tape_symbol: String, /// The newest trade listed: its time and how many trades share that time. tape_cursor: Option<(DateTime, usize)>, + /// Open financials in place of the charts: the symbol and whether its figures had arrived + /// when the panel was made. + financials: Option<((String, bool), FinancialsPanel)>, } impl Default for State { @@ -155,6 +159,7 @@ impl Default for State { adding_symbol: false, tape_symbol: String::new(), tape_cursor: None, + financials: None, } } } @@ -244,7 +249,6 @@ impl Terminal { if let Some(storage) = &self.services.storage { market.details.set_storage(storage.clone()); } - market.details.set_financials_visible(false); market.details.set_feed(self.feed.clone()); market.highlights.set_feed(self.feed.clone()); market.news.set_feed(self.feed.clone()); @@ -290,6 +294,47 @@ impl Terminal { .set_notification_cnt(RightBarIcon::Notifications, unread); self.feed_heatmap(ctx); self.feed_market_panels(ctx); + self.feed_financials(); + } + + /// Offers Financials once the feed has answered with figures for the details' symbol, and + /// keeps open financials on that symbol, showing its figures once they arrive. + fn feed_financials(&mut self) { + let details = &mut self.panels.market.details; + let available = details.financials().is_some(); + details.set_financials_visible(available); + let key = (details.symbol().unwrap_or_default().to_owned(), available); + if details.take_financials_request() { + self.panel = None; + } else if self + .panels + .financials + .as_ref() + .is_none_or(|(shown, _)| *shown == key) + { + return; + } + let title = self.charts[self.active] + .instrument() + .filter(|instrument| instrument.symbol == key.0) + .and_then(|instrument| instrument.description.clone()) + .unwrap_or_else(|| key.0.clone()); + let panel = FinancialsPanel::new(title, details.financials().cloned()); + self.panels.financials = Some((key, panel)); + } + + /// Replaces the chart workspace until the user returns to it. + pub(super) fn show_financials(&mut self, ui: &mut egui::Ui) -> bool { + let Some((_, panel)) = &mut self.panels.financials else { + return false; + }; + let back = egui::Frame::NONE + .inner_margin(12.0) + .show(ui, |ui| panel.show(ui)); + if back.inner { + self.panels.financials = None; + } + true } /// Subscribes to every heatmap symbol, including symbols outside the active watchlist. @@ -804,7 +849,10 @@ impl Terminal { } pub(super) fn panels_modal(&self) -> bool { - self.panels.import.is_some() || self.panels.wide_watchlist || self.panels.profile.is_some() + self.panels.import.is_some() + || self.panels.wide_watchlist + || self.panels.profile.is_some() + || self.panels.financials.is_some() } } @@ -1043,6 +1091,124 @@ mod tests { assert_eq!(listed, 1); } + /// Unsupported feeds leave no entry; host figures open in place of the chart, and a late + /// answer for another symbol cannot replace the active company's figures. + #[test] + fn financials_only_offer_and_show_the_active_symbols_host_figures() { + use super::super::test_support::click; + use egui_charts::data::{CompanyFinancials, FinancialPage}; + use std::sync::Mutex; + + #[derive(Default)] + struct Host(Mutex)>>); + impl Datafeed for Host { + fn resolve(&self, symbol: &str, reply: Reply) { + reply.send(Ok(Instrument::new(symbol).with_description("Host company"))); + } + + fn history(&self, request: HistoryRequest, reply: Reply) { + TestFeed.history(request, reply); + } + + fn financials(&self, symbol: &str, reply: Reply) { + self.0.lock().unwrap().push((symbol.into(), reply)); + } + } + let menu = |terminal: &mut Terminal| { + frame(terminal, SIZE, vec![]); + let ctx = terminal.ctx.clone().unwrap(); + let output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, SIZE)), + ..Default::default() + }, + |ui| drop(terminal.show(ui)), + ); + // The symbol details' More button is below the watchlist's More button. + let more = output + .platform_output + .accesskit_update + .iter() + .flat_map(|update| &update.nodes) + .filter(|(_, node)| node.label() == Some("More")) + .filter_map(|(_, node)| node.bounds()) + .max_by(|a, b| a.y0.total_cmp(&b.y0)) + .expect("symbol menu"); + let pos = egui::pos2( + ((more.x0 + more.x1) / 2.0) as f32, + ((more.y0 + more.y1) / 2.0) as f32, + ); + output.drop_without_applying_deltas(); + click(terminal, SIZE, pos); + frame(terminal, SIZE, vec![]) + }; + let mut unsupported = terminal(); + frame(&mut unsupported, SIZE, vec![]); + let shown = menu(&mut unsupported); + assert!(shown.text_at("Copy symbol").is_some()); + assert!(shown.text_at("Financials").is_none()); + + let host = Arc::new(Host::default()); + let mut terminal = Terminal::new(host.clone()).with_symbol("AAPL"); + frame(&mut terminal, SIZE, vec![]); + assert!(menu(&mut terminal).text_at("Financials").is_none()); + egui::Popup::close_all(&terminal.ctx.clone().unwrap()); + let (symbol, reply) = host.0.lock().unwrap().pop().unwrap(); + assert_eq!(symbol, "AAPL"); + let figures = |name: &str, value| { + CompanyFinancials::new( + Some("USD".into()), + vec![ + FinancialPage::new("Income statement", vec!["FY 2025".into()]) + .with_row(name, vec![Some(value)]), + ], + ) + }; + reply.send(Ok(figures("Host revenue", 42.0))); + let shown = menu(&mut terminal); + click( + &mut terminal, + SIZE, + shown.text_at("Financials").expect("host figures available"), + ); + let shown = frame(&mut terminal, SIZE, vec![]); + assert!(shown.text_at("Back to chart").is_some()); + let shown = texts(&mut terminal); + assert!(shown.iter().any(|text| text == "Host company")); + assert!(shown.iter().any(|text| text == "Host revenue")); + assert!(shown.iter().any(|text| text == "42.00")); + assert_eq!(terminal.panel, None, "analysis gets the whole workspace"); + assert!( + host.0.lock().unwrap().is_empty(), + "do not request per frame" + ); + + terminal.switch_symbol("MSFT"); + frame(&mut terminal, SIZE, vec![]); + let (_, late) = host.0.lock().unwrap().pop().unwrap(); + assert!( + !texts(&mut terminal) + .iter() + .any(|text| text == "Host revenue") + ); + terminal.switch_symbol("NVDA"); + frame(&mut terminal, SIZE, vec![]); + let (symbol, current) = host.0.lock().unwrap().pop().unwrap(); + assert_eq!(symbol, "NVDA"); + current.send(Ok(figures("Current revenue", 84.0))); + late.send(Ok(figures("Stale revenue", 21.0))); + let shown = texts(&mut terminal); + assert!(shown.iter().any(|text| text == "Current revenue")); + assert!(!shown.iter().any(|text| text == "Stale revenue")); + let shown = frame(&mut terminal, SIZE, vec![]); + click(&mut terminal, SIZE, shown.text_at("Back to chart").unwrap()); + assert!( + frame(&mut terminal, SIZE, vec![]) + .text_at("Back to chart") + .is_none() + ); + } + /// Host pushes reach hidden panels once, quotes cover heatmap symbols outside the list, /// and bar-derived figures use returns from a known base rather than price differences. #[test] diff --git a/vendor/egui-charts/terminal/src/studies.rs b/vendor/egui-charts/terminal/src/studies.rs index 7cb2993..7f67a1a 100644 --- a/vendor/egui-charts/terminal/src/studies.rs +++ b/vendor/egui-charts/terminal/src/studies.rs @@ -29,7 +29,7 @@ pub(super) struct State { /// The chart settings as last applied. The groups that apply a part of them to their own /// components (alerts, trading display, bottom bar) read it. pub(super) settings: ChartSettingsState, - symbol_search: SymbolSearchDialog, + pub(super) symbol_search: SymbolSearchDialog, shortcuts: KeyboardShortcutsDialog, /// The symbol last entered in the recent symbols of the search. recorded: Option, @@ -258,7 +258,7 @@ impl Terminal { } StudyContextMenuAction::Copy => { if let Some(text) = self.chart().copy_indicator(id) { - self.ctx().copy_text(text); + self.copy_text(text); } } StudyContextMenuAction::Settings => { @@ -653,7 +653,7 @@ mod tests { state.watermark.mode = WatermarkMode::Symbol; state.margins.top_percent = 12.5; state.margins.bottom_percent = 7.5; - state.margins.right_bars = 17; + state.margins.right_bars = 17.0; settings(&mut terminal, state.clone()); let chart = terminal.chart(); assert_eq!(chart.config().candle_border_width, 0.0); diff --git a/vendor/egui-charts/terminal/src/time.rs b/vendor/egui-charts/terminal/src/time.rs index bb8e972..0550706 100644 --- a/vendor/egui-charts/terminal/src/time.rs +++ b/vendor/egui-charts/terminal/src/time.rs @@ -14,7 +14,7 @@ use egui_charts::ui::floating_replay_control::ReplayControlAction; use egui_charts::ui::timeframe_toolbar::{ DatePicker, DatePickerAction, DateRange, SessionType, TimeframeToolbar, TimeframeToolbarAction, }; -use egui_charts::ui::top_toolbar::TopToolbarAction; +use egui_charts::ui::top_toolbar::{ChartTypePreferences, TimeframePreferences, TopToolbarAction}; use egui_charts::ui_kit::dialog::DialogFooter; use egui_charts::ui_kit::modal::Modal; use egui_charts::widget::{SeriesId, ShortcutRequest, VisibleTimeRange}; @@ -144,12 +144,24 @@ impl Terminal { pub(super) fn time_settings(&mut self, settings: &mut UserSettings, direction: Direction) { let selector = &mut self.top_toolbar.timeframe_selector; + let chart_types = &mut self.top_toolbar.chart_type_selector; match direction { - Direction::Save => settings.interval_favorites = selector.preferences().favorites, + Direction::Save => { + let preferences = selector.preferences(); + settings.interval_favorites = preferences.favorites; + settings.custom_intervals = preferences.custom_timeframes; + settings.hidden_intervals = preferences.hidden_timeframes; + settings.chart_type_favorites = chart_types.preferences().favorites; + } Direction::Load => { - let mut preferences = selector.preferences(); - preferences.favorites = settings.interval_favorites.clone(); - selector.set_preferences(preferences); + selector.set_preferences(TimeframePreferences { + favorites: settings.interval_favorites.clone(), + custom_timeframes: settings.custom_intervals.clone(), + hidden_timeframes: settings.hidden_intervals.clone(), + }); + chart_types.set_preferences(ChartTypePreferences { + favorites: settings.chart_type_favorites.clone(), + }); } } } @@ -199,7 +211,7 @@ impl Terminal { let visible = visible_bars_for_range(range, chart.bars(SeriesId::MAIN)); let width = chart.get_rendered_price_rect().width(); // Include the latest slot in the scale's exclusive data range. - let spacing = width.max(1.0) / (visible.max(1) as f32 + 0.5); + let spacing = (width - 1.0).max(1.0) / (visible.max(1) as f32 + 0.5); chart.disable_tracking_mode(); chart.apply_synced_time_scale(spacing, 0.5); if self.layout.sync.sync_date_range @@ -545,7 +557,7 @@ fn session_text(session: &Session, zone: Option<&TimezoneId>) -> String { #[cfg(test)] mod tests { - use super::super::test_support::{SIZE, TestFeed, click, frame, key}; + use super::super::test_support::{MemoryStorage, SIZE, TestFeed, click, frame, key}; use super::*; use egui::{Event, Key, Modifiers, vec2}; use egui_charts::data::Datafeed; @@ -562,6 +574,65 @@ mod tests { terminal } + /// Guards that custom, hidden and starred intervals and starred chart types are saved with + /// the settings and restored on the next start, and that a save from before the interval and + /// chart type lists existed still restores its starred intervals. + #[test] + fn interval_and_chart_type_preferences_survive_a_restart() { + let storage = Arc::new(MemoryStorage::default()); + let start = || { + let mut terminal = Terminal::new(Arc::new(TestFeed)) + .with_symbol("AAPL") + .with_storage(storage.clone()); + frame(&mut terminal, SIZE, vec![]); + terminal + }; + let custom = "7min".parse().unwrap(); + let intervals = TimeframePreferences { + favorites: vec![Timeframe::Min5, custom], + custom_timeframes: vec![custom], + hidden_timeframes: vec![Timeframe::Min1], + }; + let chart_types = ChartTypePreferences { + favorites: vec![ChartType::Bars], + }; + let mut first = start(); + first + .top_toolbar + .timeframe_selector + .set_preferences(intervals.clone()); + first + .top_toolbar + .chart_type_selector + .set_preferences(chart_types.clone()); + assert!(first.flush_storage()); + drop(first); + + let mut restored = start(); + assert_eq!( + restored.top_toolbar.timeframe_selector.preferences(), + intervals + ); + assert_eq!( + restored.top_toolbar.chart_type_selector.preferences(), + chart_types + ); + let mut older = + UserSettings::from_json(r#"{"version":1,"interval_favorites":["Min5"]}"#).unwrap(); + restored.time_settings(&mut older, Direction::Load); + assert_eq!( + restored.top_toolbar.timeframe_selector.preferences(), + TimeframePreferences { + favorites: vec![Timeframe::Min5], + ..TimeframePreferences::default() + } + ); + assert_eq!( + restored.top_toolbar.chart_type_selector.preferences(), + ChartTypePreferences::default() + ); + } + /// The bottom bar follows the chart's adjustment choice and the feed's capability, /// while the comparison group handles its clicks and the host can hide it. #[test] @@ -753,7 +824,7 @@ mod tests { "{range:?} {shown_start} {shown_end} {start} {end}" ); let expected = - chart.get_rendered_price_rect().width() / ((end - start) as f32 + 0.5); + (chart.get_rendered_price_rect().width() - 1.0) / ((end - start) as f32 + 0.5); assert!((chart.get_time_scale_state().0 - expected).abs() < 0.001); } terminal.charts.push( diff --git a/vendor/egui-charts/terminal/src/trading.rs b/vendor/egui-charts/terminal/src/trading.rs index 21505ce..1c42fc3 100644 --- a/vendor/egui-charts/terminal/src/trading.rs +++ b/vendor/egui-charts/terminal/src/trading.rs @@ -622,17 +622,17 @@ mod tests { impl Signals for HostSignals { fn subscribe(&self, symbol: &str, timeframe: Timeframe, events: Events) { use egui_charts::model::{Signal, SignalId, SignalShape}; - events.push(SignalEvent::Upsert(Signal { - id: SignalId("host".into()), - shape: SignalShape::Marker { + let mut signal = Signal::new( + SignalId("host".into()), + SignalShape::Marker { time: feed_end() - TimeDelta::milliseconds(timeframe.duration_ms()) * 250, price: Some(if symbol == "BTCUSD" { 61_000.0 } else { 180.0 }), direction: egui_charts::model::Direction::Neutral, }, - category: "Host".into(), - label: Some("Host analytics".into()), - tooltip: None, - })); + "Host", + ); + signal.label = Some("Host analytics".into()); + events.push(SignalEvent::Upsert(signal)); } } From eae3a82a0652617d5e37daccfa8b59c97ae0d135 Mon Sep 17 00:00:00 2001 From: vybie <168300406+vybie@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:39:57 -0800 Subject: [PATCH 2/4] Isolate options UI tests and record live checks --- RELEASE-CHECKLIST.md | 4 +++- RELEASE-NOTES-0.4.0.md | 2 +- crates/ui-egui/src/terminal_app.rs | 27 ++++++++++++++++++++++----- 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/RELEASE-CHECKLIST.md b/RELEASE-CHECKLIST.md index 8564951..8037bc1 100644 --- a/RELEASE-CHECKLIST.md +++ b/RELEASE-CHECKLIST.md @@ -8,10 +8,12 @@ Release scope: read-only Tradier options chains and contract charts, Pine indica - [ ] Complete `RELEASE-NOTES-0.4.0.md` and update `CHANGELOG.md` for the final release. Verify the notes against the final source and packages. - [ ] Run the dependency license audit for Windows personal and community and both macOS targets on the final lockfile. Review any changes and include the generated notices. The strict macOS checks previously reported missing notices; the packaging script records these as warnings at the owner's direction. The open upstream and provider-rights issues are not resolved by a successful build. - [ ] Run the appropriate workspace, options, Pine and vendored chart tests on the final source. Verify the community and personal Windows release builds; the personal build must update and verify `target/personal/tradecraft.exe`. -- [ ] Validate options chains and contract charts with real Tradier data and appropriate account entitlements, including timestamps and missing values. Synthetic tests do not establish live behavior. +- [ ] Validate the complete interactive options workflow and broader symbol/entitlement coverage, including timestamps and missing values. A read-only live Tradier check retrieved an SPY chain with calls and puts, and one selected contract returned eight daily and 206 five-minute bars on November 14, 2026. This does not establish streaming, every entitlement, or end-to-end chart behavior. - [ ] Build and test both macOS architectures for this revision using GitHub Actions. Inspect the app bundles and notice inventories; the prior 0.3.0 builds do not validate 0.4.0. Interactive Mac validation, including Keychain and workspace restart, remains outstanding. - [ ] Check the final Windows and macOS archives, version, executable identities and notices against the same release source. Follow the review and release process before publishing. The November 14 legal and provenance review records unresolved provider authorization, upstream source and asset provenance, and other distribution questions. These require separate review; no blanket compliance clearance has been established. Preserve that detailed review privately unless its owner authorizes publication. +The first 0.4.0 GitHub Mac run exposed two options UI test failures on Apple Silicon. The tests were adjusted to use isolated storage and are being checked again; do not infer a Mac app failure or a successful Mac validation from that initial result alone. + The 0.3.0 alpha was published for Windows, Apple Silicon and Intel macOS. Its tag and assets are historical and should not be replaced by this release. diff --git a/RELEASE-NOTES-0.4.0.md b/RELEASE-NOTES-0.4.0.md index 8501e46..9d5686a 100644 --- a/RELEASE-NOTES-0.4.0.md +++ b/RELEASE-NOTES-0.4.0.md @@ -8,7 +8,7 @@ With Tradier selected, open **Options** from a chart or a watchlist symbol. Choo Choose which optional columns to display and keep those preferences between sessions. The chain shows the underlying price among the strikes and presents per-share prices alongside their ×100 amounts for convenient comparison. -The chain is a manually refreshed snapshot. Availability depends on the Tradier account and provider; the ×100 display is before fees and adjusted contracts may differ. Live Tradier options data and contract charts still require verification. +The chain is a manually refreshed snapshot. Availability depends on the Tradier account and provider; the ×100 display is before fees and adjusted contracts may differ. A live SPY chain and one contract's daily and five-minute history were checked; the complete interactive workflow and broader coverage still need verification. ## Pine indicators diff --git a/crates/ui-egui/src/terminal_app.rs b/crates/ui-egui/src/terminal_app.rs index a0c3529..0e1bfea 100644 --- a/crates/ui-egui/src/terminal_app.rs +++ b/crates/ui-egui/src/terminal_app.rs @@ -683,6 +683,22 @@ mod tests { use super::*; use egui_charts::data::{Datafeed, HistoryPage, HistoryRequest, Reply}; use egui_kittest::kittest::Queryable; + + struct EmptyOptionsTestStorage; + impl egui_charts::services::Storage for EmptyOptionsTestStorage { + fn list(&self, _: egui_charts::services::StoreKind, reply: Reply>) { reply.send(Ok(vec![])); } + fn load(&self, _: egui_charts::services::StoreKind, _: &str, reply: Reply>) { reply.send(Ok(None)); } + fn save(&self, _: egui_charts::services::StoreKind, _: &str, _: String, reply: Reply<()>) { reply.send(Ok(())); } + fn delete(&self, _: egui_charts::services::StoreKind, _: &str, reply: Reply<()>) { reply.send(Ok(())); } + } + + fn isolated_options_test_app() -> TerminalApp { + let mut app = TerminalApp::new(); + let placeholder = Terminal::new(app.feed.clone()); + app.terminal = std::mem::replace(&mut app.terminal, placeholder) + .with_storage(Arc::new(EmptyOptionsTestStorage)); + app + } #[test] fn quit_never_times_out_into_discarding_pending_saves() { let start = Instant::now(); @@ -1737,11 +1753,11 @@ mod tests { } #[test] fn option_chart_tab_displays_readable_contract_name() { - let mut app = TerminalApp::new(); - app.terminal.chart_mut().set_symbol("SPY261116C00755000"); let mut h = egui_kittest::Harness::builder() .with_size(egui::vec2(1400.0, 800.0)) - .build_ui_state(|ui, app: &mut TerminalApp| app.show_ui(ui), app); + .build_ui_state(|ui, app: &mut TerminalApp| app.show_ui(ui), isolated_options_test_app()); + h.run_steps(3); + h.state_mut().terminal.chart_mut().set_symbol("SPY261116C00755000"); h.run_steps(3); assert!(h.query_by_label("SPY 755C").is_some()); assert_eq!(h.state().terminal.chart().symbol(), "SPY261116C00755000"); @@ -1749,13 +1765,14 @@ mod tests { #[test] fn options_toolbar_opens_for_active_instrument() { - let mut app = TerminalApp::new(); + let mut app = isolated_options_test_app(); app.settings.provider = Provider::Yahoo; - app.terminal.chart_mut().set_symbol("SPY"); let mut h = egui_kittest::Harness::builder() .with_size(egui::vec2(1400.0, 800.0)) .build_ui_state(|ui, app: &mut TerminalApp| app.show_ui(ui), app); h.run_steps(3); + h.state_mut().terminal.chart_mut().set_symbol("SPY"); + h.run_steps(3); h.get_by_label("Options").click(); h.run_steps(3); assert!(h.query_by_label("Options · SPY").is_some()); From 2b3f44de5458818003caef5c0602eb35da303cc2 Mon Sep 17 00:00:00 2001 From: vybie <168300406+vybie@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:41:12 -0800 Subject: [PATCH 3/4] Record 0.4.0 candidate validation --- ARCHITECTURE.md | 2 +- CHANGELOG.md | 2 +- RELEASE-CHECKLIST.md | 6 +++--- RELEASE-NOTES-0.4.0.md | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index a79ea42..2f92980 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -47,7 +47,7 @@ The current Windows dependency baseline also includes `regex` 1.13.1, `regex-aut - TradeCraft began as a single binary crate, with market data coupled to `egui-charts` and live candle logic in the UI. The workspace now has separate crates and a UI-independent engine. Existing Git history is preserved; the initial commit was made after the initial code already existed and cannot be changed without rewriting history. - The upstream egui-charts terminal owns the live GUI's chart, indicator and layout state. The existing engine remains UI-independent and supports the isolated `--commands` and `--script ` interface; those commands do not control the terminal window. The terminal feed adapter is in the UI crate and calls the provider and engine layers. A comprehensive command registry covering every UI action and an MCP server are not implemented. - The egui-charts source is vendored at `vendor/egui-charts`. Its upstream revision is recorded in `vendor/EGUI-CHARTS-UPSTREAM`; local modifications include host integration, data services and session controls. The scheduled GitHub workflow compares that revision with upstream `main` and opens or updates an issue when they differ. It also opens one tracking issue per newly observed stable upstream release. It does not merge changes automatically. Review the full vendored diff and validate personal Windows, community Windows and macOS builds when updating the dependency; retain its upstream license files, font and icon notices. -- The November 14 upstream integration advances egui-charts from `c9a7f0bbe6410eb6bc69fd2f2e8a6394919ac4f2` to `7a852a5152f9a5c3f3cc556f70170094e976d823`, preserving TradeCraft's Pine table colours, chart panning, provider integration and terminal customizations. Three upstream tests are adapted to TradeCraft's deliberate behavior: keep the user's near-live offset and hide custom intervals when the feed only supports presets. The terminal adds a direct dependency on `png` 0.17.16, already present in the locked application graph. This update was prepared on the macOS branch as shared source, but a macOS build and interactive validation of this revision remain outstanding. The previous macOS build results above do not validate this update. +- The November 14 upstream integration advances egui-charts from `c9a7f0bbe6410eb6bc69fd2f2e8a6394919ac4f2` to `7a852a5152f9a5c3f3cc556f70170094e976d823`, preserving TradeCraft's Pine table colours, chart panning, provider integration and terminal customizations. Three upstream tests are adapted to TradeCraft's deliberate behavior: keep the user's near-live offset and hide custom intervals when the feed only supports presets. The terminal adds a direct dependency on `png` 0.17.16, already present in the locked application graph. Both macOS architectures passed automated builds and provider/UI tests for candidate commit `eae3a82`; interactive validation remains outstanding. - The terminal's file storage saves named documents using encoded names and a temporary-file rename. Saved layout and drawing restoration, crash recovery, and multi-process conflicts need further verification. Alert definitions and statuses are saved locally; evaluation operates only while the app runs. Tradier charts and watchlists share one dynamically updated market stream; initial quotes use REST snapshots. Yahoo watchlist quotes use delayed REST data. Symbol search combines the selected provider with Kraken crypto pairs. The experimental Pine editor uses an adapted interpreter from DimmOFF's egui-charts fork; its subset and output require further compatibility, resource and live-data verification. - The chart-tab strip saves open chart workspaces in terminal settings and restores them on startup or after changing providers. Switching tabs pauses inactive chart feeds while the watchlist uses the shared Tradier stream. Experimental Pine studies embed their applied source in the snapshot; the last complete snapshot is retained when an unregistered study cannot be serialized. Named layouts remain separate. File storage uses OS file locks and revision checks for settings and drawing conflicts. Workspace restart coverage uses an in-memory store; full process-crash recovery and cross-process behavior still need end-to-end verification. - On a Tradier stream reconnect, chart recovery requests the missing historical range, restores completed bars, then reconciles the forming candle using complete one-minute bars and buffered later ticks. The chart reports recovery or errors; Tradier's intraday retention limits apply. Initial-load history overlap, provider corrections and late trade reconciliation remain open, and recovery under real market-hour interruptions needs further verification. diff --git a/CHANGELOG.md b/CHANGELOG.md index 498ad09..6a80358 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ - Add a read-only Tradier options chain with expiration selection, calls and puts, configurable columns, quotes and available Greeks; open a contract in a chart tab. - Improve Pine indicator support, including lower-timeframe requests, session flags and historical prior-day values. Compatibility and live behavior still need verification. -- Update the vendored egui-charts main branch to `7a852a5`, including upstream chart and study improvements, while retaining TradeCraft's provider, Pine and chart interaction changes. macOS validation of this update is pending. +- Update the vendored egui-charts main branch to `7a852a5`, including upstream chart and study improvements, while retaining TradeCraft's provider, Pine and chart interaction changes. Both macOS architectures passed automated builds; interactive validation remains pending. ## 0.3.0 — alpha diff --git a/RELEASE-CHECKLIST.md b/RELEASE-CHECKLIST.md index 8037bc1..a5c1ed2 100644 --- a/RELEASE-CHECKLIST.md +++ b/RELEASE-CHECKLIST.md @@ -2,18 +2,18 @@ ## 0.4.0 alpha — in preparation -Release scope: read-only Tradier options chains and contract charts, Pine indicator improvements, and the egui-charts update to `7a852a5`. The source is on `codex/macos-build`; much of the release work is uncommitted. The current 0.4.0 version is a release candidate, not a published release. +Release scope: read-only Tradier options chains and contract charts, Pine indicator improvements, and the egui-charts update to `7a852a5`. The candidate source is committed on `codex/macos-build` and proposed in PR #9. The current 0.4.0 version is a release candidate, not a published release. - [ ] Review the complete source diff, including untracked application files, and reconcile the changes from all project chats. Preserve the TradeCraft-specific egui-charts changes and reconcile Pine imports with attribution and review records. - [ ] Complete `RELEASE-NOTES-0.4.0.md` and update `CHANGELOG.md` for the final release. Verify the notes against the final source and packages. - [ ] Run the dependency license audit for Windows personal and community and both macOS targets on the final lockfile. Review any changes and include the generated notices. The strict macOS checks previously reported missing notices; the packaging script records these as warnings at the owner's direction. The open upstream and provider-rights issues are not resolved by a successful build. - [ ] Run the appropriate workspace, options, Pine and vendored chart tests on the final source. Verify the community and personal Windows release builds; the personal build must update and verify `target/personal/tradecraft.exe`. - [ ] Validate the complete interactive options workflow and broader symbol/entitlement coverage, including timestamps and missing values. A read-only live Tradier check retrieved an SPY chain with calls and puts, and one selected contract returned eight daily and 206 five-minute bars on November 14, 2026. This does not establish streaming, every entitlement, or end-to-end chart behavior. -- [ ] Build and test both macOS architectures for this revision using GitHub Actions. Inspect the app bundles and notice inventories; the prior 0.3.0 builds do not validate 0.4.0. Interactive Mac validation, including Keychain and workspace restart, remains outstanding. +- [x] Build and test both macOS architectures for the candidate using GitHub Actions. Run 43686509325 passed both architectures at `eae3a82`; `8ee1f94` has an identical source tree. Downloaded ZIPs passed integrity checks, report version 0.4.0, contain the expected Mach-O architectures and record ten missing notice texts each. Interactive Mac validation, including Keychain and workspace restart, remains outstanding. Rebuild packages if release contents change. - [ ] Check the final Windows and macOS archives, version, executable identities and notices against the same release source. Follow the review and release process before publishing. The November 14 legal and provenance review records unresolved provider authorization, upstream source and asset provenance, and other distribution questions. These require separate review; no blanket compliance clearance has been established. Preserve that detailed review privately unless its owner authorizes publication. -The first 0.4.0 GitHub Mac run exposed two options UI test failures on Apple Silicon. The tests were adjusted to use isolated storage and are being checked again; do not infer a Mac app failure or a successful Mac validation from that initial result alone. +The first 0.4.0 GitHub Mac run exposed two options UI test failures on Apple Silicon. After test storage was isolated, both architecture jobs passed. The separate strict license workflow passed both Windows configurations, failed on Apple Silicon for ten missing notice texts and cancelled the Intel job; Mac packaging recorded those gaps as warnings. The 0.3.0 alpha was published for Windows, Apple Silicon and Intel macOS. Its tag and assets are historical and should not be replaced by this release. diff --git a/RELEASE-NOTES-0.4.0.md b/RELEASE-NOTES-0.4.0.md index 9d5686a..30e16b9 100644 --- a/RELEASE-NOTES-0.4.0.md +++ b/RELEASE-NOTES-0.4.0.md @@ -22,4 +22,4 @@ The charting library has been updated with improvements to built-in studies, dra ## Release status -TradeCraft remains a read-only alpha. The Windows personal and community editions maintain separate provider preferences. Mac builds and interactive platform behavior require validation for this revision. Provider distribution rights, upstream provenance and third-party notice questions remain documented in the project records; no blanket compliance clearance is implied. +TradeCraft remains a read-only alpha. The Windows personal and community editions maintain separate provider preferences. Both Mac architectures passed automated builds, but interactive Mac testing remains outstanding; the apps are unsigned and not notarized. Provider distribution rights, upstream provenance and third-party notice questions remain documented in the project records; no blanket compliance clearance is implied. From 3076a94a6d24c005b3c358569e4275b46429cf9d Mon Sep 17 00:00:00 2001 From: vybie <168300406+vybie@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:05:46 -0800 Subject: [PATCH 4/4] Prepare 0.4.0 release documentation --- CHANGELOG.md | 2 ++ RELEASE-CHECKLIST.md | 16 ++++++++-------- RELEASE-NOTES-0.4.0.md | 2 +- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a80358..b64a22a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.4.0 — alpha + - Add a read-only Tradier options chain with expiration selection, calls and puts, configurable columns, quotes and available Greeks; open a contract in a chart tab. - Improve Pine indicator support, including lower-timeframe requests, session flags and historical prior-day values. Compatibility and live behavior still need verification. - Update the vendored egui-charts main branch to `7a852a5`, including upstream chart and study improvements, while retaining TradeCraft's provider, Pine and chart interaction changes. Both macOS architectures passed automated builds; interactive validation remains pending. diff --git a/RELEASE-CHECKLIST.md b/RELEASE-CHECKLIST.md index a5c1ed2..4d1c7b3 100644 --- a/RELEASE-CHECKLIST.md +++ b/RELEASE-CHECKLIST.md @@ -1,16 +1,16 @@ # Release coordination -## 0.4.0 alpha — in preparation +## 0.4.0 alpha -Release scope: read-only Tradier options chains and contract charts, Pine indicator improvements, and the egui-charts update to `7a852a5`. The candidate source is committed on `codex/macos-build` and proposed in PR #9. The current 0.4.0 version is a release candidate, not a published release. +Release scope: read-only Tradier options chains and contract charts, Pine indicator improvements, and the egui-charts update to `7a852a5`. Release source is on `codex/macos-build` and proposed in PR #9. -- [ ] Review the complete source diff, including untracked application files, and reconcile the changes from all project chats. Preserve the TradeCraft-specific egui-charts changes and reconcile Pine imports with attribution and review records. -- [ ] Complete `RELEASE-NOTES-0.4.0.md` and update `CHANGELOG.md` for the final release. Verify the notes against the final source and packages. -- [ ] Run the dependency license audit for Windows personal and community and both macOS targets on the final lockfile. Review any changes and include the generated notices. The strict macOS checks previously reported missing notices; the packaging script records these as warnings at the owner's direction. The open upstream and provider-rights issues are not resolved by a successful build. -- [ ] Run the appropriate workspace, options, Pine and vendored chart tests on the final source. Verify the community and personal Windows release builds; the personal build must update and verify `target/personal/tradecraft.exe`. +- [ ] Complete the comprehensive source and provenance review, including Pine imports and vendored changes. This remains follow-up work; prior reviews do not establish full clearance. +- [x] Prepare `RELEASE-NOTES-0.4.0.md` and `CHANGELOG.md` for the release. +- [ ] Resolve the missing macOS notices and remaining upstream and provider-rights questions. Windows personal and community audits passed; strict macOS checks have reported ten missing notice texts. Mac packaging records these as warnings at the owner's direction. +- [x] Candidate Windows personal and community release builds and both workspace test configurations passed; the pinned personal executable was verified against its build. Mac provider and UI tests passed on both architectures. Further interactive and broad compatibility testing remains open. - [ ] Validate the complete interactive options workflow and broader symbol/entitlement coverage, including timestamps and missing values. A read-only live Tradier check retrieved an SPY chain with calls and puts, and one selected contract returned eight daily and 206 five-minute bars on November 14, 2026. This does not establish streaming, every entitlement, or end-to-end chart behavior. -- [x] Build and test both macOS architectures for the candidate using GitHub Actions. Run 43686509325 passed both architectures at `eae3a82`; `8ee1f94` has an identical source tree. Downloaded ZIPs passed integrity checks, report version 0.4.0, contain the expected Mach-O architectures and record ten missing notice texts each. Interactive Mac validation, including Keychain and workspace restart, remains outstanding. Rebuild packages if release contents change. -- [ ] Check the final Windows and macOS archives, version, executable identities and notices against the same release source. Follow the review and release process before publishing. +- [x] Build and test both macOS architectures using GitHub Actions. Run 43691123701 passed both architectures at `2b3f44d`; ZIPs passed integrity checks, report version 0.4.0, contain the expected Mach-O architectures and record ten missing notice texts each. Interactive Mac validation, including Keychain and workspace restart, remains outstanding. The apps are unsigned and not notarized. +- [ ] Verify final archives and published asset checksums against the release source. The November 14 legal and provenance review records unresolved provider authorization, upstream source and asset provenance, and other distribution questions. These require separate review; no blanket compliance clearance has been established. Preserve that detailed review privately unless its owner authorizes publication. diff --git a/RELEASE-NOTES-0.4.0.md b/RELEASE-NOTES-0.4.0.md index 30e16b9..b11f086 100644 --- a/RELEASE-NOTES-0.4.0.md +++ b/RELEASE-NOTES-0.4.0.md @@ -1,4 +1,4 @@ -# TradeCraft 0.4.0 alpha — release candidate +# TradeCraft 0.4.0 alpha TradeCraft 0.4.0 adds a read-only options workflow, expands custom Pine indicator support and updates the charting library with new indicator and chart controls.