Files
managing-apps/src/Managing.Infrastructure.Database/MongoDb/MongoMappers.cs
2025-07-10 22:07:21 +07:00

1097 lines
36 KiB
C#

using System.Text.Json;
using Managing.Domain.Accounts;
using Managing.Domain.Backtests;
using Managing.Domain.Bots;
using Managing.Domain.Candles;
using Managing.Domain.MoneyManagements;
using Managing.Domain.Risk;
using Managing.Domain.Scenarios;
using Managing.Domain.Statistics;
using Managing.Domain.Strategies;
using Managing.Domain.Synth.Models;
using Managing.Domain.Trades;
using Managing.Domain.Users;
using Managing.Domain.Workers;
using Managing.Domain.Workflows.Synthetics;
using Managing.Infrastructure.Databases.MongoDb.Collections;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb;
public static class MongoMappers
{
#region Statistics
internal static TopVolumeTickerDto Map(TopVolumeTicker topVolumeTicker)
{
return new TopVolumeTickerDto
{
Ticker = topVolumeTicker.Ticker,
Date = topVolumeTicker.Date,
Volume = topVolumeTicker.Volume,
Rank = topVolumeTicker.Rank,
Exchange = topVolumeTicker.Exchange
};
}
internal static IList<TopVolumeTicker> Map(IEnumerable<TopVolumeTickerDto> top)
{
return top.Select(topElement => new TopVolumeTicker
{
Ticker = topElement.Ticker,
Date = topElement.Date,
Volume = topElement.Volume,
Rank = topElement.Rank,
Exchange = topElement.Exchange
}).ToList();
}
#endregion
#region Accounts
internal static AccountDto Map(Account request)
{
return new AccountDto
{
Name = request.Name,
Exchanges = request.Exchange,
Key = request.Key,
Secret = request.Secret,
Type = request.Type,
User = Map(request.User)
};
}
internal static IEnumerable<Account> Map(IEnumerable<AccountDto> accounts)
{
return accounts.Select(account => Map(account));
}
internal static Account Map(AccountDto account, bool hideKeys = false)
{
if (account == null) return null;
var a = new Account
{
Name = account.Name,
Exchange = account.Exchanges,
};
if (!hideKeys)
{
a.Key = account.Key;
a.Secret = account.Secret;
}
a.Exchange = account.Exchanges;
a.Type = account.Type;
a.User = Map(account.User);
return a;
}
#endregion
#region Workers
internal static WorkerDto Map(Worker worker)
{
return new WorkerDto
{
WorkerType = worker.WorkerType,
StartTime = worker.StartTime,
LastRunTime = worker.LastRunTime,
ExecutionCount = worker.ExecutionCount,
Delay = worker.Delay
};
}
internal static Worker Map(WorkerDto worker)
{
if (worker == null)
return null;
return new Worker
{
WorkerType = worker.WorkerType,
StartTime = worker.StartTime,
LastRunTime = worker.LastRunTime,
ExecutionCount = worker.ExecutionCount,
Delay = worker.Delay,
IsActive = worker.IsActive
};
}
#endregion
#region Backtests
internal static Backtest Map(BacktestDto b)
{
if (b == null)
return null;
var config = Map(b.Config);
var bTest = new Backtest(
config,
b.Positions?.Select(p => Map(p)).ToList() ?? new List<Position>(),
b.Signals?.Select(s => Map(s)).ToList() ?? new List<Signal>())
{
FinalPnl = b.FinalPnl,
WinRate = b.WinRate,
GrowthPercentage = b.GrowthPercentage,
HodlPercentage = b.HodlPercentage,
Id = b.Identifier,
OptimizedMoneyManagement = Map(b.OptimizedMoneyManagement),
User = Map(b.User),
Statistics = b.Statistics,
StartDate = b.StartDate,
EndDate = b.EndDate,
Score = b.Score,
RequestId = b.RequestId
};
return bTest;
}
internal static BacktestDto Map(Backtest result)
{
if (result == null)
return null;
return new BacktestDto
{
Identifier = result.Id,
FinalPnl = result.FinalPnl,
WinRate = result.WinRate,
GrowthPercentage = result.GrowthPercentage,
HodlPercentage = result.HodlPercentage,
Config = Map(result.Config),
Positions = Map(result.Positions),
Signals = result.Signals.Select(s => Map(s)).ToList(),
MoneyManagement = Map(result.Config.MoneyManagement),
OptimizedMoneyManagement = Map(result.OptimizedMoneyManagement),
User = Map(result.User),
Statistics = result.Statistics,
StartDate = result.StartDate,
EndDate = result.EndDate,
Score = result.Score,
RequestId = result.RequestId
};
}
#endregion
#region Genetic Requests
internal static GeneticRequest Map(GeneticRequestDto dto)
{
if (dto == null)
return null;
return new GeneticRequest
{
RequestId = dto.RequestId,
User = Map(dto.User),
CreatedAt = dto.CreatedAt,
CompletedAt = dto.CompletedAt,
Status = Enum.Parse<GeneticRequestStatus>(dto.Status),
Ticker = dto.Ticker,
Timeframe = dto.Timeframe,
StartDate = dto.StartDate,
EndDate = dto.EndDate,
Balance = dto.Balance,
PopulationSize = dto.PopulationSize,
Generations = dto.Generations,
MutationRate = dto.MutationRate,
SelectionMethod = dto.SelectionMethod,
ElitismPercentage = dto.ElitismPercentage,
MaxTakeProfit = dto.MaxTakeProfit,
EligibleIndicators = dto.EligibleIndicators,
BestFitness = dto.BestFitness,
BestIndividual = dto.BestIndividual,
ErrorMessage = dto.ErrorMessage,
ProgressInfo = dto.ProgressInfo
};
}
internal static GeneticRequestDto Map(GeneticRequest geneticRequest)
{
if (geneticRequest == null)
return null;
return new GeneticRequestDto
{
RequestId = geneticRequest.RequestId,
User = Map(geneticRequest.User),
CompletedAt = geneticRequest.CompletedAt,
Status = geneticRequest.Status.ToString(),
Ticker = geneticRequest.Ticker,
Timeframe = geneticRequest.Timeframe,
StartDate = geneticRequest.StartDate,
EndDate = geneticRequest.EndDate,
Balance = geneticRequest.Balance,
PopulationSize = geneticRequest.PopulationSize,
Generations = geneticRequest.Generations,
MutationRate = geneticRequest.MutationRate,
SelectionMethod = geneticRequest.SelectionMethod,
ElitismPercentage = geneticRequest.ElitismPercentage,
MaxTakeProfit = geneticRequest.MaxTakeProfit,
EligibleIndicators = geneticRequest.EligibleIndicators,
BestFitness = geneticRequest.BestFitness,
BestIndividual = geneticRequest.BestIndividual,
ErrorMessage = geneticRequest.ErrorMessage,
ProgressInfo = geneticRequest.ProgressInfo
};
}
#endregion
#region Candles
public static Candle Map(CandleDto candle)
{
if (candle == null)
return null;
return new Candle()
{
Ticker = candle.Ticker,
BaseVolume = candle.BaseVolume,
Close = candle.Close,
Date = candle.OpenTime,
Open = candle.Open,
OpenTime = candle.OpenTime,
High = candle.High,
Low = candle.Low,
QuoteVolume = candle.QuoteVolume,
TakerBuyBaseVolume = candle.TakerBuyBaseVolume,
TakerBuyQuoteVolume = candle.TakerBuyQuoteVolume,
TradeCount = candle.TradeCount,
Exchange = candle.Exchange,
};
}
public static CandleDto Map(Candle candle)
{
return new CandleDto
{
Exchange = candle.Exchange,
Ticker = candle.Ticker,
OpenTime = candle.OpenTime,
Open = candle.Open,
Close = candle.Close,
High = candle.High,
Low = candle.Low,
BaseVolume = candle.BaseVolume,
QuoteVolume = candle.QuoteVolume,
TradeCount = candle.TradeCount,
TakerBuyBaseVolume = candle.TakerBuyBaseVolume,
TakerBuyQuoteVolume = candle.TakerBuyQuoteVolume
};
}
public static List<CandleDto> Map(List<Candle> candles)
{
return candles.ConvertAll(candle => Map(candle));
}
#endregion
#region Positions
public static PositionDto Map(Position position)
{
var p = new PositionDto
{
Date = position.Date,
Open = Map(position.Open),
OriginDirection = position.OriginDirection,
Identifier = position.Identifier,
SignalIdentifier = position.SignalIdentifier,
Status = position.Status,
AccountName = position.AccountName,
MoneyManagement = Map(position.MoneyManagement),
Initiator = position.Initiator,
Ticker = position.Ticker,
User = Map(position.User)
};
if (position.StopLoss != null)
p.StopLoss = Map(position.StopLoss);
if (position.TakeProfit1 != null)
p.TakeProfit1 = Map(position.TakeProfit1);
if (position.TakeProfit2 != null)
p.TakeProfit2 = Map(position.TakeProfit2);
if (position.ProfitAndLoss != null)
p.ProfitAndLoss = position.ProfitAndLoss.Realized;
return p;
}
private static TradeDto Map(Trade trade)
{
return new TradeDto
{
Date = trade.Date,
Direction = trade.Direction,
Status = trade.Status,
TradeType = trade.TradeType,
Ticker = trade.Ticker,
Quantity = trade.Quantity,
Price = trade.Price,
Leverage = trade.Leverage,
ExchangeOrderId = trade.ExchangeOrderId,
Message = trade.Message
};
}
public static Position Map(PositionDto dto)
{
var position = new Position(dto.Identifier, dto.AccountName, originDirection: dto.OriginDirection, dto.Ticker,
Map(dto.MoneyManagement), dto.Initiator, dto.Date, Map(dto.User))
{
Open = new Trade(date: dto.Open.Date, direction: dto.Open.Direction, status: dto.Open.Status,
tradeType: dto.Open.TradeType, ticker: dto.Open.Ticker, quantity: dto.Open.Quantity,
price: dto.Open.Price, leverage: dto.Open.Leverage, exchangeOrderId: dto.Open.ExchangeOrderId,
message: dto.Open.Message),
ProfitAndLoss = new ProfitAndLoss { Realized = dto.ProfitAndLoss },
Status = dto.Status,
SignalIdentifier = dto.SignalIdentifier,
Identifier = dto.Identifier,
User = Map(dto.User)
};
if (dto.StopLoss != null)
{
position.StopLoss = new Trade(date: dto.StopLoss.Date, direction: dto.StopLoss.Direction,
status: dto.StopLoss.Status, tradeType: dto.StopLoss.TradeType, ticker: dto.StopLoss.Ticker,
quantity: dto.StopLoss.Quantity, price: dto.StopLoss.Price, leverage: dto.StopLoss.Leverage,
exchangeOrderId: dto.StopLoss.ExchangeOrderId, message: dto.StopLoss.Message);
}
if (dto.TakeProfit1 != null)
{
position.TakeProfit1 = new Trade(date: dto.TakeProfit1.Date, direction: dto.TakeProfit1.Direction,
status: dto.TakeProfit1.Status, tradeType: dto.TakeProfit1.TradeType, ticker: dto.TakeProfit1.Ticker,
quantity: dto.TakeProfit1.Quantity, price: dto.TakeProfit1.Price, leverage: dto.TakeProfit1.Leverage,
exchangeOrderId: dto.TakeProfit1.ExchangeOrderId, message: dto.TakeProfit1.Message);
}
if (dto.TakeProfit2 != null)
{
position.TakeProfit2 = new Trade(date: dto.TakeProfit2.Date, direction: dto.TakeProfit2.Direction,
status: dto.TakeProfit2.Status, tradeType: dto.TakeProfit2.TradeType, ticker: dto.TakeProfit2.Ticker,
quantity: dto.TakeProfit2.Quantity, price: dto.TakeProfit2.Price, leverage: dto.TakeProfit2.Leverage,
exchangeOrderId: dto.TakeProfit2.ExchangeOrderId, message: dto.TakeProfit2.Message);
}
return position;
}
internal static List<PositionDto> Map(List<Position> positions)
{
return positions.ConvertAll(position => Map(position));
}
#endregion
#region Signals
public static SignalDto Map(Signal signal)
{
return new SignalDto
{
Direction = signal.Direction,
Confidence = signal.Confidence,
Date = signal.Date,
Candle = Map(signal.Candle),
Identifier = signal.Identifier,
Ticker = signal.Ticker,
Status = signal.Status,
Timeframe = signal.Timeframe,
Type = signal.IndicatorType,
User = signal.User != null ? Map(signal.User) : null,
IndicatorName = signal.IndicatorName
};
}
internal static Signal Map(SignalDto bSignal)
{
var candle = Map(bSignal.Candle);
var signal = new Signal(
bSignal.Ticker,
bSignal.Direction,
bSignal.Confidence,
candle,
bSignal.Date,
TradingExchanges.Binance, //TODO FIXME When the signal status is modified from controller
bSignal.Type,
bSignal.SignalType,
bSignal.IndicatorName,
bSignal.User != null ? Map(bSignal.User) : null)
{
Status = bSignal.Status
};
if (bSignal.User != null)
{
signal.User = Map(bSignal.User);
}
return signal;
}
#endregion
#region Scenarios
public static ScenarioDto Map(Scenario scenario)
{
if (scenario == null)
return null;
return new ScenarioDto
{
Name = scenario.Name,
Indicators = Map(scenario.Indicators),
LoopbackPeriod = scenario.LoopbackPeriod ?? 1,
User = scenario.User != null ? Map(scenario.User) : null
};
}
internal static IEnumerable<Scenario> Map(IEnumerable<ScenarioDto> dtos)
{
return dtos.Select(d => Map(d));
}
internal static Scenario Map(ScenarioDto d)
{
if (d == null)
return null;
var scenario = new Scenario(d.Name, d.LoopbackPeriod)
{
Indicators = d.Indicators.Select(s => Map(s)).ToList(),
User = d.User != null ? Map(d.User) : null
};
return scenario;
}
private static List<IndicatorDto> Map(List<Indicator> indicators)
{
return indicators.ConvertAll(strategy => Map(strategy));
}
internal static Indicator Map(IndicatorDto indicatorDto)
{
if (indicatorDto == null)
return null;
return new Indicator(indicatorDto.Name, indicatorDto.Type)
{
SignalType = indicatorDto.SignalType,
MinimumHistory = indicatorDto.MinimumHistory,
Period = indicatorDto.Period,
FastPeriods = indicatorDto.FastPeriods,
SlowPeriods = indicatorDto.SlowPeriods,
SignalPeriods = indicatorDto.SignalPeriods,
Multiplier = indicatorDto.Multiplier,
SmoothPeriods = indicatorDto.SmoothPeriods,
StochPeriods = indicatorDto.StochPeriods,
CyclePeriods = indicatorDto.CyclePeriods,
User = indicatorDto.User != null ? Map(indicatorDto.User) : null
};
}
internal static IndicatorDto Map(Indicator indicator)
{
if (indicator == null)
return null;
return new IndicatorDto
{
Name = indicator.Name,
Type = indicator.Type,
SignalType = indicator.SignalType,
MinimumHistory = indicator.MinimumHistory,
Period = indicator.Period,
FastPeriods = indicator.FastPeriods,
SlowPeriods = indicator.SlowPeriods,
SignalPeriods = indicator.SignalPeriods,
Multiplier = indicator.Multiplier,
SmoothPeriods = indicator.SmoothPeriods,
StochPeriods = indicator.StochPeriods,
CyclePeriods = indicator.CyclePeriods,
User = indicator.User != null ? Map(indicator.User) : null
};
}
internal static IEnumerable<Indicator> Map(IEnumerable<IndicatorDto> indicators)
{
return indicators.Select(indicator => Map(indicator));
}
#endregion
#region Money Management
public static MoneyManagementDto Map(MoneyManagement request)
{
if (request == null) return null;
return new MoneyManagementDto
{
Timeframe = request.Timeframe,
StopLoss = request.StopLoss,
TakeProfit = request.TakeProfit,
Leverage = request.Leverage,
Name = request.Name,
User = request.User != null ? Map(request.User) : null
};
}
public static MoneyManagement Map(MoneyManagementDto request)
{
if (request == null)
return null;
return new MoneyManagement
{
Timeframe = request.Timeframe,
StopLoss = request.StopLoss,
TakeProfit = request.TakeProfit,
Leverage = request.Leverage,
Name = request.Name,
User = request.User != null ? Map(request.User) : null
};
}
internal static User Map(UserDto user)
{
if (user == null)
return null;
return new User
{
Name = user.Name,
AgentName = user.AgentName,
AvatarUrl = user.AvatarUrl,
TelegramChannel = user.TelegramChannel
};
}
internal static UserDto Map(User user)
{
return new UserDto
{
Name = user.Name,
AgentName = user.AgentName,
AvatarUrl = user.AvatarUrl,
TelegramChannel = user.TelegramChannel
};
}
internal static SpotlighOverviewDto Map(SpotlightOverview overview)
{
return new SpotlighOverviewDto
{
Spotlights = Map(overview.Spotlights),
DateTime = overview.DateTime,
Identifier = overview.Identifier,
ScenarioCount = overview.ScenarioCount,
};
}
private static List<SpotlightDto> Map(List<Spotlight> spotlights)
{
return spotlights.ConvertAll(spotlight => new SpotlightDto
{
Scenario = new ScenarioDto
{
Name = spotlight.Scenario.Name,
Indicators =
spotlight.Scenario.Indicators.ConvertAll(
spotlightScenarioStrategy => Map(spotlightScenarioStrategy))
},
TickerSignals = spotlight.TickerSignals.ConvertAll(spotlightTickerSignal => new TickerSignalDto
{
Ticker = spotlightTickerSignal.Ticker,
FiveMinutes =
spotlightTickerSignal.FiveMinutes?.ConvertAll(spotlightTickerSignalFiveMinute =>
Map(spotlightTickerSignalFiveMinute)) ?? new List<SignalDto>(),
FifteenMinutes =
spotlightTickerSignal.FifteenMinutes?.ConvertAll(spotlightTickerSignalFifteenMinute =>
Map(spotlightTickerSignalFifteenMinute)) ?? new List<SignalDto>(),
OneHour = spotlightTickerSignal.OneHour?.ConvertAll(spotlightTickerSignalOneHour =>
Map(spotlightTickerSignalOneHour)) ?? new List<SignalDto>(),
FourHour = spotlightTickerSignal.FourHour?.ConvertAll(spotlightTickerSignalFourHour =>
Map(spotlightTickerSignalFourHour)) ?? new List<SignalDto>(),
OneDay = spotlightTickerSignal.OneDay?.ConvertAll(spotlightTickerSignalOneDay =>
Map(spotlightTickerSignalOneDay)) ?? new List<SignalDto>()
})
});
}
internal static SpotlightOverview Map(SpotlighOverviewDto overview)
{
return new SpotlightOverview
{
Spotlights = Map(overview.Spotlights),
DateTime = overview.DateTime,
Identifier = overview.Identifier,
ScenarioCount = overview.ScenarioCount
};
}
private static List<Spotlight> Map(List<SpotlightDto> spotlights)
{
return spotlights.ConvertAll(spotlight => new Spotlight
{
Scenario = new Scenario(name: spotlight.Scenario.Name)
{
Indicators =
spotlight.Scenario.Indicators.ConvertAll(
spotlightScenarioStrategy => Map(spotlightScenarioStrategy))
},
TickerSignals = spotlight.TickerSignals.ConvertAll(spotlightTickerSignal => new TickerSignal
{
Ticker = spotlightTickerSignal.Ticker,
FiveMinutes = spotlightTickerSignal.FiveMinutes.ConvertAll(spotlightTickerSignalFiveMinute =>
Map(spotlightTickerSignalFiveMinute)),
FifteenMinutes = spotlightTickerSignal.FifteenMinutes.ConvertAll(spotlightTickerSignalFifteenMinute =>
Map(spotlightTickerSignalFifteenMinute)),
OneHour = spotlightTickerSignal.OneHour.ConvertAll(spotlightTickerSignalOneHour =>
Map(spotlightTickerSignalOneHour)),
FourHour = spotlightTickerSignal.FourHour.ConvertAll(spotlightTickerSignalFourHour =>
Map(spotlightTickerSignalFourHour)),
OneDay = spotlightTickerSignal.OneDay.ConvertAll(spotlightTickerSignalOneDay =>
Map(spotlightTickerSignalOneDay))
})
});
}
internal static IList<SpotlightOverview> Map(IEnumerable<SpotlighOverviewDto> overviews)
{
return overviews.Select(Map).ToList();
}
internal static FeeDto Map(Fee fee)
{
return new FeeDto
{
Cost = fee.Cost,
Exchange = fee.Exchange,
LastUpdate = fee.LastUpdate
};
}
internal static Fee Map(FeeDto fee)
{
if (fee == null) return null;
return new Fee
{
Cost = fee.Cost,
Exchange = fee.Exchange,
LastUpdate = fee.LastUpdate
};
}
internal static List<Trader> Map(IEnumerable<BestTraderDto> enumerable)
{
return enumerable.Select(enumerableElement => new Trader
{
Address = enumerableElement.Address,
Winrate = enumerableElement.Winrate,
Pnl = enumerableElement.Pnl,
TradeCount = enumerableElement.TradeCount,
AverageWin = enumerableElement.AverageWin,
AverageLoss = enumerableElement.AverageLoss,
Roi = enumerableElement.Roi
}).ToList();
}
internal static BestTraderDto Map(Trader trader)
{
return new BestTraderDto
{
Address = trader.Address,
Winrate = trader.Winrate,
Pnl = trader.Pnl,
TradeCount = trader.TradeCount,
AverageWin = trader.AverageWin,
AverageLoss = trader.AverageLoss,
Roi = trader.Roi
};
}
internal static List<Trader> Map(IEnumerable<BadTraderDto> enumerable)
{
return enumerable.Select(enumerableElement => new Trader
{
Address = enumerableElement.Address,
Winrate = enumerableElement.Winrate,
Pnl = enumerableElement.Pnl,
TradeCount = enumerableElement.TradeCount,
AverageWin = enumerableElement.AverageWin,
AverageLoss = enumerableElement.AverageLoss,
Roi = enumerableElement.Roi
}).ToList();
}
internal static BadTraderDto BadTraderMap(Trader trader)
{
return new BadTraderDto
{
Address = trader.Address,
Winrate = trader.Winrate,
Pnl = trader.Pnl,
TradeCount = trader.TradeCount,
AverageWin = trader.AverageWin,
AverageLoss = trader.AverageLoss,
Roi = trader.Roi
};
}
internal static WorkflowDto Map(SyntheticWorkflow workflow)
{
return new WorkflowDto
{
Name = workflow.Name,
Description = workflow.Description,
Usage = workflow.Usage,
Flows = workflow.Flows
};
}
internal static SyntheticWorkflow Map(WorkflowDto m)
{
if (m == null) return null;
return new SyntheticWorkflow
{
Name = m.Name,
Usage = m.Usage,
Description = m.Description,
Flows = m.Flows.ToList(),
};
}
internal static BotDto Map(BotBackup bot)
{
if (bot == null) return null;
return new BotDto
{
User = Map(bot.User),
Identifier = bot.Identifier,
Data = bot.Data,
LastStatus = bot.LastStatus
};
}
internal static BotBackup Map(BotDto b)
{
if (b == null) return null;
return new BotBackup
{
User = Map(b.User),
Identifier = b.Identifier,
Data = b.Data,
LastStatus = b.LastStatus
};
}
#endregion
public static FundingRate Map(FundingRateDto fundingRate)
{
if (fundingRate == null)
return null;
return new FundingRate
{
Exchange = fundingRate.Exchange,
Rate = fundingRate.Rate,
Ticker = fundingRate.Ticker,
Date = fundingRate.Date,
Direction = fundingRate.Direction
};
}
public static FundingRateDto Map(FundingRate fundingRate)
{
return new FundingRateDto
{
Exchange = fundingRate.Exchange,
Rate = fundingRate.Rate,
Ticker = fundingRate.Ticker,
Date = fundingRate.Date,
Direction = fundingRate.Direction
};
}
#region Synth
/// <summary>
/// Maps domain SynthMinersLeaderboard to MongoDB DTO
/// </summary>
internal static SynthMinersLeaderboardDto Map(SynthMinersLeaderboard leaderboard)
{
if (leaderboard == null) return null;
return new SynthMinersLeaderboardDto
{
Asset = leaderboard.Asset,
TimeIncrement = leaderboard.TimeIncrement,
SignalDate = leaderboard.SignalDate,
IsBacktest = leaderboard.IsBacktest,
MinersData = JsonSerializer.Serialize(leaderboard.Miners),
CacheKey = leaderboard.GetCacheKey()
};
}
/// <summary>
/// Maps MongoDB DTO to domain SynthMinersLeaderboard
/// </summary>
internal static SynthMinersLeaderboard Map(SynthMinersLeaderboardDto dto)
{
if (dto == null) return null;
var miners = string.IsNullOrEmpty(dto.MinersData)
? new List<MinerInfo>()
: JsonSerializer.Deserialize<List<MinerInfo>>(dto.MinersData) ?? new List<MinerInfo>();
return new SynthMinersLeaderboard
{
Id = dto.Id.ToString(),
Asset = dto.Asset,
TimeIncrement = dto.TimeIncrement,
SignalDate = dto.SignalDate,
IsBacktest = dto.IsBacktest,
Miners = miners,
CreatedAt = dto.CreatedAt
};
}
/// <summary>
/// Maps domain SynthMinersPredictions to MongoDB DTO
/// </summary>
internal static SynthMinersPredictionsDto Map(SynthMinersPredictions predictions)
{
if (predictions == null) return null;
return new SynthMinersPredictionsDto
{
Asset = predictions.Asset,
TimeIncrement = predictions.TimeIncrement,
TimeLength = predictions.TimeLength,
SignalDate = predictions.SignalDate,
IsBacktest = predictions.IsBacktest,
MinerUidsData = JsonSerializer.Serialize(predictions.MinerUids),
PredictionsData = JsonSerializer.Serialize(predictions.Predictions),
CacheKey = predictions.GetCacheKey()
};
}
/// <summary>
/// Maps MongoDB DTO to domain SynthMinersPredictions
/// </summary>
internal static SynthMinersPredictions Map(SynthMinersPredictionsDto dto)
{
if (dto == null) return null;
var minerUids = string.IsNullOrEmpty(dto.MinerUidsData)
? new List<int>()
: JsonSerializer.Deserialize<List<int>>(dto.MinerUidsData) ?? new List<int>();
var predictions = string.IsNullOrEmpty(dto.PredictionsData)
? new List<MinerPrediction>()
: JsonSerializer.Deserialize<List<MinerPrediction>>(dto.PredictionsData) ?? new List<MinerPrediction>();
return new SynthMinersPredictions
{
Id = dto.Id.ToString(),
Asset = dto.Asset,
TimeIncrement = dto.TimeIncrement,
TimeLength = dto.TimeLength,
SignalDate = dto.SignalDate,
IsBacktest = dto.IsBacktest,
MinerUids = minerUids,
Predictions = predictions,
CreatedAt = dto.CreatedAt
};
}
/// <summary>
/// Maps domain SynthPrediction to MongoDB DTO
/// </summary>
internal static SynthPredictionDto Map(SynthPrediction prediction)
{
if (prediction == null) return null;
return new SynthPredictionDto
{
Asset = prediction.Asset,
MinerUid = prediction.MinerUid,
TimeIncrement = prediction.TimeIncrement,
TimeLength = prediction.TimeLength,
SignalDate = prediction.SignalDate,
IsBacktest = prediction.IsBacktest,
PredictionData = JsonSerializer.Serialize(prediction.Prediction),
CacheKey = prediction.GetCacheKey()
};
}
/// <summary>
/// Maps MongoDB DTO to domain SynthPrediction
/// </summary>
internal static SynthPrediction Map(SynthPredictionDto dto)
{
if (dto == null) return null;
var prediction = string.IsNullOrEmpty(dto.PredictionData)
? null
: JsonSerializer.Deserialize<MinerPrediction>(dto.PredictionData);
return new SynthPrediction
{
Id = dto.Id.ToString(),
Asset = dto.Asset,
MinerUid = dto.MinerUid,
TimeIncrement = dto.TimeIncrement,
TimeLength = dto.TimeLength,
SignalDate = dto.SignalDate,
IsBacktest = dto.IsBacktest,
Prediction = prediction,
CreatedAt = dto.CreatedAt
};
}
#endregion
#region TradingBotConfig
public static TradingBotConfigDto Map(TradingBotConfig config)
{
if (config == null)
return null;
return new TradingBotConfigDto
{
AccountName = config.AccountName,
MoneyManagement = Map(config.MoneyManagement),
Ticker = config.Ticker,
Timeframe = config.Timeframe,
IsForWatchingOnly = config.IsForWatchingOnly,
BotTradingBalance = config.BotTradingBalance,
IsForBacktest = config.IsForBacktest,
CooldownPeriod = config.CooldownPeriod,
MaxLossStreak = config.MaxLossStreak,
FlipPosition = config.FlipPosition,
Name = config.Name,
RiskManagement = Map(config.RiskManagement),
Scenario = Map(config.Scenario),
ScenarioName = config.ScenarioName,
MaxPositionTimeHours = config.MaxPositionTimeHours,
CloseEarlyWhenProfitable = config.CloseEarlyWhenProfitable,
FlipOnlyWhenInProfit = config.FlipOnlyWhenInProfit,
UseSynthApi = config.UseSynthApi,
UseForPositionSizing = config.UseForPositionSizing,
UseForSignalFiltering = config.UseForSignalFiltering,
UseForDynamicStopLoss = config.UseForDynamicStopLoss
};
}
public static TradingBotConfig Map(TradingBotConfigDto dto)
{
if (dto == null)
return null;
return new TradingBotConfig
{
AccountName = dto.AccountName,
MoneyManagement = Map(dto.MoneyManagement),
Ticker = dto.Ticker,
Timeframe = dto.Timeframe,
IsForWatchingOnly = dto.IsForWatchingOnly,
BotTradingBalance = dto.BotTradingBalance,
IsForBacktest = dto.IsForBacktest,
CooldownPeriod = dto.CooldownPeriod,
MaxLossStreak = dto.MaxLossStreak,
FlipPosition = dto.FlipPosition,
Name = dto.Name,
RiskManagement = Map(dto.RiskManagement),
Scenario = Map(dto.Scenario),
ScenarioName = dto.ScenarioName,
MaxPositionTimeHours = dto.MaxPositionTimeHours,
CloseEarlyWhenProfitable = dto.CloseEarlyWhenProfitable,
FlipOnlyWhenInProfit = dto.FlipOnlyWhenInProfit,
UseSynthApi = dto.UseSynthApi,
UseForPositionSizing = dto.UseForPositionSizing,
UseForSignalFiltering = dto.UseForSignalFiltering,
UseForDynamicStopLoss = dto.UseForDynamicStopLoss
};
}
#endregion
#region RiskManagement
public static RiskManagementDto Map(RiskManagement riskManagement)
{
if (riskManagement == null)
return null;
return new RiskManagementDto
{
AdverseProbabilityThreshold = riskManagement.AdverseProbabilityThreshold,
FavorableProbabilityThreshold = riskManagement.FavorableProbabilityThreshold,
RiskAversion = riskManagement.RiskAversion,
KellyMinimumThreshold = riskManagement.KellyMinimumThreshold,
KellyMaximumCap = riskManagement.KellyMaximumCap,
MaxLiquidationProbability = riskManagement.MaxLiquidationProbability,
SignalValidationTimeHorizonHours = riskManagement.SignalValidationTimeHorizonHours,
PositionMonitoringTimeHorizonHours = riskManagement.PositionMonitoringTimeHorizonHours,
PositionWarningThreshold = riskManagement.PositionWarningThreshold,
PositionAutoCloseThreshold = riskManagement.PositionAutoCloseThreshold,
KellyFractionalMultiplier = riskManagement.KellyFractionalMultiplier,
RiskTolerance = riskManagement.RiskTolerance,
UseExpectedUtility = riskManagement.UseExpectedUtility,
UseKellyCriterion = riskManagement.UseKellyCriterion
};
}
public static RiskManagement Map(RiskManagementDto dto)
{
if (dto == null)
return null;
return new RiskManagement
{
AdverseProbabilityThreshold = dto.AdverseProbabilityThreshold,
FavorableProbabilityThreshold = dto.FavorableProbabilityThreshold,
RiskAversion = dto.RiskAversion,
KellyMinimumThreshold = dto.KellyMinimumThreshold,
KellyMaximumCap = dto.KellyMaximumCap,
MaxLiquidationProbability = dto.MaxLiquidationProbability,
SignalValidationTimeHorizonHours = dto.SignalValidationTimeHorizonHours,
PositionMonitoringTimeHorizonHours = dto.PositionMonitoringTimeHorizonHours,
PositionWarningThreshold = dto.PositionWarningThreshold,
PositionAutoCloseThreshold = dto.PositionAutoCloseThreshold,
KellyFractionalMultiplier = dto.KellyFractionalMultiplier,
RiskTolerance = dto.RiskTolerance,
UseExpectedUtility = dto.UseExpectedUtility,
UseKellyCriterion = dto.UseKellyCriterion
};
}
#endregion
}