81 lines
3.2 KiB
C#
81 lines
3.2 KiB
C#
using Google.Protobuf.WellKnownTypes;
|
|
using KLHZ.Trader.Core.DataLayer;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Tinkoff.InvestApi;
|
|
using Tinkoff.InvestApi.V1;
|
|
using Candle = KLHZ.Trader.Core.DataLayer.Entities.Prices.Candle;
|
|
|
|
namespace KLHZ.Trader.HistoryLoader.Controllers
|
|
{
|
|
[ApiController]
|
|
[Route("[controller]/[action]")]
|
|
public class LoaderController : ControllerBase
|
|
{
|
|
private readonly InvestApiClient _investApiClient;
|
|
private readonly IDbContextFactory<TraderDbContext> _dbContextFactory;
|
|
|
|
public LoaderController(InvestApiClient client, IDbContextFactory<TraderDbContext> dbContextFactory)
|
|
{
|
|
_dbContextFactory = dbContextFactory;
|
|
_investApiClient = client;
|
|
}
|
|
[HttpGet]
|
|
public async Task Load(string figi)
|
|
{
|
|
using var context1 = await _dbContextFactory.CreateDbContextAsync();
|
|
context1.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
|
|
var existed = (await context1.Candles.Where(c => c.Figi == figi).Select(c => c.Time)
|
|
.ToArrayAsync()).Select(t => t.ToUniversalTime())
|
|
.ToHashSet();
|
|
var dt = DateTime.UtcNow;
|
|
var i = -400;
|
|
while (i < 0)
|
|
{
|
|
try
|
|
{
|
|
|
|
var req = new GetCandlesRequest()
|
|
{
|
|
Interval = CandleInterval._5Sec,
|
|
From = Timestamp.FromDateTime(dt.AddHours(i)),
|
|
To = Timestamp.FromDateTime(dt.AddHours(i + 1)),
|
|
InstrumentId = figi,
|
|
};
|
|
var candles = await _investApiClient.MarketData.GetCandlesAsync(req);
|
|
i++;
|
|
using var context = await _dbContextFactory.CreateDbContextAsync();
|
|
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
|
|
var forAdd = new List<Candle>();
|
|
foreach (var c in candles.Candles)
|
|
{
|
|
var dt1 = c.Time.ToDateTime().ToUniversalTime();
|
|
if (!existed.Contains(dt1))
|
|
{
|
|
var ca = new Candle
|
|
{
|
|
Figi = figi,
|
|
Ticker = string.Empty,
|
|
Time = dt1,
|
|
Open = c.Open,
|
|
Close = c.Close,
|
|
Volume = c.Volume,
|
|
High = c.High,
|
|
Low = c.Low,
|
|
};
|
|
forAdd.Add(ca);
|
|
existed.Add(dt1);
|
|
}
|
|
}
|
|
await context.Candles.AddRangeAsync(forAdd);
|
|
await context.SaveChangesAsync();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|