param( [Parameter(Mandatory = $true)] [string]$ExpectAccount, [Parameter(Mandatory = $true)] [string]$ExpectInstrument, [string]$LogDirectory = [System.IO.Path]::Combine($env:USERPROFILE, 'Documents', 'NinjaTrader 8', 'log', 'nt8-sdk'), [string]$RepoStrategyBasePath = '', [string]$DeployedStrategyBasePath = [System.IO.Path]::Combine($env:USERPROFILE, 'Documents', 'NinjaTrader 8', 'bin', 'Custom', 'Strategies', 'NT8StrategyBase.cs'), [string]$NtStrategiesDirectory = [System.IO.Path]::Combine($env:USERPROFILE, 'Documents', 'NinjaTrader 8', 'bin', 'Custom', 'Strategies'), [string]$GateDirectory = '', [switch]$Freeze, [switch]$Verify ) Set-StrictMode -Version 2.0 $ErrorActionPreference = 'Stop' $script:AllPassed = $true function Get-ScriptDirectory { $scriptPath = $MyInvocation.ScriptName if ([string]::IsNullOrEmpty($scriptPath)) { $scriptPath = $MyInvocation.MyCommand.Path } if ([string]::IsNullOrEmpty($scriptPath)) { return [System.IO.Directory]::GetCurrentDirectory() } return Split-Path -Parent $scriptPath } $script:ScriptDir = Get-ScriptDirectory $script:RepoRoot = [System.IO.Path]::GetFullPath((Join-Path $script:ScriptDir '..\..')) if ([string]::IsNullOrEmpty($RepoStrategyBasePath)) { $RepoStrategyBasePath = [System.IO.Path]::GetFullPath((Join-Path $script:RepoRoot 'src\NT8.Adapters\Strategies\NT8StrategyBase.cs')) } if ([string]::IsNullOrEmpty($GateDirectory)) { $GateDirectory = [System.IO.Path]::GetFullPath((Join-Path $script:RepoRoot 'docs\gate-runs\gate3')) } function Write-CheckResult { param( [int]$Number, [bool]$Passed, [string]$Title, [string]$Detail, [string]$Remedy ) if ($Passed) { [Console]::WriteLine(('PASS {0}. {1} - {2}' -f $Number, $Title, $Detail)) } else { $script:AllPassed = $false [Console]::WriteLine(('FAIL {0}. {1} - {2}' -f $Number, $Title, $Detail)) [Console]::WriteLine((' Remedy: {0}' -f $Remedy)) } } function Get-SettingsValue { param( [hashtable]$Values, [string]$Key ) if ($Values.ContainsKey($Key)) { return [string]$Values[$Key] } return $null } function Get-SettingsTimestamp { param([System.IO.FileInfo]$File) if ($File.Name -match 'settings_.+_(\d{8})_(\d{6})\.txt$') { return [DateTime]::ParseExact(($matches[1] + '_' + $matches[2]), 'yyyyMMdd_HHmmss', [System.Globalization.CultureInfo]::InvariantCulture) } return $File.LastWriteTime } function Get-SettingsExports { param([string]$DirectoryPath) if (-not (Test-Path -LiteralPath $DirectoryPath -PathType Container)) { return @() } return @(Get-ChildItem -LiteralPath $DirectoryPath -Recurse -File -Filter 'settings_Simple_ORB_NT8_*.txt' | Sort-Object @{ Expression = { Get-SettingsTimestamp -File $_ } }, FullName) } function Get-LatestSettingsExport { param([string]$DirectoryPath) $files = @(Get-SettingsExports -DirectoryPath $DirectoryPath) if ($files.Count -eq 0) { return $null } return $files[$files.Count - 1] } function Parse-SettingsExport { param([string]$FilePath) $values = @{} $lines = Get-Content -LiteralPath $FilePath -ErrorAction Stop foreach ($line in $lines) { if ([string]::IsNullOrWhiteSpace($line)) { continue } if ($line.StartsWith('===') -or $line.StartsWith('---')) { continue } $parts = $line -split '\s*:\s*', 2 if ($parts.Length -ne 2) { continue } $key = $parts[0].Trim() $value = $parts[1].Trim() $values[$key] = $value } return $values } function Convert-SettingsToObject { param([hashtable]$Values) $ordered = New-Object System.Collections.Specialized.OrderedDictionary $keys = @($Values.Keys | Sort-Object) foreach ($key in $keys) { $ordered.Add($key, [string]$Values[$key]) } return $ordered } function Test-RequiredSetting { param( [hashtable]$Values, [string]$Key, [string]$Expected ) $actual = Get-SettingsValue -Values $Values -Key $Key if ($actual -eq $null) { return @{ Passed = $false; Message = ('missing {0}' -f $Key) } } if ($actual -ne $Expected) { return @{ Passed = $false; Message = ('{0}={1} (expected {2})' -f $Key, $actual, $Expected) } } return @{ Passed = $true; Message = ('{0}={1}' -f $Key, $actual) } } function Get-FreeSpaceBytes { param([string]$DirectoryPath) $resolved = Resolve-Path -LiteralPath $DirectoryPath $root = [System.IO.Path]::GetPathRoot($resolved.Path) $drive = New-Object System.IO.DriveInfo($root) return $drive.AvailableFreeSpace } function Invoke-ExternalCapture { param( [string]$Command, [string]$OutputPath, [string]$WorkingDirectory ) $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = 'powershell.exe' $psi.Arguments = '-NoProfile -ExecutionPolicy Bypass -Command "' + $Command.Replace('"', '\"') + '"' $psi.WorkingDirectory = $WorkingDirectory $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true $psi.UseShellExecute = $false $process = [System.Diagnostics.Process]::Start($psi) $stdout = $process.StandardOutput.ReadToEnd() $stderr = $process.StandardError.ReadToEnd() $process.WaitForExit() $content = $stdout if (-not [string]::IsNullOrEmpty($stderr)) { $content += "`r`nSTDERR:`r`n" + $stderr } [System.IO.File]::WriteAllText($OutputPath, $content) return $process.ExitCode } function Get-GitSha { $sha = (& git -C $script:RepoRoot rev-parse HEAD 2>$null) if ($LASTEXITCODE -ne 0) { throw 'git rev-parse HEAD failed' } return [string]$sha } function Get-GitPorcelain { $status = (& git -C $script:RepoRoot status --porcelain 2>$null) if ($LASTEXITCODE -ne 0) { throw 'git status --porcelain failed' } return ,@($status) } function Write-DeployedSourceHashes { param( [string]$DirectoryPath, [string]$TextPath, [string]$JsonPath ) $items = @() $lines = New-Object System.Collections.Generic.List[string] if (Test-Path -LiteralPath $DirectoryPath -PathType Container) { $files = @(Get-ChildItem -LiteralPath $DirectoryPath -Recurse -File -Filter '*.cs' | Sort-Object FullName) foreach ($file in $files) { $hash = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash $relative = $file.FullName.Substring($DirectoryPath.Length).TrimStart('\') $lines.Add(('{0} {1}' -f $hash, $relative)) $items += @{ path = $relative; sha256 = $hash } } } [System.IO.File]::WriteAllLines($TextPath, $lines.ToArray()) ($items | ConvertTo-Json -Depth 5) | Out-File -LiteralPath $JsonPath -Encoding UTF8 return $items } function Copy-PrecedingSettingsExports { param( [System.IO.FileInfo[]]$Exports, [string]$Destination ) if (-not (Test-Path -LiteralPath $Destination)) { New-Item -ItemType Directory -Path $Destination | Out-Null } $selected = @($Exports | Select-Object -Last 3) foreach ($file in $selected) { Copy-Item -LiteralPath $file.FullName -Destination (Join-Path $Destination $file.Name) -Force } return $selected } function Write-DecisionDraft { param( [string]$Path, [string]$CaptureName, [hashtable]$Settings, [string]$ConfigHash, [string]$CodeVersion, [string]$GitSha ) $lines = New-Object System.Collections.Generic.List[string] $lines.Add('# DEC-GATE3-CONFIG') $lines.Add('') $lines.Add('- **ID:** DEC-GATE3-CONFIG') $lines.Add(('- **Date:** {0}' -f (Get-Date -Format 'yyyy-MM-dd'))) $lines.Add('- **Status:** draft') $lines.Add('- **Reason:** GAP-034 is not closed; Gate Run #3 cannot start with an unexplained zero-trade defect.') $lines.Add(('- **Capture:** `{0}`' -f $CaptureName)) $lines.Add(('- **Git Commit:** `{0}`' -f $GitSha)) $lines.Add(('- **ConfigHash:** `{0}`' -f $ConfigHash)) $lines.Add(('- **CodeVersion:** `{0}`' -f $CodeVersion)) $lines.Add('') $lines.Add('## Frozen Parameters') $lines.Add('') $lines.Add('| Parameter | Value |') $lines.Add('|---|---|') foreach ($key in @($Settings.Keys | Sort-Object)) { $lines.Add(('| `{0}` | `{1}` |' -f $key, $Settings[$key])) } [System.IO.File]::WriteAllLines($Path, $lines.ToArray()) } function New-SignificantManifest { param( [string]$CaptureName, [hashtable]$Settings, [string]$ConfigHash, [string]$CodeVersion, [string]$GitSha, [object[]]$DeployedHashes, [bool]$TestsPassed, [bool]$ConfigDiffPassed ) return [ordered]@{ capture = $CaptureName config_hash = $ConfigHash code_version = $CodeVersion git_sha = $GitSha git_status_clean = $true tests_passed = $TestsPassed configdiff_passed = $ConfigDiffPassed settings = Convert-SettingsToObject -Values $Settings deployed_strategy_hashes = $DeployedHashes } } function Write-JsonFile { param( [string]$Path, [object]$Value ) ($Value | ConvertTo-Json -Depth 20) | Out-File -LiteralPath $Path -Encoding UTF8 } function Compare-Manifest { param( [object]$Baseline, [object]$Current ) $baselineComparable = $Baseline | Select-Object -Property * -ExcludeProperty capture $currentComparable = $Current | Select-Object -Property * -ExcludeProperty capture $baselineJson = ($baselineComparable | ConvertTo-Json -Depth 20) $currentJson = ($currentComparable | ConvertTo-Json -Depth 20) if ($baselineJson -eq $currentJson) { return '' } return "BASELINE:`r`n$baselineJson`r`n`r`nCURRENT:`r`n$currentJson" } function Invoke-GateCapture { param([bool]$VerifyMode) $timestamp = Get-Date -Format 'yyyyMMdd_HHmmss' if (-not (Test-Path -LiteralPath $GateDirectory)) { New-Item -ItemType Directory -Path $GateDirectory | Out-Null } $captureName = if ($VerifyMode) { 'verify_' + $timestamp } else { 'freeze_' + $timestamp } $captureDir = Join-Path $GateDirectory $captureName $suffix = 1 while (Test-Path -LiteralPath $captureDir) { $captureName = if ($VerifyMode) { 'verify_' + $timestamp + '_' + $suffix } else { 'freeze_' + $timestamp + '_' + $suffix } $captureDir = Join-Path $GateDirectory $captureName $suffix++ } New-Item -ItemType Directory -Path $captureDir | Out-Null $gitStatus = Get-GitPorcelain [System.IO.File]::WriteAllLines((Join-Path $captureDir 'git-status-porcelain.txt'), $gitStatus) if ($gitStatus.Count -ne 0) { [System.IO.File]::WriteAllText((Join-Path $captureDir 'FREEZE_FAILED.txt'), 'git status --porcelain is not clean. Freeze/verify baseline is invalid until the working tree is clean.') [Console]::WriteLine(('FAIL: git status --porcelain is not clean. Capture written to {0}' -f $captureDir)) return 1 } $gitSha = Get-GitSha [System.IO.File]::WriteAllText((Join-Path $captureDir 'git-commit.txt'), $gitSha) $settingsExports = @(Get-SettingsExports -DirectoryPath $LogDirectory) if ($settingsExports.Count -eq 0) { throw 'No settings_Simple_ORB_NT8_*.txt export found.' } $latestSettings = $settingsExports[$settingsExports.Count - 1] $settingsValues = Parse-SettingsExport -FilePath $latestSettings.FullName Copy-Item -LiteralPath $latestSettings.FullName -Destination (Join-Path $captureDir $latestSettings.Name) -Force $configHash = Get-SettingsValue -Values $settingsValues -Key 'ConfigHash' $codeVersion = Get-SettingsValue -Values $settingsValues -Key 'CodeVersion' [System.IO.File]::WriteAllText((Join-Path $captureDir 'config-hash.txt'), [string]$configHash) [System.IO.File]::WriteAllText((Join-Path $captureDir 'code-version.txt'), [string]$codeVersion) $testOutput = Join-Path $captureDir 'full-test-suite.txt' $testCommand = 'dotnet test NT8-SDK.sln --configuration Release --verbosity minimal' $testExit = Invoke-ExternalCapture -Command $testCommand -OutputPath $testOutput -WorkingDirectory $script:RepoRoot $testsPassed = $testExit -eq 0 $hashTextPath = Join-Path $captureDir 'deployed-strategy-source-hashes.txt' $hashJsonPath = Join-Path $captureDir 'deployed-strategy-source-hashes.json' $deployedHashes = @(Write-DeployedSourceHashes -DirectoryPath $NtStrategiesDirectory -TextPath $hashTextPath -JsonPath $hashJsonPath) $precedingDir = Join-Path $captureDir 'preceding-3-settings' $selectedSettings = @(Copy-PrecedingSettingsExports -Exports $settingsExports -Destination $precedingDir) $configDiffOutput = Join-Path $captureDir 'configdiff-preceding-3-sessions.txt' $configDiffCommand = 'python tools\configdiff\configdiff.py "' + $precedingDir + '"' $configDiffExit = Invoke-ExternalCapture -Command $configDiffCommand -OutputPath $configDiffOutput -WorkingDirectory $script:RepoRoot $configDiffPassed = $configDiffExit -eq 0 $metadata = [ordered]@{ captured_at = (Get-Date).ToString('o') capture = $captureName settings_source = $latestSettings.FullName settings_copied = $latestSettings.Name preceding_settings = @($selectedSettings | ForEach-Object { $_.FullName }) config_hash = $configHash code_version = $codeVersion git_sha = $gitSha tests_exit_code = $testExit configdiff_exit_code = $configDiffExit } Write-JsonFile -Path (Join-Path $captureDir 'capture-metadata.json') -Value $metadata $manifest = New-SignificantManifest -CaptureName $captureName -Settings $settingsValues -ConfigHash $configHash -CodeVersion $codeVersion -GitSha $gitSha -DeployedHashes $deployedHashes -TestsPassed $testsPassed -ConfigDiffPassed $configDiffPassed Write-JsonFile -Path (Join-Path $captureDir 'manifest.json') -Value $manifest if (-not $VerifyMode) { Write-JsonFile -Path (Join-Path $GateDirectory 'baseline.json') -Value $manifest Write-DecisionDraft -Path (Join-Path $GateDirectory 'DEC-GATE3-CONFIG.md') -CaptureName $captureName -Settings $settingsValues -ConfigHash $configHash -CodeVersion $codeVersion -GitSha $gitSha [Console]::WriteLine(('Freeze draft capture written to {0}' -f $captureDir)) } else { $baselinePath = Join-Path $GateDirectory 'baseline.json' if (-not (Test-Path -LiteralPath $baselinePath -PathType Leaf)) { throw 'No baseline.json found. Run -Freeze first.' } $baseline = Get-Content -LiteralPath $baselinePath -Raw | ConvertFrom-Json $diff = Compare-Manifest -Baseline $baseline -Current $manifest if ([string]::IsNullOrEmpty($diff)) { [System.IO.File]::WriteAllText((Join-Path $captureDir 'verify-result.txt'), 'PASS') [Console]::WriteLine(('VERIFY PASS: {0}' -f $captureDir)) } else { [System.IO.File]::WriteAllText((Join-Path $captureDir 'verify-diff.txt'), $diff) [Console]::WriteLine(('VERIFY FAIL: baseline differs. Diff written to {0}' -f (Join-Path $captureDir 'verify-diff.txt'))) return 1 } } if (-not $testsPassed) { [Console]::WriteLine('FAIL: full test suite did not pass.') return 1 } if (-not $configDiffPassed) { [Console]::WriteLine('FAIL: configdiff preceding-3-sessions report detected drift.') return 1 } return 0 } function Invoke-PreflightChecks { [Console]::WriteLine('NT8 SDK preflight') [Console]::WriteLine(('LogDirectory: {0}' -f $LogDirectory)) [Console]::WriteLine(('ExpectAccount: {0}' -f $ExpectAccount)) [Console]::WriteLine(('ExpectInstrument: {0}' -f $ExpectInstrument)) [Console]::WriteLine('') $todayStamp = Get-Date -Format 'yyyyMMdd' $latestSettings = $null $settingsValues = $null try { $ntProcesses = @(Get-Process -Name 'NinjaTrader' -ErrorAction SilentlyContinue) Write-CheckResult -Number 1 -Passed ($ntProcesses.Count -eq 1) -Title 'Exactly one NinjaTrader process running' -Detail ('found {0} NinjaTrader process(es)' -f $ntProcesses.Count) -Remedy 'Close extra NinjaTrader instances or start NinjaTrader so exactly one process is running before enabling the strategy.' $logDirExists = Test-Path -LiteralPath $LogDirectory -PathType Container $logDirWritable = $false $currentDayLogExists = $false $logDetailParts = @() if (-not $logDirExists) { $logDetailParts += 'log directory missing' } else { $probePath = Join-Path $LogDirectory 'preflight_write_test.tmp' try { [System.IO.File]::WriteAllText($probePath, 'ok') Remove-Item -LiteralPath $probePath -Force -ErrorAction SilentlyContinue $logDirWritable = $true } catch { $logDirWritable = $false } $existingSessionLogs = @(Get-ChildItem -LiteralPath $LogDirectory -File -Filter ('session_{0}_*.log' -f $todayStamp) -ErrorAction SilentlyContinue) $currentDayLogExists = $existingSessionLogs.Count -gt 0 $logDetailParts += ('writable={0}' -f $logDirWritable) $logDetailParts += ('current-day session logs={0}' -f $existingSessionLogs.Count) } Write-CheckResult -Number 2 -Passed ($logDirExists -and $logDirWritable -and (-not $currentDayLogExists)) -Title 'Log directory writable and no current-day session log present' -Detail ([string]::Join('; ', $logDetailParts)) -Remedy ('Create/fix permissions on the log directory and archive or remove any existing session_' + $todayStamp + '_*.log before starting a new session.') if ($logDirExists) { $latestSettings = Get-LatestSettingsExport -DirectoryPath $LogDirectory if ($latestSettings -ne $null) { $settingsValues = Parse-SettingsExport -FilePath $latestSettings.FullName } } $requiredChecks = @( @{ Key = 'TestMode'; Expected = 'False' }, @{ Key = 'EnableKillSwitch'; Expected = 'True' }, @{ Key = 'EnableVerboseLogging'; Expected = 'True' }, @{ Key = 'EnableFileLogging'; Expected = 'True' }, @{ Key = 'MinTradeGrade'; Expected = '5' }, @{ Key = 'MaxDailyTrades'; Expected = '1' } ) $settingsPassed = $true $settingsMessages = @() if ($latestSettings -eq $null -or $settingsValues -eq $null) { $settingsPassed = $false $settingsMessages += 'no settings_Simple_ORB_NT8_*.txt export found' } else { foreach ($check in $requiredChecks) { $result = Test-RequiredSetting -Values $settingsValues -Key $check.Key -Expected $check.Expected $settingsMessages += $result.Message if (-not $result.Passed) { $settingsPassed = $false } } } Write-CheckResult -Number 3 -Passed $settingsPassed -Title 'Most recent settings export has required gate values' -Detail ([string]::Join('; ', $settingsMessages)) -Remedy 'Export fresh settings from the intended strategy instance and set TestMode=False, EnableKillSwitch=True, EnableVerboseLogging=True, EnableFileLogging=True, MinTradeGrade=5, and MaxDailyTrades=1 before enabling.' $matchPassed = $true $matchMessages = @() if ($latestSettings -eq $null -or $settingsValues -eq $null) { $matchPassed = $false $matchMessages += 'no settings export available for account/instrument validation' } else { $actualAccount = Get-SettingsValue -Values $settingsValues -Key 'Account' $actualInstrument = Get-SettingsValue -Values $settingsValues -Key 'Instrument' if ($actualAccount -ne $ExpectAccount) { $matchPassed = $false } if ($actualInstrument -ne $ExpectInstrument) { $matchPassed = $false } $matchMessages += ('Account={0} (expected {1})' -f $actualAccount, $ExpectAccount) $matchMessages += ('Instrument={0} (expected {1})' -f $actualInstrument, $ExpectInstrument) } Write-CheckResult -Number 4 -Passed $matchPassed -Title 'Most recent settings export matches expected account and instrument' -Detail ([string]::Join('; ', $matchMessages)) -Remedy 'Load the correct workspace/strategy settings, export them again, and confirm Account and Instrument match the morning run plan before enabling.' $hashPassed = $false $hashDetail = '' if ((Test-Path -LiteralPath $RepoStrategyBasePath -PathType Leaf) -and (Test-Path -LiteralPath $DeployedStrategyBasePath -PathType Leaf)) { $repoHash = (Get-FileHash -LiteralPath $RepoStrategyBasePath -Algorithm SHA256).Hash $deployedHash = (Get-FileHash -LiteralPath $DeployedStrategyBasePath -Algorithm SHA256).Hash $hashPassed = $repoHash -eq $deployedHash $hashDetail = ('repo={0} deployed={1}' -f $repoHash, $deployedHash) } else { $hashDetail = 'repo or deployed NT8StrategyBase.cs missing' } Write-CheckResult -Number 5 -Passed $hashPassed -Title 'Deployed NT8StrategyBase.cs matches repo copy' -Detail $hashDetail -Remedy 'Redeploy NT8StrategyBase.cs from the repo to the NinjaTrader Strategies directory and confirm the deployed source exactly matches the repo copy before enabling.' $spacePassed = $false $spaceDetail = '' if ($logDirExists) { $freeBytes = Get-FreeSpaceBytes -DirectoryPath $LogDirectory $spacePassed = $freeBytes -gt 1GB $spaceDetail = ('free space={0} GB' -f [Math]::Round(($freeBytes / 1GB), 2)) } else { $spaceDetail = 'log directory missing' } Write-CheckResult -Number 6 -Passed $spacePassed -Title 'Disk space greater than 1 GB in log directory drive' -Detail $spaceDetail -Remedy 'Free disk space on the log drive or move the log directory to a drive with more than 1 GB available before enabling the strategy.' } catch { $script:AllPassed = $false [Console]::WriteLine(('FAIL PRECHECK - unexpected error: {0}' -f $_.Exception.Message)) [Console]::WriteLine(' Remedy: Fix the reported error and rerun preflight before enabling the strategy.') } [Console]::WriteLine('') if ($script:AllPassed) { [Console]::WriteLine('OVERALL: PASS') return 0 } [Console]::WriteLine('OVERALL: FAIL') return 1 } if ($Freeze -and $Verify) { [Console]::WriteLine('Use only one mode: -Freeze or -Verify.') exit 2 } if ($Freeze) { exit (Invoke-GateCapture -VerifyMode $false) } if ($Verify) { exit (Invoke-GateCapture -VerifyMode $true) } exit (Invoke-PreflightChecks)