feat: 创建组合选择策略时自动带入策略配置的标的作为初始持仓
This commit is contained in:
parent
1a529387e7
commit
02c0864393
@ -36,8 +36,55 @@ public class PortfolioService : IPortfolioService
|
||||
|
||||
_db.Insertable(portfolio).ExecuteCommand();
|
||||
|
||||
// 如果选择了策略,自动加载策略配置的标的作为初始持仓
|
||||
var strategyStocks = new List<StockItem>();
|
||||
if (!string.IsNullOrEmpty(request.strategyId))
|
||||
{
|
||||
var strategy = _db.Queryable<Strategy>()
|
||||
.Where(s => s.Id == request.strategyId && s.UserId == userId)
|
||||
.First();
|
||||
|
||||
if (strategy != null && !string.IsNullOrEmpty(strategy.Config))
|
||||
{
|
||||
try
|
||||
{
|
||||
// 风险平价策略
|
||||
if (strategy.Type?.Equals("risk_parity", StringComparison.OrdinalIgnoreCase) == true)
|
||||
{
|
||||
var config = System.Text.Json.JsonSerializer.Deserialize<RiskParityConfig>(strategy.Config);
|
||||
if (config?.Assets != null)
|
||||
{
|
||||
foreach (var asset in config.Assets)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(asset.Symbol))
|
||||
{
|
||||
strategyStocks.Add(new StockItem
|
||||
{
|
||||
code = asset.Symbol,
|
||||
name = asset.Symbol,
|
||||
price = 0, // 价格留空,用户后续填写
|
||||
amount = 0, // 数量留空,用户后续填写
|
||||
currency = request.currency,
|
||||
assetType = "Stock"
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 其他策略类型可以在这里扩展
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "解析策略配置失败,策略ID: {StrategyId}", request.strategyId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 合并用户传入的持仓和策略自动生成的持仓
|
||||
var allStocks = (request.stocks ?? new List<StockItem>()).Concat(strategyStocks).DistinctBy(s => s.code).ToList();
|
||||
|
||||
// 创建初始持仓
|
||||
foreach (var stock in request.stocks ?? new List<StockItem>())
|
||||
foreach (var stock in allStocks)
|
||||
{
|
||||
if (stock.code == null || stock.name == null)
|
||||
{
|
||||
|
||||
Loading…
Reference in New Issue
Block a user