docker files fixes from liaqat

This commit is contained in:
alirehmani
2024-05-03 16:39:25 +05:00
commit 464a8730e8
587 changed files with 44288 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using MongoDB.Driver;
using System.Linq.Expressions;
namespace Managing.Infrastructure.Databases.MongoDb.Abstractions
{
public interface IMongoRepository<TDocument> where TDocument : IDocument
{
IQueryable<TDocument> AsQueryable();
IEnumerable<TDocument> FilterBy(
Expression<Func<TDocument, bool>> filterExpression);
IEnumerable<TDocument> FindAll();
IEnumerable<TDocument> FilterBy(FilterDefinition<TDocument> filter);
IEnumerable<TProjected> FilterBy<TProjected>(
Expression<Func<TDocument, bool>> filterExpression,
Expression<Func<TDocument, TProjected>> projectionExpression);
TDocument FindOne(Expression<Func<TDocument, bool>> filterExpression);
Task<TDocument> FindOneAsync(Expression<Func<TDocument, bool>> filterExpression);
TDocument FindById(string id);
Task<TDocument> FindByIdAsync(string id);
void InsertOne(TDocument document);
Task InsertOneAsync(TDocument document);
void InsertMany(ICollection<TDocument> documents);
Task InsertManyAsync(ICollection<TDocument> documents);
void ReplaceOne(TDocument document);
Task ReplaceOneAsync(TDocument document);
void DeleteOne(Expression<Func<TDocument, bool>> filterExpression);
Task DeleteOneAsync(Expression<Func<TDocument, bool>> filterExpression);
void DeleteById(string id);
Task DeleteByIdAsync(string id);
void DeleteMany(Expression<Func<TDocument, bool>> filterExpression);
Task DeleteManyAsync(Expression<Func<TDocument, bool>> filterExpression);
void Update(TDocument entity);
void CreateIndex(string column);
void DropCollection();
}
}

View File

@@ -0,0 +1,13 @@
namespace Managing.Infrastructure.Databases.MongoDb.Attributes
{
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class BsonCollectionAttribute : Attribute
{
public string CollectionName { get; }
public BsonCollectionAttribute(string collectionName)
{
CollectionName = collectionName;
}
}
}

View File

@@ -0,0 +1,16 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb.Collections;
[BsonCollection("Accounts")]
public class AccountDto : Document
{
public UserDto User { get; set; }
public string Name { get; set; }
public TradingExchanges Exchanges { get; set; }
public AccountType Type { get; set; }
public string Key { get; set; }
public string Secret { get; set; }
}

View File

@@ -0,0 +1,26 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb.Collections
{
[BsonCollection("Backtests")]
public class BacktestDto : Document
{
public decimal FinalPnl { get; set; }
public int WinRate { get; set; }
public decimal GrowthPercentage { get; set; }
public decimal HodlPercentage { get; set; }
public Ticker Ticker { get; set; }
public string Scenario { get; set; }
public List<PositionDto> Positions { get; set; }
public List<SignalDto> Signals { get; set; }
public Timeframe Timeframe { get; set; }
public RiskLevel RiskLevel { get; set; }
public string AccountName { get; set; }
public List<CandleDto> Candles { get; set; }
public BotType BotType { get; set; }
public MoneyManagementDto MoneyManagement { get; internal set; }
public MoneyManagementDto OptimizedMoneyManagement { get; internal set; }
}
}

View File

@@ -0,0 +1,17 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
namespace Managing.Infrastructure.Databases.MongoDb.Collections;
[BsonCollection("BadTrader")]
public class BadTraderDto : Document
{
public string Address { get; set; }
public int Winrate { get; set; }
public decimal Pnl { get; set; }
public int TradeCount { get; set; }
public decimal AverageWin { get; set; }
public decimal AverageLoss { get; set; }
public decimal Roi { get; set; }
}

View File

@@ -0,0 +1,16 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
namespace Managing.Infrastructure.Databases.MongoDb.Collections;
[BsonCollection("BestTrader")]
public class BestTraderDto : Document
{
public string Address { get; set; }
public int Winrate { get; set; }
public decimal Pnl { get; set; }
public int TradeCount { get; set; }
public decimal AverageWin { get; set; }
public decimal AverageLoss { get; set; }
public decimal Roi { get; set; }
}

View File

@@ -0,0 +1,28 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using MongoDB.Bson.Serialization.Attributes;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb.Collections
{
[BsonCollection("Candles")]
public class CandleDto : Document
{
public TradingExchanges Exchange { get; set; }
public Timeframe Timeframe { get; set; }
public string Ticker { get; set; }
[BsonDateTimeOptions]
public DateTime OpenTime { get; set; }
[BsonDateTimeOptions]
public DateTime CloseTime { get; set; }
public decimal Open { get; set; }
public decimal Close { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public decimal BaseVolume { get; set; }
public decimal QuoteVolume { get; set; }
public int TradeCount { get; set; }
public decimal TakerBuyBaseVolume { get; set; }
public decimal TakerBuyQuoteVolume { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb.Collections;
[BsonCollection("Fees")]
public class FeeDto : Document
{
public decimal Cost { get; set; }
public TradingExchanges Exchange { get; set; }
public DateTime LastUpdate { get; set; }
}

View File

@@ -0,0 +1,18 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb.Collections
{
[BsonCollection("MoneyManagement")]
public class MoneyManagementDto : Document
{
public Timeframe Timeframe { get; set; }
public RiskLevel RiskLevel { get; set; }
public decimal BalanceAtRisk { get; set; }
public decimal StopLoss { get; set; }
public decimal TakeProfit { get; set; }
public decimal Leverage { get; set; }
public string Name { get; internal set; }
}
}

View File

@@ -0,0 +1,27 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using MongoDB.Bson.Serialization.Attributes;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb.Collections
{
[BsonCollection("Positions")]
public class PositionDto : Document
{
[BsonDateTimeOptions]
public DateTime Date { get; set; }
public TradeDto Open { get; set; }
public TradeDto StopLoss { get; set; }
public TradeDto TakeProfit1 { get; set; }
public TradeDto TakeProfit2 { get; set; }
public decimal ProfitAndLoss { get; set; }
public TradeDirection OriginDirection { get; set; }
public string Identifier { get; set; }
public PositionStatus Status { get; set; }
public Ticker Ticker { get; set; }
public string SignalIdentifier { get; set; }
public string AccountName { get; set; }
public MoneyManagementDto MoneyManagement { get; set; }
public PositionInitiator Initiator { get; set; }
}
}

View File

@@ -0,0 +1,12 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
namespace Managing.Infrastructure.Databases.MongoDb.Collections
{
[BsonCollection("Scenarios")]
public class ScenarioDto : Document
{
public string Name { get; set; }
public List<StrategyDto> Strategies { get; set; }
}
}

View File

@@ -0,0 +1,21 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb.Collections
{
[BsonCollection("Signals")]
public class SignalDto : Document
{
public TradeDirection Direction { get; set; }
public Confidence Confidence { get; set; }
public DateTime Date { get; set; }
public CandleDto Candle { get; set; }
public string Identifier { get; set; }
public Ticker Ticker { get; set; }
public SignalStatus Status { get; set; }
public Timeframe Timeframe { get; set; }
public StrategyType Type { get; set; }
public SignalType SignalType { get; set; }
}
}

View File

@@ -0,0 +1,30 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb.Collections;
[BsonCollection("SpotlighOverview")]
public class SpotlighOverviewDto : Document
{
public List<SpotlightDto> Spotlights { get; set; }
public DateTime DateTime { get; set; }
public Guid Identifier { get; set; }
public int ScenarioCount { get; set; }
}
public class SpotlightDto
{
public ScenarioDto Scenario { get; set; }
public List<TickerSignalDto> TickerSignals { get; set; }
}
public class TickerSignalDto
{
public Ticker Ticker { get; set; }
public List<SignalDto> FiveMinutes { get; set; }
public List<SignalDto> FifteenMinutes { get; set; }
public List<SignalDto> OneHour { get; set; }
public List<SignalDto> FourHour { get; set; }
public List<SignalDto> OneDay { get; set; }
}

View File

@@ -0,0 +1,23 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb.Collections
{
[BsonCollection("Strategies")]
public class StrategyDto : Document
{
public StrategyType Type { get; set; }
public Timeframe Timeframe { get; set; }
public string Name { get; set; }
public int? Period { get; set; }
public int? FastPeriods { get; set; }
public int? SlowPeriods { get; set; }
public int? SignalPeriods { get; set; }
public double? Multiplier { get; set; }
public int? StochPeriods { get; set; }
public int? SmoothPeriods { get; set; }
public int? CyclePeriods { get; set; }
public SignalType SignalType { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb.Collections;
[BsonCollection("TopVolumeTickers")]
public class TopVolumeTickerDto : Document
{
public Ticker Ticker { get; set; }
public DateTime Date { get; set; }
public decimal Volume { get; set; }
public int Rank { get; set; }
public TradingExchanges Exchange { get; set; }
}

View File

@@ -0,0 +1,24 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using MongoDB.Bson.Serialization.Attributes;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb.Collections
{
[BsonCollection("Trades")]
public class TradeDto : Document
{
[BsonDateTimeOptions]
public DateTime Date { get; set; }
public TradeDirection Direction { get; set; }
public TradeStatus Status { get; set; }
public TradeType TradeType { get; set; }
public Ticker Ticker { get; set; }
public decimal Fee { get; set; }
public decimal Quantity { get; set; }
public decimal Price { get; set; }
public decimal Leverage { get; set; }
public string ExchangeOrderId { get; set; }
public string Message { get; set; }
}
}

View File

@@ -0,0 +1,10 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
namespace Managing.Infrastructure.Databases.MongoDb.Collections;
[BsonCollection("Users")]
public class UserDto : Document
{
public string Name { get; set; }
}

View File

@@ -0,0 +1,16 @@
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb.Collections;
[BsonCollection("Workers")]
public class WorkerDto : Document
{
public WorkerType WorkerType { get; set; }
public DateTime StartTime { get; set; }
public DateTime? LastRunTime { get; set; }
public int ExecutionCount { get; set; }
public TimeSpan Delay { get; set; }
public bool IsActive { get; set; }
}

View File

@@ -0,0 +1,16 @@
using Managing.Domain.Workflows.Synthetics;
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using static Managing.Common.Enums;
namespace Managing.Infrastructure.Databases.MongoDb.Collections;
[BsonCollection("Workflow")]
public class WorkflowDto : Document
{
public string Name { get; set; }
public string Description { get; set; }
public WorkflowUsage Usage { get; set; }
public List<SyntheticFlow> Flows { get; set; }
}

View File

@@ -0,0 +1,13 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace Managing.Infrastructure.Databases.MongoDb.Configurations
{
public abstract class Document : IDocument
{
[BsonId]
public ObjectId Id { get; set; }
[BsonDateTimeOptions]
public DateTime CreatedAt => Id.CreationTime;
}
}

View File

@@ -0,0 +1,14 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace Managing.Infrastructure.Databases.MongoDb.Configurations
{
public interface IDocument
{
[BsonId]
[BsonRepresentation(BsonType.String)]
ObjectId Id { get; set; }
DateTime CreatedAt { get; }
}
}

View File

@@ -0,0 +1,8 @@
namespace Managing.Infrastructure.Databases.MongoDb
{
public interface IManagingDatabaseSettings
{
string ConnectionString { get; set; }
string DatabaseName { get; set; }
}
}

View File

@@ -0,0 +1,7 @@
namespace Managing.Infrastructure.Databases.MongoDb;
public class ManagingDatabaseSettings : IManagingDatabaseSettings
{
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}

View File

@@ -0,0 +1,20 @@
using MongoDB.Bson;
using MongoDB.Driver;
namespace Managing.Infrastructure.Databases.MongoDb
{
public static class MongoHelpers
{
public static async Task EnsureIndexExists(this IMongoDatabase database, string collectionName, string indexName)
{
var collection = database.GetCollection<BsonDocument>(collectionName);
var index = new BsonDocument
{
{indexName, 1}
};
var indexModel = new CreateIndexModel<BsonDocument>(index, new CreateIndexOptions { Unique = true });
await collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false);
}
}
}

View File

@@ -0,0 +1,654 @@
using Managing.Domain.Accounts;
using Managing.Domain.Backtests;
using Managing.Domain.Candles;
using Managing.Domain.MoneyManagements;
using Managing.Domain.Scenarios;
using Managing.Domain.Statistics;
using Managing.Domain.Strategies;
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)
{
return new Backtest(
ticker: b.Ticker,
scenario: b.Scenario,
positions: b.Positions.ConvertAll(bPosition => Map(bPosition)),
signals: b.Signals != null ? b.Signals.ConvertAll(bSignal => Map(bSignal)) : null,
timeframe: b.Timeframe,
candles: b.Candles.ConvertAll(bCandle => Map(bCandle)),
accountName: b.AccountName,
botType: b.BotType)
{
Id = b.Id.ToString(),
FinalPnl = b.FinalPnl,
WinRate = b.WinRate,
GrowthPercentage = b.GrowthPercentage,
HodlPercentage = b.HodlPercentage,
MoneyManagement = Map(b.MoneyManagement),
OptimizedMoneyManagement = Map(b.OptimizedMoneyManagement)
};
}
internal static BacktestDto Map(Backtest result)
{
var backtest = new BacktestDto
{
FinalPnl = result.FinalPnl,
WinRate = result.WinRate,
GrowthPercentage = result.GrowthPercentage,
HodlPercentage = result.HodlPercentage,
Candles = Map(result.Candles),
Positions = Map(result.Positions),
AccountName = result.AccountName,
BotType = result.BotType,
MoneyManagement = Map(result.MoneyManagement),
OptimizedMoneyManagement = Map(result.OptimizedMoneyManagement),
};
backtest.Timeframe = result.Timeframe;
backtest.Ticker = result.Ticker;
backtest.Scenario = result.Scenario;
return backtest;
}
#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
};
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.AccountName, originDirection: dto.OriginDirection, dto.Ticker, Map(dto.MoneyManagement), dto.Initiator, dto.Date)
{
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
};
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
{
Identifier = signal.Identifier,
Direction = signal.Direction,
Candle = Map(signal.Candle),
Confidence = signal.Confidence,
Date = signal.Date,
Ticker = signal.Ticker,
Status = signal.Status,
Timeframe = signal.Timeframe,
Type = signal.StrategyType
};
}
internal static Signal Map(SignalDto bSignal)
{
return new Signal(ticker: bSignal.Ticker, direction: bSignal.Direction, confidence: bSignal.Confidence,
candle: Map(bSignal.Candle), date: bSignal.Date, exchange: default, timeframe: bSignal.Timeframe,
strategyType: bSignal.Type, signalType: bSignal.SignalType)
{
Status = bSignal.Status
};
}
#endregion
#region Scenarios
public static ScenarioDto Map(Scenario scenario)
{
return new ScenarioDto()
{
Name = scenario.Name,
Strategies = Map(scenario.Strategies),
};
}
internal static IEnumerable<Scenario> Map(IEnumerable<ScenarioDto> dtos)
{
return dtos.Select(d => Map(d));
}
internal static Scenario Map(ScenarioDto d)
{
return new Scenario(d.Name)
{
Name = d.Name,
Strategies = Map(d.Strategies).ToList()
};
}
private static List<StrategyDto> Map(List<Strategy> strategies)
{
return strategies.ConvertAll(strategy => Map(strategy));
}
internal static Strategy Map(StrategyDto strategyDto)
{
return new Strategy(name: strategyDto.Name, timeframe: strategyDto.Timeframe, type: strategyDto.Type)
{
Period = strategyDto.Period,
FastPeriods = strategyDto.FastPeriods,
SlowPeriods = strategyDto.SlowPeriods,
SignalPeriods = strategyDto.SignalPeriods,
Multiplier = strategyDto.Multiplier,
SmoothPeriods = strategyDto.SmoothPeriods,
StochPeriods = strategyDto.StochPeriods,
CyclePeriods = strategyDto.CyclePeriods
};
}
internal static StrategyDto Map(Strategy strategy)
{
var dto = new StrategyDto
{
Type = strategy.Type,
Timeframe = strategy.Timeframe,
Name = strategy.Name,
SignalType = strategy.SignalType
};
switch (strategy.Type)
{
case StrategyType.RsiDivergenceConfirm:
case StrategyType.RsiDivergence:
case StrategyType.EmaCross:
case StrategyType.EmaTrend:
case StrategyType.StDev:
dto.Period = strategy.Period;
break;
case StrategyType.MacdCross:
dto.SlowPeriods = strategy.SlowPeriods;
dto.FastPeriods = strategy.FastPeriods;
dto.SignalPeriods = strategy.SignalPeriods;
break;
case StrategyType.ThreeWhiteSoldiers:
break;
case StrategyType.ChandelierExit:
case StrategyType.SuperTrend:
dto.Period = strategy.Period;
dto.Multiplier = strategy.Multiplier;
break;
case StrategyType.StochRsiTrend:
dto.Period = strategy.Period;
dto.StochPeriods = strategy.StochPeriods;
dto.SignalPeriods = strategy.SignalPeriods;
dto.SmoothPeriods = strategy.SmoothPeriods;
break;
case StrategyType.Stc:
dto.SlowPeriods = strategy.SlowPeriods;
dto.FastPeriods = strategy.FastPeriods;
dto.CyclePeriods = strategy.CyclePeriods;
break;
default:
break;
}
return dto;
}
internal static IEnumerable<Strategy> Map(IEnumerable<StrategyDto> strategies)
{
return strategies.Select(strategy => Map(strategy));
}
#endregion
#region Money Management
public static MoneyManagementDto Map(MoneyManagement request)
{
if (request == null) return null;
return new MoneyManagementDto
{
Timeframe = request.Timeframe,
BalanceAtRisk = request.BalanceAtRisk,
StopLoss = request.StopLoss,
TakeProfit = request.TakeProfit,
Leverage = request.Leverage,
Name = request.Name
};
}
public static MoneyManagement Map(MoneyManagementDto request)
{
if (request == null)
return null;
return new MoneyManagement
{
Timeframe = request.Timeframe,
BalanceAtRisk = request.BalanceAtRisk,
StopLoss = request.StopLoss,
TakeProfit = request.TakeProfit,
Leverage = request.Leverage,
Name = request.Name
};
}
internal static User Map(UserDto user)
{
if (user == null)
return null;
return new User
{
Name = user.Name,
};
}
internal static UserDto Map(User user)
{
return new UserDto
{
Name = user.Name
};
}
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,
Strategies = spotlight.Scenario.Strategies.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)
{
Strategies = spotlight.Scenario.Strategies.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(),
};
}
#endregion
}

View File

@@ -0,0 +1,178 @@
using Managing.Infrastructure.Databases.MongoDb.Abstractions;
using Managing.Infrastructure.Databases.MongoDb.Attributes;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Linq.Expressions;
namespace Managing.Infrastructure.Databases.MongoDb
{
public class MongoRepository<TDocument> : IMongoRepository<TDocument>
where TDocument : IDocument
{
private readonly IMongoCollection<TDocument> _collection;
private readonly IMongoDatabase _database;
public MongoRepository(IManagingDatabaseSettings settings)
{
_database = new MongoClient(settings.ConnectionString).GetDatabase(settings.DatabaseName);
_collection = _database.GetCollection<TDocument>(GetCollectionName(typeof(TDocument)));
}
private protected string GetCollectionName(Type documentType)
{
return ((BsonCollectionAttribute)documentType.GetCustomAttributes(
typeof(BsonCollectionAttribute),
true)
.FirstOrDefault())?.CollectionName;
}
public virtual IQueryable<TDocument> AsQueryable()
{
return _collection.AsQueryable();
}
public virtual IEnumerable<TDocument> FilterBy(
Expression<Func<TDocument, bool>> filterExpression)
{
return _collection.Find(filterExpression).ToEnumerable();
}
public virtual IEnumerable<TDocument> FilterBy(FilterDefinition<TDocument> filter)
{
return _collection.Find(filter).ToEnumerable();
}
public virtual IEnumerable<TDocument> FindAll()
{
return _collection.Find(_ => true).ToEnumerable();
}
public virtual IEnumerable<TProjected> FilterBy<TProjected>(
Expression<Func<TDocument, bool>> filterExpression,
Expression<Func<TDocument, TProjected>> projectionExpression)
{
return _collection.Find(filterExpression).Project(projectionExpression).ToEnumerable();
}
public virtual TDocument FindOne(Expression<Func<TDocument, bool>> filterExpression)
{
return _collection.Find(filterExpression).FirstOrDefault();
}
public virtual Task<TDocument> FindOneAsync(Expression<Func<TDocument, bool>> filterExpression)
{
return Task.Run(() => _collection.Find(filterExpression).FirstOrDefaultAsync());
}
public virtual TDocument FindById(string id)
{
var objectId = new ObjectId(id);
var filter = Builders<TDocument>.Filter.Eq(doc => doc.Id, objectId);
return _collection.Find(filter).SingleOrDefault();
}
public virtual Task<TDocument> FindByIdAsync(string id)
{
return Task.Run(() =>
{
var objectId = new ObjectId(id);
var filter = Builders<TDocument>.Filter.Eq(doc => doc.Id, objectId);
return _collection.Find(filter).SingleOrDefaultAsync();
});
}
public virtual void InsertOne(TDocument document)
{
_collection.InsertOne(document);
}
public virtual Task InsertOneAsync(TDocument document)
{
return Task.Run(() => _collection.InsertOneAsync(document));
}
public void InsertMany(ICollection<TDocument> documents)
{
_collection.InsertMany(documents);
}
public void DropCollection()
{
_database.DropCollection(GetCollectionName(typeof(TDocument)));
}
public virtual async Task InsertManyAsync(ICollection<TDocument> documents)
{
await _collection.InsertManyAsync(documents);
}
public void ReplaceOne(TDocument document)
{
var filter = Builders<TDocument>.Filter.Eq(doc => doc.Id, document.Id);
_collection.FindOneAndReplace(filter, document);
}
public virtual async Task ReplaceOneAsync(TDocument document)
{
var filter = Builders<TDocument>.Filter.Eq(doc => doc.Id, document.Id);
await _collection.FindOneAndReplaceAsync(filter, document);
}
public virtual void Update(TDocument entity)
{
if (entity.Id == ObjectId.Empty)
{
entity.Id = ObjectId.GenerateNewId();
}
var option = new ReplaceOptions { IsUpsert = true };
_collection.ReplaceOne(x => entity != null && x.Id == entity.Id, entity, option);
}
public virtual void DeleteOne(Expression<Func<TDocument, bool>> filterExpression)
{
_collection.FindOneAndDelete(filterExpression);
}
public virtual Task DeleteOneAsync(Expression<Func<TDocument, bool>> filterExpression)
{
return Task.Run(() => _collection.FindOneAndDeleteAsync(filterExpression));
}
public virtual void DeleteById(string id)
{
var objectId = new ObjectId(id);
var filter = Builders<TDocument>.Filter.Eq(doc => doc.Id, objectId);
_collection.FindOneAndDelete(filter);
}
public virtual Task DeleteByIdAsync(string id)
{
return Task.Run(() =>
{
var objectId = new ObjectId(id);
var filter = Builders<TDocument>.Filter.Eq(doc => doc.Id, objectId);
_collection.FindOneAndDeleteAsync(filter);
});
}
public virtual void DeleteMany(Expression<Func<TDocument, bool>> filterExpression)
{
_collection.DeleteMany(filterExpression);
}
public virtual Task DeleteManyAsync(Expression<Func<TDocument, bool>> filterExpression)
{
return _collection.DeleteManyAsync(filterExpression);
}
public virtual void CreateIndex(string column)
{
var keys = Builders<TDocument>.IndexKeys.Ascending(column);
var indexOptions = new CreateIndexOptions { Unique = true };
var model = new CreateIndexModel<TDocument>(keys, indexOptions);
_collection.Indexes.CreateOne(model);
}
}
}