Private/Application/ExchangeSessionService.ps1

function ConvertTo-ExchangeLocalMinutes {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidatePattern('^(?:[01]\d|2[0-3]):[0-5]\d$')]
        [string]$Time
    )

    $parts = $Time.Split(':')
    ([int]$parts[0] * 60) + [int]$parts[1]
}

function ConvertTo-ExchangeUtcBoundary {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [datetime]$LocalDate,

        [Parameter(Mandatory)]
        [System.TimeZoneInfo]$TimeZone
    )

    $unspecified = [datetime]::SpecifyKind($LocalDate, [DateTimeKind]::Unspecified)
    if ($TimeZone.IsInvalidTime($unspecified)) {
        throw "The scheduled local time '$($unspecified.ToString('s'))' does not exist in time zone '$($TimeZone.Id)'."
    }

    if ($TimeZone.IsAmbiguousTime($unspecified)) {
        $offset = $TimeZone.GetAmbiguousTimeOffsets($unspecified) |
            Sort-Object -Descending |
            Select-Object -First 1
        return [DateTimeOffset]::new($unspecified, $offset).ToUniversalTime()
    }

    [DateTimeOffset]::new([TimeZoneInfo]::ConvertTimeToUtc($unspecified, $TimeZone))
}

function Get-ExchangeSessionState {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Exchange,

        [Parameter(Mandatory)]
        [datetimeoffset]$AtUtc,

        [Parameter()]
        [string[]]$HolidayDates = @(),

        [Parameter()]
        [ValidateSet('verified', 'unverified')]
        [string]$HolidayCoverageStatus = 'verified'
    )

    foreach ($requiredProperty in @('exchangeId', 'name', 'region', 'timeZoneId', 'sourceId', 'openTimeLocal', 'closeTimeLocal')) {
        if ($null -eq $Exchange.PSObject.Properties[$requiredProperty]) {
            throw "Exchange is missing required field '$requiredProperty'."
        }
    }

    $timeZone = [System.TimeZoneInfo]::FindSystemTimeZoneById([string]$Exchange.timeZoneId)
    $localNow = [System.TimeZoneInfo]::ConvertTime($AtUtc.ToUniversalTime(), $timeZone)
    $openMinutes = ConvertTo-ExchangeLocalMinutes -Time $Exchange.openTimeLocal
    $closeMinutes = ConvertTo-ExchangeLocalMinutes -Time $Exchange.closeTimeLocal
    $isOvernight = $closeMinutes -lt $openMinutes
    $localMinutes = ($localNow.Hour * 60) + $localNow.Minute
    $sessionDate = $localNow.Date

    if ($isOvernight -and $localMinutes -lt $closeMinutes) {
        $sessionDate = $sessionDate.AddDays(-1)
    }

    $sessionDateText = $sessionDate.ToString('yyyy-MM-dd', [System.Globalization.CultureInfo]::InvariantCulture)
    $state = 'closed'
    $openAtUtc = $null
    $closeAtUtc = $null
    $breakStartAtUtc = $null
    $breakEndAtUtc = $null

    if ($sessionDate.DayOfWeek -notin @([DayOfWeek]::Saturday, [DayOfWeek]::Sunday)) {
        $openLocal = $sessionDate.AddMinutes($openMinutes)
        $closeDate = if ($isOvernight) { $sessionDate.AddDays(1) } else { $sessionDate }
        $closeLocal = $closeDate.AddMinutes($closeMinutes)
        $openAtUtc = ConvertTo-ExchangeUtcBoundary -LocalDate $openLocal -TimeZone $timeZone
        $closeAtUtc = ConvertTo-ExchangeUtcBoundary -LocalDate $closeLocal -TimeZone $timeZone

        if ($HolidayDates -contains $sessionDateText) {
            $state = 'holiday'
        }
        elseif ($AtUtc.ToUniversalTime() -lt $openAtUtc) {
            $state = 'pre-market'
        }
        elseif ($AtUtc.ToUniversalTime() -ge $closeAtUtc) {
            $state = 'closed'
        }
        else {
            if ($Exchange.breakStartLocal -and $Exchange.breakEndLocal) {
                $breakStart = $sessionDate.AddMinutes(
                    (ConvertTo-ExchangeLocalMinutes -Time $Exchange.breakStartLocal)
                )
                $breakEnd = $sessionDate.AddMinutes(
                    (ConvertTo-ExchangeLocalMinutes -Time $Exchange.breakEndLocal)
                )
                if ($breakEnd -le $breakStart) {
                    $breakEnd = $breakEnd.AddDays(1)
                }
                $breakStartAtUtc = ConvertTo-ExchangeUtcBoundary -LocalDate $breakStart -TimeZone $timeZone
                $breakEndAtUtc = ConvertTo-ExchangeUtcBoundary -LocalDate $breakEnd -TimeZone $timeZone
            }

            if ($null -ne $breakStartAtUtc -and
                $AtUtc.ToUniversalTime() -ge $breakStartAtUtc -and
                $AtUtc.ToUniversalTime() -lt $breakEndAtUtc) {
                $state = 'break'
            }
            else {
                $state = 'open'
            }
        }
    }

    $scheduledState = $state
    if ($HolidayCoverageStatus -eq 'unverified' -and
        $scheduledState -in @('open', 'pre-market', 'break')) {
        $state = 'unknown'
    }

    $nextBoundaryAtUtc = $null
    $nextBoundaryType = $null
    switch ($scheduledState) {
        'open' {
            $nextBoundaryAtUtc = $closeAtUtc
            $nextBoundaryType = 'close'
        }
        'pre-market' {
            $nextBoundaryAtUtc = $openAtUtc
            $nextBoundaryType = 'open'
        }
        'break' {
            $nextBoundaryAtUtc = $breakEndAtUtc
            $nextBoundaryType = 'reopen'
        }
        default {
            for ($dayOffset = 0; $dayOffset -le 14; $dayOffset++) {
                $candidateDate = $localNow.Date.AddDays($dayOffset)
                if ($candidateDate.DayOfWeek -in @([DayOfWeek]::Saturday, [DayOfWeek]::Sunday)) {
                    continue
                }

                $candidateDateText = $candidateDate.ToString(
                    'yyyy-MM-dd',
                    [System.Globalization.CultureInfo]::InvariantCulture
                )
                if ($HolidayDates -contains $candidateDateText) {
                    continue
                }

                $candidateOpenAtUtc = ConvertTo-ExchangeUtcBoundary `
                    -LocalDate $candidateDate.AddMinutes($openMinutes) -TimeZone $timeZone
                if ($candidateOpenAtUtc -gt $AtUtc.ToUniversalTime()) {
                    $nextBoundaryAtUtc = $candidateOpenAtUtc
                    $nextBoundaryType = 'open'
                    break
                }
            }
        }
    }

    [pscustomobject][ordered]@{
        exchangeId = $Exchange.exchangeId
        sourceId = $Exchange.sourceId
        sessionDate = $sessionDate
        state = $state
        scheduledState = $scheduledState
        holidayCoverageStatus = $HolidayCoverageStatus
        localTime = $localNow.DateTime
        timeZoneId = $timeZone.Id
        openAtUtc = $openAtUtc
        closeAtUtc = $closeAtUtc
        breakStartAtUtc = $breakStartAtUtc
        breakEndAtUtc = $breakEndAtUtc
        nextBoundaryAtUtc = $nextBoundaryAtUtc
        nextBoundaryType = $nextBoundaryType
    }
}

function Get-ExchangeSessionCatalog {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$ExchangeDataPath,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$HolidayDataPath,

        [Parameter(Mandatory)]
        [datetimeoffset]$AtUtc,

        [Parameter()]
        [ValidateSet('verified', 'unverified')]
        [string]$HolidayCoverageStatus = 'unverified'
    )

    foreach ($path in @($ExchangeDataPath, $HolidayDataPath)) {
        if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
            throw "Required exchange reference data is missing: $path"
        }
    }

    $exchangeCatalog = Get-Content -LiteralPath $ExchangeDataPath -Raw -ErrorAction Stop |
        ConvertFrom-Json -ErrorAction Stop
    if ($null -eq $exchangeCatalog.Exchanges -or $exchangeCatalog.Exchanges -is [string]) {
        throw 'Exchange reference data must contain an Exchanges array.'
    }

    $holidayCatalog = Get-Content -LiteralPath $HolidayDataPath -Raw -ErrorAction Stop |
        ConvertFrom-Json -AsHashtable -ErrorAction Stop
    if ($holidayCatalog -isnot [System.Collections.IDictionary]) {
        throw 'Holiday reference data must be an object keyed by exchange ID.'
    }

    $regionsByCountry = @{
        'United States' = 'North America'
        Canada = 'North America'
        Mexico = 'North America'
        Brazil = 'South America'
        'United Kingdom' = 'Europe'
        France = 'Europe'
        Germany = 'Europe'
        Switzerland = 'Europe'
        Russia = 'Europe'
        Japan = 'Asia'
        China = 'Asia'
        'Hong Kong' = 'Asia'
        India = 'Asia'
        'South Korea' = 'Asia'
        Taiwan = 'Asia'
        Singapore = 'Asia'
        Australia = 'Oceania'
        'South Africa' = 'Africa'
    }

    foreach ($entry in $exchangeCatalog.Exchanges) {
        if ($null -eq $entry -or
            [string]::IsNullOrWhiteSpace([string]$entry.Code) -or
            [string]::IsNullOrWhiteSpace([string]$entry.Country)) {
            throw 'Exchange reference data contains an entry without a stable code or country.'
        }

        $exchange = New-Exchange -ExchangeId $entry.Code -Name $entry.Name `
            -Region $(if ($regionsByCountry.ContainsKey([string]$entry.Country)) {
                $regionsByCountry[[string]$entry.Country]
            }
            else {
                'Other'
            }) `
            -TimeZoneId $entry.TimeZoneId -SourceId 'exchange-data-catalog' `
            -OpenTimeLocal $entry.OpenTimeLocal -CloseTimeLocal $entry.CloseTimeLocal `
            -BreakStartLocal $entry.LunchBreakStart -BreakEndLocal $entry.LunchBreakEnd
        $holidayDates = if ($HolidayCoverageStatus -eq 'verified' -and
            $holidayCatalog.ContainsKey([string]$entry.Code)) {
            @($holidayCatalog[[string]$entry.Code])
        }
        else {
            @()
        }
        $session = New-ExchangeSession -Exchange $exchange -AtUtc $AtUtc `
            -HolidayDates $holidayDates -HolidayCoverageStatus $HolidayCoverageStatus

        [pscustomobject][ordered]@{
            exchangeId = $session.exchangeId
            name = [string]$entry.Name
            symbol = [string]$entry.Symbol
            country = [string]$entry.Country
            city = [string]$entry.City
            region = $exchange.region
            timeZoneId = $session.timeZoneId
            sourceId = $session.sourceId
            state = $session.state
            scheduledState = $session.scheduledState
            holidayCoverageStatus = $session.holidayCoverageStatus
            sessionDate = $session.sessionDate
            localTime = $session.localTime
            openAtUtc = $session.openAtUtc
            closeAtUtc = $session.closeAtUtc
            breakStartAtUtc = $session.breakStartAtUtc
            breakEndAtUtc = $session.breakEndAtUtc
            nextBoundaryAtUtc = $session.nextBoundaryAtUtc
            nextBoundaryType = $session.nextBoundaryType
            latitude = $entry.Latitude
            longitude = $entry.Longitude
        }
    }
}