diff --git a/PolyTrader.App.csproj b/PolyTrader.App.csproj index c3ca23e..7ff1e0e 100644 --- a/PolyTrader.App.csproj +++ b/PolyTrader.App.csproj @@ -22,6 +22,10 @@ + + + + diff --git a/services/ConfigMigrator.cs b/services/ConfigMigrator.cs index eb8295b..e12b057 100644 --- a/services/ConfigMigrator.cs +++ b/services/ConfigMigrator.cs @@ -1,16 +1,13 @@ using System; -using System.Collections.Generic; -using System.Globalization; using System.IO; using System.Linq; -using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using PolyTrader.Core.Persistence; using PolyTrader.Core.Persistence.Ef; +using PolyTrader.Modules.CopyTrading.ConfigImport; using PolyTrader.Modules.CopyTrading.Persistence; using PolyTrader.Modules.CopyTrading.Persistence.Ef; -using PolyTraderSharp.Models; namespace PolyTraderSharp.Services { @@ -49,45 +46,11 @@ namespace PolyTraderSharp.Services int accCount = 0, setCount = 0; if (File.Exists(accPath)) { - using var doc = JsonDocument.Parse(File.ReadAllText(accPath)); - foreach (var el in doc.RootElement.EnumerateArray()) + foreach (var imp in MongoExportParser.ParseAccounts(File.ReadAllText(accPath))) { - var acc = new AccountState - { - AccountId = el.GetProperty("_id").GetInt32(), - Name = Str(el, "Name"), - WalletAddress = Str(el, "WalletAddress"), - ApiKey = Str(el, "ApiKey"), - ApiSecret = Str(el, "ApiSecret"), - ApiPassphrase = Str(el, "ApiPassphrase"), - PrivateKey = Str(el, "PrivateKey"), - IsDemo = Bool(el, "IsDemo"), - IsActive = Bool(el, "IsActive", true), - CloseOnlyMode = Bool(el, "CloseOnlyMode"), - PayoutAddress = Str(el, "PayoutAddress"), - PayoutLimitUsd = Dec(el, "PayoutLimitUsd", 0m), - TotalBalance = Dec(el, "TotalBalance", 0m), - AvailableBalance = Dec(el, "AvailableBalance", 0m), - HasOpenLimitOrders = Bool(el, "HasOpenLimitOrders") - }; - dstAccounts.Upsert(acc); + dstAccounts.Upsert(imp.Account); + dstSettings.Upsert(imp.Settings); accCount++; - - var s = new CopyTradingAccountSettings - { - AccountId = acc.AccountId, - PerMarketLimit = Dec(el, "PerMarketLimit", 5.0m), - MaxPriceDifference = Dec(el, "MaxPriceDifference", 2.0m), - MaxBuyPrice = Dec(el, "MaxBuyPrice", 0.98m), - ProfitTarget = Dec(el, "ProfitTarget", 50.0m), - PreRedeemLimit = Dec(el, "PreRedeemLimit", 0.0m), - PerMasterLimit = Dec(el, "PerMasterLimit", 10.0m), - perMaxTime6h = Dec(el, "perMaxTime6h", 20.0m), - perMaxTime24h = Dec(el, "perMaxTime24h", 20.0m), - perMaxTime72h = Dec(el, "perMaxTime72h", 20.0m), - perMaxTimeNone = Dec(el, "perMaxTimeNone", 40.0m) - }; - dstSettings.Upsert(s); setCount++; } } @@ -102,25 +65,8 @@ namespace PolyTraderSharp.Services int trCount = 0; if (File.Exists(trPath)) { - using var doc = JsonDocument.Parse(File.ReadAllText(trPath)); - foreach (var el in doc.RootElement.EnumerateArray()) + foreach (var t in MongoExportParser.ParseTraders(File.ReadAllText(trPath))) { - var t = new TrackedTrader - { - Id = el.GetProperty("_id").GetInt32(), - WalletAddress = Str(el, "WalletAddress"), - DisplayName = Str(el, "DisplayName"), - Category = Str(el, "Category", "NEW_BIG_BET"), - Description = Str(el, "Description"), - Reasoning = Str(el, "Reasoning"), - IsActive = Bool(el, "IsActive", true), - IsHidden = Bool(el, "IsHidden"), - TotalTrades = Int(el, "TotalTrades"), - WinningTrades = Int(el, "WinningTrades"), - Winrate30t = Dbl(el, "Winrate30t"), - TotalPnl = Dbl(el, "TotalPnl"), - AssignedAccountIds = IntSet(el, "AssignedAccountIds") - }; dstTraders.Upsert(t); trCount++; } @@ -180,68 +126,6 @@ namespace PolyTraderSharp.Services private static string Short(string s) => string.IsNullOrEmpty(s) || s.Length <= 12 ? s : $"{s[..6]}…{s[^4..]}"; - // --- JSON-Helfer (mongoexport: Dezimalwerte als Strings, null moeglich) --- - private static string Str(JsonElement el, string name, string fallback = "") - { - if (el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String) - return v.GetString() ?? fallback; - return fallback; - } - - private static bool Bool(JsonElement el, string name, bool fallback = false) - { - if (el.TryGetProperty(name, out var v)) - { - if (v.ValueKind == JsonValueKind.True) return true; - if (v.ValueKind == JsonValueKind.False) return false; - } - return fallback; - } - - private static int Int(JsonElement el, string name, int fallback = 0) - { - if (el.TryGetProperty(name, out var v)) - { - if (v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var n)) return n; - if (v.ValueKind == JsonValueKind.String && int.TryParse(v.GetString(), NumberStyles.Any, CultureInfo.InvariantCulture, out var s)) return s; - } - return fallback; - } - - private static double Dbl(JsonElement el, string name, double fallback = 0) - { - if (el.TryGetProperty(name, out var v)) - { - if (v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out var n)) return n; - if (v.ValueKind == JsonValueKind.String && double.TryParse(v.GetString(), NumberStyles.Any, CultureInfo.InvariantCulture, out var s)) return s; - } - return fallback; - } - - private static decimal Dec(JsonElement el, string name, decimal fallback) - { - if (el.TryGetProperty(name, out var v)) - { - if (v.ValueKind == JsonValueKind.Number && v.TryGetDecimal(out var n)) return n; - if (v.ValueKind == JsonValueKind.String && decimal.TryParse(v.GetString(), NumberStyles.Any, CultureInfo.InvariantCulture, out var s)) return s; - } - return fallback; - } - - private static HashSet IntSet(JsonElement el, string name) - { - var set = new HashSet(); - if (el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Array) - { - foreach (var item in v.EnumerateArray()) - { - if (item.ValueKind == JsonValueKind.Number && item.TryGetInt32(out var n)) set.Add(n); - else if (item.ValueKind == JsonValueKind.String && int.TryParse(item.GetString(), NumberStyles.Any, CultureInfo.InvariantCulture, out var s)) set.Add(s); - } - } - return set; - } - private static string Redact(string conn) => System.Text.RegularExpressions.Regex.Replace(conn, "(?i)(password=)[^;]*", "$1***"); } diff --git a/src/PolyTrader.Modules.CopyTrading/ConfigImport/MongoExportParser.cs b/src/PolyTrader.Modules.CopyTrading/ConfigImport/MongoExportParser.cs new file mode 100644 index 0000000..c4d2341 --- /dev/null +++ b/src/PolyTrader.Modules.CopyTrading/ConfigImport/MongoExportParser.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.Json; +using PolyTraderSharp.Models; + +namespace PolyTrader.Modules.CopyTrading.ConfigImport +{ + /// + /// Parst mongoexport-JSON (Standard-Array, KEIN Extended JSON) in die Zielmodelle. + /// Robust gegen die typischen Export-Eigenheiten: Dezimalwerte als Strings ("0.5"), + /// null-Felder, fehlende Felder (→ Default). Bewusst als reine, testbare Logik + /// getrennt von der DB-Anbindung im ConfigMigrator. + /// + public static class MongoExportParser + { + /// Ein Account-Dokument liefert die Core-Account-Daten UND die + /// (im Alt-Dokument mitgeführten) Copytrading-Detail-Einstellungen. + public sealed record AccountImport(AccountState Account, CopyTradingAccountSettings Settings); + + public static List ParseAccounts(string json) + { + var result = new List(); + using var doc = JsonDocument.Parse(json); + if (doc.RootElement.ValueKind != JsonValueKind.Array) return result; + + foreach (var el in doc.RootElement.EnumerateArray()) + { + var acc = new AccountState + { + AccountId = el.GetProperty("_id").GetInt32(), + Name = Str(el, "Name"), + WalletAddress = Str(el, "WalletAddress"), + ApiKey = Str(el, "ApiKey"), + ApiSecret = Str(el, "ApiSecret"), + ApiPassphrase = Str(el, "ApiPassphrase"), + PrivateKey = Str(el, "PrivateKey"), + IsDemo = Bool(el, "IsDemo"), + IsActive = Bool(el, "IsActive", true), + CloseOnlyMode = Bool(el, "CloseOnlyMode"), + PayoutAddress = Str(el, "PayoutAddress"), + PayoutLimitUsd = Dec(el, "PayoutLimitUsd", 0m), + TotalBalance = Dec(el, "TotalBalance", 0m), + AvailableBalance = Dec(el, "AvailableBalance", 0m), + HasOpenLimitOrders = Bool(el, "HasOpenLimitOrders") + }; + + var settings = new CopyTradingAccountSettings + { + AccountId = acc.AccountId, + PerMarketLimit = Dec(el, "PerMarketLimit", 5.0m), + MaxPriceDifference = Dec(el, "MaxPriceDifference", 2.0m), + MaxBuyPrice = Dec(el, "MaxBuyPrice", 0.98m), + ProfitTarget = Dec(el, "ProfitTarget", 50.0m), + PreRedeemLimit = Dec(el, "PreRedeemLimit", 0.0m), + PerMasterLimit = Dec(el, "PerMasterLimit", 10.0m), + perMaxTime6h = Dec(el, "perMaxTime6h", 20.0m), + perMaxTime24h = Dec(el, "perMaxTime24h", 20.0m), + perMaxTime72h = Dec(el, "perMaxTime72h", 20.0m), + perMaxTimeNone = Dec(el, "perMaxTimeNone", 40.0m) + }; + + result.Add(new AccountImport(acc, settings)); + } + return result; + } + + public static List ParseTraders(string json) + { + var result = new List(); + using var doc = JsonDocument.Parse(json); + if (doc.RootElement.ValueKind != JsonValueKind.Array) return result; + + foreach (var el in doc.RootElement.EnumerateArray()) + { + result.Add(new TrackedTrader + { + Id = el.GetProperty("_id").GetInt32(), + WalletAddress = Str(el, "WalletAddress"), + DisplayName = Str(el, "DisplayName"), + Category = Str(el, "Category", "NEW_BIG_BET"), + Description = Str(el, "Description"), + Reasoning = Str(el, "Reasoning"), + IsActive = Bool(el, "IsActive", true), + IsHidden = Bool(el, "IsHidden"), + TotalTrades = Int(el, "TotalTrades"), + WinningTrades = Int(el, "WinningTrades"), + Winrate30t = Dbl(el, "Winrate30t"), + TotalPnl = Dbl(el, "TotalPnl"), + AssignedAccountIds = IntSet(el, "AssignedAccountIds") + }); + } + return result; + } + + // --- JSON-Helfer (mongoexport: Dezimalwerte als Strings, null möglich) --- + private static string Str(JsonElement el, string name, string fallback = "") + { + if (el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String) + return v.GetString() ?? fallback; + return fallback; + } + + private static bool Bool(JsonElement el, string name, bool fallback = false) + { + if (el.TryGetProperty(name, out var v)) + { + if (v.ValueKind == JsonValueKind.True) return true; + if (v.ValueKind == JsonValueKind.False) return false; + } + return fallback; + } + + private static int Int(JsonElement el, string name, int fallback = 0) + { + if (el.TryGetProperty(name, out var v)) + { + if (v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var n)) return n; + if (v.ValueKind == JsonValueKind.String && int.TryParse(v.GetString(), NumberStyles.Any, CultureInfo.InvariantCulture, out var s)) return s; + } + return fallback; + } + + private static double Dbl(JsonElement el, string name, double fallback = 0) + { + if (el.TryGetProperty(name, out var v)) + { + if (v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out var n)) return n; + if (v.ValueKind == JsonValueKind.String && double.TryParse(v.GetString(), NumberStyles.Any, CultureInfo.InvariantCulture, out var s)) return s; + } + return fallback; + } + + private static decimal Dec(JsonElement el, string name, decimal fallback) + { + if (el.TryGetProperty(name, out var v)) + { + if (v.ValueKind == JsonValueKind.Number && v.TryGetDecimal(out var n)) return n; + if (v.ValueKind == JsonValueKind.String && decimal.TryParse(v.GetString(), NumberStyles.Any, CultureInfo.InvariantCulture, out var s)) return s; + } + return fallback; + } + + private static HashSet IntSet(JsonElement el, string name) + { + var set = new HashSet(); + if (el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Array) + { + foreach (var item in v.EnumerateArray()) + { + if (item.ValueKind == JsonValueKind.Number && item.TryGetInt32(out var n)) set.Add(n); + else if (item.ValueKind == JsonValueKind.String && int.TryParse(item.GetString(), NumberStyles.Any, CultureInfo.InvariantCulture, out var s)) set.Add(s); + } + } + return set; + } + } +} diff --git a/tests/PolyTrader.Tests/DbContextMappingTests.cs b/tests/PolyTrader.Tests/DbContextMappingTests.cs new file mode 100644 index 0000000..349eca0 --- /dev/null +++ b/tests/PolyTrader.Tests/DbContextMappingTests.cs @@ -0,0 +1,85 @@ +using System; +using System.Linq; +using Microsoft.EntityFrameworkCore; +using PolyTrader.Core.Persistence.Ef; +using PolyTrader.Modules.CopyTrading.Persistence.Ef; +using PolyTrader.Tests.TestSupport; +using PolyTraderSharp.Models; +using Xunit; + +namespace PolyTrader.Tests +{ + /// + /// Sichert die projektweiten Mapping-Invarianten ab: Core-Tabellen mit Präfix core_, + /// Modul-Tabellen mit mod_<modul>_, korrekte Schlüssel, UI-Klasse nicht gemappt. + /// + public class DbContextMappingTests + { + private static CoreDbContext CoreCtx() => + new InMemoryContextFactory(o => new CoreDbContext(o)).CreateDbContext(); + + private static CopyTradingDbContext CtCtx() => + new InMemoryContextFactory(o => new CopyTradingDbContext(o)).CreateDbContext(); + + [Theory] + [InlineData(typeof(AccountState), "core_accounts")] + [InlineData(typeof(Position), "core_positions")] + [InlineData(typeof(MarketData), "core_markets")] + [InlineData(typeof(TradeRecord), "core_trade_log")] + public void Core_entities_map_to_core_prefixed_tables(Type clrType, string expectedTable) + { + using var ctx = CoreCtx(); + var entity = ctx.Model.FindEntityType(clrType); + Assert.NotNull(entity); + Assert.Equal(expectedTable, entity!.GetTableName()); + } + + [Theory] + [InlineData(typeof(ClosedTrade), "mod_copytrading_closed_trades")] + [InlineData(typeof(TrackedTrader), "mod_copytrading_traders")] + [InlineData(typeof(CopyTradingAccountSettings), "mod_copytrading_account_settings")] + [InlineData(typeof(MasterTraderHistoryRecord), "mod_copytrading_mt_history")] + public void Module_entities_map_to_mod_copytrading_prefixed_tables(Type clrType, string expectedTable) + { + using var ctx = CtCtx(); + var entity = ctx.Model.FindEntityType(clrType); + Assert.NotNull(entity); + Assert.Equal(expectedTable, entity!.GetTableName()); + } + + [Fact] + public void Position_has_composite_key_account_isdemo_token() + { + using var ctx = CoreCtx(); + var key = ctx.Model.FindEntityType(typeof(Position))!.FindPrimaryKey(); + Assert.NotNull(key); + Assert.Equal( + new[] { nameof(Position.AccountId), nameof(Position.IsDemo), nameof(Position.TokenId) }, + key!.Properties.Select(p => p.Name).ToArray()); + } + + [Fact] + public void TrackedTrader_key_is_id() + { + using var ctx = CtCtx(); + var key = ctx.Model.FindEntityType(typeof(TrackedTrader))!.FindPrimaryKey(); + Assert.Equal(nameof(TrackedTrader.Id), Assert.Single(key!.Properties).Name); + } + + [Fact] + public void ClosedTradeRow_ui_class_is_not_mapped() + { + using var ctx = CtCtx(); + Assert.Null(ctx.Model.FindEntityType(typeof(ClosedTradeRow))); + } + + [Fact] + public void AccountState_open_positions_is_ignored() + { + using var ctx = CoreCtx(); + var entity = ctx.Model.FindEntityType(typeof(AccountState))!; + Assert.Null(entity.FindProperty(nameof(AccountState.OpenPositions))); + Assert.Null(entity.FindNavigation(nameof(AccountState.OpenPositions))); + } + } +} diff --git a/tests/PolyTrader.Tests/MarketRepositoryTests.cs b/tests/PolyTrader.Tests/MarketRepositoryTests.cs new file mode 100644 index 0000000..a74af05 --- /dev/null +++ b/tests/PolyTrader.Tests/MarketRepositoryTests.cs @@ -0,0 +1,46 @@ +using System.Linq; +using PolyTrader.Core.Persistence.Ef; +using PolyTrader.Tests.TestSupport; +using PolyTraderSharp.Models; +using Xunit; + +namespace PolyTrader.Tests +{ + public class MarketRepositoryTests + { + private static EfMarketRepository NewRepo() => + new(new InMemoryContextFactory(o => new CoreDbContext(o))); + + [Fact] + public void GetActive_returns_only_non_closed_markets() + { + var repo = NewRepo(); + repo.Upsert(new MarketData { Id = "m1", Closed = false }); + repo.Upsert(new MarketData { Id = "m2", Closed = true }); + + var active = repo.GetActive(); + Assert.Single(active); + Assert.Equal("m1", active[0].Id); + } + + [Fact] + public void Upsert_updates_existing_market() + { + var repo = NewRepo(); + repo.Upsert(new MarketData { Id = "m1", Question = "old" }); + repo.Upsert(new MarketData { Id = "m1", Question = "new" }); + + Assert.Equal("new", repo.GetById("m1")!.Question); + } + + [Fact] + public void FindByTokenId_matches_within_clob_token_ids() + { + var repo = NewRepo(); + repo.Upsert(new MarketData { Id = "m1", ClobTokenIds = "[\"abc\",\"def\"]" }); + + Assert.Equal("m1", repo.FindByTokenId("def")!.Id); + Assert.Null(repo.FindByTokenId("zzz")); + } + } +} diff --git a/tests/PolyTrader.Tests/MongoExportParserTests.cs b/tests/PolyTrader.Tests/MongoExportParserTests.cs new file mode 100644 index 0000000..703394b --- /dev/null +++ b/tests/PolyTrader.Tests/MongoExportParserTests.cs @@ -0,0 +1,120 @@ +using System.Collections.Generic; +using System.Linq; +using PolyTrader.Modules.CopyTrading.ConfigImport; +using Xunit; + +namespace PolyTrader.Tests +{ + /// + /// Sichert das robuste Parsen der mongoexport-JSON ab: Dezimalwerte als Strings, + /// null-Felder, fehlende Felder → Default, Account-Arrays. + /// + public class MongoExportParserTests + { + [Fact] + public void ParseAccounts_reads_core_fields_and_string_decimals() + { + const string json = """ + [{ + "_id": 1, + "Name": "Richard Test", + "WalletAddress": "0x628", + "IsDemo": false, + "IsActive": true, + "TotalBalance": "64.763626", + "AvailableBalance": "1.155226" + }] + """; + + var imp = Assert.Single(MongoExportParser.ParseAccounts(json)); + Assert.Equal(1, imp.Account.AccountId); + Assert.Equal("Richard Test", imp.Account.Name); + Assert.Equal("0x628", imp.Account.WalletAddress); + Assert.False(imp.Account.IsDemo); + Assert.True(imp.Account.IsActive); + Assert.Equal(64.763626m, imp.Account.TotalBalance); + Assert.Equal(1.155226m, imp.Account.AvailableBalance); + } + + [Fact] + public void ParseAccounts_maps_old_limit_fields_into_settings() + { + const string json = """ + [{ "_id": 3, "PerMarketLimit": "10", "PerMasterLimit": "20", "MaxBuyPrice": "0.85", "PreRedeemLimit": "99.5" }] + """; + + var imp = Assert.Single(MongoExportParser.ParseAccounts(json)); + Assert.Equal(3, imp.Settings.AccountId); + Assert.Equal(10m, imp.Settings.PerMarketLimit); + Assert.Equal(20m, imp.Settings.PerMasterLimit); + Assert.Equal(0.85m, imp.Settings.MaxBuyPrice); + Assert.Equal(99.5m, imp.Settings.PreRedeemLimit); + } + + [Fact] + public void ParseAccounts_null_string_falls_back_to_empty() + { + const string json = """[{ "_id": 3, "PayoutAddress": null }]"""; + + var imp = Assert.Single(MongoExportParser.ParseAccounts(json)); + Assert.Equal(string.Empty, imp.Account.PayoutAddress); + } + + [Fact] + public void ParseAccounts_missing_settings_fields_use_defaults() + { + const string json = """[{ "_id": 1 }]"""; + + var imp = Assert.Single(MongoExportParser.ParseAccounts(json)); + Assert.Equal(5.0m, imp.Settings.PerMarketLimit); + Assert.Equal(2.0m, imp.Settings.MaxPriceDifference); + Assert.Equal(0.98m, imp.Settings.MaxBuyPrice); + Assert.Equal(40.0m, imp.Settings.perMaxTimeNone); + } + + [Fact] + public void ParseTraders_reads_fields_and_assigned_accounts() + { + const string json = """ + [{ + "_id": 2, + "WalletAddress": "0xa2711", + "DisplayName": "0xa2711", + "Category": "TRADING_BOT", + "IsActive": false, + "TotalTrades": 32, + "TotalPnl": 7386.655743958501, + "AssignedAccountIds": [1, 3], + "Description": null + }] + """; + + var t = Assert.Single(MongoExportParser.ParseTraders(json)); + Assert.Equal(2, t.Id); + Assert.Equal("TRADING_BOT", t.Category); + Assert.False(t.IsActive); + Assert.Equal(32, t.TotalTrades); + Assert.Equal(7386.655743958501, t.TotalPnl, 6); + Assert.Equal(new HashSet { 1, 3 }, t.AssignedAccountIds); + Assert.Equal(string.Empty, t.Description); + } + + [Fact] + public void ParseTraders_missing_category_uses_default() + { + const string json = """[{ "_id": 5, "DisplayName": "x" }]"""; + + var t = Assert.Single(MongoExportParser.ParseTraders(json)); + Assert.Equal("NEW_BIG_BET", t.Category); + Assert.Empty(t.AssignedAccountIds); + } + + [Fact] + public void Parse_returns_empty_for_non_array_or_empty() + { + Assert.Empty(MongoExportParser.ParseAccounts("{}")); + Assert.Empty(MongoExportParser.ParseAccounts("[]")); + Assert.Empty(MongoExportParser.ParseTraders("[]")); + } + } +} diff --git a/tests/PolyTrader.Tests/PositionRepositoryTests.cs b/tests/PolyTrader.Tests/PositionRepositoryTests.cs new file mode 100644 index 0000000..7534c34 --- /dev/null +++ b/tests/PolyTrader.Tests/PositionRepositoryTests.cs @@ -0,0 +1,79 @@ +using System.Linq; +using PolyTrader.Core.Persistence.Ef; +using PolyTrader.Tests.TestSupport; +using PolyTraderSharp.Models; +using Xunit; + +namespace PolyTrader.Tests +{ + public class PositionRepositoryTests + { + private static EfPositionRepository NewRepo() => + new(new InMemoryContextFactory(o => new CoreDbContext(o))); + + [Fact] + public void Live_and_demo_positions_are_kept_separate_per_account() + { + var repo = NewRepo(); + repo.UpsertLive(1, new Position { TokenId = "t1" }); + repo.UpsertDemo(1, new Position { TokenId = "t1" }); + repo.UpsertLive(2, new Position { TokenId = "t1" }); + + Assert.Single(repo.GetLive(1)); + Assert.Single(repo.GetDemo(1)); + Assert.Single(repo.GetLive(2)); + Assert.Empty(repo.GetDemo(2)); + } + + [Fact] + public void Upsert_sets_account_and_demo_flag_on_position() + { + var repo = NewRepo(); + repo.UpsertDemo(5, new Position { TokenId = "t1" }); + + var pos = repo.FindDemo(5, "t1"); + Assert.NotNull(pos); + Assert.Equal(5, pos!.AccountId); + Assert.True(pos.IsDemo); + } + + [Fact] + public void Upsert_updates_existing_position_without_duplicating() + { + var repo = NewRepo(); + repo.UpsertLive(1, new Position { TokenId = "t1", Size = 10m }); + repo.UpsertLive(1, new Position { TokenId = "t1", Size = 20m }); + + var live = repo.GetLive(1); + Assert.Single(live); + Assert.Equal(20m, live[0].Size); + } + + [Fact] + public void DeleteLive_removes_only_live() + { + var repo = NewRepo(); + repo.UpsertLive(1, new Position { TokenId = "t1" }); + repo.UpsertDemo(1, new Position { TokenId = "t1" }); + + repo.DeleteLive(1, "t1"); + + Assert.Empty(repo.GetLive(1)); + Assert.Single(repo.GetDemo(1)); + } + + [Fact] + public void DropDemo_clears_only_demo_positions_of_account() + { + var repo = NewRepo(); + repo.UpsertDemo(1, new Position { TokenId = "t1" }); + repo.UpsertDemo(1, new Position { TokenId = "t2" }); + repo.UpsertLive(1, new Position { TokenId = "t3" }); + + repo.DropDemo(1); + + Assert.Empty(repo.GetDemo(1)); + Assert.Single(repo.GetLive(1)); + } + } +} diff --git a/tests/PolyTrader.Tests/TradeLogRepositoryTests.cs b/tests/PolyTrader.Tests/TradeLogRepositoryTests.cs new file mode 100644 index 0000000..efd1f62 --- /dev/null +++ b/tests/PolyTrader.Tests/TradeLogRepositoryTests.cs @@ -0,0 +1,52 @@ +using System; +using System.Linq; +using PolyTrader.Core.Persistence.Ef; +using PolyTrader.Tests.TestSupport; +using PolyTraderSharp.Models; +using Xunit; + +namespace PolyTrader.Tests +{ + public class TradeLogRepositoryTests + { + private static EfTradeLogRepository NewRepo() => + new(new InMemoryContextFactory(o => new CoreDbContext(o))); + + [Fact] + public void GetRecent_orders_by_closed_at_descending_and_limits() + { + var repo = NewRepo(); + var t = new DateTime(2026, 7, 1, 0, 0, 0, DateTimeKind.Utc); + repo.Insert(new TradeRecord { Id = "a", ClosedAt = t.AddHours(1) }); + repo.Insert(new TradeRecord { Id = "b", ClosedAt = t.AddHours(3) }); + repo.Insert(new TradeRecord { Id = "c", ClosedAt = t.AddHours(2) }); + + var recent = repo.GetRecent(2); + + Assert.Equal(2, recent.Count); + Assert.Equal("b", recent[0].Id); + Assert.Equal("c", recent[1].Id); + } + + [Fact] + public void Find_filters_by_module_name() + { + var repo = NewRepo(); + repo.Insert(new TradeRecord { Id = "a", ModuleName = "CopyTrading" }); + repo.Insert(new TradeRecord { Id = "b", ModuleName = "Other" }); + + var ct = repo.Find(x => x.ModuleName == "CopyTrading"); + Assert.Single(ct); + Assert.Equal("a", ct[0].Id); + } + + [Fact] + public void Generated_id_is_unique_per_record() + { + var a = new TradeRecord(); + var b = new TradeRecord(); + Assert.False(string.IsNullOrEmpty(a.Id)); + Assert.NotEqual(a.Id, b.Id); + } + } +}