From 8d08082f22e044b232402d3463d7999567e46ed7 Mon Sep 17 00:00:00 2001 From: knightmare2600 Date: Fri, 9 Oct 2026 22:59:50 +0100 Subject: [PATCH 1/4] fix: save and restore map style, projection and overlays user-preferences.example.json has shipped MapStyle, MapProjection and MapOverlays since the map overhaul, but nothing read them: the map always started on Earth at Night / Flat / Day-Night, and Save-UserPreferences rewrote the file with a fixed key set, deleting the three keys on the first save. There is no save on window close (it minimises to the tray), so map changes were never persisted. - Save-UserPreferences now writes MapStyle, MapProjection and MapOverlays from the current toolbar state. - The style and projection pickers and the ten overlay toggles save when changed, as the exchange toggles already do. - Saved settings are applied straight after the pickers are populated, before change handlers are attached, so start-up does not redraw the map once per toggle. - New Private/Get-MapPreferenceState resolves the saved values. Unknown styles/projections fall back to the defaults; overlay names with no toggle (e.g. 'TimeLine' from the original example file) are ignored; an empty MapOverlays list means all overlays off; a missing key keeps the XAML defaults. - PSExchangeClock.psm1 now dot-sources Private/*.ps1 (not exported). - Pester tests in Tests/MapPreferences.Tests.ps1. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 ++++ PSExchangeClock/PSExchangeClock.psm1 | 11 +++ .../Private/Get-MapPreferenceState.ps1 | 37 +++++++++ .../New-StockExchangeCountdownDashboard.ps1 | 80 ++++++++++++++----- README.md | 3 + Tests/MapPreferences.Tests.ps1 | 75 +++++++++++++++++ 6 files changed, 199 insertions(+), 21 deletions(-) create mode 100644 PSExchangeClock/Private/Get-MapPreferenceState.ps1 create mode 100644 Tests/MapPreferences.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d10eca..688a613 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,20 @@ All notable changes to PSExchangeClock will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- Pester tests under `Tests/` (run with `Invoke-Pester ./Tests`), starting with map preference restore + +### Fixed + +- Map style, projection and overlay choices were never restored at start-up and were dropped whenever preferences were saved. They are now saved when changed and restored on launch (`MapStyle`, `MapProjection`, `MapOverlays`) + +### Changed + +- `PSExchangeClock.psm1` also loads non-exported helpers from `Private/` + ## [1.1.0] - 2026-09-28 ### Fixed diff --git a/PSExchangeClock/PSExchangeClock.psm1 b/PSExchangeClock/PSExchangeClock.psm1 index 6bb50e1..159a9c2 100644 --- a/PSExchangeClock/PSExchangeClock.psm1 +++ b/PSExchangeClock/PSExchangeClock.psm1 @@ -1,6 +1,17 @@ # PSExchangeClock module loader $PSModuleRoot = $PSScriptRoot +# Dot-source private helpers (not exported) +$privateFunctions = Get-ChildItem -Path "$PSModuleRoot\Private\*.ps1" -ErrorAction SilentlyContinue +foreach ($function in $privateFunctions) { + try { + . $function.FullName + } + catch { + Write-Error "Failed to import private helpers $($function.BaseName): $_" + } +} + # Dot-source all public functions $publicFunctions = Get-ChildItem -Path "$PSModuleRoot\Public\*.ps1" -ErrorAction SilentlyContinue foreach ($function in $publicFunctions) { diff --git a/PSExchangeClock/Private/Get-MapPreferenceState.ps1 b/PSExchangeClock/Private/Get-MapPreferenceState.ps1 new file mode 100644 index 0000000..b6e10d5 --- /dev/null +++ b/PSExchangeClock/Private/Get-MapPreferenceState.ps1 @@ -0,0 +1,37 @@ +function Get-MapPreferenceState { + <# + .SYNOPSIS + Resolves the saved map style, projection and overlays from user preferences. + .DESCRIPTION + Unknown or missing values resolve to $null so the caller keeps its own + defaults. Overlays resolve to $null only when MapOverlays is absent; an + empty saved list means "all overlays off". Unknown overlay names (for + example 'TimeLine' from older example files, which has no toggle) are + ignored. + .OUTPUTS + Hashtable with Style, Projection and Overlays. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + $UserPreferences, + [string[]]$ValidStyles = @(), + [string[]]$ValidProjections = @(), + [string[]]$OverlayNames = @() + ) + + $state = @{ Style = $null; Projection = $null; Overlays = $null } + if (-not $UserPreferences) { return $state } + + if ($UserPreferences.MapStyle -and $ValidStyles -contains $UserPreferences.MapStyle) { + $state.Style = [string]$UserPreferences.MapStyle + } + if ($UserPreferences.MapProjection -and $ValidProjections -contains $UserPreferences.MapProjection) { + $state.Projection = [string]$UserPreferences.MapProjection + } + if ($UserPreferences.PSObject.Properties['MapOverlays']) { + $saved = @($UserPreferences.MapOverlays | Where-Object { $_ }) + $state.Overlays = @($OverlayNames | Where-Object { $saved -contains $_ }) + } + return $state +} diff --git a/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 b/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 index 8c48fcb..a41abf5 100644 --- a/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 +++ b/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 @@ -143,6 +143,11 @@ function New-StockExchangeCountdownDashboard { if ($chkNotify15 -and $chkNotify15.IsChecked) { $prefs.NotifyThresholds += 15 } if ($chkNotify5 -and $chkNotify5.IsChecked) { $prefs.NotifyThresholds += 5 } if ($chkAlwaysOnTop) { $prefs.AlwaysOnTop = [bool]$chkAlwaysOnTop.IsChecked } + if ($cmbMapStyle -and $cmbMapStyle.SelectedItem) { $prefs.MapStyle = [string]$cmbMapStyle.SelectedItem.Tag } + if ($script:mapProjection) { $prefs.MapProjection = [string]$script:mapProjection } + if ($script:mapOverlayToggles) { + $prefs.MapOverlays = @($script:mapOverlayToggles.Keys | Where-Object { $script:mapOverlayToggles[$_].IsChecked }) + } } catch { } # API keys are stored via the secrets backend, not in JSON @@ -995,6 +1000,38 @@ public static class CredManager { } $cmbMapProjection.SelectedIndex = 0 + # Overlay toggles by preference name (MapOverlays in user-preferences.json) + $script:mapOverlayToggles = [ordered]@{ + DayNight = $chkTerminator + TimeZoneBands = $chkTimeZoneBands + PoliticalBorders = $chkPoliticalBounds + TimeZoneBoundaries = $chkTZBoundaries + Earthquakes = $chkEarthquakes + Volcanoes = $chkVolcanoes + NaturalEvents = $chkNaturalEvents + ConflictZones = $chkConflictZones + SubmarineCables = $chkSubmarineCables + PowerPlants = $chkPowerPlants + } + + # Restore saved map settings (runs before the change handlers are attached, so no redraws) + $mapState = Get-MapPreferenceState -UserPreferences $script:userPrefs ` + -ValidStyles @($mapStyleOptions | ForEach-Object { $_.Value }) ` + -ValidProjections @($projOptions | ForEach-Object { $_.Value }) ` + -OverlayNames @($script:mapOverlayToggles.Keys) + if ($mapState.Style) { + $cmbMapStyle.SelectedIndex = [array]::IndexOf(@($mapStyleOptions | ForEach-Object { $_.Value }), $mapState.Style) + } + if ($mapState.Projection) { + $cmbMapProjection.SelectedIndex = [array]::IndexOf(@($projOptions | ForEach-Object { $_.Value }), $mapState.Projection) + $script:mapProjection = $mapState.Projection + } + if ($null -ne $mapState.Overlays) { + foreach ($name in $script:mapOverlayToggles.Keys) { + $script:mapOverlayToggles[$name].IsChecked = $mapState.Overlays -contains $name + } + } + # ── Market Data Cache ───────────────────────────────────────── $script:newsCache = @{ @@ -4737,7 +4774,7 @@ public static class CredManager { # ── Map Toolbar Event Handlers ──────────────────────────────── # Map style ComboBox - $cmbMapStyle.Add_SelectionChanged({ Initialize-WorldMap }) + $cmbMapStyle.Add_SelectionChanged({ Initialize-WorldMap; Save-UserPreferences }) # Map projection ComboBox $cmbMapProjection.Add_SelectionChanged({ @@ -4746,30 +4783,31 @@ public static class CredManager { $script:mapProjection = $sel.Tag $script:expandedCluster = $null Initialize-WorldMap + Save-UserPreferences } }) # Overlay toggles - $chkTerminator.Add_Checked({ Initialize-WorldMap }) - $chkTerminator.Add_Unchecked({ Initialize-WorldMap }) - $chkTimeZoneBands.Add_Checked({ Initialize-WorldMap }) - $chkTimeZoneBands.Add_Unchecked({ Initialize-WorldMap }) - $chkPoliticalBounds.Add_Checked({ Initialize-WorldMap }) - $chkPoliticalBounds.Add_Unchecked({ Initialize-WorldMap }) - $chkEarthquakes.Add_Checked({ Initialize-WorldMap }) - $chkEarthquakes.Add_Unchecked({ Initialize-WorldMap }) - $chkVolcanoes.Add_Checked({ Initialize-WorldMap }) - $chkVolcanoes.Add_Unchecked({ Initialize-WorldMap }) - $chkNaturalEvents.Add_Checked({ Initialize-WorldMap }) - $chkNaturalEvents.Add_Unchecked({ Initialize-WorldMap }) - $chkSubmarineCables.Add_Checked({ Initialize-WorldMap }) - $chkSubmarineCables.Add_Unchecked({ Initialize-WorldMap }) - $chkPowerPlants.Add_Checked({ Initialize-WorldMap }) - $chkPowerPlants.Add_Unchecked({ Initialize-WorldMap }) - $chkTZBoundaries.Add_Checked({ Initialize-WorldMap }) - $chkTZBoundaries.Add_Unchecked({ Initialize-WorldMap }) - $chkConflictZones.Add_Checked({ Initialize-WorldMap }) - $chkConflictZones.Add_Unchecked({ Initialize-WorldMap }) + $chkTerminator.Add_Checked({ Initialize-WorldMap; Save-UserPreferences }) + $chkTerminator.Add_Unchecked({ Initialize-WorldMap; Save-UserPreferences }) + $chkTimeZoneBands.Add_Checked({ Initialize-WorldMap; Save-UserPreferences }) + $chkTimeZoneBands.Add_Unchecked({ Initialize-WorldMap; Save-UserPreferences }) + $chkPoliticalBounds.Add_Checked({ Initialize-WorldMap; Save-UserPreferences }) + $chkPoliticalBounds.Add_Unchecked({ Initialize-WorldMap; Save-UserPreferences }) + $chkEarthquakes.Add_Checked({ Initialize-WorldMap; Save-UserPreferences }) + $chkEarthquakes.Add_Unchecked({ Initialize-WorldMap; Save-UserPreferences }) + $chkVolcanoes.Add_Checked({ Initialize-WorldMap; Save-UserPreferences }) + $chkVolcanoes.Add_Unchecked({ Initialize-WorldMap; Save-UserPreferences }) + $chkNaturalEvents.Add_Checked({ Initialize-WorldMap; Save-UserPreferences }) + $chkNaturalEvents.Add_Unchecked({ Initialize-WorldMap; Save-UserPreferences }) + $chkSubmarineCables.Add_Checked({ Initialize-WorldMap; Save-UserPreferences }) + $chkSubmarineCables.Add_Unchecked({ Initialize-WorldMap; Save-UserPreferences }) + $chkPowerPlants.Add_Checked({ Initialize-WorldMap; Save-UserPreferences }) + $chkPowerPlants.Add_Unchecked({ Initialize-WorldMap; Save-UserPreferences }) + $chkTZBoundaries.Add_Checked({ Initialize-WorldMap; Save-UserPreferences }) + $chkTZBoundaries.Add_Unchecked({ Initialize-WorldMap; Save-UserPreferences }) + $chkConflictZones.Add_Checked({ Initialize-WorldMap; Save-UserPreferences }) + $chkConflictZones.Add_Unchecked({ Initialize-WorldMap; Save-UserPreferences }) # Overlays flyout popup toggle $btnOverlays.Add_Checked({ diff --git a/README.md b/README.md index 6915f89..7ae594c 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,9 @@ User preferences are stored in `%APPDATA%\PSExchangeClock\user-preferences.json` | `ActiveExchanges` | Array of exchange codes to display | All 20 exchanges | | `NotifyThresholds` | Minutes before close to show notifications | `[30, 15, 5]` | | `AlwaysOnTop` | Keep dashboard window above other windows | `false` | +| `MapStyle` | World map style: `NightSatellite`, `BlueMarble`, `VectorDark` or `Minimal` | `NightSatellite` | +| `MapProjection` | `Flat` or `Globe` | `Flat` | +| `MapOverlays` | Overlays switched on: `DayNight`, `TimeZoneBands`, `PoliticalBorders`, `TimeZoneBoundaries`, `Earthquakes`, `Volcanoes`, `NaturalEvents`, `ConflictZones`, `SubmarineCables`, `PowerPlants`. An empty list means all off; unknown names are ignored | `["DayNight"]` | | `CommodityBaseCurrency` | Currency for commodity price display | `EUR` | | `SecretsBackend` | Where API keys are stored | `CredentialManager` | diff --git a/Tests/MapPreferences.Tests.ps1 b/Tests/MapPreferences.Tests.ps1 new file mode 100644 index 0000000..870d41e --- /dev/null +++ b/Tests/MapPreferences.Tests.ps1 @@ -0,0 +1,75 @@ +#requires -Version 7.0 +#requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +BeforeAll { + $script:moduleRoot = Join-Path (Split-Path $PSScriptRoot -Parent) 'PSExchangeClock' + . (Join-Path $script:moduleRoot 'Private/Get-MapPreferenceState.ps1') + + # Mirrors the option values and toggle names in New-StockExchangeCountdownDashboard + $script:styles = @('NightSatellite', 'BlueMarble', 'VectorDark', 'Minimal') + $script:projections = @('Flat', 'Globe') + $script:overlays = @('DayNight', 'TimeZoneBands', 'PoliticalBorders', 'TimeZoneBoundaries', 'Earthquakes', + 'Volcanoes', 'NaturalEvents', 'ConflictZones', 'SubmarineCables', 'PowerPlants') + + function Resolve-Map($Prefs) { + Get-MapPreferenceState -UserPreferences $Prefs -ValidStyles $script:styles -ValidProjections $script:projections -OverlayNames $script:overlays + } + function ConvertTo-SavedPrefs([hashtable]$Prefs) { + # Same serialisation as Save-UserPreferences + $Prefs | ConvertTo-Json -Depth 3 | ConvertFrom-Json + } +} + +Describe 'Map preference restore' { + It 'restores style, projection and overlays after a save/load round trip' { + $saved = ConvertTo-SavedPrefs @{ MapStyle = 'BlueMarble'; MapProjection = 'Globe'; MapOverlays = @('Earthquakes', 'PowerPlants') } + $s = Resolve-Map $saved + $s.Style | Should -Be 'BlueMarble' + $s.Projection | Should -Be 'Globe' + $s.Overlays | Should -Be @('Earthquakes', 'PowerPlants') + } + + It 'restores a single saved overlay' { + $s = Resolve-Map (ConvertTo-SavedPrefs @{ MapOverlays = @('Volcanoes') }) + $s.Overlays | Should -Be @('Volcanoes') + } + + It 'treats an empty saved overlay list as all overlays off' { + $s = Resolve-Map (ConvertTo-SavedPrefs @{ MapOverlays = @() }) + # An empty list is "all off", not "unset" + $null -eq $s.Overlays | Should -BeFalse + @($s.Overlays).Count | Should -Be 0 + } + + It 'keeps the built-in defaults when nothing is saved' { + $s = Resolve-Map (ConvertTo-SavedPrefs @{ ActiveExchanges = @('XNYS') }) + $s.Style | Should -BeNullOrEmpty + $s.Projection | Should -BeNullOrEmpty + $null -eq $s.Overlays | Should -BeTrue + } + + It 'keeps the built-in defaults when there is no preferences file' { + $s = Resolve-Map $null + $s.Style | Should -BeNullOrEmpty + $null -eq $s.Overlays | Should -BeTrue + } + + It 'ignores unknown style and projection values' { + $s = Resolve-Map (ConvertTo-SavedPrefs @{ MapStyle = 'Sepia'; MapProjection = 'Mercator' }) + $s.Style | Should -BeNullOrEmpty + $s.Projection | Should -BeNullOrEmpty + } + + It 'ignores overlay names with no toggle, such as TimeLine from older example files' { + $s = Resolve-Map (ConvertTo-SavedPrefs @{ MapOverlays = @('DayNight', 'TimeLine') }) + $s.Overlays | Should -Be @('DayNight') + } + + It 'loads the shipped example preferences' { + $example = Get-Content (Join-Path $script:moduleRoot 'Data/user-preferences.example.json') -Raw | ConvertFrom-Json + $s = Resolve-Map $example + $s.Style | Should -Be 'NightSatellite' + $s.Projection | Should -Be 'Flat' + $s.Overlays | Should -Be @('DayNight') + } +} From 833d6453174986b9e76002d0332677d0f28e11d7 Mon Sep 17 00:00:00 2001 From: knightmare2600 Date: Fri, 9 Oct 2026 23:00:39 +0100 Subject: [PATCH 2/4] feat: add Nasdaq Copenhagen (XCSE) as a supported exchange MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds Nasdaq Copenhagen (Nasdaq København) as the 21st exchange, using the existing exchange, holiday, map, flyout, world-clock and preference mechanisms. It is not active by default; existing saved selections are left unchanged. Exchange - Code XCSE, symbol OMXC, Copenhagen, Denmark, DKK, 55.6761 / 12.5683. - TimeZoneId 'Romance Standard Time' (Windows ID that .NET maps from IANA Europe/Copenhagen); CET/CEST comes from the OS timezone rules. - Main-market equities 09:00-17:00 local. New optional exchange fields OpeningAuctionStart (08:45) and ClosingAuctionStart (16:55) make the status read "Opening auction - opens in ..." and "Closing auction - ends in ..." instead of presenting the call phases as pre-market or continuous trading. Status values, colours and notifications are unchanged. The flyout lists both auction windows. - Sources: Nasdaq European Markets Trading Hours and Holiday Schedule (https://www.nasdaq.com/european-market-activity/trading-hours) and the Nasdaq INET Nordic Auctions factsheet 1015-26. Holidays - holidays.json gains the official Nasdaq Copenhagen equity closures for 2025-2027 (checked 2026-10-09). Nasdaq lists no Copenhagen half days. These differ from Danish public holidays (24 and 31 December are exchange closures). Later years are not yet published. Supporting changes - Exchange status logic moved from the dashboard into Private/Get-ExchangeSessionStatus.ps1 (behaviour preserved) so it can be tested without WPF. Countdowns are now measured in UTC, so they stay correct on DST transition days. Format-CountdownSpan replaces the inline countdown formatting. - Private/Test-ExchangeActive holds the existing saved-selection logic. - Get-StockExchangeData appends built-in exchanges missing from a cache younger than 30 days, without overwriting cached entries, so existing installs see the new exchange without -ForceRefresh. - README, about help, docs and manifest description updated (20 -> 21 exchanges); README's ActiveExchanges default corrected to the seeded example list. - Pester tests: sessions, auctions, weekends, holidays, CET/CEST transitions, machine-timezone independence, missing holiday data, selection persistence and cache handling. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + PSExchangeClock/Data/exchange-data.json | 17 + PSExchangeClock/Data/exchange-details.json | 13 +- PSExchangeClock/Data/holidays.json | 11 +- PSExchangeClock/PSExchangeClock.psd1 | 2 +- .../Private/Get-ExchangeSessionStatus.ps1 | 180 +++++++++ .../Public/Get-StockExchangeData.ps1 | 44 ++- .../New-StockExchangeCountdownDashboard.ps1 | 90 ++--- .../en-US/about_PSExchangeClock.help.txt | 10 +- README.md | 32 +- Tests/PSExchangeClock.Tests.ps1 | 350 ++++++++++++++++++ docs/index.md | 4 +- 12 files changed, 677 insertions(+), 83 deletions(-) create mode 100644 PSExchangeClock/Private/Get-ExchangeSessionStatus.ps1 create mode 100644 Tests/PSExchangeClock.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 688a613..d9e3837 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,15 +9,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Nasdaq Copenhagen (`XCSE`)** — main-market equities 09:00–17:00 Copenhagen time (`Romance Standard Time`), with the 08:45–09:00 opening auction and 16:55–17:00 closing auction shown as auctions rather than pre-market or continuous trading; map marker, flyout details and world clock via the existing mechanisms; not active by default +- Official Nasdaq Copenhagen closures for 2025–2027 in `holidays.json` +- Optional `OpeningAuctionStart` and `ClosingAuctionStart` fields on exchange records - Pester tests under `Tests/` (run with `Invoke-Pester ./Tests`), starting with map preference restore +- Tests for Nasdaq Copenhagen session status, auctions, holidays, DST transitions, selection and exchange-data caching ### Fixed - Map style, projection and overlay choices were never restored at start-up and were dropped whenever preferences were saved. They are now saved when changed and restored on launch (`MapStyle`, `MapProjection`, `MapOverlays`) +- Countdowns are now measured in UTC, so they stay correct on DST transition days +- `Get-StockExchangeData` now appends built-in exchanges missing from a cache younger than 30 days, so new exchanges appear for existing installs ### Changed - `PSExchangeClock.psm1` also loads non-exported helpers from `Private/` +- Exchange status and selection logic moved to `Private/` helpers so it can be tested without WPF ## [1.1.0] - 2026-09-28 diff --git a/PSExchangeClock/Data/exchange-data.json b/PSExchangeClock/Data/exchange-data.json index 508f8c2..7f9e80b 100644 --- a/PSExchangeClock/Data/exchange-data.json +++ b/PSExchangeClock/Data/exchange-data.json @@ -302,6 +302,23 @@ "Latitude": 55.7558, "Longitude": 37.6173, "IsDefault": false + }, + { + "Name": "Nasdaq Copenhagen", + "Code": "XCSE", + "Symbol": "OMXC", + "Country": "Denmark", + "City": "Copenhagen", + "TimeZoneId": "Romance Standard Time", + "OpenTimeLocal": "09:00", + "CloseTimeLocal": "17:00", + "OpeningAuctionStart": "08:45", + "ClosingAuctionStart": "16:55", + "LunchBreakStart": null, + "LunchBreakEnd": null, + "Latitude": 55.6761, + "Longitude": 12.5683, + "IsDefault": false } ] } diff --git a/PSExchangeClock/Data/exchange-details.json b/PSExchangeClock/Data/exchange-details.json index 8975163..4f17577 100644 --- a/PSExchangeClock/Data/exchange-details.json +++ b/PSExchangeClock/Data/exchange-details.json @@ -218,5 +218,16 @@ "Website": "https://www.moex.com/en", "Regulator": "Bank of Russia", "Description": "Moscow Exchange is Russia's largest exchange group, operating trading markets in equities, bonds, derivatives, currencies, and commodities." + }, + "XCSE": { + "PrimaryIndex": "OMX Copenhagen 25 (OMXC25)", + "MarketCapUSD": "n/a", + "ListedCompanies": "n/a", + "Currency": "DKK", + "CurrencySymbol": "kr.", + "Founded": 1808, + "Website": "https://www.nasdaq.com/european-markets/about-nordic-exchanges", + "Regulator": "Finanstilsynet", + "Description": "Nasdaq Copenhagen (Nasdaq København) is Denmark's stock exchange and part of Nasdaq Nordic. Main-market equities trade 09:00-17:00 Copenhagen time, with a closing auction from 16:55. Its benchmark is the OMX Copenhagen 25 index." } -} \ No newline at end of file +} diff --git a/PSExchangeClock/Data/holidays.json b/PSExchangeClock/Data/holidays.json index a0ec1da..4a6bf7a 100644 --- a/PSExchangeClock/Data/holidays.json +++ b/PSExchangeClock/Data/holidays.json @@ -19,5 +19,14 @@ "XMEX": [], "XSES": [], "XTAI": [], - "XMOS": [] + "XMOS": [], + "_comment_XCSE": "Nasdaq Copenhagen equity closures from the official Nasdaq European Markets holiday schedule (https://www.nasdaq.com/european-market-activity/trading-hours), checked 2026-10-09. Nasdaq lists no half trading days for Copenhagen in 2025-2027. Not identical to Danish public holidays: Dec 24 and Dec 31 are exchange closures. Dates beyond 2027 are not yet published.", + "XCSE": [ + "2025-01-01", "2025-04-17", "2025-04-18", "2025-04-21", "2025-05-29", "2025-05-30", + "2025-06-05", "2025-06-09", "2025-12-24", "2025-12-25", "2025-12-26", "2025-12-31", + "2026-01-01", "2026-04-02", "2026-04-03", "2026-04-06", "2026-05-14", "2026-05-15", + "2026-05-25", "2026-06-05", "2026-12-24", "2026-12-25", "2026-12-31", + "2027-01-01", "2027-03-25", "2027-03-26", "2027-03-29", "2027-05-06", "2027-05-07", + "2027-05-17", "2027-12-24", "2027-12-31" + ] } \ No newline at end of file diff --git a/PSExchangeClock/PSExchangeClock.psd1 b/PSExchangeClock/PSExchangeClock.psd1 index ed79c88..4852e7a 100644 --- a/PSExchangeClock/PSExchangeClock.psd1 +++ b/PSExchangeClock/PSExchangeClock.psd1 @@ -6,7 +6,7 @@ Author = 'PowerShellYoungTeam' CompanyName = 'PowerShellYoungTeam' Copyright = '(c) 2026 PowerShellYoungTeam. All rights reserved.' - Description = 'A real-time WPF dashboard for monitoring global stock exchange closing times, market data, forex, crypto, commodities, indices, and financial news — covering 20 major exchanges worldwide.' + Description = 'A real-time WPF dashboard for monitoring global stock exchange closing times, market data, forex, crypto, commodities, indices, and financial news — covering 21 major exchanges worldwide.' PowerShellVersion = '7.0' CLRVersion = '4.0' diff --git a/PSExchangeClock/Private/Get-ExchangeSessionStatus.ps1 b/PSExchangeClock/Private/Get-ExchangeSessionStatus.ps1 new file mode 100644 index 0000000..af449d2 --- /dev/null +++ b/PSExchangeClock/Private/Get-ExchangeSessionStatus.ps1 @@ -0,0 +1,180 @@ +function Format-CountdownSpan { + <# + .SYNOPSIS + Formats a TimeSpan as HH:MM:SS, truncating (not rounding) whole hours. + #> + [CmdletBinding()] + [OutputType([string])] + param([Parameter(Mandatory)][TimeSpan]$TimeSpan) + + '{0:D2}:{1:D2}:{2:D2}' -f [int][math]::Floor($TimeSpan.TotalHours), $TimeSpan.Minutes, $TimeSpan.Seconds +} + +function Get-ExchangeSessionStatus { + <# + .SYNOPSIS + Computes the trading status of an exchange at a given UTC instant. + .DESCRIPTION + Pure status calculation used by the dashboard. The exchange's local wall + clock is derived from its Windows timezone ID, so DST is handled by the + operating system's timezone rules rather than fixed UTC offsets. + Countdowns are measured in UTC, so they stay correct on DST transition days. + + An exchange may optionally define OpeningAuctionStart and ClosingAuctionStart + (HH:mm). From OpeningAuctionStart until OpenTimeLocal, and from + ClosingAuctionStart until CloseTimeLocal, the status text reports the + auction (call phase) rather than pre-market or continuous trading. The + status values themselves are unchanged (PreMarket / ClosingSoon / + ClosingImminent), so colours and notifications behave as before. + .PARAMETER Exchange + Exchange object with Code, TimeZoneId, OpenTimeLocal, CloseTimeLocal and + optional LunchBreakStart, LunchBreakEnd, OpeningAuctionStart and + ClosingAuctionStart. + .PARAMETER UtcNow + The instant to evaluate. Defaults to the current UTC time. + .PARAMETER Holidays + Hashtable of exchange code to an array of yyyy-MM-dd closure dates. + Missing or empty data means only weekends and session hours apply. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)][PSCustomObject]$Exchange, + [datetime]$UtcNow = [DateTime]::UtcNow, + [hashtable]$Holidays = @{} + ) + + if ($UtcNow.Kind -eq [DateTimeKind]::Local) { + $UtcNow = $UtcNow.ToUniversalTime() + } + else { + $UtcNow = [DateTime]::SpecifyKind($UtcNow, [DateTimeKind]::Utc) + } + + $tz = $null + try { + $tz = [System.TimeZoneInfo]::FindSystemTimeZoneById($Exchange.TimeZoneId) + $localNow = [System.TimeZoneInfo]::ConvertTimeFromUtc($UtcNow, $tz) + } + catch { + $localNow = $UtcNow + } + + # Converts an exchange-local wall-clock time to UTC for countdown arithmetic + $toUtc = { + param([datetime]$Local) + if ($tz) { + try { + return [System.TimeZoneInfo]::ConvertTimeToUtc([DateTime]::SpecifyKind($Local, [DateTimeKind]::Unspecified), $tz) + } + catch { + # Wall-clock time inside a DST gap; fall back to treating it as UTC + Write-Verbose "Cannot convert $Local in $($Exchange.TimeZoneId) to UTC: $($_.Exception.Message)" + } + } + return [DateTime]::SpecifyKind($Local, [DateTimeKind]::Utc) + } + + $dayOfWeek = $localNow.DayOfWeek + + # Weekend check + if ($dayOfWeek -eq 'Saturday' -or $dayOfWeek -eq 'Sunday') { + return @{ Status = 'Closed'; Text = 'Weekend'; TimeRemaining = $null; CountdownTarget = $null } + } + + # Holiday check + $todayStr = $localNow.ToString('yyyy-MM-dd') + if ($Holidays -and $Holidays.ContainsKey($Exchange.Code) -and $Holidays[$Exchange.Code] -contains $todayStr) { + return @{ Status = 'Holiday'; Text = 'Holiday - Closed'; TimeRemaining = $null; CountdownTarget = $null } + } + + # Parse times + $openParts = $Exchange.OpenTimeLocal -split ':' + $closeParts = $Exchange.CloseTimeLocal -split ':' + $openTime = $localNow.Date.AddHours([int]$openParts[0]).AddMinutes([int]$openParts[1]) + $closeTime = $localNow.Date.AddHours([int]$closeParts[0]).AddMinutes([int]$closeParts[1]) + + # Lunch break + $lunchStart = $null + $lunchEnd = $null + if ($Exchange.LunchBreakStart -and $Exchange.LunchBreakEnd) { + $lsParts = $Exchange.LunchBreakStart -split ':' + $leParts = $Exchange.LunchBreakEnd -split ':' + $lunchStart = $localNow.Date.AddHours([int]$lsParts[0]).AddMinutes([int]$lsParts[1]) + $lunchEnd = $localNow.Date.AddHours([int]$leParts[0]).AddMinutes([int]$leParts[1]) + } + + # Opening auction (optional) + $openAuctionStart = $null + if ($Exchange.OpeningAuctionStart) { + $oaParts = $Exchange.OpeningAuctionStart -split ':' + $openAuctionStart = $localNow.Date.AddHours([int]$oaParts[0]).AddMinutes([int]$oaParts[1]) + } + + # Closing auction (optional) + $auctionStart = $null + if ($Exchange.ClosingAuctionStart) { + $caParts = $Exchange.ClosingAuctionStart -split ':' + $auctionStart = $localNow.Date.AddHours([int]$caParts[0]).AddMinutes([int]$caParts[1]) + } + + # Pre-market + if ($localNow -lt $openTime) { + $remaining = (& $toUtc $openTime) - $UtcNow + $prefix = if ($openAuctionStart -and $localNow -ge $openAuctionStart) { 'Opening auction - opens in' } else { 'Opens in' } + return @{ Status = 'PreMarket'; Text = "$prefix $(Format-CountdownSpan -TimeSpan $remaining)"; TimeRemaining = $remaining; CountdownTarget = 'Open' } + } + + # Post-close + if ($localNow -ge $closeTime) { + return @{ Status = 'Closed'; Text = 'Closed'; TimeRemaining = $null; CountdownTarget = $null } + } + + # Lunch break + if ($lunchStart -and $lunchEnd -and $localNow -ge $lunchStart -and $localNow -lt $lunchEnd) { + $remaining = (& $toUtc $lunchEnd) - $UtcNow + return @{ Status = 'LunchBreak'; Text = "Lunch - Reopens in $(Format-CountdownSpan -TimeSpan $remaining)"; TimeRemaining = $remaining; CountdownTarget = 'Reopen' } + } + + # Open - countdown to close + $remaining = (& $toUtc $closeTime) - $UtcNow + $countdownStr = Format-CountdownSpan -TimeSpan $remaining + $text = "Closes in $countdownStr" + + if ($auctionStart -and $localNow -ge $auctionStart) { + # Closing call: no continuous matching, uncross at the end of the period + $text = "Closing auction - ends in $countdownStr" + } + + if ($remaining.TotalMinutes -le 5) { + return @{ Status = 'ClosingImminent'; Text = $text; TimeRemaining = $remaining; CountdownTarget = 'Close' } + } + elseif ($remaining.TotalMinutes -le 30) { + return @{ Status = 'ClosingSoon'; Text = $text; TimeRemaining = $remaining; CountdownTarget = 'Close' } + } + else { + return @{ Status = 'Open'; Text = $text; TimeRemaining = $remaining; CountdownTarget = 'Close' } + } +} + +function Test-ExchangeActive { + <# + .SYNOPSIS + Decides whether an exchange is active from saved user preferences. + .DESCRIPTION + Saved ActiveExchanges take precedence; exchanges absent from the saved + list stay inactive, so new exchanges never alter an existing selection. + With no saved list, the exchange's IsDefault flag applies. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)][PSCustomObject]$Exchange, + $UserPreferences + ) + + if ($UserPreferences -and $UserPreferences.ActiveExchanges) { + return [bool](@($UserPreferences.ActiveExchanges) -contains $Exchange.Code) + } + return [bool]$Exchange.IsDefault +} diff --git a/PSExchangeClock/Public/Get-StockExchangeData.ps1 b/PSExchangeClock/Public/Get-StockExchangeData.ps1 index 00e908a..965b356 100644 --- a/PSExchangeClock/Public/Get-StockExchangeData.ps1 +++ b/PSExchangeClock/Public/Get-StockExchangeData.ps1 @@ -3,16 +3,21 @@ function Get-StockExchangeData { <# .SYNOPSIS - Retrieves stock exchange trading hours for 20 major global exchanges. + Retrieves stock exchange trading hours for 21 major global exchanges. .DESCRIPTION Fetches trading hours data from Wikipedia, parses it, and saves to a local - JSON cache file. Includes hardcoded fallback data for 20 major exchanges + JSON cache file. Includes hardcoded fallback data for 21 major exchanges so the tool works offline. Used by PSExchangeClock to determine exchange open/close times, lunch breaks, and geographic coordinates. Supported exchanges: NYSE, NASDAQ, LSE, Euronext Paris, Tokyo, Shanghai, Hong Kong, Toronto, Frankfurt, Sydney, Bombay, NSE India, Korea, - Switzerland, Johannesburg, B3 Brazil, Mexico, Singapore, Taiwan, Moscow. + Switzerland, Johannesburg, B3 Brazil, Mexico, Singapore, Taiwan, Moscow, + Nasdaq Copenhagen. + + A cache younger than 30 days is used as-is, except that any built-in + exchange missing from it (for example one added in a newer module version) + is appended from the hardcoded data. Cached entries are never overwritten. .PARAMETER ForceRefresh Bypass the cache and re-scrape from Wikipedia. .PARAMETER OutputPath @@ -42,7 +47,7 @@ param( function Get-DefaultExchangeData { <# .SYNOPSIS - Returns hardcoded data for 20 major stock exchanges. + Returns hardcoded data for 21 major stock exchanges. #> @( [PSCustomObject]@{ @@ -344,6 +349,30 @@ function Get-DefaultExchangeData { Latitude = 55.7558 Longitude = 37.6173 IsDefault = $false + }, + # Nasdaq Copenhagen main market equities, 09:00-17:00 local. + # 08:45-09:00 opening auction (random uncross 09:00:00-09:00:05); + # 16:55-17:00 closing auction (no continuous matching; random uncross + # 16:59:30-17:00). Sources: Nasdaq European Markets Trading Hours + # https://www.nasdaq.com/european-market-activity/trading-hours and the + # Nasdaq INET Nordic Auctions factsheet (1015-26) + # https://www.nasdaq.com/INETNordicAuctionsFactsheet + [PSCustomObject]@{ + Name = 'Nasdaq Copenhagen' + Code = 'XCSE' + Symbol = 'OMXC' + Country = 'Denmark' + City = 'Copenhagen' + TimeZoneId = 'Romance Standard Time' + OpenTimeLocal = '09:00' + CloseTimeLocal = '17:00' + OpeningAuctionStart = '08:45' + ClosingAuctionStart = '16:55' + LunchBreakStart = $null + LunchBreakEnd = $null + Latitude = 55.6761 + Longitude = 12.5683 + IsDefault = $false } ) } @@ -460,6 +489,13 @@ if (-not $ForceRefresh -and (Test-Path $OutputPath)) { $age = (Get-Date) - [datetime]$cached.LastUpdated if ($age.TotalDays -lt 30) { Write-Verbose "Cache is $([int]$age.TotalDays) days old. Using cached data." + # Append built-in exchanges the cache predates, without touching cached entries + $cachedCodes = @($cached.Exchanges | ForEach-Object { $_.Code }) + $missing = @(Get-DefaultExchangeData | Where-Object { $_.Code -notin $cachedCodes }) + if ($missing.Count -gt 0) { + Write-Verbose "Adding $($missing.Count) exchange(s) missing from cache: $(($missing | ForEach-Object { $_.Code }) -join ', ')" + return @($cached.Exchanges) + $missing + } return $cached.Exchanges } Write-Verbose "Cache is $([int]$age.TotalDays) days old. Refreshing." diff --git a/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 b/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 index a41abf5..6fe66da 100644 --- a/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 +++ b/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 @@ -9,7 +9,7 @@ function New-StockExchangeCountdownDashboard { live market data. Built in PowerShell with a professional dark-themed interface. Features include: - - Live countdown timers with color-coded status for 20 major exchanges worldwide + - Live countdown timers with color-coded status for 21 major exchanges worldwide - Interactive world map with clickable exchange markers (NASA Earth at Night imagery) - World clocks across multiple time zones - Market data sidebar: financial news (RSS), forex rates, cryptocurrency prices, @@ -353,67 +353,8 @@ public static class CredManager { function Get-ExchangeStatus { param([PSCustomObject]$Exchange) - - $localNow = Get-ExchangeLocalTime -Exchange $Exchange - $dayOfWeek = $localNow.DayOfWeek - - # Weekend check - if ($dayOfWeek -eq 'Saturday' -or $dayOfWeek -eq 'Sunday') { - return @{ Status = 'Closed'; Text = 'Weekend'; TimeRemaining = $null; CountdownTarget = $null } - } - - # Holiday check - $todayStr = $localNow.ToString('yyyy-MM-dd') - if ($holidays.ContainsKey($Exchange.Code) -and $holidays[$Exchange.Code] -contains $todayStr) { - return @{ Status = 'Holiday'; Text = 'Holiday - Closed'; TimeRemaining = $null; CountdownTarget = $null } - } - - # Parse times - $openParts = $Exchange.OpenTimeLocal -split ':' - $closeParts = $Exchange.CloseTimeLocal -split ':' - $openTime = $localNow.Date.AddHours([int]$openParts[0]).AddMinutes([int]$openParts[1]) - $closeTime = $localNow.Date.AddHours([int]$closeParts[0]).AddMinutes([int]$closeParts[1]) - - # Lunch break - $lunchStart = $null - $lunchEnd = $null - if ($Exchange.LunchBreakStart -and $Exchange.LunchBreakEnd) { - $lsParts = $Exchange.LunchBreakStart -split ':' - $leParts = $Exchange.LunchBreakEnd -split ':' - $lunchStart = $localNow.Date.AddHours([int]$lsParts[0]).AddMinutes([int]$lsParts[1]) - $lunchEnd = $localNow.Date.AddHours([int]$leParts[0]).AddMinutes([int]$leParts[1]) - } - - # Pre-market - if ($localNow -lt $openTime) { - $remaining = $openTime - $localNow - return @{ Status = 'PreMarket'; Text = "Opens in $("{0:D2}:{1:D2}:{2:D2}" -f [int]$remaining.TotalHours, $remaining.Minutes, $remaining.Seconds)"; TimeRemaining = $remaining; CountdownTarget = 'Open' } - } - - # Post-close - if ($localNow -ge $closeTime) { - return @{ Status = 'Closed'; Text = 'Closed'; TimeRemaining = $null; CountdownTarget = $null } - } - - # Lunch break - if ($lunchStart -and $lunchEnd -and $localNow -ge $lunchStart -and $localNow -lt $lunchEnd) { - $remaining = $lunchEnd - $localNow - return @{ Status = 'LunchBreak'; Text = "Lunch - Reopens in $("{0:D2}:{1:D2}:{2:D2}" -f [int]$remaining.TotalHours, $remaining.Minutes, $remaining.Seconds)"; TimeRemaining = $remaining; CountdownTarget = 'Reopen' } - } - - # Open — countdown to close (skip lunch if applicable) - $remaining = $closeTime - $localNow - $countdownStr = "{0:D2}:{1:D2}:{2:D2}" -f [int]$remaining.TotalHours, $remaining.Minutes, $remaining.Seconds - - if ($remaining.TotalMinutes -le 5) { - return @{ Status = 'ClosingImminent'; Text = "Closes in $countdownStr"; TimeRemaining = $remaining; CountdownTarget = 'Close' } - } - elseif ($remaining.TotalMinutes -le 30) { - return @{ Status = 'ClosingSoon'; Text = "Closes in $countdownStr"; TimeRemaining = $remaining; CountdownTarget = 'Close' } - } - else { - return @{ Status = 'Open'; Text = "Closes in $countdownStr"; TimeRemaining = $remaining; CountdownTarget = 'Close' } - } + # Status logic lives in Private/Get-ExchangeSessionStatus.ps1 so it can be tested without WPF + Get-ExchangeSessionStatus -Exchange $Exchange -UtcNow ([DateTime]::UtcNow) -Holidays $holidays } function Get-StatusColor { @@ -2478,11 +2419,8 @@ public static class CredManager { $script:notificationsFired = @{} foreach ($ex in $allExchanges) { - $isActive = $ex.IsDefault - # Apply saved preferences if available - if ($script:userPrefs -and $script:userPrefs.ActiveExchanges) { - $isActive = $script:userPrefs.ActiveExchanges -contains $ex.Code - } + # Saved preferences win; exchanges absent from them stay inactive + $isActive = Test-ExchangeActive -Exchange $ex -UserPreferences $script:userPrefs $row = [PSCustomObject]@{ DisplayName = $ex.Name Code = $ex.Code @@ -2494,6 +2432,8 @@ public static class CredManager { CloseTime = $ex.CloseTimeLocal LunchBreakStart = $ex.LunchBreakStart LunchBreakEnd = $ex.LunchBreakEnd + OpeningAuctionStart = $ex.OpeningAuctionStart + ClosingAuctionStart = $ex.ClosingAuctionStart Latitude = $ex.Latitude Longitude = $ex.Longitude IsActive = $isActive @@ -2645,6 +2585,8 @@ public static class CredManager { $exObj = [PSCustomObject]@{ TimeZoneId = $row.TimeZoneId; OpenTimeLocal = $row.OpenTime; CloseTimeLocal = $row.CloseTime LunchBreakStart = $row.LunchBreakStart; LunchBreakEnd = $row.LunchBreakEnd; Code = $row.Code + OpeningAuctionStart = $row.OpeningAuctionStart + ClosingAuctionStart = $row.ClosingAuctionStart } $si = Get-ExchangeStatus -Exchange $exObj $rank = $priority.IndexOf($si.Status) @@ -4266,6 +4208,8 @@ public static class CredManager { CloseTimeLocal = $row.CloseTime LunchBreakStart = $row.LunchBreakStart LunchBreakEnd = $row.LunchBreakEnd + OpeningAuctionStart = $row.OpeningAuctionStart + ClosingAuctionStart = $row.ClosingAuctionStart Code = $row.Code } $statusInfo = Get-ExchangeStatus -Exchange $exObj @@ -4320,6 +4264,12 @@ public static class CredManager { Add-FlyoutRow -Label 'Countdown' -Value $row.CountdownText -ValueColor $statusColor Add-FlyoutRow -Label 'Local Time' -Value $row.CurrentLocalTime Add-FlyoutRow -Label 'Hours' -Value "$($row.OpenTime) – $($row.CloseTime)" + if ($row.OpeningAuctionStart) { + Add-FlyoutRow -Label 'Opening Auction' -Value "$($row.OpeningAuctionStart) – $($row.OpenTime)" + } + if ($row.ClosingAuctionStart) { + Add-FlyoutRow -Label 'Closing Auction' -Value "$($row.ClosingAuctionStart) – $($row.CloseTime) (no continuous trading)" + } Add-FlyoutRow -Label 'Location' -Value "$($row.City), $($row.Country)" # Divider @@ -4571,6 +4521,8 @@ public static class CredManager { CloseTimeLocal = $row.CloseTime LunchBreakStart = $row.LunchBreakStart LunchBreakEnd = $row.LunchBreakEnd + OpeningAuctionStart = $row.OpeningAuctionStart + ClosingAuctionStart = $row.ClosingAuctionStart Code = $row.Code } @@ -4582,7 +4534,7 @@ public static class CredManager { $row.StatusColor = $color if ($statusInfo.TimeRemaining) { - $row.CountdownText = "{0:D2}:{1:D2}:{2:D2}" -f [int]$statusInfo.TimeRemaining.TotalHours, $statusInfo.TimeRemaining.Minutes, $statusInfo.TimeRemaining.Seconds + $row.CountdownText = Format-CountdownSpan -TimeSpan $statusInfo.TimeRemaining } else { $row.CountdownText = '--:--:--' @@ -4648,7 +4600,7 @@ public static class CredManager { # Update status bar if ($nextCloseExchange -and $nextCloseRemaining) { - $ncs = "{0:D2}:{1:D2}:{2:D2}" -f [int]$nextCloseRemaining.TotalHours, $nextCloseRemaining.Minutes, $nextCloseRemaining.Seconds + $ncs = Format-CountdownSpan -TimeSpan $nextCloseRemaining $txtNextClose.Text = "Next close: $nextCloseExchange in $ncs" $window.Title = "PSExchangeClock — Next: $nextCloseExchange $ncs" } diff --git a/PSExchangeClock/en-US/about_PSExchangeClock.help.txt b/PSExchangeClock/en-US/about_PSExchangeClock.help.txt index e364c12..f9d0159 100644 --- a/PSExchangeClock/en-US/about_PSExchangeClock.help.txt +++ b/PSExchangeClock/en-US/about_PSExchangeClock.help.txt @@ -12,9 +12,10 @@ LONG DESCRIPTION The dashboard provides: - * Live countdown timers with color-coded status for 20 major stock + * Live countdown timers with color-coded status for 21 major stock exchanges worldwide (NYSE, NASDAQ, LSE, Tokyo, Shanghai, Hong Kong, - Frankfurt, Euronext Paris, Toronto, Sydney, and more) + Frankfurt, Euronext Paris, Toronto, Sydney, Nasdaq Copenhagen, and + more) * An interactive world map with clickable exchange markers and flyout detail panels (supports NASA Earth at Night satellite imagery or @@ -93,6 +94,11 @@ CONFIGURATION the module's Data directory. Each exchange code (e.g., XNYS, XLON) maps to an array of ISO 8601 date strings (YYYY-MM-DD). + Nasdaq Copenhagen (XCSE) ships with the official Nasdaq closure dates for + 2025-2027. Other exchanges ship with empty lists. Dates after the last + listed year are not known to the module: on those days the exchange is + treated as open on any weekday until the file is updated. + SEE ALSO New-StockExchangeCountdownDashboard Get-StockExchangeData diff --git a/README.md b/README.md index 7ae594c..1448f02 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ A real-time WPF dashboard for monitoring global stock exchange closing times, li ## Features -- **Live countdown timers** with color-coded status (green → yellow → red) for 20 major stock exchanges worldwide +- **Live countdown timers** with color-coded status (green → yellow → red) for 21 major stock exchanges worldwide - **Interactive world map** with clickable exchange markers — NASA Earth at Night satellite imagery or vector continent outlines, flat and globe projections, zoom & pan - **Map overlays** toggled from the toolbar: - *Geo* — day/night terminator, timezone bands, political borders, timezone boundaries @@ -89,7 +89,7 @@ User preferences are stored in `%APPDATA%\PSExchangeClock\user-preferences.json` | Setting | Description | Default | |---------|-------------|---------| -| `ActiveExchanges` | Array of exchange codes to display | All 20 exchanges | +| `ActiveExchanges` | Array of exchange codes to display | Seeded from `user-preferences.example.json` (`XNYS`, `XNAS`, `XLON`) | | `NotifyThresholds` | Minutes before close to show notifications | `[30, 15, 5]` | | `AlwaysOnTop` | Keep dashboard window above other windows | `false` | | `MapStyle` | World map style: `NightSatellite`, `BlueMarble`, `VectorDark` or `Minimal` | `NightSatellite` | @@ -133,6 +133,32 @@ Edit the `holidays.json` file in the module's `Data` directory to add market hol | SGX | Singapore Exchange | Singapore | SGT | | TWSE | Taiwan Stock Exchange | Taipei | CST | | MOEX | Moscow Exchange | Moscow | MSK | +| OMXC | Nasdaq Copenhagen (Nasdaq København) | Copenhagen | CET/CEST | + +### Nasdaq Copenhagen + +| Property | Value | +|----------|-------| +| Code (MIC) | `XCSE` | +| Timezone | `Romance Standard Time` (Windows ID; IANA `Europe/Copenhagen`) — DST from the OS timezone database, no fixed offset | +| Main-market equities | 09:00–17:00 Copenhagen time | +| Opening auction | 08:45–09:00 — random uncross 09:00:00–09:00:05 | +| Continuous trading | 09:00–16:55 | +| Closing auction (closing call) | 16:55–17:00 — no continuous matching; random uncross 16:59:30–17:00 | +| Currency | DKK | +| Default active | No — enable it in the exchange grid; existing saved selections are left unchanged | + +Sources: [Nasdaq European Markets Trading Hours and Holiday Schedule](https://www.nasdaq.com/european-market-activity/trading-hours) and the [Nasdaq INET Nordic Auctions factsheet](https://www.nasdaq.com/INETNordicAuctionsFactsheet) (1015-26). + +During the auctions the status reads *Opening auction - opens in …* (08:45–09:00) and *Closing auction - ends in …* (16:55–17:00) rather than *Opens in …* / *Closes in …*, and the exchange flyout shows both auction windows. The status colours stay as they were (PreMarket blue; closing red), so notifications are unchanged. The random uncross means continuous trading can start up to five seconds after 09:00; the dashboard switches to *Open* at exactly 09:00. Extended and after-hours sessions for other instrument types (ETFs, warrants, certificates, fixed income) are not modelled. + +**Holidays.** `holidays.json` includes the official Nasdaq Copenhagen equity closures for 2025, 2026 and 2027 (checked 2026-10-09). Exchange closures are not the same as Danish public holidays: Christmas Eve (24 Dec) and New Year's Eve (31 Dec) are exchange closures, and Nasdaq lists no half trading days for Copenhagen in those years. Limitations: + +- Dates after 2027 are not yet published by Nasdaq. Until `holidays.json` is updated, weekdays in later years are treated as trading days. +- If `holidays.json` is missing or unreadable, a warning is written and every exchange falls back to weekday/session-hours logic only. There is no online holiday refresh. +- Unscheduled closures and any future early closes are not known in advance; add them to `holidays.json` by hand. Early closes cannot be expressed in `holidays.json` (it only marks whole-day closures). + +Existing installs: `Get-StockExchangeData` appends any built-in exchange missing from a cache younger than 30 days, so Nasdaq Copenhagen appears without `-ForceRefresh`. Cached entries are not overwritten. ## Data Sources @@ -154,7 +180,7 @@ Edit the `holidays.json` file in the module's `Data` directory to add market hol ## Refreshing Exchange Data -The module includes hardcoded fallback data for all 20 exchanges. To pull the latest trading hours from Wikipedia: +The module includes hardcoded fallback data for all 21 exchanges. To pull the latest trading hours from Wikipedia: ```powershell Get-StockExchangeData -ForceRefresh diff --git a/Tests/PSExchangeClock.Tests.ps1 b/Tests/PSExchangeClock.Tests.ps1 new file mode 100644 index 0000000..4656b31 --- /dev/null +++ b/Tests/PSExchangeClock.Tests.ps1 @@ -0,0 +1,350 @@ +#requires -Version 7.0 +#requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Deterministic tests: every status is evaluated at a fixed UTC instant and all +# network calls are mocked. Run with: Invoke-Pester -Path ./Tests + +BeforeAll { + $script:moduleRoot = Join-Path (Split-Path $PSScriptRoot -Parent) 'PSExchangeClock' + $script:dataDir = Join-Path $script:moduleRoot 'Data' + + . (Join-Path $script:moduleRoot 'Private/Get-ExchangeSessionStatus.ps1') + Import-Module (Join-Path $script:moduleRoot 'PSExchangeClock.psd1') -Force + + # Load holidays exactly as the dashboard does + $script:holidays = @{} + $holidayJson = Get-Content (Join-Path $script:dataDir 'holidays.json') -Raw | ConvertFrom-Json + foreach ($prop in $holidayJson.PSObject.Properties) { + $script:holidays[$prop.Name] = @($prop.Value) + } + + # Built-in exchange list via the offline path (Wikipedia scrape mocked to fail) + Mock -ModuleName PSExchangeClock Invoke-WebRequest { throw 'offline' } + $script:allExchanges = @(Get-StockExchangeData -ForceRefresh -OutputPath (Join-Path $TestDrive 'exchange-data.json') -WarningAction SilentlyContinue) + $script:xcse = $script:allExchanges | Where-Object { $_.Code -eq 'XCSE' } + + function Get-Utc([string]$Iso) { + [DateTime]::SpecifyKind([DateTime]::ParseExact($Iso, 'yyyy-MM-ddTHH:mm:ss', [cultureinfo]::InvariantCulture), [DateTimeKind]::Utc) + } + function Get-XcseStatus([string]$UtcIso, [hashtable]$Holidays = $script:holidays) { + Get-ExchangeSessionStatus -Exchange $script:xcse -UtcNow (Get-Utc $UtcIso) -Holidays $Holidays + } +} + +Describe 'Nasdaq Copenhagen exchange definition' { + It 'is a built-in exchange with the expected attributes' { + $script:xcse | Should -Not -BeNullOrEmpty + $script:xcse.Name | Should -Be 'Nasdaq Copenhagen' + $script:xcse.Country | Should -Be 'Denmark' + $script:xcse.City | Should -Be 'Copenhagen' + $script:xcse.TimeZoneId | Should -Be 'Romance Standard Time' + $script:xcse.OpenTimeLocal | Should -Be '09:00' + $script:xcse.CloseTimeLocal | Should -Be '17:00' + $script:xcse.OpeningAuctionStart | Should -Be '08:45' + $script:xcse.ClosingAuctionStart | Should -Be '16:55' + $script:xcse.Latitude | Should -Be 55.6761 + $script:xcse.Longitude | Should -Be 12.5683 + $script:xcse.IsDefault | Should -BeFalse + } + + It 'uses a Windows timezone ID that maps to IANA Europe/Copenhagen' { + $windowsId = $null + [System.TimeZoneInfo]::TryConvertIanaIdToWindowsId('Europe/Copenhagen', [ref]$windowsId) | Should -BeTrue + $windowsId | Should -Be $script:xcse.TimeZoneId + } + + It 'keeps all 20 previously supported exchanges' { + $expected = 'XNYS', 'XNAS', 'XLON', 'XPAR', 'XTKS', 'XSHG', 'XHKG', 'XTSE', 'XETR', 'XASX', + 'XBOM', 'XNSE', 'XKRX', 'XSWX', 'XJSE', 'BVMF', 'XMEX', 'XSES', 'XTAI', 'XMOS' + foreach ($code in $expected) { + $script:allExchanges.Code | Should -Contain $code + } + $script:allExchanges.Count | Should -Be 21 + } + + It 'has exchange details for the flyout, in DKK and linked to OMXC25' { + $details = Get-Content (Join-Path $script:dataDir 'exchange-details.json') -Raw | ConvertFrom-Json + $details.XCSE | Should -Not -BeNullOrEmpty + $details.XCSE.Currency | Should -Be 'DKK' + $details.XCSE.PrimaryIndex | Should -Match 'OMXC25' + } + + It 'is present in the shipped exchange-data.json fallback' { + $shipped = Get-Content (Join-Path $script:dataDir 'exchange-data.json') -Raw | ConvertFrom-Json + ($shipped.Exchanges | Where-Object { $_.Code -eq 'XCSE' }).TimeZoneId | Should -Be 'Romance Standard Time' + } +} + +Describe 'Nasdaq Copenhagen session status' { + # 2026-10-08 is a Thursday; Copenhagen is on CEST (UTC+2) + Context 'Normal trading day' { + It 'is PreMarket before 09:00 with a countdown to the open' { + $s = Get-XcseStatus '2026-10-08T06:30:00' # 08:30 local + $s.Status | Should -Be 'PreMarket' + $s.Text | Should -Be 'Opens in 00:30:00' + $s.CountdownTarget | Should -Be 'Open' + } + + It 'reports the opening auction, not pre-market, from 08:45' { + (Get-XcseStatus '2026-10-08T06:44:59').Text | Should -Be 'Opens in 00:15:01' + $s = Get-XcseStatus '2026-10-08T06:45:00' # 08:45 local + $s.Status | Should -Be 'PreMarket' + $s.Text | Should -Be 'Opening auction - opens in 00:15:00' + (Get-XcseStatus '2026-10-08T06:59:59').Text | Should -Be 'Opening auction - opens in 00:00:01' + (Get-XcseStatus '2026-10-08T07:00:00').Status | Should -Be 'Open' + } + + It 'counts down more than an hour without rounding the hours up' { + $s = Get-XcseStatus '2026-10-08T00:24:00' # 02:24 local, 6h36m to open + $s.Text | Should -Be 'Opens in 06:36:00' + } + + It 'is Open during continuous trading' { + $s = Get-XcseStatus '2026-10-08T10:00:00' # 12:00 local + $s.Status | Should -Be 'Open' + $s.Text | Should -Be 'Closes in 05:00:00' + $s.CountdownTarget | Should -Be 'Close' + } + + It 'is ClosingSoon within 30 minutes of the close' { + $s = Get-XcseStatus '2026-10-08T14:40:00' # 16:40 local + $s.Status | Should -Be 'ClosingSoon' + $s.Text | Should -Be 'Closes in 00:20:00' + } + + It 'reports continuous trading one second before the closing auction' { + $s = Get-XcseStatus '2026-10-08T14:54:59' # 16:54:59 local + $s.Text | Should -Be 'Closes in 00:05:01' + } + + It 'reports the closing auction, not continuous trading, from 16:55' { + $s = Get-XcseStatus '2026-10-08T14:55:00' # 16:55 local + $s.Status | Should -Be 'ClosingImminent' + $s.Text | Should -Be 'Closing auction - ends in 00:05:00' + $s = Get-XcseStatus '2026-10-08T14:57:30' # 16:57:30 local + $s.Text | Should -Be 'Closing auction - ends in 00:02:30' + } + + It 'is Closed at and after 17:00' { + (Get-XcseStatus '2026-10-08T15:00:00').Status | Should -Be 'Closed' + $s = Get-XcseStatus '2026-10-08T19:00:00' + $s.Status | Should -Be 'Closed' + $s.TimeRemaining | Should -BeNullOrEmpty + $s.CountdownTarget | Should -BeNullOrEmpty + } + } + + Context 'Weekends' { + It 'is closed on Saturday' { + $s = Get-XcseStatus '2026-10-10T10:00:00' + $s.Status | Should -Be 'Closed' + $s.Text | Should -Be 'Weekend' + } + + It 'is closed on Sunday' { + (Get-XcseStatus '2026-10-11T10:00:00').Text | Should -Be 'Weekend' + } + } + + Context 'Exchange holidays (official Nasdaq schedule)' { + It 'ships the official 2025-2027 Copenhagen closures' { + $expected = @( + '2025-01-01', '2025-04-17', '2025-04-18', '2025-04-21', '2025-05-29', '2025-05-30', + '2025-06-05', '2025-06-09', '2025-12-24', '2025-12-25', '2025-12-26', '2025-12-31', + '2026-01-01', '2026-04-02', '2026-04-03', '2026-04-06', '2026-05-14', '2026-05-15', + '2026-05-25', '2026-06-05', '2026-12-24', '2026-12-25', '2026-12-31', + '2027-01-01', '2027-03-25', '2027-03-26', '2027-03-29', '2027-05-06', '2027-05-07', + '2027-05-17', '2027-12-24', '2027-12-31' + ) + $script:holidays['XCSE'] | Should -Be $expected + } + + It 'lists only weekdays' { + foreach ($d in $script:holidays['XCSE']) { + ([datetime]::ParseExact($d, 'yyyy-MM-dd', [cultureinfo]::InvariantCulture)).DayOfWeek | Should -BeIn @('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday') + } + } + + It 'is a Holiday on Christmas Eve (an exchange closure, not a Danish public holiday)' { + $s = Get-XcseStatus '2026-12-24T10:00:00' # Thursday, CET + $s.Status | Should -Be 'Holiday' + $s.TimeRemaining | Should -BeNullOrEmpty + } + + It 'is a Holiday on Constitution Day' { + (Get-XcseStatus '2026-06-05T10:00:00').Status | Should -Be 'Holiday' + } + + It 'is a Holiday on the day after Ascension' { + (Get-XcseStatus '2026-05-15T10:00:00').Status | Should -Be 'Holiday' + } + + It 'trades normally on the next listed trading day' { + (Get-XcseStatus '2026-12-28T10:00:00').Status | Should -Be 'Open' # Monday, 11:00 CET + } + + It 'does not apply another exchange''s holidays to Copenhagen' { + # 2026-01-06 is a Stockholm/Helsinki closure but not a Copenhagen one + (Get-XcseStatus '2026-01-06T10:00:00').Status | Should -Be 'Open' + } + } + + Context 'CET/CEST transitions' { + It 'opens at 08:00 UTC on the Friday before CEST starts (CET, UTC+1)' { + (Get-XcseStatus '2026-03-27T07:30:00').Text | Should -Be 'Opens in 00:30:00' + (Get-XcseStatus '2026-03-27T08:00:00').Status | Should -Be 'Open' + } + + It 'opens at 07:00 UTC on the Monday after CEST starts (UTC+2)' { + (Get-XcseStatus '2026-03-30T06:30:00').Text | Should -Be 'Opens in 00:30:00' + (Get-XcseStatus '2026-03-30T07:00:00').Status | Should -Be 'Open' + (Get-XcseStatus '2026-03-30T07:30:00').Status | Should -Be 'Open' + } + + It 'closes at 15:00 UTC on the Friday before CEST ends' { + (Get-XcseStatus '2026-10-23T15:00:00').Status | Should -Be 'Closed' + (Get-XcseStatus '2026-10-23T14:57:00').Text | Should -Be 'Closing auction - ends in 00:03:00' + } + + It 'closes at 16:00 UTC on the Monday after CEST ends (CET)' { + (Get-XcseStatus '2026-10-26T15:00:00').Text | Should -Be 'Closes in 01:00:00' + (Get-XcseStatus '2026-10-26T15:57:00').Text | Should -Be 'Closing auction - ends in 00:03:00' + (Get-XcseStatus '2026-10-26T16:00:00').Status | Should -Be 'Closed' + } + + It 'treats both 2026 transition Sundays as weekends' { + (Get-XcseStatus '2026-03-29T10:00:00').Text | Should -Be 'Weekend' + (Get-XcseStatus '2026-10-25T10:00:00').Text | Should -Be 'Weekend' + } + + It 'measures countdowns in real elapsed time across a weekday DST change' { + # EU transitions are on Sundays, so use a synthetic exchange in Israel, + # where DST started on Friday 2026-03-27 at 02:00 (UTC+2 -> UTC+3). + $synthetic = [PSCustomObject]@{ + Code = 'TEST'; TimeZoneId = 'Israel Standard Time'; OpenTimeLocal = '09:00'; CloseTimeLocal = '17:00' + } + # 01:00 local (UTC+2) -> 09:00 local (UTC+3) is 7 real hours, not 8 wall-clock hours + $s = Get-ExchangeSessionStatus -Exchange $synthetic -UtcNow (Get-Utc '2026-03-26T23:00:00') + $s.Text | Should -Be 'Opens in 07:00:00' + } + } + + Context 'Computer timezone differs from Copenhagen' { + It 'gives the same result for a UTC instant passed as a local-kind DateTime' { + $utc = Get-Utc '2026-10-08T10:00:00' + $a = Get-ExchangeSessionStatus -Exchange $script:xcse -UtcNow $utc -Holidays $script:holidays + $b = Get-ExchangeSessionStatus -Exchange $script:xcse -UtcNow $utc.ToLocalTime() -Holidays $script:holidays + $b.Text | Should -Be $a.Text + $b.Status | Should -Be $a.Status + } + + It 'is independent of the process timezone (<_>)' -Skip:(-not ($IsLinux -or $IsMacOS)) -ForEach @('America/New_York', 'Asia/Tokyo', 'Pacific/Auckland') { + $privatePath = Join-Path $script:moduleRoot 'Private/Get-ExchangeSessionStatus.ps1' + $cmd = ". '$privatePath'; " + + '$x = [PSCustomObject]@{ Code = ''XCSE''; TimeZoneId = ''Romance Standard Time''; OpenTimeLocal = ''09:00''; CloseTimeLocal = ''17:00''; ClosingAuctionStart = ''16:55'' }; ' + + '$u = [DateTime]::SpecifyKind([DateTime]''2026-10-08T06:30:00'', ''Utc''); ' + + '(Get-ExchangeSessionStatus -Exchange $x -UtcNow $u).Text + ''|'' + (Get-ExchangeSessionStatus -Exchange $x -UtcNow $u.ToLocalTime()).Text + ''|'' + [TimeZoneInfo]::Local.Id' + $oldTz = $env:TZ + try { + $env:TZ = $_ + $out = & (Get-Process -Id $PID).Path -NoProfile -NonInteractive -Command $cmd + } + finally { + $env:TZ = $oldTz + } + $parts = "$out".Trim() -split '\|' + $parts[2] | Should -Be $_ + $parts[0] | Should -Be 'Opens in 00:30:00' + $parts[1] | Should -Be 'Opens in 00:30:00' + } + } + + Context 'Missing or unavailable data' { + It 'falls back to weekday and session-hours logic when holiday data is missing' { + (Get-XcseStatus '2026-12-24T10:00:00' -Holidays @{}).Status | Should -Be 'Open' + (Get-XcseStatus '2026-12-24T10:00:00' -Holidays $null).Status | Should -Be 'Open' + } + + It 'falls back when holiday data has no entry for Copenhagen' { + (Get-XcseStatus '2026-12-24T10:00:00' -Holidays @{ XNYS = @('2026-12-24') }).Status | Should -Be 'Open' + } + + It 'does not throw for an unresolvable timezone ID' { + $broken = [PSCustomObject]@{ Code = 'XCSE'; TimeZoneId = 'No Such Zone'; OpenTimeLocal = '09:00'; CloseTimeLocal = '17:00' } + { Get-ExchangeSessionStatus -Exchange $broken -UtcNow (Get-Utc '2026-10-08T10:00:00') } | Should -Not -Throw + } + + It 'returns no countdown while closed, so notifications are not raised' { + foreach ($t in '2026-10-08T19:00:00', '2026-10-10T10:00:00', '2026-12-24T10:00:00') { + $s = Get-XcseStatus $t + $s.Status | Should -Not -BeIn @('Open', 'ClosingSoon', 'ClosingImminent') + $s.TimeRemaining | Should -BeNullOrEmpty + } + } + } + + Context 'Existing exchanges are unaffected by the closing-auction field' { + It 'keeps the plain countdown text for exchanges without ClosingAuctionStart' { + $xetr = $script:allExchanges | Where-Object { $_.Code -eq 'XETR' } + # 2026-10-08 15:20 UTC = 17:20 CEST, 10 minutes before the 17:30 close + $s = Get-ExchangeSessionStatus -Exchange $xetr -UtcNow (Get-Utc '2026-10-08T15:20:00') + $s.Text | Should -Be 'Closes in 00:10:00' + $s.Status | Should -Be 'ClosingSoon' + } + } +} + +Describe 'Exchange selection and persistence' { + It 'activates Copenhagen when it is in the saved selection (after a JSON round trip)' { + $saved = @{ ActiveExchanges = @('XNYS', 'XCSE') } | ConvertTo-Json -Depth 3 | ConvertFrom-Json + Test-ExchangeActive -Exchange $script:xcse -UserPreferences $saved | Should -BeTrue + } + + It 'handles a saved selection containing only Copenhagen' { + $saved = @{ ActiveExchanges = @('XCSE') } | ConvertTo-Json -Depth 3 | ConvertFrom-Json + Test-ExchangeActive -Exchange $script:xcse -UserPreferences $saved | Should -BeTrue + } + + It 'leaves an existing user selection unchanged (Copenhagen not auto-enabled)' { + $example = Get-Content (Join-Path $script:dataDir 'user-preferences.example.json') -Raw | ConvertFrom-Json + Test-ExchangeActive -Exchange $script:xcse -UserPreferences $example | Should -BeFalse + $xnys = $script:allExchanges | Where-Object { $_.Code -eq 'XNYS' } + Test-ExchangeActive -Exchange $xnys -UserPreferences $example | Should -BeTrue + } + + It 'falls back to IsDefault when no preferences are saved' { + Test-ExchangeActive -Exchange $script:xcse -UserPreferences $null | Should -BeFalse + $xnys = $script:allExchanges | Where-Object { $_.Code -eq 'XNYS' } + Test-ExchangeActive -Exchange $xnys -UserPreferences $null | Should -BeTrue + } +} + +Describe 'Get-StockExchangeData cache handling' { + BeforeAll { + Mock -ModuleName PSExchangeClock Invoke-WebRequest { throw 'offline' } + } + + It 'appends Copenhagen to a fresh cache that predates it, without changing cached entries' { + $path = Join-Path $TestDrive 'old-cache.json' + [PSCustomObject]@{ + LastUpdated = (Get-Date).AddDays(-2).ToString('o') + Source = 'test' + Version = '1.0' + Exchanges = @([PSCustomObject]@{ Name = 'Customised NYSE'; Code = 'XNYS'; TimeZoneId = 'Eastern Standard Time'; OpenTimeLocal = '09:30'; CloseTimeLocal = '15:00' }) + } | ConvertTo-Json -Depth 5 | Set-Content $path + + $result = @(Get-StockExchangeData -OutputPath $path) + ($result | Where-Object { $_.Code -eq 'XNYS' }).Name | Should -Be 'Customised NYSE' + ($result | Where-Object { $_.Code -eq 'XNYS' }).CloseTimeLocal | Should -Be '15:00' + ($result | Where-Object { $_.Code -eq 'XCSE' }).Name | Should -Be 'Nasdaq Copenhagen' + @($result | Where-Object { $_.Code -eq 'XNYS' }).Count | Should -Be 1 + Should -Invoke -ModuleName PSExchangeClock Invoke-WebRequest -Times 0 -Exactly -Scope It + } + + It 'falls back to built-in data, including Copenhagen, when offline with no cache' { + $path = Join-Path $TestDrive 'none.json' + $result = @(Get-StockExchangeData -OutputPath $path -WarningAction SilentlyContinue) + $result.Code | Should -Contain 'XCSE' + Test-Path $path | Should -BeTrue + } +} diff --git a/docs/index.md b/docs/index.md index 0edebcb..a8f453b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -5,7 +5,7 @@ title: PSExchangeClock # PSExchangeClock -**A real-time WPF dashboard for monitoring 20 global stock exchange closing times, live market data, forex, cryptocurrency, commodities, indices, and financial news — built entirely in PowerShell.** +**A real-time WPF dashboard for monitoring 21 global stock exchange closing times, live market data, forex, cryptocurrency, commodities, indices, and financial news — built entirely in PowerShell.** [![PowerShell Gallery Version](https://img.shields.io/powershellgallery/v/PSExchangeClock)](https://www.powershellgallery.com/packages/PSExchangeClock) [![PowerShell Gallery Downloads](https://img.shields.io/powershellgallery/dt/PSExchangeClock)](https://www.powershellgallery.com/packages/PSExchangeClock) @@ -20,7 +20,7 @@ Start-PSExchangeClock ## What it does -- **Live countdown timers** with color-coded status (green → yellow → red → purple for holidays) for 20 major exchanges worldwide +- **Live countdown timers** with color-coded status (green → yellow → red → purple for holidays) for 21 major exchanges worldwide - **Interactive world map** — NASA Earth at Night imagery, flat and globe projections, zoom & pan, clickable exchange markers - **Map overlays** — day/night terminator, timezone bands and boundaries, political borders, earthquakes, volcanoes, natural events, conflict zones, submarine cables, and power plants - **Market data sidebar** — catalog-driven financial news with source/category filters and manual refresh, live forex, crypto, indices, commodities, and individual stock quotes From 18ad8296808d9a03ad09be3739b037efe0bed7eb Mon Sep 17 00:00:00 2001 From: knightmare2600 Date: Fri, 9 Oct 2026 23:01:03 +0100 Subject: [PATCH 3/4] feat: add OMX Copenhagen 25 (OMXC25) to the Indices tab, off by default Adds OMXC25 as a true index (not an ETF proxy) on the existing Indices tab, associated with Nasdaq Copenhagen (XCSE), Denmark, DKK. Provider and plan - Twelve Data /quote, symbol OMXC25. Twelve Data's /indices catalogue lists it as "OMX Copenhagen 25 Index" (DKK) with access level "Pro", so free/Basic keys get HTTP 403. The index is therefore turned off by default: the row is shown greyed out with a note explaining why, and no request is made. Enable it by adding "EnabledIndices": ["OMXC25"] to user-preferences.json (new optional preference, carried through Save-UserPreferences; no Settings UI yet). When enabled - Fetched in its own request with its own 15-minute cache, so a plan restriction or failure never affects the existing ETF batch. - HTTP 403/404 stop further requests for that key for the session (no wasted credits); 429/network errors retry after the TTL and keep showing the last good quote. - Status line: Intraday (may be delayed) / Last close / Stale / Unavailable, judged against the dashboard's own Nasdaq Copenhagen hours and holidays rather than Twelve Data's is_market_open (which files OMXC25 under Stockholm, XSTO). Stale values are greyed out. Twelve Data does not state whether quotes are real-time, so nothing is labelled "live". Quote time is shown in Copenhagen time. Code - Private/IndexQuotes.ps1: index definitions (the eight ETF proxies moved here unchanged), Test-IndexEnabled, Twelve Data quote parsing, per-index cache with back-off, and quote-status classification. - README: OMXC25 section with enabling and troubleshooting steps. - Pester tests: registration, opt-in, parsing, mocked retrieval, network failure, cache/TTL/back-off and quote status. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + PSExchangeClock/Private/IndexQuotes.ps1 | 304 ++++++++++++++++++ .../New-StockExchangeCountdownDashboard.ps1 | 242 +++++++++++--- .../en-US/about_PSExchangeClock.help.txt | 6 +- README.md | 48 ++- Tests/PSExchangeClock.Tests.ps1 | 232 +++++++++++++ 6 files changed, 781 insertions(+), 55 deletions(-) create mode 100644 PSExchangeClock/Private/IndexQuotes.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index d9e3837..c6e8676 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,8 +12,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Nasdaq Copenhagen (`XCSE`)** — main-market equities 09:00–17:00 Copenhagen time (`Romance Standard Time`), with the 08:45–09:00 opening auction and 16:55–17:00 closing auction shown as auctions rather than pre-market or continuous trading; map marker, flyout details and world clock via the existing mechanisms; not active by default - Official Nasdaq Copenhagen closures for 2025–2027 in `holidays.json` - Optional `OpeningAuctionStart` and `ClosingAuctionStart` fields on exchange records +- **OMX Copenhagen 25 (`OMXC25`)** on the Indices tab via Twelve Data symbol `OMXC25`. It needs a Twelve Data Pro plan, so it is **turned off by default** and shown with a note saying why; enable it with the new optional `EnabledIndices` preference. When enabled it is fetched separately from the ETF batch, with Intraday / Last close / Stale / Unavailable status, quote time in Copenhagen time, and a session-long back-off after HTTP 403/404 +- Optional `EnabledIndices` user preference, carried through preference saves - Pester tests under `Tests/` (run with `Invoke-Pester ./Tests`), starting with map preference restore - Tests for Nasdaq Copenhagen session status, auctions, holidays, DST transitions, selection and exchange-data caching +- Tests for OMXC25 registration, opt-in, quote parsing, caching/back-off and quote status ### Fixed @@ -25,6 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `PSExchangeClock.psm1` also loads non-exported helpers from `Private/` - Exchange status and selection logic moved to `Private/` helpers so it can be tested without WPF +- Index-quote logic lives in `Private/IndexQuotes.ps1`; the ETF proxy list moved there unchanged ## [1.1.0] - 2026-09-28 diff --git a/PSExchangeClock/Private/IndexQuotes.ps1 b/PSExchangeClock/Private/IndexQuotes.ps1 new file mode 100644 index 0000000..1b96e92 --- /dev/null +++ b/PSExchangeClock/Private/IndexQuotes.ps1 @@ -0,0 +1,304 @@ +function Get-IndexDefinition { + <# + .SYNOPSIS + Returns the indices shown on the dashboard's Indices tab. + .DESCRIPTION + EtfProxy entries are US-listed ETFs on the Twelve Data free (Basic) tier, + fetched together in one batched request. Index entries are true index + symbols fetched individually, so a plan restriction on one index cannot + affect the ETF batch. + + OMXC25: Twelve Data lists symbol 'OMXC25' ("OMX Copenhagen 25 Index", DKK) + in its /indices catalogue with access level 'Pro' - a Basic key receives + HTTP 403 (upgrade required). It is therefore off by default + (EnabledByDefault = $false) and is only requested when the user lists it + in EnabledIndices in user-preferences.json. + #> + [CmdletBinding()] + [OutputType([PSCustomObject[]])] + param() + + $etfs = @( + @{ Symbol = 'SPY'; Name = 'S&P 500 (SPY)' }, + @{ Symbol = 'QQQ'; Name = 'NASDAQ 100 (QQQ)' }, + @{ Symbol = 'DIA'; Name = 'Dow Jones (DIA)' }, + @{ Symbol = 'EWU'; Name = 'FTSE 100 (EWU)' }, + @{ Symbol = 'EWG'; Name = 'DAX (EWG)' }, + @{ Symbol = 'EWJ'; Name = 'Nikkei 225 (EWJ)' }, + @{ Symbol = 'FXI'; Name = 'China Large-Cap (FXI)' }, + @{ Symbol = 'INDA'; Name = 'India (INDA)' } + ) + + foreach ($etf in $etfs) { + [PSCustomObject]@{ + Symbol = $etf.Symbol + Name = $etf.Name + Kind = 'EtfProxy' + Provider = 'TwelveData' + ExchangeCode = $null + Country = $null + Currency = 'USD' + EnabledByDefault = $true + DisabledReason = $null + } + } + + [PSCustomObject]@{ + Symbol = 'OMXC25' + Name = 'OMX Copenhagen 25 (OMXC25)' + Kind = 'Index' + Provider = 'TwelveData' + ExchangeCode = 'XCSE' + Country = 'Denmark' + Currency = 'DKK' + EnabledByDefault = $false + DisabledReason = 'Turned off: needs a Twelve Data Pro plan or higher (free/Basic keys get HTTP 403). To enable, add "EnabledIndices": ["OMXC25"] to user-preferences.json.' + } +} + +function Test-IndexEnabled { + <# + .SYNOPSIS + Decides whether an index is fetched and shown, from user preferences. + .DESCRIPTION + An index listed in the EnabledIndices preference is enabled; otherwise + its EnabledByDefault flag applies. Existing preference files without + EnabledIndices keep the defaults. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)][PSCustomObject]$Definition, + $UserPreferences + ) + + if ($UserPreferences -and $UserPreferences.EnabledIndices -and (@($UserPreferences.EnabledIndices) -contains $Definition.Symbol)) { + return $true + } + return [bool]$Definition.EnabledByDefault +} + +function ConvertFrom-TwelveDataQuote { + <# + .SYNOPSIS + Normalises a Twelve Data /quote response (success or error) into a quote object. + .DESCRIPTION + Error responses carry 'code' and 'message'. Codes 403 (plan upgrade + required) and 404 (symbol not found) are permanent for a given key and + symbol; anything else (429 rate limit, 5xx) is transient. + QuoteTimeUtc comes from last_quote_at (last minute candle) when present, + otherwise from timestamp (opening of the daily bar). + #> + [CmdletBinding()] + [OutputType([PSCustomObject])] + param( + [Parameter(Mandatory)][AllowNull()]$Response, + [string]$Symbol + ) + + $unavailable = { + param($Code, [string]$Message) + [PSCustomObject]@{ + Symbol = $Symbol + IsAvailable = $false + Price = $null + Change = $null + QuoteTimeUtc = $null + ErrorCode = $Code + ErrorMessage = $Message + IsPermanentError = ($Code -in @(403, 404)) + } + } + + if ($null -eq $Response) { + return & $unavailable $null 'Empty response from provider' + } + if ($Response.code -or $Response.status -eq 'error') { + return & $unavailable ([int]$Response.code) "$($Response.message)" + } + + $price = 0.0 + if (-not $Response.close -or -not [double]::TryParse("$($Response.close)", [System.Globalization.NumberStyles]::Float, [cultureinfo]::InvariantCulture, [ref]$price)) { + return & $unavailable $null 'Quote contained no price' + } + + $change = 0 + $prev = 0.0 + if ($Response.previous_close -and [double]::TryParse("$($Response.previous_close)", [System.Globalization.NumberStyles]::Float, [cultureinfo]::InvariantCulture, [ref]$prev) -and $prev -ne 0) { + $change = [math]::Round((($price - $prev) / $prev) * 100, 2) + } + + $quoteTime = $null + $epoch = if ($Response.last_quote_at) { $Response.last_quote_at } else { $Response.timestamp } + if ($epoch) { + $quoteTime = [DateTimeOffset]::FromUnixTimeSeconds([long]$epoch).UtcDateTime + } + + [PSCustomObject]@{ + Symbol = $Symbol + IsAvailable = $true + Price = [math]::Round($price, 2) + Change = $change + QuoteTimeUtc = $quoteTime + ErrorCode = $null + ErrorMessage = $null + IsPermanentError = $false + } +} + +function Get-TwelveDataIndexQuote { + <# + .SYNOPSIS + Fetches a single symbol from the Twelve Data /quote endpoint. + .DESCRIPTION + Never throws: network failures and HTTP errors are returned as an + unavailable quote object so callers can fall back to cached data. + #> + [CmdletBinding()] + [OutputType([PSCustomObject])] + param( + [Parameter(Mandatory)][string]$Symbol, + [Parameter(Mandatory)][string]$ApiKey, + [int]$TimeoutSec = 15 + ) + + $url = "https://api.twelvedata.com/quote?symbol=$([uri]::EscapeDataString($Symbol))&apikey=$([uri]::EscapeDataString($ApiKey))" + try { + $response = Invoke-RestMethod -Uri $url -TimeoutSec $TimeoutSec -ErrorAction Stop + } + catch { + $code = $null + if ($_.Exception.Response) { + try { $code = [int]$_.Exception.Response.StatusCode } + catch { Write-Verbose "No HTTP status code on error response: $($_.Exception.Message)" } + } + if ($_.ErrorDetails -and $_.ErrorDetails.Message) { + try { + $body = $_.ErrorDetails.Message | ConvertFrom-Json -ErrorAction Stop + if ($body.code) { return ConvertFrom-TwelveDataQuote -Response $body -Symbol $Symbol } + } + catch { Write-Verbose "Error body for $Symbol was not JSON: $($_.Exception.Message)" } + } + Write-Verbose "Twelve Data quote for $Symbol failed: $($_.Exception.Message)" + return [PSCustomObject]@{ + Symbol = $Symbol + IsAvailable = $false + Price = $null + Change = $null + QuoteTimeUtc = $null + ErrorCode = $code + ErrorMessage = $_.Exception.Message + IsPermanentError = ($code -in @(403, 404)) + } + } + + ConvertFrom-TwelveDataQuote -Response $response -Symbol $Symbol +} + +function Get-CachedIndexQuote { + <# + .SYNOPSIS + Refreshes one index quote through a session cache with fallback. + .DESCRIPTION + - Within TtlMinutes of the last attempt, the cached entry is returned unchanged. + - A successful fetch replaces LastGood. + - A failed fetch keeps the previous LastGood (shown as stale or last close) + and records LastError. + - A permanent error (403/404) blocks further requests for that symbol and + API key for the rest of the session, so a Basic-plan key does not spend + a request credit on OMXC25 every refresh. + .OUTPUTS + The cache entry hashtable: LastGood, LastFetchUtc, LastAttemptUtc, + LastError, ErrorCode, Blocked. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)][PSCustomObject]$Definition, + [Parameter(Mandatory)][string]$ApiKey, + [Parameter(Mandatory)][hashtable]$Cache, + [datetime]$NowUtc = [DateTime]::UtcNow, + [int]$TtlMinutes = 15 + ) + + # Keyed per API key so entering a different key in Settings retries a blocked symbol + $key = "$($Definition.Symbol)|$($ApiKey.GetHashCode())" + if (-not $Cache.ContainsKey($key)) { + $Cache[$key] = @{ + LastGood = $null + LastFetchUtc = $null + LastAttemptUtc = $null + LastError = $null + ErrorCode = $null + Blocked = $false + } + } + $entry = $Cache[$key] + + if ($entry.Blocked) { return $entry } + if ($entry.LastAttemptUtc -and ($NowUtc - $entry.LastAttemptUtc).TotalMinutes -lt $TtlMinutes) { return $entry } + + $entry.LastAttemptUtc = $NowUtc + $quote = Get-TwelveDataIndexQuote -Symbol $Definition.Symbol -ApiKey $ApiKey + if ($quote.IsAvailable) { + $entry.LastGood = $quote + $entry.LastFetchUtc = $NowUtc + $entry.LastError = $null + $entry.ErrorCode = $null + } + else { + $entry.LastError = $quote.ErrorMessage + $entry.ErrorCode = $quote.ErrorCode + if ($quote.IsPermanentError) { $entry.Blocked = $true } + } + return $entry +} + +function Get-IndexQuoteStatus { + <# + .SYNOPSIS + Classifies an index quote as Intraday, Stale, LastClose or Unavailable. + .DESCRIPTION + Uses the dashboard's own status for the index's home exchange (hours, + weekends, holidays.json) rather than the provider's is_market_open flag, + because Twelve Data catalogues OMXC25 under the Stockholm MIC (XSTO), + whose hours and holidays differ from Copenhagen's. + + - Unavailable: no quote at all. + - Intraday: market in session and quote no older than StaleAfterMinutes. + Twelve Data does not report whether a quote is real-time or delayed, so + intraday values are never labelled "live". + - Stale: market in session but quote older than StaleAfterMinutes, or + market closed and quote older than LastCloseMaxAgeDays. + - LastClose: market not in session and quote recent enough to be the + latest session's close. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param( + $QuoteTimeUtc, + [Parameter(Mandatory)][string]$MarketStatus, + [datetime]$NowUtc = [DateTime]::UtcNow, + [int]$StaleAfterMinutes = 30, + [int]$LastCloseMaxAgeDays = 7 + ) + + if ($null -eq $QuoteTimeUtc) { + return @{ Status = 'Unavailable'; Label = 'Unavailable' } + } + + $age = $NowUtc - [datetime]$QuoteTimeUtc + $inSession = $MarketStatus -in @('Open', 'ClosingSoon', 'ClosingImminent') + + if ($inSession) { + if ($age.TotalMinutes -le $StaleAfterMinutes) { + return @{ Status = 'Intraday'; Label = 'Intraday (may be delayed)' } + } + return @{ Status = 'Stale'; Label = 'Stale' } + } + + if ($age.TotalDays -le $LastCloseMaxAgeDays) { + return @{ Status = 'LastClose'; Label = 'Last close' } + } + return @{ Status = 'Stale'; Label = 'Stale' } +} diff --git a/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 b/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 index 6fe66da..3e18383 100644 --- a/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 +++ b/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 @@ -150,6 +150,10 @@ function New-StockExchangeCountdownDashboard { } } catch { } + # No UI for EnabledIndices yet: carry the hand-edited value through each save + if ($script:userPrefs -and $script:userPrefs.EnabledIndices) { + $prefs.EnabledIndices = @($script:userPrefs.EnabledIndices) + } # API keys are stored via the secrets backend, not in JSON $prefs | ConvertTo-Json -Depth 3 | Set-Content -Path $prefsPath -Encoding UTF8 } @@ -987,6 +991,7 @@ public static class CredManager { $script:fxCache = @{ Data = $null; LastFetch = [datetime]::MinValue } $script:cryptoCache = @{ Data = $null; LastFetch = [datetime]::MinValue } $script:indicesCache = @{ Data = $null; LastFetch = [datetime]::MinValue } + $script:indexQuoteCache = @{} $script:commoditiesCache = @{ Data = $null; LastFetch = [datetime]::MinValue } $script:stockQuoteCache = @{} @@ -1225,64 +1230,82 @@ public static class CredManager { param([string]$ApiKey) if ([string]::IsNullOrWhiteSpace($ApiKey)) { return $null } + $definitions = @(Get-IndexDefinition) + # Check cache (15 minute TTL) if ($script:indicesCache.Data -and ([datetime]::Now - $script:indicesCache.LastFetch).TotalMinutes -lt 15) { - return $script:indicesCache.Data - } - - # Free tier: index symbols (SPX, DJI etc.) require paid plans. - # Use index-tracking ETFs which are available on the free tier. - $indices = @( - @{ Symbol = 'SPY'; Name = 'S&P 500 (SPY)' }, - @{ Symbol = 'QQQ'; Name = 'NASDAQ 100 (QQQ)' }, - @{ Symbol = 'DIA'; Name = 'Dow Jones (DIA)' }, - @{ Symbol = 'EWU'; Name = 'FTSE 100 (EWU)' }, - @{ Symbol = 'EWG'; Name = 'DAX (EWG)' }, - @{ Symbol = 'EWJ'; Name = 'Nikkei 225 (EWJ)' }, - @{ Symbol = 'FXI'; Name = 'China Large-Cap (FXI)' }, - @{ Symbol = 'INDA'; Name = 'India (INDA)' } - ) - - # Fetch in small batches to stay within 8 credits/min free tier limit - $result = @() - $batches = @() - for ($i = 0; $i -lt $indices.Count; $i += 8) { - $batch = $indices[$i..([math]::Min($i + 7, $indices.Count - 1))] - $batches += , @($batch) + $result = @($script:indicesCache.Data) } + else { + # Free tier: index symbols (SPX, DJI etc.) require paid plans. + # Use index-tracking ETFs which are available on the free tier. + $indices = @($definitions | Where-Object { $_.Kind -eq 'EtfProxy' }) - try { - foreach ($batch in $batches) { - $symbolList = ($batch | ForEach-Object { $_.Symbol }) -join ',' - $url = "https://api.twelvedata.com/quote?symbol=$symbolList&apikey=$ApiKey" - $response = Invoke-RestMethod -Uri $url -TimeoutSec 15 - foreach ($idx in $batch) { - # Single symbol returns data directly; multiple returns keyed object - $data = if ($batch.Count -eq 1) { $response } else { $response.($idx.Symbol) } - if ($data -and $data.close -and -not $data.code) { - $change = 0 - if ($data.previous_close -and [double]$data.previous_close -ne 0) { - $change = [math]::Round((([double]$data.close - [double]$data.previous_close) / [double]$data.previous_close) * 100, 2) - } - $result += [PSCustomObject]@{ - Symbol = $idx.Symbol - Name = $idx.Name - Price = [math]::Round([double]$data.close, 2) - Change = $change + # Fetch in small batches to stay within 8 credits/min free tier limit + $result = @() + $batches = @() + for ($i = 0; $i -lt $indices.Count; $i += 8) { + $batch = $indices[$i..([math]::Min($i + 7, $indices.Count - 1))] + $batches += , @($batch) + } + + try { + foreach ($batch in $batches) { + $symbolList = ($batch | ForEach-Object { $_.Symbol }) -join ',' + $url = "https://api.twelvedata.com/quote?symbol=$symbolList&apikey=$ApiKey" + $response = Invoke-RestMethod -Uri $url -TimeoutSec 15 + foreach ($idx in $batch) { + # Single symbol returns data directly; multiple returns keyed object + $data = if ($batch.Count -eq 1) { $response } else { $response.($idx.Symbol) } + if ($data -and $data.close -and -not $data.code) { + $change = 0 + if ($data.previous_close -and [double]$data.previous_close -ne 0) { + $change = [math]::Round((([double]$data.close - [double]$data.previous_close) / [double]$data.previous_close) * 100, 2) + } + $result += [PSCustomObject]@{ + Symbol = $idx.Symbol + Name = $idx.Name + Price = [math]::Round([double]$data.close, 2) + Change = $change + } } } } + if ($result.Count -gt 0) { + $script:indicesCache.Data = $result + $script:indicesCache.LastFetch = [datetime]::Now + } } - if ($result.Count -gt 0) { - $script:indicesCache.Data = $result - $script:indicesCache.LastFetch = [datetime]::Now + catch { + Write-Verbose "Twelve Data API failed: $($_.Exception.Message)" + $result = @() } - return $result } - catch { - Write-Verbose "Twelve Data API failed: $($_.Exception.Message)" - return $null + + # True index symbols are fetched one at a time with their own cache, so a + # plan restriction (e.g. OMXC25 needs Twelve Data Pro) never affects the ETFs + foreach ($def in @($definitions | Where-Object { $_.Kind -eq 'Index' })) { + if (-not (Test-IndexEnabled -Definition $def -UserPreferences $script:userPrefs)) { + # Turned off (e.g. needs a paid plan): shown with a note, never requested + $result += [PSCustomObject]@{ + Symbol = $def.Symbol; Name = $def.Name; Price = $null; Change = $null + Definition = $def; CacheEntry = $null; Disabled = $true + } + continue + } + $entry = Get-CachedIndexQuote -Definition $def -ApiKey $ApiKey -Cache $script:indexQuoteCache + $result += [PSCustomObject]@{ + Symbol = $def.Symbol + Name = $def.Name + Price = if ($entry.LastGood) { $entry.LastGood.Price } else { $null } + Change = if ($entry.LastGood) { $entry.LastGood.Change } else { $null } + Definition = $def + CacheEntry = $entry + Disabled = $false + } } + + return $result } function Get-CommodityPrices { @@ -1971,17 +1994,19 @@ public static class CredManager { return } - $indices = Get-StockIndices -ApiKey $apiKey - if (-not $indices -or $indices.Count -eq 0) { + $indices = @(Get-StockIndices -ApiKey $apiKey) + $etfRows = @($indices | Where-Object { -not $_.Definition }) + $indexRows = @($indices | Where-Object { $_.Definition }) + if ($etfRows.Count -eq 0) { $lbl = New-Object System.Windows.Controls.TextBlock $lbl.Text = 'Index data unavailable — may be rate-limited (8 req/min free tier). Try again in a minute.' $lbl.Foreground = $Converter.ConvertFromString('#888888'); $lbl.FontSize = 11; $lbl.TextWrapping = 'Wrap' $lbl.Margin = [System.Windows.Thickness]::new(0, 10, 0, 0) $marketDataContent.Children.Add($lbl) | Out-Null - return + if ($indexRows.Count -eq 0) { return } } - foreach ($idx in $indices) { + foreach ($idx in $etfRows) { $changeColor = if ($idx.Change -ge 0) { '#00CC66' } else { '#FF4444' } $arrow = if ($idx.Change -ge 0) { [char]0x25B2 } else { [char]0x25BC } @@ -2017,9 +2042,122 @@ public static class CredManager { $marketDataContent.Children.Add($grid) | Out-Null } + # True indices (e.g. OMXC25) with quote status from their home exchange + foreach ($idx in $indexRows) { + Add-MarketSeparator -Converter $Converter + $def = $idx.Definition + if ($idx.Disabled) { + $lblName = New-Object System.Windows.Controls.TextBlock + $lblName.Text = "$($idx.Name) — $($def.Country)"; $lblName.FontSize = 11 + $lblName.Foreground = $Converter.ConvertFromString('#777777') + $marketDataContent.Children.Add($lblName) | Out-Null + $lblNote = New-Object System.Windows.Controls.TextBlock + $lblNote.Text = $def.DisabledReason + $lblNote.FontSize = 9; $lblNote.TextWrapping = 'Wrap' + $lblNote.Foreground = $Converter.ConvertFromString('#888888') + $lblNote.Margin = [System.Windows.Thickness]::new(0, 0, 0, 4) + $marketDataContent.Children.Add($lblNote) | Out-Null + continue + } + $entry = $idx.CacheEntry + $exRow = $script:exchangeRows | Where-Object { $_.Code -eq $def.ExchangeCode } | Select-Object -First 1 + $marketStatus = 'Closed' + $exName = $def.ExchangeCode + $exTz = $null + if ($exRow) { + $exName = $exRow.DisplayName + $exTz = $exRow.TimeZoneId + $exObj = [PSCustomObject]@{ + TimeZoneId = $exRow.TimeZoneId; OpenTimeLocal = $exRow.OpenTime; CloseTimeLocal = $exRow.CloseTime + LunchBreakStart = $exRow.LunchBreakStart; LunchBreakEnd = $exRow.LunchBreakEnd; Code = $exRow.Code + OpeningAuctionStart = $exRow.OpeningAuctionStart + ClosingAuctionStart = $exRow.ClosingAuctionStart + } + $marketStatus = (Get-ExchangeStatus -Exchange $exObj).Status + } + $quoteTime = if ($entry.LastGood) { $entry.LastGood.QuoteTimeUtc } else { $null } + $hasQuote = [bool]$entry.LastGood + $qs = if ($hasQuote -and -not $quoteTime) { + # Price without a provider timestamp: age cannot be judged, so never show it as current + @{ Status = 'Stale'; Label = 'Quote time unknown' } + } + else { + Get-IndexQuoteStatus -QuoteTimeUtc $quoteTime -MarketStatus $marketStatus + } + + $grid = New-Object System.Windows.Controls.Grid + $c1 = New-Object System.Windows.Controls.ColumnDefinition; $c1.Width = [System.Windows.GridLength]::new(1, [System.Windows.GridUnitType]::Star) + $c2 = New-Object System.Windows.Controls.ColumnDefinition; $c2.Width = [System.Windows.GridLength]::new(0, [System.Windows.GridUnitType]::Auto) + $c3 = New-Object System.Windows.Controls.ColumnDefinition; $c3.Width = [System.Windows.GridLength]::new(0, [System.Windows.GridUnitType]::Auto) + $grid.ColumnDefinitions.Add($c1); $grid.ColumnDefinitions.Add($c2); $grid.ColumnDefinitions.Add($c3) + $grid.Margin = [System.Windows.Thickness]::new(0, 0, 0, 2) + + $lblName = New-Object System.Windows.Controls.TextBlock + $lblName.Text = $idx.Name; $lblName.FontSize = 11 + $lblName.Foreground = $Converter.ConvertFromString('#E0E0E0'); $lblName.VerticalAlignment = 'Center' + [System.Windows.Controls.Grid]::SetColumn($lblName, 0) + $grid.Children.Add($lblName) | Out-Null + + # Stale and unavailable values are greyed out so they are not mistaken for current data + $priceColor = if ($qs.Status -in @('Intraday', 'LastClose')) { '#E0E0E0' } else { '#777777' } + $lblPrice = New-Object System.Windows.Controls.TextBlock + $lblPrice.Text = if ($hasQuote) { "$($def.Currency) $($idx.Price.ToString('N2'))" } else { [string][char]0x2014 } + $lblPrice.FontSize = 11 + $lblPrice.Foreground = $Converter.ConvertFromString($priceColor) + $lblPrice.FontFamily = [System.Windows.Media.FontFamily]::new('Consolas'); $lblPrice.HorizontalAlignment = 'Right' + $lblPrice.VerticalAlignment = 'Center' + [System.Windows.Controls.Grid]::SetColumn($lblPrice, 1) + $grid.Children.Add($lblPrice) | Out-Null + + if ($hasQuote) { + $changeColor = if ($qs.Status -notin @('Intraday', 'LastClose')) { '#777777' } elseif ($idx.Change -ge 0) { '#00CC66' } else { '#FF4444' } + $arrow = if ($idx.Change -ge 0) { [char]0x25B2 } else { [char]0x25BC } + $lblChange = New-Object System.Windows.Controls.TextBlock + $lblChange.Text = " $arrow $($idx.Change)%"; $lblChange.FontSize = 10 + $lblChange.Foreground = $Converter.ConvertFromString($changeColor) + $lblChange.FontFamily = [System.Windows.Media.FontFamily]::new('Consolas') + $lblChange.VerticalAlignment = 'Center'; $lblChange.Margin = [System.Windows.Thickness]::new(6, 0, 0, 0) + [System.Windows.Controls.Grid]::SetColumn($lblChange, 2) + $grid.Children.Add($lblChange) | Out-Null + } + $marketDataContent.Children.Add($grid) | Out-Null + + # Status line: market, quote status, quote time in exchange-local time, last error + $parts = @("$exName, $($def.Country)", $qs.Label) + if ($quoteTime) { + $shown = $quoteTime + $tzLabel = 'UTC' + if ($exTz) { + try { + $tzInfo = [System.TimeZoneInfo]::FindSystemTimeZoneById($exTz) + $shown = [System.TimeZoneInfo]::ConvertTimeFromUtc([DateTime]::SpecifyKind($quoteTime, 'Utc'), $tzInfo) + $tzLabel = "$($exRow.City) time" + } + catch { Write-Verbose "Quote time shown in UTC; timezone $exTz unavailable: $($_.Exception.Message)" } + } + $parts += "as of $($shown.ToString('dd MMM HH:mm')) $tzLabel" + } + if ($entry.Blocked -and $entry.ErrorCode -eq 403) { + $parts += 'Requires a Twelve Data Pro plan or higher (HTTP 403)' + } + elseif ($entry.Blocked) { + $parts += "Not available from provider ($($entry.ErrorCode)): $($entry.LastError)" + } + elseif ($entry.LastError) { + $errCode = if ($entry.ErrorCode) { " ($($entry.ErrorCode))" } else { '' } + $parts += "Last refresh failed$errCode — retrying in 15 min" + } + $lblStatus = New-Object System.Windows.Controls.TextBlock + $lblStatus.Text = $parts -join ' · ' + $lblStatus.FontSize = 9; $lblStatus.TextWrapping = 'Wrap' + $lblStatus.Foreground = $Converter.ConvertFromString('#888888') + $lblStatus.Margin = [System.Windows.Thickness]::new(0, 0, 0, 4) + $marketDataContent.Children.Add($lblStatus) | Out-Null + } + Add-MarketSeparator -Converter $Converter $footer = New-Object System.Windows.Controls.TextBlock - $footer.Text = "Source: Twelve Data (ETF proxies) | Updated: $(Format-RelativeTime -Time $script:indicesCache.LastFetch)" + $footer.Text = "Source: Twelve Data (ETF proxies; OMXC25 index) | Updated: $(Format-RelativeTime -Time $script:indicesCache.LastFetch)" $footer.FontSize = 9; $footer.Foreground = $Converter.ConvertFromString('#555555') $footer.TextWrapping = 'Wrap' $marketDataContent.Children.Add($footer) | Out-Null diff --git a/PSExchangeClock/en-US/about_PSExchangeClock.help.txt b/PSExchangeClock/en-US/about_PSExchangeClock.help.txt index f9d0159..23b24b9 100644 --- a/PSExchangeClock/en-US/about_PSExchangeClock.help.txt +++ b/PSExchangeClock/en-US/about_PSExchangeClock.help.txt @@ -37,7 +37,11 @@ LONG DESCRIPTION - Breaking financial news (Reuters, BBC, CNBC RSS feeds) - Live forex rates (Frankfurter API / ECB XML fallback) - Cryptocurrency prices (CoinGecko API, top 10 coins) - - Stock indices (S&P 500, NASDAQ, DAX, FTSE, Nikkei via ETF proxies) + - Stock indices (S&P 500, NASDAQ, DAX, FTSE, Nikkei via ETF proxies; + OMX Copenhagen 25 as a true index, which needs a Twelve Data Pro + plan and is turned off by default; enable it by adding + "EnabledIndices": ["OMXC25"] to user-preferences.json. Shown with + Intraday / Last close / Stale / Unavailable status) - Commodity prices (Gold, Silver, Oil, Natural Gas, Wheat) - Individual stock quotes with company profiles and statistics diff --git a/README.md b/README.md index 1448f02..ab6bd86 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ A real-time WPF dashboard for monitoring global stock exchange closing times, li - Breaking financial news from the configurable `market-news-feeds.json` catalog (BBC Business, CNBC Markets, and EIA), with source/category filters, manual refresh, and live/degraded/cached status - Live forex rates (Frankfurter API / ECB XML fallback) - Cryptocurrency prices (CoinGecko API — top 10 coins) - - Stock indices (S&P 500, NASDAQ Composite, DAX, FTSE 100, Nikkei 225 via ETF proxies) + - Stock indices (S&P 500, NASDAQ Composite, DAX, FTSE 100, Nikkei 225 via ETF proxies, plus the OMX Copenhagen 25 index — see [OMXC25](#omxc25-omx-copenhagen-25)) - Commodity prices (Gold, Silver, Oil, Natural Gas, Wheat, Platinum) - Individual stock quotes with company profiles and statistics - **Desktop notifications** at configurable thresholds (30, 15, 5 min) before exchange close @@ -97,6 +97,7 @@ User preferences are stored in `%APPDATA%\PSExchangeClock\user-preferences.json` | `MapOverlays` | Overlays switched on: `DayNight`, `TimeZoneBands`, `PoliticalBorders`, `TimeZoneBoundaries`, `Earthquakes`, `Volcanoes`, `NaturalEvents`, `ConflictZones`, `SubmarineCables`, `PowerPlants`. An empty list means all off; unknown names are ignored | `["DayNight"]` | | `CommodityBaseCurrency` | Currency for commodity price display | `EUR` | | `SecretsBackend` | Where API keys are stored | `CredentialManager` | +| `EnabledIndices` | Optional indices to fetch that are off by default (currently only `OMXC25`, which needs a Twelve Data Pro plan) | not set (off) | ### Holiday Overrides @@ -168,7 +169,7 @@ Existing installs: `Get-StockExchangeData` appends any built-in exchange missing | Financial news | BBC Business, CNBC Markets, and U.S. EIA RSS feeds configured in `market-news-feeds.json` | Varies by provider | | Forex rates | [Frankfurter API](https://www.frankfurter.app/) / ECB XML | Unlimited | | Cryptocurrency | [CoinGecko API](https://www.coingecko.com/) | Unlimited | -| Indices & Commodities | [Twelve Data API](https://twelvedata.com/) | 800 req/day | +| Indices & Commodities | [Twelve Data API](https://twelvedata.com/) (OMXC25: symbol `OMXC25`, Pro plan) | 800 req/day | | Stock quotes | [Alpha Vantage API](https://www.alphavantage.co/) | 25 req/day | | World map image | [NASA GSFC Earth at Night](https://earthobservatory.nasa.gov/) | One-time download | | Earthquakes | [USGS Earthquake Hazards](https://earthquake.usgs.gov/) | Unlimited | @@ -178,6 +179,49 @@ Existing installs: `Get-StockExchangeData` appends any built-in exchange missing | Power plants | [WRI Global Power Plant Database](https://datasets.wri.org/datasets/global-power-plant-database) | Bundled data | | Submarine cables | [TeleGeography](https://www.submarinecablemap.com/) | Bundled data | +## OMXC25 (OMX Copenhagen 25) + +[OMX Copenhagen 25](https://indexes.nasdaqomx.com/Index/Overview/OMXC25) is Nasdaq's market-value-weighted, free-float-adjusted and capped index of the 25 largest and most-traded shares on Nasdaq Copenhagen, quoted in DKK ([methodology](https://indexes.nasdaqomx.com/docs/Methodology_OMXC25.pdf)). + +| Property | Value | +|----------|-------| +| Provider | Twelve Data `/quote` (the existing Indices provider) | +| Symbol | `OMXC25` — listed in Twelve Data's `/indices` catalogue as "OMX Copenhagen 25 Index", DKK | +| Plan required | **Pro** or higher (Twelve Data catalogue `access.plan = "Pro"`). The free Basic key returns HTTP 403 | +| Default | **Turned off.** The Indices tab shows the row greyed out with a note saying why, and no request is made | +| Home exchange | Nasdaq Copenhagen (`XCSE`), Denmark | +| Refresh | Every 15 minutes, like the other indices | + +### Enabling OMXC25 + +If your Twelve Data key is on a Pro plan or higher, add `EnabledIndices` to `%APPDATA%\PSExchangeClock\user-preferences.json` and restart the dashboard: + +```json +"EnabledIndices": ["OMXC25"] +``` + +There is no Settings control for this yet. The dashboard keeps the value when it saves your preferences. Remove the entry to turn it off again. + +Unlike the other Indices rows (US-listed ETF proxies), OMXC25 is a true index value and is fetched in its own request, so a plan restriction never affects the ETF rows. Each OMXC25 row shows a status line: + +| Status | Meaning | +|--------|---------| +| Intraday (may be delayed) | Nasdaq Copenhagen is in session and the quote is no older than 30 minutes. Twelve Data does not say whether a quote is real-time or delayed, so values are never labelled "live" | +| Last close | Copenhagen is closed (pre-open, after 17:00, weekend or `holidays.json` closure) and the quote is from the last 7 days | +| Stale | In session but the quote is more than 30 minutes old, or closed with a quote older than 7 days. The value is greyed out | +| Unavailable | No quote has been received this session | + +The quote time is shown in Copenhagen time. Session status comes from the dashboard's own Nasdaq Copenhagen hours and holidays, not from the provider's `is_market_open` flag, because Twelve Data files OMXC25 under the Stockholm MIC (`XSTO`), whose hours and holidays differ. + +### Troubleshooting missing or stale OMXC25 quotes + +- **"Turned off: needs a Twelve Data Pro plan…"** — the default. See [Enabling OMXC25](#enabling-omxc25). +- **"Requires a Twelve Data Pro plan or higher (HTTP 403)"** — your key's plan does not include this index. After a 403 the dashboard stops requesting OMXC25 for that key for the rest of the session, so it does not spend credits. Upgrade the plan, or ignore the row. Entering a different key in Settings retries it. +- **"Last refresh failed (429) — retrying in 15 min"** — rate limit (8 credits/min on the free tier). The last good value, if any, is still shown with its own status. +- **"Last refresh failed — retrying in 15 min"** with no code — network or timeout. Check connectivity to `api.twelvedata.com`. +- **Stale while the market is open** — the provider has not updated the index for over 30 minutes. Compare with [Nasdaq's OMXC25 page](https://indexes.nasdaqomx.com/Index/Overview/OMXC25). +- **No Indices tab at all** — no Twelve Data key is set; add one in **Settings**. + ## Refreshing Exchange Data The module includes hardcoded fallback data for all 21 exchanges. To pull the latest trading hours from Wikipedia: diff --git a/Tests/PSExchangeClock.Tests.ps1 b/Tests/PSExchangeClock.Tests.ps1 index 4656b31..6c30b4c 100644 --- a/Tests/PSExchangeClock.Tests.ps1 +++ b/Tests/PSExchangeClock.Tests.ps1 @@ -9,6 +9,7 @@ BeforeAll { $script:dataDir = Join-Path $script:moduleRoot 'Data' . (Join-Path $script:moduleRoot 'Private/Get-ExchangeSessionStatus.ps1') + . (Join-Path $script:moduleRoot 'Private/IndexQuotes.ps1') Import-Module (Join-Path $script:moduleRoot 'PSExchangeClock.psd1') -Force # Load holidays exactly as the dashboard does @@ -348,3 +349,234 @@ Describe 'Get-StockExchangeData cache handling' { Test-Path $path | Should -BeTrue } } + +Describe 'OMXC25 index' { + BeforeAll { + $script:defs = @(Get-IndexDefinition) + $script:omx = $script:defs | Where-Object { $_.Symbol -eq 'OMXC25' } + + # Sample Twelve Data /quote payload (shape from the Twelve Data API documentation) + $script:samplePayload = [PSCustomObject]@{ + symbol = 'OMXC25' + name = 'OMX Copenhagen 25 Index' + currency = 'DKK' + datetime = '2026-10-08' + timestamp = 1791442800 # 2026-10-08T07:00:00Z, opening bar + last_quote_at = 1791453600 # 2026-10-08T10:00:00Z + close = '1824.92' + previous_close = '1800.03' + is_market_open = $true + } + } + + Context 'Registration' { + It 'is registered as a true index on Nasdaq Copenhagen, Denmark, in DKK' { + $script:omx | Should -Not -BeNullOrEmpty + $script:omx.Name | Should -Be 'OMX Copenhagen 25 (OMXC25)' + $script:omx.Kind | Should -Be 'Index' + $script:omx.Provider | Should -Be 'TwelveData' + $script:omx.ExchangeCode | Should -Be 'XCSE' + $script:omx.Country | Should -Be 'Denmark' + $script:omx.Currency | Should -Be 'DKK' + } + + It 'resolves its exchange code to Nasdaq Copenhagen' { + $ex = $script:allExchanges | Where-Object { $_.Code -eq $script:omx.ExchangeCode } + $ex.Name | Should -Be 'Nasdaq Copenhagen' + $ex.Country | Should -Be $script:omx.Country + } + + It 'is turned off by default with a note explaining the Pro plan requirement' { + $script:omx.EnabledByDefault | Should -BeFalse + $script:omx.DisabledReason | Should -Match 'Pro plan' + $script:omx.DisabledReason | Should -Match 'EnabledIndices' + Test-IndexEnabled -Definition $script:omx -UserPreferences $null | Should -BeFalse + } + + It 'stays off for existing preference files without EnabledIndices' { + $example = Get-Content (Join-Path $script:dataDir 'user-preferences.example.json') -Raw | ConvertFrom-Json + Test-IndexEnabled -Definition $script:omx -UserPreferences $example | Should -BeFalse + } + + It 'is enabled when listed in EnabledIndices (after a JSON round trip)' { + $saved = @{ EnabledIndices = @('OMXC25') } | ConvertTo-Json -Depth 3 | ConvertFrom-Json + Test-IndexEnabled -Definition $script:omx -UserPreferences $saved | Should -BeTrue + } + + It 'leaves the ETF proxies enabled regardless of EnabledIndices' { + $saved = @{ EnabledIndices = @('OMXC25') } | ConvertTo-Json -Depth 3 | ConvertFrom-Json + foreach ($etf in @($script:defs | Where-Object { $_.Kind -eq 'EtfProxy' })) { + Test-IndexEnabled -Definition $etf -UserPreferences $saved | Should -BeTrue + Test-IndexEnabled -Definition $etf -UserPreferences $null | Should -BeTrue + } + } + + It 'keeps the existing ETF proxies unchanged and in order' { + $etfs = @($script:defs | Where-Object { $_.Kind -eq 'EtfProxy' }) + $etfs.Symbol | Should -Be @('SPY', 'QQQ', 'DIA', 'EWU', 'EWG', 'EWJ', 'FXI', 'INDA') + $etfs[0].Name | Should -Be 'S&P 500 (SPY)' + } + } + + Context 'Quote parsing' { + It 'parses a valid quote' { + $q = ConvertFrom-TwelveDataQuote -Response $script:samplePayload -Symbol 'OMXC25' + $q.IsAvailable | Should -BeTrue + $q.Price | Should -Be 1824.92 + $q.Change | Should -Be 1.38 + $q.QuoteTimeUtc | Should -Be (Get-Utc '2026-10-08T10:00:00') + } + + It 'falls back to timestamp when last_quote_at is absent' { + $p = $script:samplePayload.PSObject.Copy() + $p.PSObject.Properties.Remove('last_quote_at') + (ConvertFrom-TwelveDataQuote -Response $p -Symbol 'OMXC25').QuoteTimeUtc | Should -Be (Get-Utc '2026-10-08T07:00:00') + } + + It 'treats a quote without a price as unavailable' { + $p = $script:samplePayload.PSObject.Copy() + $p.close = $null + $q = ConvertFrom-TwelveDataQuote -Response $p -Symbol 'OMXC25' + $q.IsAvailable | Should -BeFalse + $q.Price | Should -BeNullOrEmpty + } + + It 'treats an empty response as unavailable' { + (ConvertFrom-TwelveDataQuote -Response $null -Symbol 'OMXC25').IsAvailable | Should -BeFalse + } + + It 'marks HTTP 403 (plan upgrade required) as a permanent error' { + $q = ConvertFrom-TwelveDataQuote -Response ([PSCustomObject]@{ code = 403; message = 'upgrade'; status = 'error' }) -Symbol 'OMXC25' + $q.IsAvailable | Should -BeFalse + $q.ErrorCode | Should -Be 403 + $q.IsPermanentError | Should -BeTrue + } + + It 'marks HTTP 429 (rate limit) as transient' { + $q = ConvertFrom-TwelveDataQuote -Response ([PSCustomObject]@{ code = 429; message = 'limit'; status = 'error' }) -Symbol 'OMXC25' + $q.IsPermanentError | Should -BeFalse + } + } + + Context 'Retrieval through Twelve Data (mocked)' { + It 'requests symbol OMXC25 from the /quote endpoint and parses the result' { + Mock Invoke-RestMethod { $script:samplePayload } + $q = Get-TwelveDataIndexQuote -Symbol 'OMXC25' -ApiKey 'test-key' + $q.IsAvailable | Should -BeTrue + $q.Price | Should -Be 1824.92 + Should -Invoke Invoke-RestMethod -Times 1 -Exactly -Scope It -ParameterFilter { + $Uri -like 'https://api.twelvedata.com/quote?symbol=OMXC25&apikey=test-key' + } + } + + It 'returns an unavailable quote instead of throwing on a network failure' { + Mock Invoke-RestMethod { throw [System.Net.Http.HttpRequestException]::new('No such host is known') } + $q = Get-TwelveDataIndexQuote -Symbol 'OMXC25' -ApiKey 'test-key' -ErrorAction Stop + $q.IsAvailable | Should -BeFalse + $q.IsPermanentError | Should -BeFalse + $q.ErrorMessage | Should -Match 'No such host' + } + } + + Context 'Cache, fallback and back-off' { + It 'keeps the last good quote when a later refresh fails' { + $cache = @{} + Mock Get-TwelveDataIndexQuote { ConvertFrom-TwelveDataQuote -Response $script:samplePayload -Symbol 'OMXC25' } + $e = Get-CachedIndexQuote -Definition $script:omx -ApiKey 'k' -Cache $cache -NowUtc (Get-Utc '2026-10-08T10:00:00') + $e.LastGood.Price | Should -Be 1824.92 + + Mock Get-TwelveDataIndexQuote { [PSCustomObject]@{ IsAvailable = $false; ErrorCode = $null; ErrorMessage = 'timeout'; IsPermanentError = $false } } + $e = Get-CachedIndexQuote -Definition $script:omx -ApiKey 'k' -Cache $cache -NowUtc (Get-Utc '2026-10-08T10:20:00') + $e.LastGood.Price | Should -Be 1824.92 + $e.LastError | Should -Be 'timeout' + $e.Blocked | Should -BeFalse + } + + It 'does not call the provider again within the 15-minute TTL' { + $cache = @{} + Mock Get-TwelveDataIndexQuote { ConvertFrom-TwelveDataQuote -Response $script:samplePayload -Symbol 'OMXC25' } + Get-CachedIndexQuote -Definition $script:omx -ApiKey 'k' -Cache $cache -NowUtc (Get-Utc '2026-10-08T10:00:00') | Out-Null + Get-CachedIndexQuote -Definition $script:omx -ApiKey 'k' -Cache $cache -NowUtc (Get-Utc '2026-10-08T10:10:00') | Out-Null + Should -Invoke Get-TwelveDataIndexQuote -Times 1 -Exactly -Scope It + Get-CachedIndexQuote -Definition $script:omx -ApiKey 'k' -Cache $cache -NowUtc (Get-Utc '2026-10-08T10:16:00') | Out-Null + Should -Invoke Get-TwelveDataIndexQuote -Times 2 -Exactly -Scope It + } + + It 'stops requesting after HTTP 403 for that key, but retries with a different key' { + $cache = @{} + Mock Get-TwelveDataIndexQuote { ConvertFrom-TwelveDataQuote -Response ([PSCustomObject]@{ code = 403; message = 'Pro plan'; status = 'error' }) -Symbol 'OMXC25' } + $e = Get-CachedIndexQuote -Definition $script:omx -ApiKey 'basic' -Cache $cache -NowUtc (Get-Utc '2026-10-08T10:00:00') + $e.Blocked | Should -BeTrue + $e.ErrorCode | Should -Be 403 + Get-CachedIndexQuote -Definition $script:omx -ApiKey 'basic' -Cache $cache -NowUtc (Get-Utc '2026-10-08T12:00:00') | Out-Null + Should -Invoke Get-TwelveDataIndexQuote -Times 1 -Exactly -Scope It + Get-CachedIndexQuote -Definition $script:omx -ApiKey 'pro' -Cache $cache -NowUtc (Get-Utc '2026-10-08T12:00:00') | Out-Null + Should -Invoke Get-TwelveDataIndexQuote -Times 2 -Exactly -Scope It + } + + It 'retries after the TTL following a rate-limit error' { + $cache = @{} + Mock Get-TwelveDataIndexQuote { ConvertFrom-TwelveDataQuote -Response ([PSCustomObject]@{ code = 429; message = 'limit'; status = 'error' }) -Symbol 'OMXC25' } + $e = Get-CachedIndexQuote -Definition $script:omx -ApiKey 'k' -Cache $cache -NowUtc (Get-Utc '2026-10-08T10:00:00') + $e.Blocked | Should -BeFalse + $e.LastGood | Should -BeNullOrEmpty + Get-CachedIndexQuote -Definition $script:omx -ApiKey 'k' -Cache $cache -NowUtc (Get-Utc '2026-10-08T10:15:00') | Out-Null + Should -Invoke Get-TwelveDataIndexQuote -Times 2 -Exactly -Scope It + } + } + + Context 'Quote status (live/delayed/stale/last close) against Copenhagen hours' { + BeforeAll { + function Get-OmxStatus([string]$NowIso, $QuoteIso) { + $now = Get-Utc $NowIso + $market = (Get-ExchangeSessionStatus -Exchange $script:xcse -UtcNow $now -Holidays $script:holidays).Status + $qt = if ($QuoteIso) { Get-Utc $QuoteIso } else { $null } + Get-IndexQuoteStatus -QuoteTimeUtc $qt -MarketStatus $market -NowUtc $now + } + } + + It 'is Intraday (never "live") for a fresh quote during the session' { + $s = Get-OmxStatus '2026-10-08T10:10:00' '2026-10-08T10:00:00' + $s.Status | Should -Be 'Intraday' + $s.Label | Should -Not -Match 'live' + } + + It 'is Intraday during the closing auction with a recent quote' { + (Get-OmxStatus '2026-10-08T14:57:00' '2026-10-08T14:54:00').Status | Should -Be 'Intraday' + } + + It 'is Stale for a delayed quote more than 30 minutes old during the session' { + (Get-OmxStatus '2026-10-08T10:45:00' '2026-10-08T10:00:00').Status | Should -Be 'Stale' + } + + It 'is Stale during the session when only yesterday''s close is available' { + (Get-OmxStatus '2026-10-08T10:00:00' '2026-10-07T14:59:00').Status | Should -Be 'Stale' + } + + It 'is LastClose after 17:00' { + (Get-OmxStatus '2026-10-08T18:00:00' '2026-10-08T14:59:00').Status | Should -Be 'LastClose' + } + + It 'is LastClose before the open' { + (Get-OmxStatus '2026-10-09T06:00:00' '2026-10-08T14:59:00').Status | Should -Be 'LastClose' + } + + It 'is LastClose across the Easter closure' { + # Last 2026 session before Easter: Wed 1 Apr; Tue 7 Apr pre-open + (Get-OmxStatus '2026-04-07T06:30:00' '2026-04-01T14:59:00').Status | Should -Be 'LastClose' + } + + It 'is LastClose on a Copenhagen holiday even though Stockholm trades' { + # 2026-05-15: Copenhagen closed (day after Ascension); Twelve Data files OMXC25 under XSTO + (Get-OmxStatus '2026-05-15T10:00:00' '2026-05-13T14:59:00').Status | Should -Be 'LastClose' + } + + It 'is Stale for a quote over seven days old while closed' { + (Get-OmxStatus '2026-10-10T10:00:00' '2026-09-30T14:59:00').Status | Should -Be 'Stale' + } + + It 'is Unavailable with no quote' { + (Get-OmxStatus '2026-10-08T10:00:00' $null).Status | Should -Be 'Unavailable' + } + } +} From 78026855af82c782f3e1f4762d1174cf345d76a3 Mon Sep 17 00:00:00 2001 From: knightmare2600 Date: Fri, 9 Oct 2026 23:07:35 +0100 Subject: [PATCH 4/4] feat: add FTSE 100 as an opt-in true index The London Stock Exchange (XLON) is already supported as an exchange; this adds its headline index, the FTSE 100, to the Indices tab using the same opt-in mechanism as OMXC25. - Twelve Data symbol 'FTSE' ("FTSE 100", GBP, mic_code XLON in the /indices catalogue, access level "Grow"). Off by default and shown greyed out with a note; enable with "EnabledIndices": ["FTSE"]. - The request is pinned with mic_code=XLON: symbol_search shows the bare ticker FTSE is also the Amundi MSCI UK IMI SRI Climate Paris Aligned ETF on Euronext Paris (XPAR). - Index definitions gain MicCode and RequiredPlan; the HTTP 403 message now names the plan the index needs instead of always saying "Pro". - Quote status is judged against London hours. holidays.json has no UK dates, so on a bank holiday an old quote shows as Stale. - Tests: registration, opt-in independent of OMXC25, mic_code sent on the request and through the cache layer, status against LSE hours. Not verified against a live Grow-plan key; request and response shape follow the Twelve Data /quote documentation. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + PSExchangeClock/Private/IndexQuotes.ps1 | 38 +++++++++-- .../New-StockExchangeCountdownDashboard.ps1 | 6 +- .../en-US/about_PSExchangeClock.help.txt | 8 +-- README.md | 18 +++++- Tests/PSExchangeClock.Tests.ps1 | 63 +++++++++++++++++++ 6 files changed, 121 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6e8676..69b1a12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Pester tests under `Tests/` (run with `Invoke-Pester ./Tests`), starting with map preference restore - Tests for Nasdaq Copenhagen session status, auctions, holidays, DST transitions, selection and exchange-data caching - Tests for OMXC25 registration, opt-in, quote parsing, caching/back-off and quote status +- **FTSE 100** as an opt-in true index on the Indices tab (Twelve Data symbol `FTSE`, pinned to `mic_code=XLON` because the bare ticker is also a Euronext Paris ETF; needs a Grow plan, so off by default). Enable with `EnabledIndices: ["FTSE"]` ### Fixed diff --git a/PSExchangeClock/Private/IndexQuotes.ps1 b/PSExchangeClock/Private/IndexQuotes.ps1 index 1b96e92..a6af762 100644 --- a/PSExchangeClock/Private/IndexQuotes.ps1 +++ b/PSExchangeClock/Private/IndexQuotes.ps1 @@ -8,11 +8,18 @@ function Get-IndexDefinition { symbols fetched individually, so a plan restriction on one index cannot affect the ETF batch. + True indices need a paid Twelve Data plan (RequiredPlan), so they are off + by default (EnabledByDefault = $false) and are only requested when the + user lists their symbol in EnabledIndices in user-preferences.json. + + FTSE 100: Twelve Data lists symbol 'FTSE' ("FTSE 100", GBP, mic_code XLON) + in its /indices catalogue with access level 'Grow'. The bare ticker + 'FTSE' is also an Amundi MSCI UK ETF on Euronext Paris, so the request + is pinned with MicCode XLON. + OMXC25: Twelve Data lists symbol 'OMXC25' ("OMX Copenhagen 25 Index", DKK) in its /indices catalogue with access level 'Pro' - a Basic key receives - HTTP 403 (upgrade required). It is therefore off by default - (EnabledByDefault = $false) and is only requested when the user lists it - in EnabledIndices in user-preferences.json. + HTTP 403 (upgrade required). #> [CmdletBinding()] [OutputType([PSCustomObject[]])] @@ -38,11 +45,27 @@ function Get-IndexDefinition { ExchangeCode = $null Country = $null Currency = 'USD' + MicCode = $null + RequiredPlan = 'Basic' EnabledByDefault = $true DisabledReason = $null } } + [PSCustomObject]@{ + Symbol = 'FTSE' + Name = 'FTSE 100' + Kind = 'Index' + Provider = 'TwelveData' + ExchangeCode = 'XLON' + Country = 'United Kingdom' + Currency = 'GBP' + MicCode = 'XLON' + RequiredPlan = 'Grow' + EnabledByDefault = $false + DisabledReason = 'Turned off: needs a Twelve Data Grow plan or higher (free/Basic keys get HTTP 403). To enable, add "FTSE" to "EnabledIndices" in user-preferences.json.' + } + [PSCustomObject]@{ Symbol = 'OMXC25' Name = 'OMX Copenhagen 25 (OMXC25)' @@ -51,6 +74,8 @@ function Get-IndexDefinition { ExchangeCode = 'XCSE' Country = 'Denmark' Currency = 'DKK' + MicCode = $null + RequiredPlan = 'Pro' EnabledByDefault = $false DisabledReason = 'Turned off: needs a Twelve Data Pro plan or higher (free/Basic keys get HTTP 403). To enable, add "EnabledIndices": ["OMXC25"] to user-preferences.json.' } @@ -159,10 +184,15 @@ function Get-TwelveDataIndexQuote { param( [Parameter(Mandatory)][string]$Symbol, [Parameter(Mandatory)][string]$ApiKey, + [string]$MicCode, [int]$TimeoutSec = 15 ) $url = "https://api.twelvedata.com/quote?symbol=$([uri]::EscapeDataString($Symbol))&apikey=$([uri]::EscapeDataString($ApiKey))" + if ($MicCode) { + # Disambiguates tickers shared by several instruments (ISO 10383 MIC) + $url += "&mic_code=$([uri]::EscapeDataString($MicCode))" + } try { $response = Invoke-RestMethod -Uri $url -TimeoutSec $TimeoutSec -ErrorAction Stop } @@ -239,7 +269,7 @@ function Get-CachedIndexQuote { if ($entry.LastAttemptUtc -and ($NowUtc - $entry.LastAttemptUtc).TotalMinutes -lt $TtlMinutes) { return $entry } $entry.LastAttemptUtc = $NowUtc - $quote = Get-TwelveDataIndexQuote -Symbol $Definition.Symbol -ApiKey $ApiKey + $quote = Get-TwelveDataIndexQuote -Symbol $Definition.Symbol -ApiKey $ApiKey -MicCode $Definition.MicCode if ($quote.IsAvailable) { $entry.LastGood = $quote $entry.LastFetchUtc = $NowUtc diff --git a/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 b/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 index 3e18383..90ee056 100644 --- a/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 +++ b/PSExchangeClock/Public/New-StockExchangeCountdownDashboard.ps1 @@ -2042,7 +2042,7 @@ public static class CredManager { $marketDataContent.Children.Add($grid) | Out-Null } - # True indices (e.g. OMXC25) with quote status from their home exchange + # True indices (FTSE 100, OMXC25) with quote status from their home exchange foreach ($idx in $indexRows) { Add-MarketSeparator -Converter $Converter $def = $idx.Definition @@ -2138,7 +2138,7 @@ public static class CredManager { $parts += "as of $($shown.ToString('dd MMM HH:mm')) $tzLabel" } if ($entry.Blocked -and $entry.ErrorCode -eq 403) { - $parts += 'Requires a Twelve Data Pro plan or higher (HTTP 403)' + $parts += "Requires a Twelve Data $($def.RequiredPlan) plan or higher (HTTP 403)" } elseif ($entry.Blocked) { $parts += "Not available from provider ($($entry.ErrorCode)): $($entry.LastError)" @@ -2157,7 +2157,7 @@ public static class CredManager { Add-MarketSeparator -Converter $Converter $footer = New-Object System.Windows.Controls.TextBlock - $footer.Text = "Source: Twelve Data (ETF proxies; OMXC25 index) | Updated: $(Format-RelativeTime -Time $script:indicesCache.LastFetch)" + $footer.Text = "Source: Twelve Data (ETF proxies; FTSE 100 and OMXC25 indices) | Updated: $(Format-RelativeTime -Time $script:indicesCache.LastFetch)" $footer.FontSize = 9; $footer.Foreground = $Converter.ConvertFromString('#555555') $footer.TextWrapping = 'Wrap' $marketDataContent.Children.Add($footer) | Out-Null diff --git a/PSExchangeClock/en-US/about_PSExchangeClock.help.txt b/PSExchangeClock/en-US/about_PSExchangeClock.help.txt index 23b24b9..08093f7 100644 --- a/PSExchangeClock/en-US/about_PSExchangeClock.help.txt +++ b/PSExchangeClock/en-US/about_PSExchangeClock.help.txt @@ -38,10 +38,10 @@ LONG DESCRIPTION - Live forex rates (Frankfurter API / ECB XML fallback) - Cryptocurrency prices (CoinGecko API, top 10 coins) - Stock indices (S&P 500, NASDAQ, DAX, FTSE, Nikkei via ETF proxies; - OMX Copenhagen 25 as a true index, which needs a Twelve Data Pro - plan and is turned off by default; enable it by adding - "EnabledIndices": ["OMXC25"] to user-preferences.json. Shown with - Intraday / Last close / Stale / Unavailable status) + FTSE 100 and OMX Copenhagen 25 as true indices, which need a + Twelve Data Grow / Pro plan and are turned off by default; enable + with "EnabledIndices": ["FTSE", "OMXC25"] in user-preferences.json. + Shown with Intraday / Last close / Stale / Unavailable status) - Commodity prices (Gold, Silver, Oil, Natural Gas, Wheat) - Individual stock quotes with company profiles and statistics diff --git a/README.md b/README.md index ab6bd86..ad6d380 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ User preferences are stored in `%APPDATA%\PSExchangeClock\user-preferences.json` | `MapOverlays` | Overlays switched on: `DayNight`, `TimeZoneBands`, `PoliticalBorders`, `TimeZoneBoundaries`, `Earthquakes`, `Volcanoes`, `NaturalEvents`, `ConflictZones`, `SubmarineCables`, `PowerPlants`. An empty list means all off; unknown names are ignored | `["DayNight"]` | | `CommodityBaseCurrency` | Currency for commodity price display | `EUR` | | `SecretsBackend` | Where API keys are stored | `CredentialManager` | -| `EnabledIndices` | Optional indices to fetch that are off by default (currently only `OMXC25`, which needs a Twelve Data Pro plan) | not set (off) | +| `EnabledIndices` | Optional true indices to fetch that are off by default: `FTSE` (FTSE 100, needs a Twelve Data Grow plan) and `OMXC25` (needs Pro) | not set (off) | ### Holiday Overrides @@ -169,7 +169,7 @@ Existing installs: `Get-StockExchangeData` appends any built-in exchange missing | Financial news | BBC Business, CNBC Markets, and U.S. EIA RSS feeds configured in `market-news-feeds.json` | Varies by provider | | Forex rates | [Frankfurter API](https://www.frankfurter.app/) / ECB XML | Unlimited | | Cryptocurrency | [CoinGecko API](https://www.coingecko.com/) | Unlimited | -| Indices & Commodities | [Twelve Data API](https://twelvedata.com/) (OMXC25: symbol `OMXC25`, Pro plan) | 800 req/day | +| Indices & Commodities | [Twelve Data API](https://twelvedata.com/) (FTSE 100: symbol `FTSE`, Grow plan; OMXC25: symbol `OMXC25`, Pro plan) | 800 req/day | | Stock quotes | [Alpha Vantage API](https://www.alphavantage.co/) | 25 req/day | | World map image | [NASA GSFC Earth at Night](https://earthobservatory.nasa.gov/) | One-time download | | Earthquakes | [USGS Earthquake Hazards](https://earthquake.usgs.gov/) | Unlimited | @@ -179,6 +179,20 @@ Existing installs: `Get-StockExchangeData` appends any built-in exchange missing | Power plants | [WRI Global Power Plant Database](https://datasets.wri.org/datasets/global-power-plant-database) | Bundled data | | Submarine cables | [TeleGeography](https://www.submarinecablemap.com/) | Bundled data | +## FTSE 100 + +The London Stock Exchange (`XLON`) is the exchange; the FTSE 100 is the index of its 100 largest listed companies, calculated by FTSE Russell. + +| Property | Value | +|----------|-------| +| Provider | Twelve Data `/quote` | +| Symbol | `FTSE` with `mic_code=XLON` — listed in Twelve Data's `/indices` catalogue as "FTSE 100", GBP. The MIC is required because the bare ticker `FTSE` is also an Amundi MSCI UK ETF on Euronext Paris | +| Plan required | **Grow** or higher (Twelve Data catalogue `access.plan = "Grow"`). The free Basic key returns HTTP 403 | +| Default | **Turned off**, shown greyed out with a note. Enable with `"EnabledIndices": ["FTSE"]` (combine with `"OMXC25"` if wanted) | +| Home exchange | London Stock Exchange (`XLON`), United Kingdom | + +It uses the same status line, caching and back-off as OMXC25 below, judged against London hours. `holidays.json` has no UK closure dates, so on a UK bank holiday an old quote shows as *Stale* rather than *Last close*. + ## OMXC25 (OMX Copenhagen 25) [OMX Copenhagen 25](https://indexes.nasdaqomx.com/Index/Overview/OMXC25) is Nasdaq's market-value-weighted, free-float-adjusted and capped index of the 25 largest and most-traded shares on Nasdaq Copenhagen, quoted in DKK ([methodology](https://indexes.nasdaqomx.com/docs/Methodology_OMXC25.pdf)). diff --git a/Tests/PSExchangeClock.Tests.ps1 b/Tests/PSExchangeClock.Tests.ps1 index 6c30b4c..a593e63 100644 --- a/Tests/PSExchangeClock.Tests.ps1 +++ b/Tests/PSExchangeClock.Tests.ps1 @@ -580,3 +580,66 @@ Describe 'OMXC25 index' { } } } + +Describe 'FTSE 100 index' { + BeforeAll { + $script:ftse = Get-IndexDefinition | Where-Object { $_.Symbol -eq 'FTSE' } + $script:xlon = $script:allExchanges | Where-Object { $_.Code -eq 'XLON' } + } + + It 'is registered as a true index on the London Stock Exchange, in GBP' { + $script:ftse | Should -Not -BeNullOrEmpty + $script:ftse.Name | Should -Be 'FTSE 100' + $script:ftse.Kind | Should -Be 'Index' + $script:ftse.ExchangeCode | Should -Be 'XLON' + $script:ftse.Country | Should -Be 'United Kingdom' + $script:ftse.Currency | Should -Be 'GBP' + $script:xlon.Name | Should -Be 'London Stock Exchange' + } + + It 'is pinned to the XLON MIC because the bare ticker FTSE is ambiguous' { + $script:ftse.MicCode | Should -Be 'XLON' + } + + It 'is turned off by default with a note explaining the Grow plan requirement' { + $script:ftse.RequiredPlan | Should -Be 'Grow' + $script:ftse.EnabledByDefault | Should -BeFalse + $script:ftse.DisabledReason | Should -Match 'Grow plan' + $script:ftse.DisabledReason | Should -Match '"FTSE"' + Test-IndexEnabled -Definition $script:ftse -UserPreferences $null | Should -BeFalse + } + + It 'is enabled independently of OMXC25' { + $omx = Get-IndexDefinition | Where-Object { $_.Symbol -eq 'OMXC25' } + $saved = @{ EnabledIndices = @('FTSE') } | ConvertTo-Json -Depth 3 | ConvertFrom-Json + Test-IndexEnabled -Definition $script:ftse -UserPreferences $saved | Should -BeTrue + Test-IndexEnabled -Definition $omx -UserPreferences $saved | Should -BeFalse + } + + It 'sends mic_code=XLON with the quote request' { + Mock Invoke-RestMethod { [PSCustomObject]@{ symbol = 'FTSE'; close = '9120.50'; previous_close = '9100.00'; last_quote_at = 1791453600 } } + $q = Get-TwelveDataIndexQuote -Symbol 'FTSE' -ApiKey 'test-key' -MicCode 'XLON' + $q.IsAvailable | Should -BeTrue + $q.Price | Should -Be 9120.5 + Should -Invoke Invoke-RestMethod -Times 1 -Exactly -Scope It -ParameterFilter { + $Uri -eq 'https://api.twelvedata.com/quote?symbol=FTSE&apikey=test-key&mic_code=XLON' + } + } + + It 'passes the MIC through the cache layer' { + Mock Get-TwelveDataIndexQuote { [PSCustomObject]@{ IsAvailable = $false; ErrorCode = 403; ErrorMessage = 'Grow'; IsPermanentError = $true } } + $e = Get-CachedIndexQuote -Definition $script:ftse -ApiKey 'basic' -Cache @{} -NowUtc (Get-Utc '2026-10-08T10:00:00') + $e.Blocked | Should -BeTrue + Should -Invoke Get-TwelveDataIndexQuote -Times 1 -Exactly -Scope It -ParameterFilter { $Symbol -eq 'FTSE' -and $MicCode -eq 'XLON' } + } + + It 'judges quote status against London hours' { + # 2026-10-08 is a Thursday; London is on BST (UTC+1); LSE closes 16:30 local = 15:30 UTC + $open = (Get-ExchangeSessionStatus -Exchange $script:xlon -UtcNow (Get-Utc '2026-10-08T15:00:00')).Status + Get-IndexQuoteStatus -QuoteTimeUtc (Get-Utc '2026-10-08T14:55:00') -MarketStatus $open -NowUtc (Get-Utc '2026-10-08T15:00:00') | + ForEach-Object { $_.Status } | Should -Be 'Intraday' + $closed = (Get-ExchangeSessionStatus -Exchange $script:xlon -UtcNow (Get-Utc '2026-10-08T15:45:00')).Status + $closed | Should -Be 'Closed' + (Get-IndexQuoteStatus -QuoteTimeUtc (Get-Utc '2026-10-08T15:29:00') -MarketStatus $closed -NowUtc (Get-Utc '2026-10-08T15:45:00')).Status | Should -Be 'LastClose' + } +}