Private/Domain/Instrument.ps1

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

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

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$ProviderSymbol,

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

        [Parameter(Mandatory)]
        [ValidateSet('forex', 'crypto', 'commodity', 'index', 'equity')]
        [string]$AssetClass,

        [Parameter()]
        [ValidatePattern('^[A-Za-z]{3}$')]
        [string]$QuoteCurrency,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Unit,

        [Parameter()]
        [switch]$IsProxy,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$ProxyFor,

        [Parameter(Mandatory)]
        [ValidateCount(1, 1000)]
        [string[]]$SourceIds
    )

    if ($AssetClass -in @('forex', 'equity') -and [string]::IsNullOrWhiteSpace($QuoteCurrency)) {
        throw "Asset class '$AssetClass' requires a quote currency."
    }

    if ($AssetClass -in @('commodity', 'index') -and [string]::IsNullOrWhiteSpace($Unit)) {
        throw "Asset class '$AssetClass' requires a unit."
    }

    if ($AssetClass -eq 'crypto' -and
        [string]::IsNullOrWhiteSpace($QuoteCurrency) -and
        [string]::IsNullOrWhiteSpace($Unit)) {
        throw 'A cryptocurrency instrument requires a quote currency or unit.'
    }

    if ($IsProxy.IsPresent -and [string]::IsNullOrWhiteSpace($ProxyFor)) {
        throw 'A proxy instrument must identify the underlying instrument.'
    }

    if (-not $IsProxy.IsPresent -and -not [string]::IsNullOrWhiteSpace($ProxyFor)) {
        throw 'ProxyFor may only be set for a proxy instrument.'
    }

    if ($IsProxy.IsPresent -and $ProxyFor -eq $InstrumentId) {
        throw 'A proxy instrument cannot identify itself as the underlying instrument.'
    }

    $normalizedSourceIds = @($SourceIds | ForEach-Object {
        if ([string]::IsNullOrWhiteSpace($_)) {
            throw 'Source IDs cannot be empty.'
        }

        $_
    } | Select-Object -Unique)

    if ($normalizedSourceIds.Count -ne $SourceIds.Count) {
        throw 'Source IDs must be unique.'
    }

    [pscustomobject][ordered]@{
        instrumentId  = $InstrumentId
        symbol        = $Symbol
        providerSymbol = if ([string]::IsNullOrWhiteSpace($ProviderSymbol)) { $Symbol } else { $ProviderSymbol }
        displayName   = $DisplayName
        assetClass    = $AssetClass
        quoteCurrency = if ([string]::IsNullOrWhiteSpace($QuoteCurrency)) { $null } else { $QuoteCurrency.ToUpperInvariant() }
        unit          = $Unit
        isProxy       = $IsProxy.IsPresent
        proxyFor      = $ProxyFor
        sourceIds     = $normalizedSourceIds
    }
}