803 lines
35 KiB
C#
803 lines
35 KiB
C#
using KLHZ.Trader.Core.Common;
|
|
using KLHZ.Trader.Core.Contracts.Declisions.Dtos.Enums;
|
|
using KLHZ.Trader.Core.Contracts.Messaging.Dtos.Interfaces;
|
|
using KLHZ.Trader.Core.Contracts.Messaging.Interfaces;
|
|
using KLHZ.Trader.Core.DataLayer.Entities.Declisions;
|
|
using KLHZ.Trader.Core.DataLayer.Entities.Declisions.Enums;
|
|
using KLHZ.Trader.Core.DataLayer.Entities.Prices;
|
|
using KLHZ.Trader.Core.Exchange.Interfaces;
|
|
using KLHZ.Trader.Core.Exchange.Models.Configs;
|
|
using KLHZ.Trader.Core.Exchange.Models.Trading;
|
|
using KLHZ.Trader.Core.Exchange.Utils;
|
|
using KLHZ.Trader.Core.Math.Declisions.Dtos.FFT.Enums;
|
|
using KLHZ.Trader.Core.Math.Declisions.Utils;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using System.Collections.Concurrent;
|
|
using System.Threading.Channels;
|
|
using Tinkoff.InvestApi;
|
|
using Asset = KLHZ.Trader.Core.Exchange.Models.AssetsAccounting.Asset;
|
|
using AssetType = KLHZ.Trader.Core.Exchange.Models.AssetsAccounting.AssetType;
|
|
using PositionType = KLHZ.Trader.Core.Exchange.Models.AssetsAccounting.PositionType;
|
|
|
|
namespace KLHZ.Trader.Core.Exchange.Services
|
|
{
|
|
public class Trader : IHostedService
|
|
{
|
|
private readonly IDataBus _dataBus;
|
|
private readonly TraderDataProvider _tradeDataProvider;
|
|
private readonly PortfolioWrapper _portfolioWrapper;
|
|
|
|
private readonly ILogger<Trader> _logger;
|
|
|
|
private readonly ConcurrentDictionary<string, TradingMode> TradingModes = new();
|
|
|
|
private readonly ConcurrentDictionary<string, DateTime> LongOpeningStops = new();
|
|
private readonly ConcurrentDictionary<string, DateTime> LongClosingStops = new();
|
|
private readonly ConcurrentDictionary<string, DateTime> ShortClosingStops = new();
|
|
private readonly ConcurrentDictionary<string, InstrumentSettings> Leverages = new();
|
|
|
|
private readonly decimal _futureComission;
|
|
private readonly decimal _shareComission;
|
|
private readonly decimal _accountCashPart;
|
|
private readonly decimal _accountCashPartFutures;
|
|
private readonly string[] _tradingInstrumentsFigis = [];
|
|
|
|
private readonly Channel<INewPrice> _pricesChannel = Channel.CreateUnbounded<INewPrice>();
|
|
private readonly Channel<IOrderbook> _ordersbookChannel = Channel.CreateUnbounded<IOrderbook>();
|
|
|
|
public Trader(
|
|
ILogger<Trader> logger,
|
|
IOptions<ExchangeConfig> options,
|
|
IDataBus dataBus,
|
|
PortfolioWrapper portfolioWrapper,
|
|
TraderDataProvider tradeDataProvider,
|
|
InvestApiClient investApiClient)
|
|
{
|
|
_portfolioWrapper = portfolioWrapper;
|
|
_tradeDataProvider = tradeDataProvider;
|
|
_logger = logger;
|
|
_dataBus = dataBus;
|
|
_futureComission = options.Value.FutureComission;
|
|
_shareComission = options.Value.ShareComission;
|
|
_accountCashPart = options.Value.AccountCashPart;
|
|
_accountCashPartFutures = options.Value.AccountCashPartFutures;
|
|
_tradingInstrumentsFigis = options.Value.TradingInstrumentsFigis;
|
|
foreach (var f in _tradingInstrumentsFigis)
|
|
{
|
|
TradingModes[f] = TradingMode.None;
|
|
}
|
|
|
|
foreach (var lev in options.Value.InstrumentsSettings)
|
|
{
|
|
Leverages.TryAdd(lev.Figi, lev);
|
|
}
|
|
}
|
|
|
|
public Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
_dataBus.AddChannel(nameof(Trader), _pricesChannel);
|
|
_dataBus.AddChannel(nameof(Trader), _ordersbookChannel);
|
|
_ = ProcessPrices();
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public async ValueTask<(DateTime[] timestamps, decimal[] prices, bool isFullIntervalExists)> GetData(INewPrice message)
|
|
{
|
|
var data2 = await _tradeDataProvider.GetData(message.Figi, TimeSpan.FromHours(1.5));
|
|
if (!data2.isFullIntervalExists)
|
|
{
|
|
data2 = await _tradeDataProvider.GetData(message.Figi, TimeSpan.FromHours(1));
|
|
}
|
|
if (!data2.isFullIntervalExists)
|
|
{
|
|
data2 = await _tradeDataProvider.GetData(message.Figi, TimeSpan.FromHours(0.75));
|
|
}
|
|
return data2;
|
|
}
|
|
|
|
private async ValueTask<ValueAmplitudePosition> CheckPosition((DateTime[] timestamps, decimal[] prices, bool isFullIntervalExists) data, INewPrice message)
|
|
{
|
|
var currentTime = message.IsHistoricalData ? message.Time : DateTime.UtcNow;
|
|
var position = ValueAmplitudePosition.None;
|
|
var fft = await _tradeDataProvider.GetFFtResult(message.Figi);
|
|
var step = message.IsHistoricalData ? 5 : 5;
|
|
if (fft.IsEmpty || (currentTime - fft.LastTime).TotalSeconds > step)
|
|
{
|
|
if (data.isFullIntervalExists)
|
|
{
|
|
var interpolatedData = SignalProcessing.InterpolateData(data.timestamps, data.prices, TimeSpan.FromSeconds(5));
|
|
fft = FFT.Analyze(interpolatedData.timestamps, interpolatedData.values, message.Figi, TimeSpan.FromMinutes(3), TimeSpan.FromMinutes(40));
|
|
await _tradeDataProvider.SetFFtResult(fft);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
position = FFT.Check(fft, message.Time);
|
|
if (position == Math.Declisions.Dtos.FFT.Enums.ValueAmplitudePosition.UpperThen30Decil)
|
|
{
|
|
await LogPrice(message, "upper30percent", message.Value);
|
|
}
|
|
if (position == Math.Declisions.Dtos.FFT.Enums.ValueAmplitudePosition.LowerThenMediana)
|
|
{
|
|
await LogPrice(message, "lower30percent", message.Value);
|
|
}
|
|
}
|
|
|
|
return position;
|
|
}
|
|
|
|
private async Task ProcessPrices()
|
|
{
|
|
var pricesCache = new Dictionary<string, List<INewPrice>>();
|
|
var timesCache = new Dictionary<string, DateTime>();
|
|
while (await _pricesChannel.Reader.WaitToReadAsync())
|
|
{
|
|
var message = await _pricesChannel.Reader.ReadAsync();
|
|
|
|
try
|
|
{
|
|
#region Ускорение обработки исторических данных при отладке
|
|
if (message.IsHistoricalData)
|
|
{
|
|
await _tradeDataProvider.AddData(message, TimeSpan.FromHours(6));
|
|
if (!pricesCache.TryGetValue(message.Figi, out var list))
|
|
{
|
|
list = new List<INewPrice>();
|
|
pricesCache[message.Figi] = list;
|
|
}
|
|
list.Add(message);
|
|
|
|
if ((list.Last().Time - list.First().Time).TotalSeconds < 0.5)
|
|
{
|
|
list.Add(message);
|
|
continue;
|
|
}
|
|
else
|
|
{
|
|
message = new PriceChange()
|
|
{
|
|
Figi = message.Figi,
|
|
Ticker = message.Ticker,
|
|
Count = message.Count,
|
|
Direction = message.Direction,
|
|
IsHistoricalData = message.IsHistoricalData,
|
|
Time = message.Time,
|
|
Value = list.Sum(l => l.Value) / list.Count
|
|
};
|
|
list.Clear();
|
|
}
|
|
}
|
|
|
|
try
|
|
{
|
|
if (timesCache.TryGetValue(message.Figi, out var dt))
|
|
{
|
|
if ((message.Time - dt).TotalSeconds > 10)
|
|
{
|
|
timesCache[message.Figi] = message.Time;
|
|
|
|
TradingModes[message.Figi] = await CalcTradingMode(message);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
timesCache[message.Figi] = message.Time;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
|
|
}
|
|
if (TradingModes.TryGetValue(message.Figi, out var mode))
|
|
{
|
|
await LogPrice(message, "trading_mode", (decimal)mode);
|
|
}
|
|
|
|
//continue;
|
|
#endregion
|
|
if (message.Figi == "BBG004730N88")
|
|
{
|
|
if (message.Direction == 1)
|
|
{
|
|
await _tradeDataProvider.AddDataTo5MinuteWindowCache(message.Figi, Constants._1minBuyCacheKey, new Contracts.Declisions.Dtos.CachedValue()
|
|
{
|
|
Time = message.Time,
|
|
Value = (decimal)message.Count
|
|
});
|
|
}
|
|
if (message.Direction == 2)
|
|
{
|
|
await _tradeDataProvider.AddDataTo5MinuteWindowCache(message.Figi, Constants._1minSellCacheKey, new Contracts.Declisions.Dtos.CachedValue()
|
|
{
|
|
Time = message.Time,
|
|
Value = (decimal)message.Count
|
|
});
|
|
|
|
}
|
|
var sberSells = await _tradeDataProvider.GetDataFrom5MinuteWindowCache("BBG004730N88", Constants._1minSellCacheKey);
|
|
var sberBuys = await _tradeDataProvider.GetDataFrom5MinuteWindowCache("BBG004730N88", Constants._1minBuyCacheKey);
|
|
var sells = sberSells.Sum(s => s.Value);
|
|
var buys = sberBuys.Sum(s => s.Value);
|
|
var su = sells + buys;
|
|
if (su != 0)
|
|
{
|
|
await LogPrice(message, "sellsbuysbalance", (sells / su - 0.5m) * 2);
|
|
}
|
|
}
|
|
|
|
if (_tradingInstrumentsFigis.Contains(message.Figi))
|
|
{
|
|
var currentTime = message.IsHistoricalData ? message.Time : DateTime.UtcNow;
|
|
|
|
try
|
|
{
|
|
ProcessStops(message, currentTime);
|
|
var windowMaxSize = 2000;
|
|
var data = await _tradeDataProvider.GetData(message.Figi, windowMaxSize);
|
|
var state = ExchangeScheduler.GetCurrentState(message.Time);
|
|
await ProcessClearing(data, state, message);
|
|
|
|
if (TradingModes[message.Figi] == TradingMode.Stable)
|
|
{
|
|
await ProcessNewPriceIMOEXF_Stable(data, state, message, windowMaxSize);
|
|
}
|
|
else if (TradingModes[message.Figi] == TradingMode.SlowDropping)
|
|
{
|
|
await ProcessNewPriceIMOEXF_Dropping(data, state, message, windowMaxSize, 2);
|
|
}
|
|
else if (TradingModes[message.Figi] == TradingMode.Dropping)
|
|
{
|
|
await ProcessNewPriceIMOEXF_Dropping(data, state, message, windowMaxSize, 6);
|
|
}
|
|
else if (TradingModes[message.Figi] == TradingMode.Growing)
|
|
{
|
|
await ProcessNewPriceIMOEXF_Growing(data, state, message, windowMaxSize);
|
|
}
|
|
else
|
|
{
|
|
await ProcessNewPriceIMOEXF2(data, state, message, windowMaxSize);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Ошибка при боработке новой цены IMOEXF");
|
|
}
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
private async Task<TradingEvent> CheckByWindowAverageMean((DateTime[] timestamps, decimal[] prices) data,
|
|
INewPrice message, int windowMaxSize, decimal uptrendStartingDetectionMeanfullStep = 0m, decimal uptrendEndingDetectionMeanfullStep = 3m)
|
|
{
|
|
var resultMoveAvFull = MovingAverage.CheckByWindowAverageMean(data.timestamps, data.prices,
|
|
windowMaxSize, 30, 180, TimeSpan.FromSeconds(20), uptrendStartingDetectionMeanfullStep, uptrendEndingDetectionMeanfullStep);
|
|
if (resultMoveAvFull.bigWindowAv != 0)
|
|
{
|
|
await LogPrice(message, Constants.BigWindowCrossingAverageProcessor, resultMoveAvFull.bigWindowAv);
|
|
await LogPrice(message, Constants.SmallWindowCrossingAverageProcessor, resultMoveAvFull.smallWindowAv);
|
|
}
|
|
return resultMoveAvFull.events;
|
|
}
|
|
|
|
private async Task<TradingEvent> CheckByWindowAverageMean2((DateTime[] timestamps, decimal[] prices) data, int smallWindow, int bigWindow,
|
|
INewPrice message, int windowMaxSize, decimal uptrendStartingDetectionMeanfullStep = 0m, decimal uptrendEndingDetectionMeanfullStep = 3m)
|
|
{
|
|
var resultMoveAvFull = MovingAverage.CheckByWindowAverageMean2(data.timestamps, data.prices,
|
|
windowMaxSize, smallWindow, bigWindow, TimeSpan.FromSeconds(20), uptrendStartingDetectionMeanfullStep, uptrendEndingDetectionMeanfullStep);
|
|
if (resultMoveAvFull.bigWindowAv != 0)
|
|
{
|
|
await LogPrice(message, Constants.BigWindowCrossingAverageProcessor, resultMoveAvFull.bigWindowAv);
|
|
await LogPrice(message, Constants.SmallWindowCrossingAverageProcessor, resultMoveAvFull.smallWindowAv);
|
|
}
|
|
return resultMoveAvFull.events;
|
|
}
|
|
|
|
private Task<TradingEvent> CheckByWindowAverageMeanNolog((DateTime[] timestamps, decimal[] prices) data,
|
|
INewPrice message, int windowMaxSize, decimal uptrendStartingDetectionMeanfullStep = 0m, decimal uptrendEndingDetectionMeanfullStep = 3m)
|
|
{
|
|
var resultMoveAvFull = MovingAverage.CheckByWindowAverageMean(data.timestamps, data.prices,
|
|
windowMaxSize, 30, 180, TimeSpan.FromSeconds(20), uptrendStartingDetectionMeanfullStep, uptrendEndingDetectionMeanfullStep);
|
|
return Task.FromResult(resultMoveAvFull.events);
|
|
}
|
|
|
|
private Task<TradingEvent> CheckByWindowAverageMeanForShotrs((DateTime[] timestamps, decimal[] prices) data,
|
|
INewPrice message, int windowMaxSize)
|
|
{
|
|
var resultMoveAvFull = MovingAverage.CheckByWindowAverageMean(data.timestamps, data.prices,
|
|
windowMaxSize, 30, 240, TimeSpan.FromSeconds(20), -1m, 1m);
|
|
return Task.FromResult(resultMoveAvFull.events);
|
|
}
|
|
|
|
private Task<TradingEvent> CheckByLocalTrends((DateTime[] timestamps, decimal[] prices) data,
|
|
INewPrice message, int windowMaxSize)
|
|
{
|
|
var res = TradingEvent.None;
|
|
if (LocalTrends.TryGetLocalTrends(data.timestamps, data.prices, TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(20), 1, out var resLocalTrends))
|
|
{
|
|
res |= (resLocalTrends & TradingEvent.UptrendStart);
|
|
if ((resLocalTrends & TradingEvent.UptrendStart) == TradingEvent.UptrendStart)
|
|
{
|
|
res |= TradingEvent.DowntrendEnd;
|
|
}
|
|
}
|
|
return Task.FromResult(res);
|
|
}
|
|
|
|
private async Task<decimal?> GetAreasRelation((DateTime[] timestamps, decimal[] prices) data, INewPrice message)
|
|
{
|
|
var areasRel = -1m;
|
|
if (ShapeAreaCalculator.TryGetAreasRelation(data.timestamps, data.prices, message.Value, Constants.AreasRelationWindow, out var rel))
|
|
{
|
|
await _tradeDataProvider.AddDataTo1MinuteWindowCache(message.Figi, Constants._1minCacheKey, new Contracts.Declisions.Dtos.CachedValue()
|
|
{
|
|
Time = message.Time,
|
|
Value = (decimal)rel
|
|
});
|
|
var areas = await _tradeDataProvider.GetDataFrom1MinuteWindowCache(message.Figi, Constants._1minCacheKey);
|
|
|
|
areasRel = (decimal)areas.Sum(a => a.Value) / areas.Length;
|
|
await LogPrice(message, Constants.AreasRelationProcessor, areasRel);
|
|
return areasRel > 0 ? areasRel : null;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private async Task<ValueAmplitudePosition> CheckPosition(INewPrice message)
|
|
{
|
|
var data2 = await GetData(message);
|
|
var position = await CheckPosition(data2, message);
|
|
return position;
|
|
}
|
|
|
|
private async Task<decimal?> CalcTrendDiff(INewPrice message)
|
|
{
|
|
var data = await _tradeDataProvider.GetData(message.Figi, TimeSpan.FromHours(1));
|
|
if (data.isFullIntervalExists && LocalTrends.TryCalcTrendDiff(data.timestamps, data.prices, out var res))
|
|
{
|
|
return res;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private async Task ClosePositions(Asset[] assets, INewPrice message, bool withProfitOnly = true)
|
|
{
|
|
var loggedDeclisions = 0;
|
|
var assetType = _tradeDataProvider.GetAssetTypeByFigi(message.Figi);
|
|
var assetsForClose = new List<Asset>();
|
|
|
|
foreach (var asset in assets)
|
|
{
|
|
if (withProfitOnly)
|
|
{
|
|
var profit = 0m;
|
|
|
|
if (assetType == AssetType.Futures)
|
|
{
|
|
profit = TradingCalculator.CaclProfit(asset.BoughtPrice, message.Value,
|
|
GetComission(assetType), GetLeverage(message.Figi, asset.Count < 0), asset.Count < 0);
|
|
}
|
|
if (profit > 0)
|
|
{
|
|
assetsForClose.Add(asset);
|
|
if (loggedDeclisions == 0)
|
|
{
|
|
loggedDeclisions++;
|
|
await LogDeclision(asset.Count < 0 ? DeclisionTradeAction.CloseShortReal : DeclisionTradeAction.CloseLongReal, message, profit);
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
assetsForClose.Add(asset);
|
|
}
|
|
}
|
|
var tasks = assetsForClose.Select(asset => _portfolioWrapper.Accounts[asset.AccountId].ClosePosition(message.Figi));
|
|
await Task.WhenAll(tasks);
|
|
}
|
|
|
|
private async Task OpenPositions(IManagedAccount[] accounts, INewPrice message, PositionType positionType, decimal stopLossShift, decimal takeProfitShift, long count = 1)
|
|
{
|
|
var loggedDeclisions = 0;
|
|
foreach (var acc in accounts)
|
|
{
|
|
if (IsOperationAllowed(acc, message.Value, 1, _accountCashPartFutures, _accountCashPart))
|
|
{
|
|
await acc.OpenPosition(message.Figi, positionType, stopLossShift, takeProfitShift, count);
|
|
}
|
|
|
|
if (loggedDeclisions == 0)
|
|
{
|
|
await LogDeclision(DeclisionTradeAction.OpenLongReal, message);
|
|
LongOpeningStops[message.Figi] = message.Time.AddMinutes(1);
|
|
loggedDeclisions++;
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task ProcessNewPriceIMOEXF2((DateTime[] timestamps, decimal[] prices) data,
|
|
ExchangeState state,
|
|
INewPrice message, int windowMaxSize)
|
|
{
|
|
if (data.timestamps.Length <= 4)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var sberSells = await _tradeDataProvider.GetDataFrom5MinuteWindowCache("BBG004730N88", Constants._1minSellCacheKey);
|
|
var sberBuys = await _tradeDataProvider.GetDataFrom5MinuteWindowCache("BBG004730N88", Constants._1minBuyCacheKey);
|
|
var sells = sberSells.Sum(s => s.Value);
|
|
var buys = sberBuys.Sum(s => s.Value);
|
|
var su = sells + buys;
|
|
if (su != 0)
|
|
{
|
|
var dsell = (sells / su - 0.5m) * 2;
|
|
}
|
|
|
|
|
|
|
|
var mavTask = CheckByWindowAverageMean(data, message, windowMaxSize, -1, 2m);
|
|
var mavTaskEnds = CheckByWindowAverageMeanNolog(data, message, windowMaxSize, -1, 1m);
|
|
var mavTaskShorts = CheckByWindowAverageMeanForShotrs(data, message, windowMaxSize);
|
|
var ltTask = CheckByLocalTrends(data, message, windowMaxSize);
|
|
var areasTask = GetAreasRelation(data, message);
|
|
var positionTask = CheckPosition(message);
|
|
var trendTask = CalcTrendDiff(message);
|
|
|
|
var ends = mavTaskEnds.Result & TradingEvent.UptrendEnd;
|
|
|
|
await Task.WhenAll(mavTask, ltTask, areasTask, positionTask, trendTask, mavTaskShorts, mavTaskEnds);
|
|
var assetType = _tradeDataProvider.GetAssetTypeByFigi(message.Figi);
|
|
var res = mavTask.Result | ltTask.Result;
|
|
res |= ends;
|
|
if ((res & TradingEvent.UptrendStart) == TradingEvent.UptrendStart
|
|
&& !LongOpeningStops.ContainsKey(message.Figi)
|
|
&& trendTask.Result.HasValue
|
|
&& state == ExchangeState.Open
|
|
&& areasTask.Result.HasValue
|
|
&& (positionTask.Result == ValueAmplitudePosition.LowerThenMediana)
|
|
)
|
|
{
|
|
if (!message.IsHistoricalData && BotModeSwitcher.CanPurchase())
|
|
{
|
|
var accounts = _portfolioWrapper.Accounts
|
|
.Where(a => !a.Value.Assets.ContainsKey(message.Figi))
|
|
.Take(1)
|
|
.Select(a => a.Value)
|
|
.ToArray();
|
|
await OpenPositions(accounts, message, PositionType.Long, 7, 10, 1);
|
|
}
|
|
|
|
await LogDeclision(DeclisionTradeAction.OpenLong, message);
|
|
}
|
|
if ((res & TradingEvent.UptrendEnd) == TradingEvent.UptrendEnd)
|
|
{
|
|
if (!message.IsHistoricalData && BotModeSwitcher.CanSell())
|
|
{
|
|
var assetsForClose = _portfolioWrapper.Accounts
|
|
.SelectMany(a => a.Value.Assets.Values)
|
|
.Where(a => a.Figi == message.Figi && a.Count > 0)
|
|
.ToArray();
|
|
await ClosePositions(assetsForClose, message);
|
|
}
|
|
await LogDeclision(DeclisionTradeAction.CloseLong, message);
|
|
}
|
|
|
|
if ((res & TradingEvent.DowntrendEnd) == TradingEvent.DowntrendEnd)
|
|
{
|
|
if (!message.IsHistoricalData && BotModeSwitcher.CanPurchase())
|
|
{
|
|
var assetsForClose = _portfolioWrapper.Accounts
|
|
.SelectMany(a => a.Value.Assets.Values)
|
|
.Where(a => a.Figi == message.Figi && a.Count < 0)
|
|
.ToArray();
|
|
await ClosePositions(assetsForClose, message);
|
|
}
|
|
await LogDeclision(DeclisionTradeAction.CloseShort, message);
|
|
}
|
|
}
|
|
|
|
private async Task ProcessNewPriceIMOEXF_Stable(
|
|
(DateTime[] timestamps, decimal[] prices) data,
|
|
ExchangeState state,
|
|
INewPrice message, int windowMaxSize)
|
|
{
|
|
if (data.timestamps.Length <= 4 || state != ExchangeState.Open)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var mavTask = CheckByWindowAverageMean2(data, 30, 180, message, windowMaxSize, 0, 0);
|
|
|
|
await Task.WhenAll(mavTask);
|
|
var assetType = _tradeDataProvider.GetAssetTypeByFigi(message.Figi);
|
|
var res = mavTask.Result;
|
|
|
|
if ((res & TradingEvent.UptrendStart) == TradingEvent.UptrendStart)
|
|
{
|
|
if (!message.IsHistoricalData && BotModeSwitcher.CanPurchase())
|
|
{
|
|
var accounts = _portfolioWrapper.Accounts
|
|
.Where(a => !a.Value.Assets.ContainsKey(message.Figi))
|
|
.Take(1)
|
|
.Select(a => a.Value)
|
|
.ToArray();
|
|
|
|
await OpenPositions(accounts, message, PositionType.Long, 5, 2, 1);
|
|
}
|
|
|
|
await LogDeclision(DeclisionTradeAction.OpenLong, message);
|
|
}
|
|
}
|
|
|
|
private async Task ProcessNewPriceIMOEXF_Growing(
|
|
(DateTime[] timestamps, decimal[] prices) data,
|
|
ExchangeState state,
|
|
INewPrice message, int windowMaxSize)
|
|
{
|
|
if (data.timestamps.Length <= 4 || state != ExchangeState.Open)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var mavTask = CheckByWindowAverageMean2(data, 30, 180, message, windowMaxSize, 0, 0);
|
|
|
|
await Task.WhenAll(mavTask);
|
|
var assetType = _tradeDataProvider.GetAssetTypeByFigi(message.Figi);
|
|
var res = mavTask.Result;
|
|
|
|
if ((res & TradingEvent.UptrendStart) == TradingEvent.UptrendStart)
|
|
{
|
|
if (!message.IsHistoricalData && BotModeSwitcher.CanPurchase())
|
|
{
|
|
var accounts = _portfolioWrapper.Accounts
|
|
.Where(a => !a.Value.Assets.ContainsKey(message.Figi))
|
|
.Take(1)
|
|
.Select(a => a.Value)
|
|
.ToArray();
|
|
|
|
await OpenPositions(accounts, message, PositionType.Long, 10, 20, 1);
|
|
}
|
|
|
|
await LogDeclision(DeclisionTradeAction.OpenLong, message);
|
|
}
|
|
|
|
if ((res & TradingEvent.UptrendEnd) == TradingEvent.UptrendEnd)
|
|
{
|
|
if (!message.IsHistoricalData && BotModeSwitcher.CanSell())
|
|
{
|
|
var assetsForClose = _portfolioWrapper.Accounts
|
|
.SelectMany(a => a.Value.Assets.Values)
|
|
.Where(a => a.Figi == message.Figi && a.Count > 0)
|
|
.ToArray();
|
|
|
|
await ClosePositions(assetsForClose, message);
|
|
}
|
|
await LogDeclision(DeclisionTradeAction.CloseLong, message);
|
|
}
|
|
}
|
|
|
|
private async Task ProcessNewPriceIMOEXF_Dropping(
|
|
(DateTime[] timestamps, decimal[] prices) data,
|
|
ExchangeState state,
|
|
INewPrice message, int windowMaxSize, decimal step)
|
|
{
|
|
if (data.timestamps.Length <= 4 && state != ExchangeState.Open)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var mavTask = CheckByWindowAverageMean2(data, 30, 180, message, windowMaxSize, 0, 0);
|
|
var positionTask = CheckPosition(message);
|
|
|
|
await Task.WhenAll(mavTask, positionTask);
|
|
var assetType = _tradeDataProvider.GetAssetTypeByFigi(message.Figi);
|
|
var res = mavTask.Result;
|
|
|
|
if ((res & TradingEvent.UptrendEnd) == TradingEvent.UptrendEnd && (positionTask.Result != ValueAmplitudePosition.LowerThenMediana))
|
|
{
|
|
if (!message.IsHistoricalData && BotModeSwitcher.CanSell())
|
|
{
|
|
var accounts = _portfolioWrapper.Accounts
|
|
.Where(a => !a.Value.Assets.ContainsKey(message.Figi))
|
|
.Take(1)
|
|
.Select(a => a.Value)
|
|
.ToArray();
|
|
|
|
|
|
await OpenPositions(accounts, message, PositionType.Short, 10, 20, 1);
|
|
}
|
|
|
|
await LogDeclision(DeclisionTradeAction.OpenShort, message);
|
|
}
|
|
|
|
if ((res & TradingEvent.UptrendStart) == TradingEvent.UptrendStart)
|
|
{
|
|
if (!ShortClosingStops.ContainsKey(message.Figi))
|
|
{
|
|
if (!message.IsHistoricalData && BotModeSwitcher.CanPurchase())
|
|
{
|
|
var assetsForClose = _portfolioWrapper.Accounts
|
|
.SelectMany(a => a.Value.Assets.Values)
|
|
.Where(a => a.Figi == message.Figi && a.Count < 0)
|
|
.ToArray();
|
|
await ClosePositions(assetsForClose, message);
|
|
}
|
|
|
|
if (message.IsHistoricalData)
|
|
{
|
|
ShortClosingStops[message.Figi] = message.Time.AddSeconds(30);
|
|
}
|
|
await LogDeclision(DeclisionTradeAction.CloseShort, message);
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task ProcessClearing((DateTime[] timestamps, decimal[] prices) data, ExchangeState state, INewPrice message)
|
|
{
|
|
if (state == ExchangeState.ClearingTime
|
|
&& !message.IsHistoricalData
|
|
&& data.timestamps.Length > 1
|
|
&& (data.timestamps[data.timestamps.Length - 1] - data.timestamps[data.timestamps.Length - 2]) > TimeSpan.FromMinutes(3))
|
|
{
|
|
var assets = _portfolioWrapper.Accounts.Values.SelectMany(a => a.Assets.Values).Where(a => a.Figi == message.Figi).ToArray();
|
|
foreach (var a in assets)
|
|
{
|
|
|
|
}
|
|
//await _tradeDataProvider.UpdateFuturesPrice(message, data.prices[data.prices.Length - 2]);
|
|
}
|
|
}
|
|
|
|
private void ProcessStops(INewPrice message, DateTime currentTime)
|
|
{
|
|
if (LongOpeningStops.TryGetValue(message.Figi, out var dt))
|
|
{
|
|
if (dt < currentTime)
|
|
{
|
|
LongOpeningStops.TryRemove(message.Figi, out _);
|
|
}
|
|
}
|
|
if (ShortClosingStops.TryGetValue(message.Figi, out var dt2))
|
|
{
|
|
if (dt2 < currentTime)
|
|
{
|
|
ShortClosingStops.TryRemove(message.Figi, out _);
|
|
}
|
|
}
|
|
if (LongClosingStops.TryGetValue(message.Figi, out var dt3))
|
|
{
|
|
if (dt3 < currentTime)
|
|
{
|
|
LongClosingStops.TryRemove(message.Figi, out _);
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task LogPrice(INewPrice message, string processor, decimal value)
|
|
{
|
|
await _tradeDataProvider.LogPrice(new ProcessedPrice()
|
|
{
|
|
Figi = message.Figi,
|
|
Ticker = message.Ticker,
|
|
Processor = processor,
|
|
Time = message.Time,
|
|
Value = value,
|
|
}, false);
|
|
}
|
|
|
|
private async Task LogDeclision(DeclisionTradeAction action, INewPrice message, decimal? profit = null)
|
|
{
|
|
await _tradeDataProvider.LogDeclision(new Declision()
|
|
{
|
|
AccountId = string.Empty,
|
|
Figi = message.Figi,
|
|
Ticker = message.Ticker,
|
|
Value = profit,
|
|
Price = message.Value,
|
|
Time = message.IsHistoricalData ? message.Time : DateTime.UtcNow,
|
|
Action = action,
|
|
}, false);
|
|
}
|
|
|
|
public Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
private decimal GetComission(AssetType assetType)
|
|
{
|
|
if (assetType == AssetType.Common)
|
|
{
|
|
return _shareComission;
|
|
}
|
|
else if (assetType == AssetType.Futures)
|
|
{
|
|
return _futureComission;
|
|
}
|
|
else
|
|
{
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
private decimal GetLeverage(string figi, bool isShort)
|
|
{
|
|
var res = 1m;
|
|
if (Leverages.TryGetValue(figi, out var leverage))
|
|
{
|
|
res = isShort ? leverage.ShortLeverage : leverage.LongLeverage;
|
|
}
|
|
return res;
|
|
}
|
|
|
|
private async Task<TradingMode> CalcTradingMode(string figi)
|
|
{
|
|
var res = TradingMode.None;
|
|
var largeData = await _tradeDataProvider.GetData(figi, TimeSpan.FromMinutes(90));
|
|
var smallData = await _tradeDataProvider.GetData(figi, TimeSpan.FromMinutes(15));
|
|
|
|
if (largeData.isFullIntervalExists && smallData.isFullIntervalExists)
|
|
{
|
|
if (LocalTrends.TryCalcTrendDiff(largeData.timestamps, largeData.prices, out var largeDataRes)
|
|
&& LocalTrends.TryCalcTrendDiff(smallData.timestamps, smallData.prices, out var smallDataRes))
|
|
{
|
|
if (largeDataRes > 0 && largeDataRes <= 4 && System.Math.Abs(smallDataRes) < 3)
|
|
{
|
|
res = TradingMode.Stable;
|
|
}
|
|
if (largeDataRes < 0 && largeDataRes >= -5 && smallDataRes < 1)
|
|
{
|
|
res = TradingMode.SlowDropping;
|
|
}
|
|
if (largeDataRes > 5 && smallDataRes > 0)
|
|
{
|
|
res = TradingMode.Growing;
|
|
}
|
|
if (largeDataRes < -5 && smallDataRes < 0)
|
|
{
|
|
res = TradingMode.Dropping;
|
|
}
|
|
}
|
|
}
|
|
return res;
|
|
}
|
|
|
|
private async Task<TradingMode> CalcTradingMode(INewPrice message)
|
|
{
|
|
var res = await CalcTradingMode(message.Figi);
|
|
//await LogPrice(message, "trading_mode", (int)res);
|
|
return res;
|
|
}
|
|
|
|
internal static bool IsOperationAllowed(IManagedAccount account, decimal boutPrice, decimal count,
|
|
decimal accountCashPartFutures, decimal accountCashPart)
|
|
{
|
|
if (!BotModeSwitcher.CanPurchase()) return false;
|
|
|
|
var balance = account.Balance;
|
|
var total = account.Total;
|
|
|
|
var futures = account.Assets.Values.FirstOrDefault(v => v.Type == AssetType.Futures);
|
|
if (futures != null)
|
|
{
|
|
if ((balance - boutPrice * count) / total < accountCashPartFutures) return false;
|
|
}
|
|
else
|
|
{
|
|
if ((balance - boutPrice * count) / total < accountCashPart) return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|
|
}
|