Repository navigation
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.
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 |
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.
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 sources coexist and must stay non-destructive to each other:
- Local or manual trades in UserDefaults and Core Data: the base layer, always preserved.
- 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.
-
Folync: a self-hosted instance acting as an authoritative read-only source. When active,
legacyPortfolioTradesholds 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.
-
NetworkServiceis the protocol, implemented byPythonNetworkService. 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 inPythonConfiguration: thepythonInterpreterPathdefault, else Stockbar's ownpython-envin Application Support. There is no system-Python fallback. -
PythonEnvironmentSetupbuilds that environment by running the bundledsetup_python_env.sh;script/setup_python_env.shruns the same script from a checkout. -
PythonWorkerPoolkeeps up to twostockbar_worker.pyprocesses running, soget_stock_data.pyandget_ohlc_data.pyrequests 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--historicaland--test-keyalso available. Candles come fromget_ohlc_data.py. Errors come back as a JSON envelope witherror: trueand anerror_code. - A failed fetch returns a placeholder
StockFetchResultwith.nanprices rather than throwing, so metadata survives. -
PythonConfiguration.validateSymbolandsanitizeSymbolrestrict symbols toA-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 = NOand 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.
-
Window.
StockbarMainWindowControllerhosts StockbarMainView.swift: a sidebar over ten sections (Overview, Holdings, Alerts, Performance, Risk, Allocation, Backups, Data Health, Diagnostics, Settings). The performance section's internal case ischarts. Settings stay embedded in the main window. -
Menu bar.
StockMenuBarControllerandStockStatusBar: oneNSStatusItemper 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()(inStockbarDesign.swift), never withcontentTransition(.numericText())itself, whichScripts/validate_invariants.shrefuses anywhere else. The modifier leaves the transition out whenfigures.rollingDigitsis off. Each SwiftUI root that AppKit hosts ends its body withstockbarRollingDigitsSetting(), 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,+Exportand+Candlestick),CandlestickChartViewandMenuPriceChartView. On the 1 Day and 1 Week ranges,ChartTimeCompressiondraws long gaps between points narrow; the line chart, its axis labels, zoom andChartInteractionViewwork in those plot times, and only labels and hover text convert back to real times. -
History.
HistoricalDataManageris split the same way: storage, snapshot recording and chart reads in the main file, with+Folync,+PortfolioMenu,+Retroactive,+Metricsand+Thinning.
| 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.
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 throughSTOCKBAR_QUOTE_CACHE_SECONDS. - Symbols with recorded failures are governed only by backoff (
shouldRetry) and the circuit breaker;shouldRefreshnever 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.
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.
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.
- UI state stays on
@MainActor, heavy work off the main thread, and Core Data writes on background contexts. - Use
StockbarRuntimeStoragefor 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, notprint.
Home · Installation · Troubleshooting · FAQ · Release History · Source · Report an issue
This wiki describes Stockbar 3.8.2.
Using Stockbar
- Installation
- Getting Started
- Menu Bar
- Main Window
- Portfolio and Holdings
- Alerts
- Charts and Analytics
Data sources
Reference
- Settings Reference
- Updates and Channels
- Backups, Export and Import
- Privacy and Security
- Troubleshooting
- FAQ
- Release History
Developers