klhztrader/KLHZ.Trader.Core.Math/Declisions/Dtos/Services/PriceHistoryCacheUnit.cs

87 lines
2.8 KiB
C#

using KLHZ.Trader.Core.Contracts.Declisions.Interfaces;
using KLHZ.Trader.Core.Contracts.Messaging.Dtos.Intarfaces;
namespace KLHZ.Trader.Core.Math.Declisions.Dtos.Services
{
public class PriceHistoryCacheUnit : IPriceHistoryCacheUnit
{
public const int ArrayMaxLength = 500;
public string Figi { get; init; }
public int Length
{
get
{
lock (_locker)
{
return _length;
}
}
}
private readonly object _locker = new();
private readonly float[] Prices = new float[ArrayMaxLength];
private readonly DateTime[] Timestamps = new DateTime[ArrayMaxLength];
private int _length = 0;
public ValueTask AddData(INewPrice priceChange)
{
lock (_locker)
{
Array.Copy(Prices, 1, Prices, 0, Prices.Length - 1);
Array.Copy(Timestamps, 1, Timestamps, 0, Timestamps.Length - 1);
Prices[Prices.Length - 1] = (float)priceChange.Value;
Timestamps[Timestamps.Length - 1] = priceChange.Time;
if (_length < ArrayMaxLength)
{
_length++;
}
}
return ValueTask.CompletedTask;
}
public ValueTask<(DateTime[] timestamps, float[] prices)> GetData()
{
lock (_locker)
{
var prices = new float[_length];
var timestamps = new DateTime[_length];
Array.Copy(Prices, Prices.Length - _length, prices, 0, prices.Length);
Array.Copy(Timestamps, Prices.Length - _length, timestamps, 0, timestamps.Length);
return ValueTask.FromResult((timestamps, prices));
}
}
public PriceHistoryCacheUnit(string figi, params INewPrice[] priceChanges)
{
Figi = figi;
if (priceChanges.Length == 0)
{
return;
}
var selectedPriceChanges = priceChanges
.OrderBy(pc => pc.Time)
.Skip(priceChanges.Length - ArrayMaxLength)
.ToArray();
var prices = selectedPriceChanges
.Select(pc => (float)pc.Value)
.ToArray();
var times = selectedPriceChanges
.Select(pc => pc.Time)
.ToArray();
Array.Copy(prices, 0, Prices, Prices.Length - prices.Length, prices.Length);
Array.Copy(times, 0, Timestamps, Timestamps.Length - times.Length, times.Length);
_length = times.Length > ArrayMaxLength ? ArrayMaxLength : times.Length;
}
}
}