b1e38ac374
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>
363 lines
11 KiB
C#
363 lines
11 KiB
C#
using System.Text.Json;
|
|
using KArtSell.BuildingBlocks.Data;
|
|
using KArtSell.BuildingBlocks.Hashing;
|
|
using KArtSell.BuildingBlocks.Reliability;
|
|
using KArtSell.BuildingBlocks.Time;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace KArtSell.Modules.ModelOperations.TradeExecution;
|
|
|
|
public class SubmitTradeCommand
|
|
{
|
|
public Guid SellDecisionId { get; set; }
|
|
public int Quantity { get; set; }
|
|
public decimal LimitPrice { get; set; }
|
|
public Guid CorrelationId { get; set; }
|
|
}
|
|
|
|
public class SubmitTradeHandler
|
|
{
|
|
private readonly ITradeSql _sql;
|
|
private readonly IKisTradeExecutionService _kis;
|
|
private readonly IDbConnectionFactory _connectionFactory;
|
|
private readonly IOutboxWriter _outbox;
|
|
private readonly IClock _clock;
|
|
private readonly ILogger<SubmitTradeHandler> _logger;
|
|
|
|
public SubmitTradeHandler(
|
|
ITradeSql sql,
|
|
IKisTradeExecutionService kis,
|
|
IDbConnectionFactory connectionFactory,
|
|
IOutboxWriter outbox,
|
|
IClock clock,
|
|
ILogger<SubmitTradeHandler> logger)
|
|
{
|
|
_sql = sql;
|
|
_kis = kis;
|
|
_connectionFactory = connectionFactory;
|
|
_outbox = outbox;
|
|
_clock = clock;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task<Guid> HandleAsync(SubmitTradeCommand command, CancellationToken ct = default)
|
|
{
|
|
var trade = Trade.Create(command.SellDecisionId, command.Quantity, command.CorrelationId, _clock.UtcNow.UtcDateTime);
|
|
await _sql.InsertTradeAsync(trade, ct);
|
|
_logger.LogInformation("Created trade: {TradeId}", trade.Id);
|
|
|
|
try
|
|
{
|
|
var (orderId, response) = await _kis.ExecuteTradeAsync(
|
|
trade.Id,
|
|
command.Quantity,
|
|
command.LimitPrice,
|
|
command.CorrelationId,
|
|
ct
|
|
);
|
|
|
|
trade.MarkSubmitted(orderId, response);
|
|
await _sql.UpdateTradeStatusAsync(
|
|
trade.Id,
|
|
TradeStatus.Submitted,
|
|
response,
|
|
null,
|
|
command.CorrelationId,
|
|
ct
|
|
);
|
|
|
|
await PublishEventAsync(
|
|
"TradeSubmitted",
|
|
new TradeSubmittedEvent
|
|
{
|
|
TradeId = trade.Id,
|
|
SellDecisionId = command.SellDecisionId,
|
|
KisOrderId = orderId,
|
|
Quantity = command.Quantity,
|
|
CorrelationId = command.CorrelationId
|
|
},
|
|
command.CorrelationId,
|
|
ct);
|
|
|
|
return trade.Id;
|
|
}
|
|
catch (KisTradeExecutionException ex)
|
|
{
|
|
trade.MarkErrored(ex);
|
|
await _sql.UpdateTradeStatusAsync(
|
|
trade.Id,
|
|
trade.Status,
|
|
ex.KisResponse,
|
|
ex.Message,
|
|
command.CorrelationId,
|
|
ct
|
|
);
|
|
|
|
_logger.LogError(
|
|
"Trade submission failed: {TradeId} {Classification}",
|
|
trade.Id, ex.Classification
|
|
);
|
|
|
|
throw;
|
|
}
|
|
}
|
|
|
|
private async Task PublishEventAsync<T>(string eventType, T @event, Guid correlationId, CancellationToken ct) where T : class
|
|
=> await TradeOutboxPublisher.PublishAsync(_connectionFactory, _outbox, _clock, eventType, @event, correlationId, ct);
|
|
}
|
|
|
|
public class PollTradeStatusCommand
|
|
{
|
|
public Guid TradeId { get; set; }
|
|
public string KisOrderId { get; set; } = string.Empty;
|
|
public Guid CorrelationId { get; set; }
|
|
}
|
|
|
|
public class PollTradeStatusHandler
|
|
{
|
|
private readonly ITradeSql _sql;
|
|
private readonly IKisTradeExecutionService _kis;
|
|
private readonly IDbConnectionFactory _connectionFactory;
|
|
private readonly IOutboxWriter _outbox;
|
|
private readonly IClock _clock;
|
|
private readonly ILogger<PollTradeStatusHandler> _logger;
|
|
|
|
public PollTradeStatusHandler(
|
|
ITradeSql sql,
|
|
IKisTradeExecutionService kis,
|
|
IDbConnectionFactory connectionFactory,
|
|
IOutboxWriter outbox,
|
|
IClock clock,
|
|
ILogger<PollTradeStatusHandler> logger)
|
|
{
|
|
_sql = sql;
|
|
_kis = kis;
|
|
_connectionFactory = connectionFactory;
|
|
_outbox = outbox;
|
|
_clock = clock;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task HandleAsync(PollTradeStatusCommand command, CancellationToken ct = default)
|
|
{
|
|
var trade = await _sql.GetTradeByIdAsync(command.TradeId, command.CorrelationId, ct);
|
|
if (trade == null)
|
|
{
|
|
_logger.LogWarning("Trade not found: {TradeId}", command.TradeId);
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
var (status, executedQty, unitPrice, response) = await _kis.GetOrderStatusAsync(
|
|
command.KisOrderId,
|
|
command.CorrelationId,
|
|
ct
|
|
);
|
|
|
|
if (status is "ACCEPTED" or "PARTIAL_FILLED" or "FULLY_FILLED")
|
|
{
|
|
trade.MarkAccepted(response);
|
|
if (status is "PARTIAL_FILLED" or "FULLY_FILLED")
|
|
{
|
|
trade.MarkFilled(executedQty, unitPrice, response, _clock.UtcNow.UtcDateTime);
|
|
}
|
|
|
|
await _sql.UpdateTradeStatusAsync(
|
|
trade.Id,
|
|
trade.Status,
|
|
response,
|
|
null,
|
|
command.CorrelationId,
|
|
ct
|
|
);
|
|
|
|
if (trade.Status is TradeStatus.FullyFilled)
|
|
{
|
|
await TradeOutboxPublisher.PublishAsync(
|
|
_connectionFactory,
|
|
_outbox,
|
|
_clock,
|
|
"TradeFilled",
|
|
new TradeFilledEvent
|
|
{
|
|
TradeId = trade.Id,
|
|
ExecutedQuantity = executedQty,
|
|
UnitPrice = unitPrice,
|
|
CorrelationId = command.CorrelationId
|
|
},
|
|
command.CorrelationId,
|
|
ct);
|
|
}
|
|
|
|
_logger.LogInformation("Trade status updated: {TradeId} -> {Status}", trade.Id, status);
|
|
}
|
|
}
|
|
catch (KisTradeExecutionException ex)
|
|
{
|
|
await _sql.UpdateTradeStatusAsync(
|
|
trade.Id,
|
|
trade.Status,
|
|
ex.KisResponse,
|
|
ex.Message,
|
|
command.CorrelationId,
|
|
ct
|
|
);
|
|
|
|
_logger.LogError("Failed to poll trade status: {TradeId}", trade.Id);
|
|
}
|
|
}
|
|
}
|
|
|
|
public class ConfirmSettlementCommand
|
|
{
|
|
public Guid TradeId { get; set; }
|
|
public string KisOrderId { get; set; } = string.Empty;
|
|
public decimal? Commission { get; set; }
|
|
public Guid CorrelationId { get; set; }
|
|
}
|
|
|
|
public class ConfirmSettlementHandler
|
|
{
|
|
private readonly ITradeSql _sql;
|
|
private readonly IKisTradeExecutionService _kis;
|
|
private readonly IDbConnectionFactory _connectionFactory;
|
|
private readonly IOutboxWriter _outbox;
|
|
private readonly IClock _clock;
|
|
private readonly ILogger<ConfirmSettlementHandler> _logger;
|
|
|
|
public ConfirmSettlementHandler(
|
|
ITradeSql sql,
|
|
IKisTradeExecutionService kis,
|
|
IDbConnectionFactory connectionFactory,
|
|
IOutboxWriter outbox,
|
|
IClock clock,
|
|
ILogger<ConfirmSettlementHandler> logger)
|
|
{
|
|
_sql = sql;
|
|
_kis = kis;
|
|
_connectionFactory = connectionFactory;
|
|
_outbox = outbox;
|
|
_clock = clock;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task HandleAsync(ConfirmSettlementCommand command, CancellationToken ct = default)
|
|
{
|
|
var trade = await _sql.GetTradeByIdAsync(command.TradeId, command.CorrelationId, ct);
|
|
if (trade == null)
|
|
{
|
|
_logger.LogWarning("Trade not found for settlement: {TradeId}", command.TradeId);
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
var (success, response) = await _kis.ConfirmSettlementAsync(
|
|
command.KisOrderId,
|
|
command.CorrelationId,
|
|
ct
|
|
);
|
|
|
|
if (success)
|
|
{
|
|
trade.MarkConfirmed(_clock.UtcNow.UtcDateTime, command.Commission);
|
|
await _sql.UpdateTradeStatusAsync(
|
|
trade.Id,
|
|
TradeStatus.Confirmed,
|
|
response,
|
|
null,
|
|
command.CorrelationId,
|
|
ct
|
|
);
|
|
|
|
await TradeOutboxPublisher.PublishAsync(
|
|
_connectionFactory,
|
|
_outbox,
|
|
_clock,
|
|
"TradeSettled",
|
|
new TradeSettledEvent
|
|
{
|
|
TradeId = trade.Id,
|
|
NetProceeds = trade.NetProceeds ?? 0,
|
|
CorrelationId = command.CorrelationId
|
|
},
|
|
command.CorrelationId,
|
|
ct);
|
|
|
|
_logger.LogInformation("Trade settlement confirmed: {TradeId}", trade.Id);
|
|
}
|
|
}
|
|
catch (KisTradeExecutionException ex)
|
|
{
|
|
await _sql.UpdateTradeStatusAsync(
|
|
trade.Id,
|
|
trade.Status,
|
|
ex.KisResponse,
|
|
ex.Message,
|
|
command.CorrelationId,
|
|
ct
|
|
);
|
|
|
|
_logger.LogError("Failed to confirm settlement: {TradeId}", trade.Id);
|
|
}
|
|
}
|
|
}
|
|
|
|
public class TradeSubmittedEvent
|
|
{
|
|
public Guid TradeId { get; set; }
|
|
public Guid SellDecisionId { get; set; }
|
|
public string KisOrderId { get; set; } = string.Empty;
|
|
public int Quantity { get; set; }
|
|
public Guid CorrelationId { get; set; }
|
|
}
|
|
|
|
public class TradeFilledEvent
|
|
{
|
|
public Guid TradeId { get; set; }
|
|
public int ExecutedQuantity { get; set; }
|
|
public decimal UnitPrice { get; set; }
|
|
public Guid CorrelationId { get; set; }
|
|
}
|
|
|
|
public class TradeSettledEvent
|
|
{
|
|
public Guid TradeId { get; set; }
|
|
public decimal NetProceeds { get; set; }
|
|
public Guid CorrelationId { get; set; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// DEBT-TRADE-001: outbox write happens in its own transaction, separate from the
|
|
/// preceding trade status update (which owns its own connection in TradeSql). Not yet
|
|
/// atomic with the state transition. See TECH_DEBT_REGISTER.md.
|
|
/// </summary>
|
|
internal static class TradeOutboxPublisher
|
|
{
|
|
public static async Task PublishAsync<T>(
|
|
IDbConnectionFactory connectionFactory,
|
|
IOutboxWriter outbox,
|
|
IClock clock,
|
|
string eventType,
|
|
T @event,
|
|
Guid correlationId,
|
|
CancellationToken ct) where T : class
|
|
{
|
|
var payload = JsonSerializer.Serialize(@event);
|
|
var message = new OutboxMessage(
|
|
Guid.NewGuid(),
|
|
eventType,
|
|
1,
|
|
payload,
|
|
correlationId.ToString(),
|
|
clock.UtcNow,
|
|
ContentHasher.Sha256(payload));
|
|
|
|
await using var connection = await connectionFactory.OpenAsync(ct);
|
|
await using var transaction = await connection.BeginTransactionAsync(ct);
|
|
await outbox.AddAsync(connection, transaction, message, ct);
|
|
await transaction.CommitAsync(ct);
|
|
}
|
|
}
|