Skip to content

Architecture

jayjay181818 edited this page Nov 17, 2026 · 1 revision

Architecture

An overview for people reading or changing the code. The canonical, versioned text is Docs/Architecture.md in the repository; implementation details change, so check the source before relying on an exact value. Working rules for contributors are in AGENTS.md. For commands, see Development.

Shape of the app

Stockbar is a macOS portfolio tracker that mixes Swift and Python. LSUIElement is false: the app has a Dock-visible window and menu bar controls. The deployment target is macOS 15.4, and the project compiles in Swift 6 language mode with strict concurrency.

The source lives under Stockbar/:

Folder Holds
Analytics/ Risk, correlation, attribution and sector analysis
Charts/ Swift Charts views, menu popovers, chart processing
Data/ DataModel, historical data, Core Data, networking
Models/ Value types: trading, menu bar settings, Trading 212
Services/ Refresh, caching, alerts, Folync, Trading 212, backup, updates
Utilities/ Runtime storage, credentials, logging, configuration
Views/ The main window and settings views
Resources/ The bundled Python scripts, requirements and setup script

Lifecycle

main.swift → acceptance preflight hooks → AppDelegate → StockMenuBarController, which owns the DataModel, the StockStatusBar and the StockbarMainWindowController.

main.swift intercepts --acceptance-preflight and --acceptance-bootstrap and exits before NSApplicationMain. That block must stay first.

Data flow

DataModel (@MainActor @Observable)        central state hub
  ├── realTimeTrades: [RealTimeTrade]             ← drives menu bar and all views
  ├── RefreshService                              ← refresh scheduling; RefreshPassScheduler serialises passes
  ├── CacheCoordinator (actor)                    ← TTL, backoff and circuit breaker
  ├── PythonNetworkService → python subprocess → get_stock_data.py
  ├── Trading212BrokerSyncService / Trading212Provider   ← broker-linked holdings
  ├── FolyncPortfolioSource / FolyncSupplementalData     ← self-hosted portfolio source
  └── Core Data (historical prices, OHLC, snapshots) + UserDefaults

Shared models (DataModel, RealTimeTrade, HistoricalDataManager, CurrencyConverter and the shared services) use @Observable, so SwiftUI redraws only the views that read the property that changed. State that views must not track is @ObservationIgnored. AppKit and service code subscribe through ObservationPublisher, which replaces $property publishers. View-owned chart view models stay ObservableObject with @StateObject.

Three portfolio sources

Three sources coexist and must stay non-destructive to each other:

  1. Local or manual trades in UserDefaults and Core Data: the base layer, always preserved.
  2. Trading 212: broker-linked holdings. Linked positions take quantity, price, average cost and profit and loss from the broker and deliberately skip the market-data providers. Credentials live in the Keychain only. Read-only; no order execution.
  3. Folync: a self-hosted instance acting as an authoritative read-only source. When active, legacyPortfolioTrades holds the shadowed local portfolio so switching back restores it. Folync-backed financial fields are read-only; watchlists, alerts and menu bar preferences stay Stockbar-owned. Supplemental routes (line history, OHLCV, benchmarks, FX) are toggled independently and never splice Folync and legacy points into one series.

InstrumentResolver maps provider tickers (especially Trading 212's) to canonical instrument identities. SymbolMetadata distinguishes benchmark symbols (^GSPC, ^FTSE) from holdings, and Trade.isWatchlistOnly marks symbols with no position maths. See Portfolio and Holdings, Trading 212 and Folync.

The Python bridge

  • NetworkService is the protocol, implemented by PythonNetworkService. The other implementation, BenchmarkQuoteService, gives made-up quotes to the benchmark's refresh workload and is taken only in an acceptance run with live providers off.
  • Process spawning is isolated in PythonProcessRunner. The interpreter and environment are in PythonConfiguration: the pythonInterpreterPath default, else Stockbar's own python-env in Application Support. There is no system-Python fallback.
  • PythonEnvironmentSetup builds that environment by running the bundled setup_python_env.sh; script/setup_python_env.sh runs the same script from a checkout.
  • PythonWorkerPool keeps up to two stockbar_worker.py processes running, so get_stock_data.py and get_ohlc_data.py requests skip interpreter start-up and package imports. The worker runs the script in place with fresh globals and returns its stdout, stderr and exit code. When every worker is busy, or one fails, the request runs as its own process. Workers are replaced when the interpreter or environment changes, stopped after a timeout or cancellation, and exit when idle or when the app quits.
  • An idle worker holds about 70 MB. With Quit Python Helper When Idle on (pythonHelper.quitWhenIdle, on by default) it exits after 90 idle seconds; off, after 15 idle minutes. The pool checks for idle workers every quarter of the timeout and reads the setting at each check. See Market Data and Python.
  • The contract is JSON on stdout, human logs on stderr only. Quotes use get_stock_data.py --json <symbols…>, with --historical and --test-key also available. Candles come from get_ohlc_data.py. Errors come back as a JSON envelope with error: true and an error_code.
  • A failed fetch returns a placeholder StockFetchResult with .nan prices rather than throwing, so metadata survives.
  • PythonConfiguration.validateSymbol and sanitizeSymbol restrict symbols to A-Z0-9.^=- to prevent argument injection. Route any new symbol path through them.
  • Inside the script, live quotes use a fixed order (yfinance, Twelve Data, then FMP) and historical data follows DATA_SOURCE_PRIORITY (default yfinance, then FMP). The quote cache is at ~/Library/Caches/stockbar-cache/quote_cache.json, lock-file guarded with an atomic replace.
  • ENABLE_USER_SCRIPT_SANDBOXING = NO and the app must stay unsandboxed: the subprocess bridge depends on it. The entitlement validator checks the app sandbox and server permissions and allows exactly one entitlement, which lets the ad hoc signed app load its Sparkle framework.

UI layer

  • Window. StockbarMainWindowController hosts StockbarMainView.swift: a sidebar over ten sections (Overview, Holdings, Alerts, Performance, Risk, Allocation, Backups, Data Health, Diagnostics, Settings). The performance section's internal case is charts. Settings stay embedded in the main window.
  • Menu bar. StockMenuBarController and StockStatusBar: one NSStatusItem per visible symbol. It also handles polling for an external display.
  • Rolling digits. A figure that rolls to a new value asks for it with stockbarRollingDigits() (in StockbarDesign.swift), never with contentTransition(.numericText()) itself, which Scripts/validate_invariants.sh refuses anywhere else. The modifier leaves the transition out when figures.rollingDigits is off. Each SwiftUI root that AppKit hosts ends its body with stockbarRollingDigitsSetting(), which reads the setting once for the whole window or popover. A new root needs it too.
  • Charts. Swift Charts: PerformanceChartView (split by concern into state and line chart plus +Comparison, +Metrics, +Export and +Candlestick), CandlestickChartView and MenuPriceChartView. On the 1 Day and 1 Week ranges, ChartTimeCompression draws long gaps between points narrow; the line chart, its axis labels, zoom and ChartInteractionView work in those plot times, and only labels and hover text convert back to real times.
  • History. HistoricalDataManager is split the same way: storage, snapshot recording and chart reads in the main file, with +Folync, +PortfolioMenu, +Retroactive, +Metrics and +Thinning.

Persistence

Store Location Contents
UserDefaults com.stockbar, through StockbarRuntimeStorage.userDefaults Trades, preferences, cache timestamps
Core Data ~/Library/Application Support/Stockbar/StockbarDataModel.sqlite Historical prices, OHLC and snapshots. The model version comes from the .xccurrentversion file; DataMigrationService holds the migration flags and CoreDataStoreRecovery handles corrupt stores.
Config JSON ~/Library/Application Support/com.stockbar/.stockbar_config.json DATA_SOURCE_PRIORITY. FMP and Twelve Data keys an earlier version wrote here are moved to the Keychain on first use.
Keychain com.stockbar.credentials (one item, CredentialVault) Trading 212 and Folync credentials and the FMP and Twelve Data keys, through Trading212CredentialStore, FolyncCredentialStore and MarketDataKeyStore. One item means one macOS prompt after an update. Older items are imported on first read and removed only after the new item reads back. The market-data keys are passed to the Python scripts as environment variables per run.

Settings export and import (SettingsTransferService) seals an allowlist of defaults (SettingsTransferKeys), the config-file keys and the Keychain credentials, and for Everything a Core Data copy, into one AES-GCM .stockbarexport file (SettingsTransferContainer). Imports validate everything first, snapshot the current state and roll back on failure. CoreDataStoreTransfer copies and replaces stores through replacePersistentStore and keeps the live store read-only until relaunch. See Backups, Export and Import.

Caching and failure policy

Stockbar/Services/CacheCoordinator.swift owns freshness, retry intervals and circuit-breaker thresholds. Preserve that policy when you add a fetch path.

  • Freshness follows the user's Main Refresh Interval (RefreshService.freshnessInterval); the Python quote cache is bounded to match through STOCKBAR_QUOTE_CACHE_SECONDS.
  • Symbols with recorded failures are governed only by backoff (shouldRetry) and the circuit breaker; shouldRefresh never returns true for them. Retry steps are 1, 2, 5 and 10 minutes, and five consecutive failures suspend a symbol for an hour. The popover exposes the suspension state and Retry Now.

Currency

CurrencyConverter (exchangerate-api.com, USD base) covers USD, GBP, EUR, JPY, CAD and AUD. Normalise GBX/GBp to GBP once, at the provider boundary. Preserve values already reported as GBP, including cost bases. Use the reported currency and existing provider-specific fallbacks; a .L suffix alone is not evidence that a value still needs dividing.

Updates

Services/AppUpdateService.swift owns Sparkle's updater and the state shown in Settings → General. Sparkle downloads, verifies and installs; Stockbar only decides whether the updater runs (UpdaterAvailability: not in Debug builds, and not in test or acceptance runs unless the feed is on loopback) and which builds it may see (UpdateChannel: Testing also allows feed items marked testing; Experimental reads a feed of its own and allows items marked experimental). The two feed addresses, the public key and the signature requirements are in Stockbar/Info.plist. How builds and the feed are produced is on Branches and Releases.

Invariants worth knowing

  • UI state stays on @MainActor, heavy work off the main thread, and Core Data writes on background contexts.
  • Use StockbarRuntimeStorage for app defaults and writable paths. An acceptance run needs a valid temporary root, a run ID and live providers disabled, and never falls back to production storage on invalid configuration.
  • Gate live network and subprocess paths through StockbarProviderAccessPolicy.
  • Never log secrets; log through Logger, not print.

Clone this wiki locally