diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d10eca..d9e3837 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,27 @@ 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 + +- **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 ### Fixed 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/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-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/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/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 8c48fcb..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, @@ -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 @@ -348,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 { @@ -995,6 +941,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 = @{ @@ -2441,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 @@ -2457,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 @@ -2608,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) @@ -4229,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 @@ -4283,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 @@ -4534,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 } @@ -4545,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 = '--:--:--' @@ -4611,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" } @@ -4737,7 +4726,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 +4735,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/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 6915f89..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,9 +89,12 @@ 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` | +| `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` | @@ -130,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 @@ -151,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/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') + } +} 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