Private/Application/HistoricalDashboard.ps1

function Get-HistoricalDashboardInstruments {
    [CmdletBinding()]
    param()

    foreach ($pair in @(
            @{ Quote = 'USD'; Name = 'US Dollar' }
            @{ Quote = 'GBP'; Name = 'Pound Sterling' }
            @{ Quote = 'JPY'; Name = 'Japanese Yen' }
            @{ Quote = 'CHF'; Name = 'Swiss Franc' }
            @{ Quote = 'CNY'; Name = 'Chinese Yuan' }
            @{ Quote = 'AUD'; Name = 'Australian Dollar' }
            @{ Quote = 'CAD'; Name = 'Canadian Dollar' }
            @{ Quote = 'INR'; Name = 'Indian Rupee' }
        )) {
        New-Instrument -InstrumentId "eur-$($pair.Quote.ToLowerInvariant())" -Symbol "EUR/$($pair.Quote)" `
            -ProviderSymbol "EUR/$($pair.Quote)" -DisplayName "Euro / $($pair.Name)" `
            -AssetClass forex -QuoteCurrency $pair.Quote -Unit "$($pair.Quote) per EUR" `
            -SourceIds @('ecb-reference-rates')
    }
    foreach ($series in @(
            @{ Id = 'SP500'; Name = 'S&P 500'; Class = 'index'; Unit = 'Index points' }
            @{ Id = 'NASDAQCOM'; Name = 'NASDAQ Composite'; Class = 'index'; Unit = 'Index points' }
            @{ Id = 'DJIA'; Name = 'Dow Jones Industrial Average'; Class = 'index'; Unit = 'Index points' }
            @{ Id = 'NIKKEI225'; Name = 'Nikkei 225'; Class = 'index'; Unit = 'Index points' }
            @{ Id = 'VIXCLS'; Name = 'CBOE Volatility Index (VIX)'; Class = 'index'; Unit = 'Index points' }
            @{ Id = 'DGS10'; Name = '10-Year US Treasury Yield'; Class = 'index'; Unit = 'Percent' }
            @{ Id = 'DCOILWTICO'; Name = 'Crude Oil WTI'; Class = 'commodity'; Unit = 'USD per barrel'; Currency = 'USD' }
            @{ Id = 'DCOILBRENTEU'; Name = 'Crude Oil Brent'; Class = 'commodity'; Unit = 'USD per barrel'; Currency = 'USD' }
            @{ Id = 'DHHNGSP'; Name = 'Natural Gas Henry Hub'; Class = 'commodity'; Unit = 'USD per MMBtu'; Currency = 'USD' }
        )) {
        $instrumentParameters = @{
            InstrumentId = "fred-$($series.Id.ToLowerInvariant())"
            Symbol = $series.Id
            ProviderSymbol = $series.Id
            DisplayName = $series.Name
            AssetClass = $series.Class
            Unit = $series.Unit
            SourceIds = @('fred')
        }
        if ($series.Currency) { $instrumentParameters.QuoteCurrency = $series.Currency }
        New-Instrument @instrumentParameters
    }
}

function New-HistoricalDashboardInstrument {
    [CmdletBinding()]
    param(
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$InstrumentId = 'eur-usd'
    )

    $instrument = @(Get-HistoricalDashboardInstruments | Where-Object instrumentId -eq $InstrumentId)[0]
    if (-not $instrument) {
        throw "Historical instrument '$InstrumentId' is not in the dashboard catalogue."
    }
    $instrument
}

function Get-HistoricalDashboardSourceLabel {
    param([string]$SourceId)
    switch ($SourceId) {
        'ecb-reference-rates' { 'ECB' }
        'fred' { 'FRED' }
        default { $SourceId }
    }
}

function Test-HistoricalDashboardSourceEligible {
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$SourceRegister,

        [Parameter(Mandatory)]
        [string]$SourceId
    )

    $sources = @($SourceRegister.sources | Where-Object sourceId -eq $SourceId)
    if ($sources.Count -ne 1) { return $false }
    $displayDecision = Get-SourcePolicyDecision -Sources $sources -SourceId $SourceId -Use display
    $persistenceDecision = Get-SourcePolicyDecision -Sources $sources -SourceId $SourceId -Use persistence
    $displayDecision.allowed -and $persistenceDecision.allowed
}

function New-HistoricalDashboardInitialSeries {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Instrument,

        [Parameter(Mandatory)]
        [pscustomobject]$SourceRegister,

        [Parameter(Mandatory)]
        [DateTimeOffset]$NowUtc
    )

    $sourceId = [string]@($Instrument.sourceIds)[0]
    $label = Get-HistoricalDashboardSourceLabel -SourceId $sourceId
    $sources = @($SourceRegister.sources | Where-Object sourceId -eq $sourceId)
    if ($sources.Count -ne 1) {
        throw "Historical chart requires one $label source-register entry."
    }

    $request = [pscustomobject]@{
        range = '1w'
        startUtc = $null
        endUtc = $null
        interval = '1d'
        sourceId = $sourceId
        upstreamSourceIds = @()
        isSupported = $false
        reason = if ($sourceId -eq 'fred') {
            'Select a range and choose Refresh to load FRED daily values (needs a free FRED API key in Settings).'
        }
        else {
            'Select a range and choose Refresh to load approved ECB daily EUR-base rates.'
        }
    }
    if (-not (Test-HistoricalDashboardSourceEligible -SourceRegister $SourceRegister -SourceId $sourceId)) {
        $request.reason = "$label historical data is disabled because display or persistence rights are not approved."
    }

    New-HistoricalSeries -Instrument $Instrument -Source $sources[0] `
        -SourceRegister $SourceRegister -Request $request -NowUtc $NowUtc
}
function New-HistoricalDashboardFixtureSeries {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Instrument,

        [Parameter(Mandatory)]
        [DateTimeOffset]$NowUtc
    )

    $observations = @(
        foreach ($dayOffset in 0..29) {
            $date = $NowUtc.ToUniversalTime().UtcDateTime.Date.AddDays(-29 + $dayOffset)
            New-MarketObservation -InstrumentId $Instrument.instrumentId `
                -SourceId 'offline-market-history-fixture' `
                -ObservedAtUtc ([DateTimeOffset]::new($date, [TimeSpan]::Zero)) `
                -RetrievedAtUtc $NowUtc -Interval '1d' `
                -Value ([decimal](1.08 + [math]::Sin($dayOffset / 5.0) / 100.0)) `
                -Currency USD -Unit $Instrument.unit -Freshness cached
        }
    )
    [pscustomobject][ordered]@{
        instrumentId = $Instrument.instrumentId
        symbol = $Instrument.symbol
        displayName = $Instrument.displayName
        quoteCurrency = $Instrument.quoteCurrency
        unit = $Instrument.unit
        isProxy = $false
        proxyFor = $null
        sourceId = 'offline-market-history-fixture'
        sourceName = 'Offline demo fixture'
        upstreamSourceIds = @()
        upstreamSourceNames = @()
        attribution = 'Synthetic fixture; not ECB rates or market data.'
        range = '1m'
        startUtc = $observations[0].observedAtUtc
        endUtc = $observations[-1].observedAtUtc
        interval = '1d'
        observations = $observations
        gaps = @()
        status = 'cached'
        freshness = 'cached'
        reason = 'Synthetic offline fixture; not market data.'
        retrievedAtUtc = $NowUtc.ToUniversalTime()
        fetchedAtUtc = $NowUtc.ToUniversalTime()
    }
}

function Invoke-HistoricalDashboardRefresh {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Instrument,

        [Parameter(Mandatory)]
        [pscustomobject]$SourceRegister,

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

        [Parameter(Mandatory)]
        [ValidateSet('1d', '1w', '1m', '3m', '6m', '1y', '5y', 'custom')]
        [string]$Range,

        [Parameter(Mandatory)]
        [DateTimeOffset]$NowUtc,

        [Parameter()]
        [DateTimeOffset]$CustomStartUtc = [DateTimeOffset]::MinValue,

        [Parameter()]
        [DateTimeOffset]$CustomEndUtc = [DateTimeOffset]::MinValue,

        [Parameter()]
        [scriptblock]$Transport,

        [Parameter()]
        [AllowNull()]
        [AllowEmptyString()]
        [string]$FredApiKey
    )

    $sourceId = [string]@($Instrument.sourceIds)[0]
    $sources = @($SourceRegister.sources | Where-Object sourceId -eq $sourceId)
    if ($sources.Count -ne 1) {
        throw "Historical refresh requires one $(Get-HistoricalDashboardSourceLabel -SourceId $sourceId) source-register entry."
    }
    $capability = if ($sourceId -eq 'fred') {
        Get-FredHistoricalCoverage -Instrument $Instrument -Sources $sources -ApiKey $FredApiKey `
            -RetrievedAtUtc $NowUtc -Transport $Transport
    }
    else {
        Get-EcbHistoricalCoverage -Instrument $Instrument -Sources $sources `
            -RetrievedAtUtc $NowUtc -Transport $Transport
    }

    $asOfUtc = $NowUtc.ToUniversalTime()
    if ($capability.IsSupported -and $asOfUtc -gt $capability.HistoryEndUtc) {
        $asOfUtc = $capability.HistoryEndUtc
    }
    $requestParameters = @{
        Capability = $capability
        Range = $Range
        Interval = '1d'
        AsOfUtc = $asOfUtc
    }
    if ($Range -eq 'custom') {
        $requestParameters.CustomStartUtc = $CustomStartUtc
        $requestParameters.CustomEndUtc = $CustomEndUtc
    }
    $request = Get-HistoricalRangeRequest @requestParameters
    if ($request.isSupported) {
        $request.startUtc = [DateTimeOffset]::new(
            $request.startUtc.ToUniversalTime().UtcDateTime.Date,
            [TimeSpan]::Zero
        )
        if ($Range -eq 'custom') {
            $request.endUtc = [DateTimeOffset]::new(
                $request.endUtc.ToUniversalTime().UtcDateTime.Date.AddDays(1).AddSeconds(-1),
                [TimeSpan]::Zero
            )
        }
    }
    if (-not $request.isSupported) {
        return New-HistoricalSeries -Instrument $Instrument -Source $sources[0] `
            -SourceRegister $SourceRegister -Request $request -NowUtc $NowUtc
    }

    $store = New-CacheStore -Directory $CacheDirectory
    $ratesCommand = if ($sourceId -eq 'fred') {
        Get-Command Get-FredHistoricalRates -CommandType Function -ErrorAction Stop
    }
    else {
        Get-Command Get-EcbHistoricalRates -CommandType Function -ErrorAction Stop
    }
    $rateArguments = @{
        Instrument = $Instrument
        Capability = $capability
        Sources = $sources
        RetrievedAtUtc = $NowUtc
        Transport = $Transport
    }
    if ($sourceId -eq 'fred') { $rateArguments.ApiKey = $FredApiKey }
    $fetch = {
        param($HistoricalRequest)
        $result = & $ratesCommand @rateArguments -Request $HistoricalRequest
        @($result.records)
    }.GetNewClosure()
    Get-HistoricalSeries -Store $store -Instrument $Instrument `
        -Capability $capability -SourceRegister $SourceRegister `
        -Request $request -Fetch $fetch -NowUtc $NowUtc `
        -CacheTtl ([TimeSpan]::FromHours(24))
}

function New-HistoricalDashboardWorkerScript {
    [CmdletBinding()]
    param()

    {
        param(
            $ModuleRoot,
            $SourceRegisterPath,
            $CacheDirectory,
            $Range,
            $CustomStartUtc,
            $CustomEndUtc,
            $InstrumentId,
            $FredApiKey
        )
        $ErrorActionPreference = 'Stop'
        foreach ($relativePath in @(
                'Private\Domain\SourcePolicy.ps1'
                'Private\Domain\Instrument.ps1'
                'Private\Domain\MarketObservation.ps1'
                'Private\Domain\SourceStatus.ps1'
                'Private\Providers\ProviderAdapter.ps1'
                'Private\Persistence\CacheStore.ps1'
                'Private\Providers\MarketHistoryProvider.ps1'
                'Private\Application\HistoricalSeriesService.ps1'
                'Private\Application\HistoricalDashboard.ps1'
            )) {
            . (Join-Path $ModuleRoot $relativePath)
        }

        $sourceRegister = Import-SourceRightsRegister -Path $SourceRegisterPath
        $instrument = if ($InstrumentId) {
            New-HistoricalDashboardInstrument -InstrumentId $InstrumentId
        }
        else {
            New-HistoricalDashboardInstrument
        }
        Invoke-HistoricalDashboardRefresh -Instrument $instrument `
            -SourceRegister $sourceRegister -CacheDirectory $CacheDirectory `
            -Range $Range -NowUtc ([DateTimeOffset]::UtcNow) `
            -CustomStartUtc $CustomStartUtc -CustomEndUtc $CustomEndUtc -FredApiKey $FredApiKey
    }
}

function New-HistoricalDashboardRefreshState {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$ModuleRoot,

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

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

        [Parameter(Mandatory)]
        [pscustomobject]$SourceRegister,

        [Parameter()]
        [AllowNull()]
        [pscustomobject]$View,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$InstrumentId = 'eur-usd'
    )

    $instrument = New-HistoricalDashboardInstrument -InstrumentId $InstrumentId
    $sourceId = [string]@($instrument.sourceIds)[0]
    $isSourceEligible = Test-HistoricalDashboardSourceEligible -SourceRegister $SourceRegister -SourceId $sourceId
    if ($null -ne $View) {
        $View.RefreshButton.IsEnabled = $isSourceEligible
        $View.CancelButton.IsEnabled = $false
    }

    [pscustomobject]@{
        ModuleRoot = [System.IO.Path]::GetFullPath($ModuleRoot)
        SourceRegisterPath = [System.IO.Path]::GetFullPath($SourceRegisterPath)
        CacheDirectory = [System.IO.Path]::GetFullPath($CacheDirectory)
        SourceRegister = $SourceRegister
        Instrument = $instrument
        InstrumentId = $instrument.instrumentId
        SourceId = $sourceId
        SourceEligible = $isSourceEligible
        View = $View
        WorkerScript = New-HistoricalDashboardWorkerScript
        Coordinator = $null
        Request = $null
    }
}

function Start-HistoricalDashboardRefresh {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$State,

        [Parameter(Mandatory)]
        [ValidateSet('1d', '1w', '1m', '3m', '6m', '1y', '5y', 'custom')]
        [string]$Range,

        [Parameter()]
        [DateTimeOffset]$CustomStartUtc = [DateTimeOffset]::MinValue,

        [Parameter()]
        [DateTimeOffset]$CustomEndUtc = [DateTimeOffset]::MinValue,

        [Parameter()]
        [AllowNull()]
        [AllowEmptyString()]
        [string]$FredApiKey
    )

    $label = Get-HistoricalDashboardSourceLabel -SourceId $State.SourceId
    if (-not $State.SourceEligible) {
        $State.View.StatusText.Text = "Refresh unavailable | $label display/persistence rights are not approved."
        return $false
    }
    if ($State.SourceId -eq 'fred' -and [string]::IsNullOrWhiteSpace($FredApiKey)) {
        $State.View.StatusText.Text = 'Refresh unavailable | Enter a free FRED API key in Settings to load this history.'
        $State.View.StatusText.ToolTip = $State.View.StatusText.Text
        return $false
    }
    if ($null -ne $State.Request) {
        $State.View.StatusText.Text = 'A historical refresh is already running.'
        return $false
    }
    if ($Range -eq 'custom' -and (
            $CustomStartUtc -eq [DateTimeOffset]::MinValue -or
            $CustomEndUtc -eq [DateTimeOffset]::MinValue -or
            $CustomStartUtc -ge $CustomEndUtc
        )) {
        $State.View.StatusText.Text = 'Choose a custom start date earlier than its end date.'
        return $false
    }

    if ($null -eq $State.Coordinator) {
        $State.Coordinator = New-RefreshCoordinator -MaxConcurrency 1 `
            -MinimumSourceIntervalMilliseconds 5000
    }
    $rangeKey = if ($Range -eq 'custom') {
        '{0}:{1}:{2}' -f $Range, $CustomStartUtc.UtcDateTime.Ticks, $CustomEndUtc.UtcDateTime.Ticks
    }
    else {
        $Range
    }
    try {
        $State.Request = Start-RefreshRequest -Coordinator $State.Coordinator `
            -Key "historical:$($State.SourceId):$($State.InstrumentId):$rangeKey" -SourceId $State.SourceId `
            -WorkerScript $State.WorkerScript -ArgumentList @(
                $State.ModuleRoot
                $State.SourceRegisterPath
                $State.CacheDirectory
                $Range
                $CustomStartUtc
                $CustomEndUtc
                $State.InstrumentId
                $(if ($State.SourceId -eq 'fred') { $FredApiKey } else { $null })
            )
        $State.View.RefreshButton.IsEnabled = $false
        $State.View.CancelButton.IsEnabled = $true
        $State.View.StatusText.Text = "Refreshing delayed daily $label data for $($State.Instrument.symbol)..."
        $State.View.StatusText.ToolTip = $State.View.StatusText.Text
        return $true
    }
    catch [System.Management.Automation.RuntimeException], [System.InvalidOperationException] {
        $message = ConvertTo-SanitizedDiagnosticText -Text $_.Exception.Message
        $State.View.StatusText.Text = "Refresh unavailable | $message"
        $State.View.StatusText.ToolTip = $State.View.StatusText.Text
        return $false
    }
}

function Set-HistoricalDashboardInstrument {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$State,

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

        [Parameter()]
        [DateTimeOffset]$NowUtc = [DateTimeOffset]::UtcNow
    )

    if ($InstrumentId -eq $State.InstrumentId) { return $false }
    if ($null -ne $State.Request) {
        $State.View.StatusText.Text = 'Wait for the current historical refresh to finish before switching instruments.'
        return $false
    }
    $instrument = New-HistoricalDashboardInstrument -InstrumentId $InstrumentId
    $State.Instrument = $instrument
    $State.InstrumentId = $instrument.instrumentId
    $State.SourceId = [string]@($instrument.sourceIds)[0]
    $State.SourceEligible = Test-HistoricalDashboardSourceEligible -SourceRegister $State.SourceRegister `
        -SourceId $State.SourceId
    if ($null -ne $State.View) {
        Set-HistoricalChartSeries -View $State.View -Series (New-HistoricalDashboardInitialSeries `
                -Instrument $instrument -SourceRegister $State.SourceRegister -NowUtc $NowUtc)
        $State.View.RefreshButton.IsEnabled = $State.SourceEligible
        $State.View.CancelButton.IsEnabled = $false
    }
    $true
}

function Cancel-HistoricalDashboardRefresh {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$State
    )

    if ($null -ne $State.Request) {
        Stop-RefreshRequest -Request $State.Request
        $State.View.StatusText.Text = 'Cancelling historical refresh...'
    }
}

function Complete-HistoricalDashboardRefresh {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$State
    )

    if ($null -eq $State.Request -or -not $State.Request.AsyncResult.IsCompleted) {
        return $false
    }

    try {
        $completion = Receive-RefreshRequest -Request $State.Request
        if ($completion.status -eq 'completed') {
            Set-HistoricalChartSeries -View $State.View -Series $completion.result
        }
        elseif ($completion.status -eq 'cancelled') {
            $State.View.StatusText.Text = 'Refresh cancelled.'
            $State.View.StatusText.ToolTip = $State.View.StatusText.Text
        }
        else {
            $State.View.StatusText.Text = "Refresh $($completion.status)."
            $State.View.StatusText.ToolTip = $State.View.StatusText.Text
        }
    }
    catch [System.Management.Automation.RuntimeException], [System.InvalidOperationException] {
        $message = ConvertTo-SanitizedDiagnosticText -Text $_.Exception.Message
        if (@($State.View.Series.observations).Count -gt 0) {
            $fetchedAt = if ($State.View.Series.fetchedAtUtc) {
                ([DateTimeOffset]$State.View.Series.fetchedAtUtc).ToUniversalTime().ToString('yyyy-MM-dd HH:mm UTC')
            }
            else {
                'unknown time'
            }
            $State.View.StatusText.Text = "Refresh failed | Previous data remains visible; last loaded $fetchedAt. $message"
        }
        else {
            $State.View.StatusText.Text = "Unavailable | Refresh failed. $message"
        }
        $State.View.StatusText.ToolTip = $State.View.StatusText.Text
    }
    finally {
        $State.Request = $null
        $State.View.RefreshButton.IsEnabled = $State.SourceEligible
        $State.View.CancelButton.IsEnabled = $false
    }
    $true
}