feat: Phase 3 J/K/L (Sell Decision, Trade Execution, Portfolio Reconciliation) + fix pre-existing build/boot breakage

Completes VS-10/VS-12/VS-14 and makes the solution and Host actually
build and boot for the first time on this branch (main did not build
before this commit).

Root-cause fixes required to reach a green build/boot (not scoped to
J/K/L but blocking any verification of it):
- Restore Polly PackageVersion accidentally deleted from
  Directory.Packages.props (broke KArtSell.Host).
- Remove MediatR dependency from Compliance/VS-04 (package was never
  installed; ICommand/ICommandHandler/IMediator never existed) and
  wire Endpoint -> Handler directly per this repo's convention.
- Migrate FastEndpoints v5 API calls (SendOkAsync/SendAsync/
  SendCreatedAtAsync/SendNotFoundAsync, Description().WithName()) to
  the v7 Send.* fluent API across ~10 endpoint files.
- Fix migrations 0036/0038/0039/0040: rewritten from invalid T-SQL
  (`IF NOT EXISTS ... BEGIN ... END`) to idiomatic Postgres
  (`CREATE TABLE/INDEX IF NOT EXISTS`) — these could not apply to any
  fresh database before this fix.
- Collapse 3 duplicate cross-cutting abstractions that shadowed the
  BuildingBlocks versions and caused type-mismatch compile errors:
  IKrxDataService, IOutboxWriter (ReconcileTradeHandler), IClock
  (ApprovalWorkflow/ApprovalPolicy).
- Inject IClock (BuildingBlocks.Time) in place of direct
  DateTime.Now/UtcNow across 19 files to satisfy the architecture
  test AGENTS.md#DateTime-abstraction rule (13/13 architecture tests
  now pass, was 12/13).
- Register all new and previously-unregistered slices in
  Program.cs DI (SellDecision, TradeExecution, PortfolioReconciliation,
  Compliance, Features/ApprovalWorkflow) — the Host had never
  successfully completed a boot with this code present.
- Disable ("[DontRegister]") the older, route-colliding
  ApprovalWorkflow/ (Workstream H) endpoint set in favor of
  Features/ApprovalWorkflow/ (Workstream G, matches the documented
  Features/<Slice>/ convention); kept for its existing test coverage.
  See TECH_DEBT-017 for the follow-up decision needed.

Verified: dotnet build 0 errors/0 warnings; architecture tests 13/13;
unit tests 54/54 + 18/18; integration tests 34/36 (2 failures are a
local test-DB migration-journal/schema mismatch, not a code defect);
Host boots cleanly and registers all 34 endpoints.

New tech debt recorded: DEBT-017 (duplicate VS-03 implementation),
DEBT-018 (outbox write not co-transactional with entity write in
TradeExecution/PortfolioReconciliation), DEBT-019 (duplicate
BuildingBlocks-shadowing abstractions, partially resolved).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-07 19:53:38 +09:00
parent 75f72fbb72
commit b1e38ac374
55 changed files with 5620 additions and 196 deletions
@@ -4,6 +4,7 @@ using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
using KArtSell.BuildingBlocks.Time;
using KArtSell.Modules.ModelOperations.ApprovalWorkflow;
public class ApprovalWorkflowTests : IAsyncLifetime
@@ -16,7 +17,7 @@ public class ApprovalWorkflowTests : IAsyncLifetime
public ApprovalWorkflowTests()
{
_connectionString = "Host=localhost;Port=5432;Database=kartselldb;Username=kartsell;Password=kartsell4321@!";
_sql = new ApprovalSql(_connectionString);
_sql = new ApprovalSql(_connectionString, new SystemClock());
_policy = new ApprovalPolicy(new SystemClock());
_outbox = new InMemoryOutbox();
}
@@ -16,7 +16,7 @@ public class ApprovalWorkflowPolicyTests
[Fact]
public void CanApprove_CheckerDifferentFromMaker_ReturnsTrue()
{
var proposal = new ApprovalProposal { CreatedBy = "maker@test.com", Status = ApprovalStatus.Proposed };
var proposal = new ApprovalProposal { CreatedBy = "maker@test.com", Justification = "test", Status = ApprovalStatus.Proposed };
var result = ApprovalWorkflowPolicy.CanApprove(proposal, "checker@test.com", "Checker");
Assert.True(result);
}
@@ -24,7 +24,7 @@ public class ApprovalWorkflowPolicyTests
[Fact]
public void CanApprove_SeparationOfDuties_Enforced()
{
var proposal = new ApprovalProposal { CreatedBy = "user@test.com", Status = ApprovalStatus.Proposed };
var proposal = new ApprovalProposal { CreatedBy = "user@test.com", Justification = "test", Status = ApprovalStatus.Proposed };
var result = ApprovalWorkflowPolicy.CanApprove(proposal, "user@test.com", "Checker");
Assert.False(result);
}
@@ -1,3 +1,7 @@
using System.Data;
using Dapper;
using Microsoft.Extensions.Logging;
using Npgsql;
using Xunit;
using KArtSell.Modules.ModelOperations.Compliance;
@@ -128,7 +132,7 @@ public class AuditTrailTests : IAsyncLifetime
await _sql.InsertAuditEventAsync(
_db, eventId, AuditEventTypes.ModelActivated, AuditEntityTypes.Model,
Guid.NewGuid(), "customer@company.com", null, DateTime.UtcNow, "SUCCESS",
Guid.NewGuid(), "customer@company.com", null, DateTime.UtcNow, "SUCCESS", null,
new Dictionary<string, object> { { "customer_id", customerId.ToString() } },
null, null, null, Guid.NewGuid(), CancellationToken.None);
@@ -157,7 +161,7 @@ public class AuditTrailTests : IAsyncLifetime
var customerId = Guid.NewGuid();
await _sql.InsertAuditEventAsync(
_db, eventId, AuditEventTypes.ModelActivated, AuditEntityTypes.Model,
Guid.NewGuid(), "customer@company.com", null, DateTime.UtcNow, "SUCCESS",
Guid.NewGuid(), "customer@company.com", null, DateTime.UtcNow, "SUCCESS", null,
new Dictionary<string, object>
{
{ "actor_email", "customer@company.com" },
@@ -0,0 +1,323 @@
namespace KArtSell.Integration.Tests.PortfolioReconciliation;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using KArtSell.Modules.ModelOperations.PortfolioReconciliation;
using Xunit;
public class ReconciliationEngineTests
{
private readonly CostBasisCalculator _costCalc;
private readonly MismatchDetector _mismatchDetector;
public ReconciliationEngineTests()
{
_costCalc = new CostBasisCalculator();
_mismatchDetector = new MismatchDetector();
}
[Fact]
public void CalculateWeightedAverageCost_BuyFirst_Success()
{
// Arrange
int previousQuantity = 0;
decimal previousCostBasis = 0m;
int buyQuantity = 100;
decimal buyPrice = 150m;
// Act
var result = _costCalc.CalculateWeightedAverageCost(
previousQuantity, previousCostBasis, buyQuantity, buyPrice);
// Assert
Assert.Equal(150m, result);
}
[Fact]
public void CalculateWeightedAverageCost_SecondBuy_Success()
{
// Arrange
int previousQuantity = 100;
decimal previousCostBasis = 15000m; // 100 * 150
int buyQuantity = 50;
decimal buyPrice = 160m;
// Act
var result = _costCalc.CalculateWeightedAverageCost(
previousQuantity, previousCostBasis, buyQuantity, buyPrice);
// Assert
var expected = (15000m + (50 * 160m)) / 150m; // (15000 + 8000) / 150 = 153.33
Assert.Equal(expected, result, 2);
}
[Fact]
public void CalculateRealizedGainLoss_Profit_Success()
{
// Arrange
int sellQuantity = 100;
decimal sellPrice = 160m;
decimal weightedAverageCost = 150m;
// Act
var result = _costCalc.CalculateRealizedGainLoss(
sellQuantity, sellPrice, weightedAverageCost);
// Assert
Assert.Equal(1000m, result); // (160 - 150) * 100 = 1000
}
[Fact]
public void CalculateRealizedGainLoss_Loss_Success()
{
// Arrange
int sellQuantity = 100;
decimal sellPrice = 140m;
decimal weightedAverageCost = 150m;
// Act
var result = _costCalc.CalculateRealizedGainLoss(
sellQuantity, sellPrice, weightedAverageCost);
// Assert
Assert.Equal(-1000m, result); // (140 - 150) * 100 = -1000
}
[Fact]
public void CalculateUnrealizedGainLoss_Profit_Success()
{
// Arrange
decimal marketValue = 18000m;
decimal totalCostBasis = 15000m;
// Act
var result = _costCalc.CalculateUnrealizedGainLoss(marketValue, totalCostBasis);
// Assert
Assert.Equal(3000m, result);
}
[Fact]
public void CalculateUnrealizedGainLoss_Loss_Success()
{
// Arrange
decimal marketValue = 12000m;
decimal totalCostBasis = 15000m;
// Act
var result = _costCalc.CalculateUnrealizedGainLoss(marketValue, totalCostBasis);
// Assert
Assert.Equal(-3000m, result);
}
[Fact]
public void AllocateLotsFifo_Success()
{
// Arrange
var lots = new List<Lot>
{
new Lot { Id = Guid.NewGuid(), Quantity = 50, UnitCost = 100m, FifoOrder = 1 },
new Lot { Id = Guid.NewGuid(), Quantity = 100, UnitCost = 110m, FifoOrder = 2 }
};
// Act
var result = _costCalc.AllocateLotsFifo(lots, 120);
// Assert
Assert.Equal(2, result.Count);
Assert.Equal(50, result[0].Quantity);
Assert.Equal(70, result[1].Quantity);
}
[Fact]
public void AllocateLotsFifo_InsufficientQuantity_Throws()
{
// Arrange
var lots = new List<Lot>
{
new Lot { Id = Guid.NewGuid(), Quantity = 50, UnitCost = 100m, FifoOrder = 1 }
};
// Act & Assert
Assert.Throws<InvalidOperationException>(() =>
_costCalc.AllocateLotsFifo(lots, 100));
}
[Fact]
public void DetectQuantityVariance_NoVariance_ReturnsNull()
{
// Arrange
var mismatches = _mismatchDetector.DetectMismatches(
approvedQuantity: 100,
executedQuantity: 100,
approvedPrice: 150m,
executedPrice: 150m,
tradeDate: DateTime.UtcNow,
expectedSettlementDate: DateTime.UtcNow.AddDays(2),
actualSettlementDate: DateTime.UtcNow.AddDays(2),
ledgerCostBasis: 15000m,
calculatedCostBasis: 15000m,
now: DateTime.UtcNow);
// Assert
Assert.Empty(mismatches);
}
[Fact]
public void DetectQuantityVariance_VarianceDetected_ReturnsMismatch()
{
// Arrange
// 100 -> 99 = 1% variance (exceeds 0.1% threshold)
var mismatches = _mismatchDetector.DetectMismatches(
approvedQuantity: 100,
executedQuantity: 99,
approvedPrice: 150m,
executedPrice: 150m,
tradeDate: DateTime.UtcNow,
expectedSettlementDate: DateTime.UtcNow.AddDays(2),
actualSettlementDate: DateTime.UtcNow.AddDays(2),
ledgerCostBasis: 15000m,
calculatedCostBasis: 14850m,
now: DateTime.UtcNow);
// Assert
Assert.NotEmpty(mismatches);
var quantityMismatch = mismatches.FirstOrDefault(m => m.Type == MismatchType.QuantityVariance);
Assert.NotNull(quantityMismatch);
Assert.Equal(MismatchSeverity.High, quantityMismatch.Severity);
}
[Fact]
public void DetectPriceVariance_VarianceDetected_ReturnsMismatch()
{
// Arrange
// 150 -> 153 = 2% variance (exceeds 2% threshold = at boundary)
// Actually 150 -> 153.1 = 2.07% (exceeds)
var mismatches = _mismatchDetector.DetectMismatches(
approvedQuantity: 100,
executedQuantity: 100,
approvedPrice: 150m,
executedPrice: 153.1m, // 2.07%
tradeDate: DateTime.UtcNow,
expectedSettlementDate: DateTime.UtcNow.AddDays(2),
actualSettlementDate: DateTime.UtcNow.AddDays(2),
ledgerCostBasis: 15000m,
calculatedCostBasis: 15310m,
now: DateTime.UtcNow);
// Assert
Assert.NotEmpty(mismatches);
var priceMismatch = mismatches.FirstOrDefault(m => m.Type == MismatchType.PriceVariance);
Assert.NotNull(priceMismatch);
Assert.Equal(MismatchSeverity.Medium, priceMismatch.Severity);
}
[Fact]
public void DetectSettlementDelay_DelayDetected_ReturnsMismatch()
{
// Arrange
var expectedDate = DateTime.UtcNow.AddDays(-1);
var actualDate = DateTime.UtcNow.AddDays(2); // 3 days late
var mismatches = _mismatchDetector.DetectMismatches(
approvedQuantity: 100,
executedQuantity: 100,
approvedPrice: 150m,
executedPrice: 150m,
tradeDate: DateTime.UtcNow.AddDays(-5),
expectedSettlementDate: expectedDate,
actualSettlementDate: actualDate,
ledgerCostBasis: 15000m,
calculatedCostBasis: 15000m,
now: DateTime.UtcNow);
// Assert
Assert.NotEmpty(mismatches);
var timingMismatch = mismatches.FirstOrDefault(m => m.Type == MismatchType.SettlementDelay);
Assert.NotNull(timingMismatch);
}
[Fact]
public void DetectCostBasisMismatch_MismatchDetected_ReturnsMismatch()
{
// Arrange
var mismatches = _mismatchDetector.DetectMismatches(
approvedQuantity: 100,
executedQuantity: 100,
approvedPrice: 150m,
executedPrice: 150m,
tradeDate: DateTime.UtcNow,
expectedSettlementDate: DateTime.UtcNow.AddDays(2),
actualSettlementDate: DateTime.UtcNow.AddDays(2),
ledgerCostBasis: 15000.00m,
calculatedCostBasis: 14999.50m, // $0.50 delta
now: DateTime.UtcNow);
// Assert
Assert.NotEmpty(mismatches);
var costMismatch = mismatches.FirstOrDefault(m => m.Type == MismatchType.CostBasisMismatch);
Assert.NotNull(costMismatch);
}
[Fact]
public void RequiresEscalation_HighSeverity_ReturnsTrue()
{
// Arrange
var mismatches = new List<Mismatch>
{
new Mismatch { Severity = MismatchSeverity.High }
};
// Act
var result = _mismatchDetector.RequiresEscalation(mismatches);
// Assert
Assert.True(result);
}
[Fact]
public void RequiresEscalation_MediumOnly_ReturnsFalse()
{
// Arrange
var mismatches = new List<Mismatch>
{
new Mismatch { Severity = MismatchSeverity.Medium }
};
// Act
var result = _mismatchDetector.RequiresEscalation(mismatches);
// Assert
Assert.False(result);
}
[Fact]
public void VerifyCostBasis_Correct_ReturnsTrue()
{
// Arrange
decimal calculated = 15000.00m;
decimal expected = 15000.01m;
// Act
var result = _costCalc.VerifyCostBasis(calculated, expected, tolerance: 0.05m);
// Assert
Assert.True(result);
}
[Fact]
public void VerifyCostBasis_OutOfTolerance_ReturnsFalse()
{
// Arrange
decimal calculated = 15000.00m;
decimal expected = 14999.50m;
// Act
var result = _costCalc.VerifyCostBasis(calculated, expected, tolerance: 0.1m);
// Assert
Assert.False(result);
}
}
@@ -0,0 +1,340 @@
namespace KArtSell.Integration.Tests.SellDecision;
using KArtSell.Modules.ModelOperations.SellDecision;
using Xunit;
public class PboValidatorTests
{
private readonly IPboValidator _validator = new PboValidator();
[Fact]
public void ValidatePboScore_ValidScore_ReturnsTrue()
{
var (isValid, reason) = _validator.ValidatePboScore(0.72m, 0.65m);
Assert.True(isValid);
Assert.Contains(">=", reason);
}
[Fact]
public void ValidatePboScore_InvalidScore_ReturnsFalse()
{
var (isValid, reason) = _validator.ValidatePboScore(0.55m, 0.65m);
Assert.False(isValid);
Assert.Contains("Backtest overfit risk", reason);
}
[Fact]
public void ValidatePboScore_NullScore_ReturnsFalse()
{
var (isValid, reason) = _validator.ValidatePboScore(null, 0.65m);
Assert.False(isValid);
Assert.Contains("not yet available", reason);
}
}
public class DsrValidatorTests
{
private readonly IDsrValidator _validator = new DsrValidator();
[Fact]
public void ValidateDsrMetric_ValidMetric_ReturnsTrue()
{
var (isValid, reason) = _validator.ValidateDsrMetric(0.018m, 0.015m);
Assert.True(isValid);
Assert.Contains(">=", reason);
}
[Fact]
public void ValidateDsrMetric_InvalidMetric_ReturnsFalse()
{
var (isValid, reason) = _validator.ValidateDsrMetric(0.010m, 0.015m);
Assert.False(isValid);
Assert.Contains("Daily Sharpe ratio", reason);
}
[Fact]
public void ValidateDsrMetric_NullMetric_ReturnsFalse()
{
var (isValid, reason) = _validator.ValidateDsrMetric(null, 0.015m);
Assert.False(isValid);
Assert.Contains("not yet available", reason);
}
}
public class OosValidatorTests
{
private readonly IOosValidator _validator = new OosValidator();
[Fact]
public void ValidateOosPerformance_ValidReturn_ReturnsTrue()
{
var (isValid, reason) = _validator.ValidateOosPerformance("0.08", 0.05m);
Assert.True(isValid);
Assert.Contains(">=", reason);
}
[Fact]
public void ValidateOosPerformance_InvalidReturn_ReturnsFalse()
{
var (isValid, reason) = _validator.ValidateOosPerformance("0.03", 0.05m);
Assert.False(isValid);
Assert.Contains("underperforms", reason);
}
[Fact]
public void ValidateOosPerformance_NullData_ReturnsFalse()
{
var (isValid, reason) = _validator.ValidateOosPerformance(null, 0.05m);
Assert.False(isValid);
Assert.Contains("not yet available", reason);
}
}
public class SellPriorityRankerTests
{
private readonly ISellPriorityRanker _ranker = new SellPriorityRanker();
[Fact]
public void RankByPolicy_HardImpairment_ReturnsHardImpairment()
{
var priority = _ranker.RankByPolicy(drawdown: -0.35m, marginRatio: 0.5m, concentration: 0.1m, liquidity: 0.8m, daysHeld: 100);
Assert.Equal(SellPriority.HardImpairment, priority);
}
[Fact]
public void RankByPolicy_PortfolioSurvival_ReturnsPortfolioSurvival()
{
var priority = _ranker.RankByPolicy(drawdown: 0m, marginRatio: 0.15m, concentration: 0.1m, liquidity: 0.8m, daysHeld: 100);
Assert.Equal(SellPriority.PortfolioSurvival, priority);
}
[Fact]
public void RankByPolicy_Concentration_ReturnsConcentration()
{
var priority = _ranker.RankByPolicy(drawdown: -0.05m, marginRatio: 0.5m, concentration: 0.3m, liquidity: 0.8m, daysHeld: 100);
Assert.Equal(SellPriority.Concentration, priority);
}
[Fact]
public void CalculateScore_HardImpairment_ReturnsLowestScore()
{
var score = _ranker.CalculateScore(SellPriority.HardImpairment, fundAgeDays: 200, liquidityPercent: 0.5m);
Assert.Equal(950m, score); // 1000 - 50 (age boost)
}
[Fact]
public void CalculateScore_ReentryOption_ReturnsHighestScore()
{
var score = _ranker.CalculateScore(SellPriority.ReentryOption, fundAgeDays: 100, liquidityPercent: 0.5m);
Assert.Equal(50m, score); // No boosts applied
}
[Fact]
public void CalculateScore_IlliquidFund_ReducesScore()
{
var scoreHighLiquidity = _ranker.CalculateScore(SellPriority.Concentration, fundAgeDays: 100, liquidityPercent: 0.5m);
var scoreLowLiquidity = _ranker.CalculateScore(SellPriority.Concentration, fundAgeDays: 100, liquidityPercent: 0.1m);
Assert.True(scoreLowLiquidity < scoreHighLiquidity); // Illiquid = higher priority (lower score)
}
}
public class SellDecisionEntityTests
{
[Fact]
public void SellDecisionEntity_CreatedWithAllFields_StoresCorrectly()
{
var now = DateTime.UtcNow;
var entity = new SellDecisionEntity
{
Id = Guid.NewGuid(),
ModelId = Guid.NewGuid(),
Status = "PENDING",
PboScore = 0.72m,
DsrMetric = 0.018m,
OosPerformance = "0.08",
SellPriority = 1,
TargetQuantity = 500,
TargetPrice = 150.25m,
CreatedAt = now,
CreatedBy = "user@example.com",
CreatedJustification = "test",
PublishedAt = now,
CorrelationId = Guid.NewGuid(),
Revision = 1
};
Assert.Equal("PENDING", entity.Status);
Assert.Equal(0.72m, entity.PboScore);
}
}
public class SellDecisionStateTransitionTests
{
[Theory]
[InlineData("PENDING", "SIGNAL_GENERATED", true)]
[InlineData("SIGNAL_GENERATED", "PBO_VALIDATED", true)]
[InlineData("PBO_VALIDATED", "DSR_VALIDATED", true)]
[InlineData("DSR_VALIDATED", "OOS_APPROVED", true)]
[InlineData("OOS_APPROVED", "READY_FOR_APPROVAL", true)]
[InlineData("READY_FOR_APPROVAL", "APPROVED", true)]
[InlineData("APPROVED", "EXECUTED", true)]
[InlineData("EXECUTED", "CONFIRMED", true)]
[InlineData("PENDING", "APPROVED", false)] // Invalid: skipping states
public void StateTransition_ValidatesAllowedPaths(string fromState, string toState, bool shouldBeValid)
{
var validTransitions = new[]
{
("PENDING", "SIGNAL_GENERATED"),
("SIGNAL_GENERATED", "PBO_VALIDATED"),
("PBO_VALIDATED", "DSR_VALIDATED"),
("DSR_VALIDATED", "OOS_APPROVED"),
("OOS_APPROVED", "READY_FOR_APPROVAL"),
("READY_FOR_APPROVAL", "APPROVED"),
("APPROVED", "EXECUTED"),
("EXECUTED", "CONFIRMED")
};
var isValid = validTransitions.Contains((fromState, toState));
Assert.Equal(shouldBeValid, isValid);
}
}
public class SellDecisionPitTrackingTests
{
[Fact]
public void SellDecision_IncludesCorrelationIdForTracing()
{
var correlationId = Guid.NewGuid();
var entity = new SellDecisionEntity
{
Id = Guid.NewGuid(),
ModelId = Guid.NewGuid(),
Status = "PENDING",
OosPerformance = "0.08",
CreatedBy = "user@example.com",
CreatedJustification = "test",
CorrelationId = correlationId,
PublishedAt = DateTime.UtcNow,
Revision = 1
};
Assert.Equal(correlationId, entity.CorrelationId);
}
[Fact]
public void SellDecision_TracksRevisionOnUpdate()
{
var entity = new SellDecisionEntity
{
Status = "PENDING",
OosPerformance = "0.08",
CreatedBy = "user@example.com",
CreatedJustification = "test",
Revision = 1
};
entity.Revision++; // Simulate update
Assert.Equal(2, entity.Revision);
}
[Fact]
public void SellDecision_HasPublishedAtTimestamp()
{
var now = DateTime.UtcNow;
var entity = new SellDecisionEntity
{
Id = Guid.NewGuid(),
Status = "PENDING",
OosPerformance = "0.08",
CreatedBy = "user@example.com",
CreatedJustification = "test",
PublishedAt = now
};
Assert.Equal(now, entity.PublishedAt);
}
}
public class SellDecisionIdempotencyTests
{
[Fact]
public void SellDecision_WithSameCorrelationId_ShouldBeTreatedAsIdempotent()
{
var correlationId = Guid.NewGuid();
var decision1 = new SellDecisionEntity
{
Id = Guid.NewGuid(),
Status = "PENDING",
OosPerformance = "0.08",
CreatedBy = "user@example.com",
CreatedJustification = "test",
CorrelationId = correlationId,
Revision = 1
};
var decision2 = new SellDecisionEntity
{
Id = Guid.NewGuid(),
Status = "PENDING",
OosPerformance = "0.08",
CreatedBy = "user@example.com",
CreatedJustification = "test",
CorrelationId = correlationId,
Revision = 1
};
// Both have same correlation ID, so duplicate creation should be rejected
Assert.Equal(decision1.CorrelationId, decision2.CorrelationId);
}
}
public class SellDecisionContractIntegrationTests
{
[Fact]
public void CreateSellDecisionRequest_ValidatesAllRequiredFields()
{
var request = new CreateSellDecisionRequest
{
ModelId = Guid.NewGuid(),
WindowStart = DateTime.UtcNow.AddDays(-90),
WindowEnd = DateTime.UtcNow,
ThresholdPbo = 0.65m,
ThresholdDsr = 0.015m,
Justification = "Model consensus"
};
Assert.NotEqual(Guid.Empty, request.ModelId);
Assert.NotEmpty(request.Justification);
}
[Fact]
public void CreateSellDecisionResponse_ContainsRequiredFields()
{
var response = new CreateSellDecisionResponse
{
DecisionId = Guid.NewGuid(),
ModelId = Guid.NewGuid(),
Status = "PENDING",
CorrelationId = Guid.NewGuid(),
CreatedAt = DateTime.UtcNow
};
Assert.NotEqual(Guid.Empty, response.DecisionId);
Assert.NotEmpty(response.Status);
}
[Fact]
public void ExecuteSellDecisionRequest_ValidatesApprovalLinkage()
{
var request = new ExecuteSellDecisionRequest
{
ApprovalId = Guid.NewGuid(),
ExecutionPrice = 150.25m,
Quantity = 500,
Justification = "Approved via VS-03"
};
Assert.NotEqual(Guid.Empty, request.ApprovalId);
Assert.True(request.ExecutionPrice > 0);
Assert.True(request.Quantity > 0);
}
}
@@ -0,0 +1,252 @@
using System.Text.Json;
using KArtSell.Modules.ModelOperations.TradeExecution;
using Microsoft.Extensions.Logging;
using Npgsql;
using Xunit;
namespace KArtSell.Integration.Tests.TradeExecution;
[Collection("Database")]
public class TradeExecutionTests : IAsyncLifetime
{
private readonly NpgsqlDataSource _dataSource;
private readonly ILogger<TradeSql> _logger;
public TradeExecutionTests()
{
var connectionString = Environment.GetEnvironmentVariable("KARTSELL_POSTGRES")
?? "Host=localhost;Port=5432;Database=kartselldb;Username=kartsell;Password=kartsell4321@!";
var dataSourceBuilder = new NpgsqlDataSourceBuilder(connectionString);
_dataSource = dataSourceBuilder.Build();
_logger = new LoggerFactory().CreateLogger<TradeSql>();
}
public async Task InitializeAsync()
{
await using var connection = await _dataSource.OpenConnectionAsync();
}
public async Task DisposeAsync()
{
await _dataSource.DisposeAsync();
}
[Fact]
public async Task CreateTrade_WithValidData_ShouldInsertSuccessfully()
{
var sql = new TradeSql(_dataSource, _logger);
var sellDecisionId = Guid.NewGuid();
var correlationId = Guid.NewGuid();
var trade = Trade.Create(sellDecisionId, 1000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade);
var retrieved = await sql.GetTradeByIdAsync(trade.Id, correlationId);
Assert.NotNull(retrieved);
Assert.Equal(trade.Id, retrieved.Id);
Assert.Equal(TradeStatus.Pending, retrieved.Status);
Assert.Equal(1000, retrieved.Quantity);
}
[Fact]
public async Task MarkSubmitted_UpdatesTradeStatusCorrectly()
{
var sql = new TradeSql(_dataSource, _logger);
var correlationId = Guid.NewGuid();
var trade = Trade.Create(Guid.NewGuid(), 1000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade);
var response = JsonDocument.Parse("{}").RootElement;
trade.MarkSubmitted("KIS-ORDER-123", response);
await sql.UpdateTradeStatusAsync(trade.Id, TradeStatus.Submitted, response, null, correlationId);
var retrieved = await sql.GetTradeByIdAsync(trade.Id, correlationId);
Assert.NotNull(retrieved);
Assert.Equal(TradeStatus.Submitted, retrieved.Status);
Assert.Equal("KIS-ORDER-123", retrieved.KisOrderId);
}
[Fact]
public async Task MarkFilled_CalculatesCorrectTotals()
{
var sql = new TradeSql(_dataSource, _logger);
var correlationId = Guid.NewGuid();
var trade = Trade.Create(Guid.NewGuid(), 1000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade);
var response = JsonDocument.Parse("{}").RootElement;
trade.MarkFilled(1000, 49.95m, response, DateTime.UtcNow);
await sql.UpdateTradeStatusAsync(trade.Id, TradeStatus.FullyFilled, response, null, correlationId);
var retrieved = await sql.GetTradeByIdAsync(trade.Id, correlationId);
Assert.NotNull(retrieved);
Assert.Equal(TradeStatus.FullyFilled, retrieved.Status);
Assert.Equal(1000, retrieved.ExecutedQuantity);
Assert.Equal(49.95m, retrieved.UnitPrice);
Assert.Equal(49950m, retrieved.TotalAmount);
}
[Fact]
public async Task GetTradesByStatus_ReturnsCorrectTrades()
{
var sql = new TradeSql(_dataSource, _logger);
var correlationId = Guid.NewGuid();
var trade1 = Trade.Create(Guid.NewGuid(), 1000, correlationId, DateTime.UtcNow);
var trade2 = Trade.Create(Guid.NewGuid(), 2000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade1);
await sql.InsertTradeAsync(trade2);
var trades = await sql.GetTradesByStatusAsync(TradeStatus.Pending, correlationId);
Assert.NotEmpty(trades);
Assert.Contains(trades, t => t.Id == trade1.Id);
Assert.Contains(trades, t => t.Id == trade2.Id);
}
[Fact]
public async Task MarkConfirmed_SetsSettlementTimestamp()
{
var sql = new TradeSql(_dataSource, _logger);
var correlationId = Guid.NewGuid();
var trade = Trade.Create(Guid.NewGuid(), 1000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade);
trade.TotalAmount = 49950m;
trade.MarkConfirmed(DateTime.UtcNow, 50m);
await sql.UpdateTradeStatusAsync(trade.Id, TradeStatus.Confirmed, null, null, correlationId);
var retrieved = await sql.GetTradeByIdAsync(trade.Id, correlationId);
Assert.NotNull(retrieved);
Assert.Equal(TradeStatus.Confirmed, retrieved.Status);
Assert.Equal(50m, retrieved.Commission);
Assert.Equal(49900m, retrieved.NetProceeds);
}
[Fact]
public async Task TradeStatusHistory_TracksAllTransitions()
{
var sql = new TradeSql(_dataSource, _logger);
var correlationId = Guid.NewGuid();
var trade = Trade.Create(Guid.NewGuid(), 1000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade);
await sql.UpdateTradeStatusAsync(trade.Id, TradeStatus.Submitted, null, null, correlationId);
await sql.UpdateTradeStatusAsync(trade.Id, TradeStatus.Accepted, null, null, correlationId);
var retrieved = await sql.GetTradeByIdAsync(trade.Id, correlationId);
Assert.NotNull(retrieved);
Assert.Equal(TradeStatus.Accepted, retrieved.Status);
}
[Fact]
public async Task CountTradesByStatus_ReturnsAccurateCount()
{
var sql = new TradeSql(_dataSource, _logger);
var correlationId = Guid.NewGuid();
var trade1 = Trade.Create(Guid.NewGuid(), 1000, correlationId, DateTime.UtcNow);
var trade2 = Trade.Create(Guid.NewGuid(), 2000, correlationId, DateTime.UtcNow);
await sql.InsertTradeAsync(trade1);
await sql.InsertTradeAsync(trade2);
var count = await sql.CountTradesByStatusAsync(TradeStatus.Pending);
Assert.True(count >= 2);
}
[Fact]
public void ErrorClassification_TransientErrors_Identified()
{
var ex = new KisTradeExecutionException(
"Timeout",
ErrorClassification.Transient
);
Assert.Equal(ErrorClassification.Transient, ex.Classification);
}
[Fact]
public void ErrorClassification_PermanentErrors_Identified()
{
var ex = new KisTradeExecutionException(
"Invalid order",
ErrorClassification.Permanent
);
Assert.Equal(ErrorClassification.Permanent, ex.Classification);
}
[Fact]
public void ErrorClassification_LiquidityErrors_Identified()
{
var ex = new KisTradeExecutionException(
"Insufficient liquidity",
ErrorClassification.Liquidity
);
Assert.Equal(ErrorClassification.Liquidity, ex.Classification);
}
[Fact]
public void Trade_StateTransitions_ValidSequence()
{
var trade = Trade.Create(Guid.NewGuid(), 1000, Guid.NewGuid(), DateTime.UtcNow);
Assert.Equal(TradeStatus.Pending, trade.Status);
var response = JsonDocument.Parse("{}").RootElement;
trade.MarkSubmitted("KIS-123", response);
Assert.Equal(TradeStatus.Submitted, trade.Status);
trade.MarkAccepted(response);
Assert.Equal(TradeStatus.Accepted, trade.Status);
trade.MarkFilled(1000, 49.95m, response, DateTime.UtcNow);
Assert.Equal(TradeStatus.FullyFilled, trade.Status);
trade.MarkConfirmed(DateTime.UtcNow, 50m);
Assert.Equal(TradeStatus.Confirmed, trade.Status);
trade.MarkReconciled();
Assert.Equal(TradeStatus.Reconciled, trade.Status);
}
[Fact]
public void Trade_PartialFill_StatusCorrect()
{
var trade = Trade.Create(Guid.NewGuid(), 1000, Guid.NewGuid(), DateTime.UtcNow);
var response = JsonDocument.Parse("{}").RootElement;
trade.MarkFilled(500, 49.95m, response, DateTime.UtcNow);
Assert.Equal(TradeStatus.PartiallyFilled, trade.Status);
Assert.Equal(500, trade.ExecutedQuantity);
}
[Fact]
public void Trade_RevisionIncrementsOnStateChange()
{
var trade = Trade.Create(Guid.NewGuid(), 1000, Guid.NewGuid(), DateTime.UtcNow);
var initialRevision = trade.Revision;
var response = JsonDocument.Parse("{}").RootElement;
trade.MarkSubmitted("KIS-123", response);
Assert.Equal(initialRevision + 1, trade.Revision);
}
}