public async Task Handle(RoundtripTargetPriceHitIntegrationEvent @event)
        {
            try
            {
                var trace = await this._traceRepository.GetByInvestmentId(@event.InvestmentId);

                if (trace == null)
                {
                    return;
                }

                var idealPeriod = trace.IdealCandlePeriod;

                int minAmounts = 0;
                foreach (var strategy in trace.TradeStrategies)
                {
                    if (strategy.GetIdealPeriod().Name == idealPeriod)
                    {
                        if (strategy.Strategy.MinimumAmountOfCandles > minAmounts)
                        {
                            minAmounts = strategy.Strategy.MinimumAmountOfCandles;
                        }
                    }
                }


                var      period = CandlePeriod.FromName(idealPeriod);
                DateTime fromWithWarmingPeriod = (DateTime)trace.DateStarted;
                var      oneCandleMinutes      = CandlePeriodService.GetOneCandleMinutesByPeriod(period);
                var      currentTime           = new RealTimeService().GetCurrentDateTime();
                var      to = currentTime.AddMinutes(-oneCandleMinutes);
                fromWithWarmingPeriod = fromWithWarmingPeriod.AddMinutes(-oneCandleMinutes * (minAmounts + 1));


                await this._trendAnalysisIntegrationEventService
                .PublishThroughEventBusAsync(new TargetPriceCandleDataRequestedIntegrationEvent(
                                                 trace.TraceId,
                                                 @event.RoundtripId,
                                                 trace.Market.ExchangeId,
                                                 trace.Market.BaseCurrency,
                                                 trace.Market.QuoteCurrency,
                                                 idealPeriod,
                                                 @event.HitPrice,
                                                 fromWithWarmingPeriod,
                                                 to
                                                 ));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Handle Integration Event: RoundtripTargetPriceHitIntegrationEvent.");
                Console.WriteLine("Result: Failure.");
                Console.WriteLine("Error Message: " + ex.Message);
            }
        }
Example #2
0
        public async Task <IActionResult> UpdateCandlesFromExchange([FromBody] UpdateCandlesFromExchangeCommand command)
        {
            /* if (!ModelState.IsValid)
             * {
             *   return BadRequest(ModelState);
             * }
             */

            try
            {
                DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
                var      from       = dtDateTime.AddSeconds(command.From);
                var      to         = dtDateTime.AddSeconds(command.To);

                var candles = await this._exchangeAccessService.GetCandlesData(
                    command.ExchangeId,
                    command.BaseCurrency,
                    command.QuoteCurrency,
                    CandlePeriod.FromName(command.CandlePeriod),
                    from,
                    to);

                var chart = await this._candleChartRepository
                            .GetByCurrencyPairAsync(command.BaseCurrency, command.QuoteCurrency, command.ExchangeId, CandlePeriod.FromName(command.CandlePeriod));

                if (chart == null)
                {
                    throw new KeyNotFoundException();
                }

                foreach (var candle in candles)
                {
                    chart.UpdateCandle(candle.Timestamp, candle.High, candle.Low, candle.Open, candle.Close, candle.Volume);
                }

                await _context.SaveEntitiesAsync();

                return(Ok(chart.CandleChartId));
            }
            catch (Exception ex)
            {
                return(NotFound(ex.Message));
            }
        }
Example #3
0
        public async Task Handle(PaperTradeDataCreatedIntegrationEvent @event)
        {
            try
            {
                var trace = await this._traceRepository.GetByTraceIdAsync(@event.TraceId);

                if (trace == null)
                {
                    return;
                }

                var candles = new List <Candle>();

                foreach (var candle in @event.Candles)
                {
                    candles.Add(new Candle(
                                    candle.Timestamp,
                                    candle.High,
                                    candle.Low,
                                    candle.Open,
                                    candle.Close,
                                    candle.Volume));
                }

                trace.CandleUpdated(candles, CandlePeriod.FromName(@event.CandlePeriod), new RealTimeService(), new IndicatorService(), @event.StrategyId);

                _traceRepository.Update(trace);


                await _traceRepository.UnitOfWork
                .SaveEntitiesAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Handle Integraion Event: PaperTradeDataCreatedIntegrationEvent \n" +
                                  "Result: Failure. \n" +
                                  "Error Message: " + ex.Message);
            }
        }
Example #4
0
        public void StartTracing(ITimeService timeService, CandlePeriod idealCandlePeriod = null)
        {
            if (timeService == null)
            {
                throw new TrendAnalysisDomainException("Time service is not provided when operating on trace.");
            }

            if (idealCandlePeriod == null)
            {
                idealCandlePeriod      = this.CalculateIdealCandlePeriod();
                this.IdealCandlePeriod = idealCandlePeriod.Name;
            }
            else
            {
                this.IdealCandlePeriod = idealCandlePeriod.Name;
            }

            if (this.TraceStatus.Id == TraceStatus.Closed.Id)
            {
                throw new TrendAnalysisDomainException("Cannot start tracing after closed.");
            }
            if (this.TraceStatus.Id != TraceStatus.Started.Id)
            {
                if (!this.TradeStrategies.Any())
                {
                    throw new TrendAnalysisDomainException("There must be at least one strategy before starting trace.");
                }
                this.DateStarted    = timeService.GetCurrentDateTime();
                this._traceStatusId = TraceStatus.Started.Id;

                this.AddDomainEvent(new TraceStartedDomainEvent(
                                        this.TraceId,
                                        CandlePeriod.FromName(this.IdealCandlePeriod),
                                        this.TraceStatus,
                                        this.DateStarted ?? throw new TrendAnalysisDomainException("DateStarted missing when changing status.")));
            }
        }
        public async Task Handle(BacktestingDataCreatedIntegrationEvent @event)
        {
            var traceId     = @event.TraceId;
            var candlesData = @event.Candles;


            var existingTrace = await _traceRepository.GetByTraceIdAsync(traceId);

            if (existingTrace == null)
            {
                return;
            }
            if (existingTrace.Investment.InvestmentId != @event.InvestmentId)
            {
                return;
            }
            if (existingTrace.Market.BaseCurrency != @event.BaseCurrency || existingTrace.Market.QuoteCurrency != @event.QuoteCurrency)
            {
                return;
            }

            DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);

            var from = dtDateTime.AddSeconds(@event.From);
            var to   = dtDateTime.AddSeconds(@event.To);

            while (from.Second != 0)
            {
                from = from.AddSeconds(1);
            }

            var timeService = new BacktestingTimeService();

            timeService.SetCurrentDateTime(from);

            var currentDateTime = timeService.GetCurrentDateTime();
            var pastCandles     = new Dictionary <string, List <Candle> >();

            foreach (var key in candlesData.Keys)
            {
                pastCandles.Add(key, new List <Candle>());


                var warmingCandles = candlesData[key].Where(c => c.Timestamp < currentDateTime).OrderBy(c => c.Timestamp).ToList();

                if (warmingCandles.Any())
                {
                    warmingCandles.Remove(warmingCandles.Last());

                    foreach (var candle in warmingCandles)
                    {
                        pastCandles[key].Add(new Candle(
                                                 candle.Timestamp,
                                                 candle.High,
                                                 candle.Low,
                                                 candle.Open,
                                                 candle.Close,
                                                 candle.Volume));
                    }
                }
            }

            try
            {
                while (currentDateTime <= to)
                {
                    /*await this._trendAnalysisIntegrationEventService.PublishThroughEventBusAsync(new BacktestingTimePassIntegrationEvent(
                     *  currentDateTime,
                     *  traceId,
                     *  @event.InvestmentId
                     *  ));*/

                    foreach (var candles in candlesData)
                    {
                        var currentCandleIndex = candles.Value.FindIndex(c => c.Timestamp == currentDateTime);

                        Models.Candle matchedCandle = null;

                        if (currentCandleIndex != -1)
                        {
                            matchedCandle = candles.Value[currentCandleIndex - 1];
                        }

                        if (matchedCandle != null)
                        {
                            /*if (matchedCandle.Timestamp == new DateTime(2018, 12, 8, 12, 0, 0))
                             * {
                             *  var testPause = 0;
                             * }*/

                            if (pastCandles.TryGetValue(candles.Key, out List <Candle> existingPastCandles))
                            {
                                existingPastCandles.Add(new Candle(
                                                            matchedCandle.Timestamp,
                                                            matchedCandle.High,
                                                            matchedCandle.Low,
                                                            matchedCandle.Open,
                                                            matchedCandle.Close,
                                                            matchedCandle.Volume));

                                if (candles.Key == CandlePeriod.OneMinute.Name)
                                {
                                    var runningCandle = candles.Value.Where(c => c.Timestamp == currentDateTime.AddMinutes(1)).SingleOrDefault();
                                    if (runningCandle != null)
                                    {
                                        var highestPrice = runningCandle.High;
                                        var lowestPrice  = runningCandle.Low;

                                        //Only need next target price when current price cross current target price.
                                        var targetPrice = Trace.CalculateTargetPrice(existingPastCandles, highestPrice);


                                        await this._trendAnalysisIntegrationEventService
                                        .PublishThroughEventBusAsync(new BacktestingPriceChangedIntegrationEvent(
                                                                         traceId,
                                                                         @event.InvestmentId,
                                                                         currentDateTime,
                                                                         highestPrice,
                                                                         lowestPrice,
                                                                         targetPrice
                                                                         ));
                                    }
                                }


                                var processingTrace = await this._traceRepository.GetByTraceIdAsync(traceId);

                                var indicatorService = new IndicatorService();


                                processingTrace.CandleUpdated(existingPastCandles, CandlePeriod.FromName(candles.Key), timeService, new IndicatorService());

                                this._traceRepository.Update(processingTrace);

                                await this._traceRepository.UnitOfWork.SaveEntitiesAsync();

                                pastCandles[candles.Key] = existingPastCandles;
                            }
                        }
                    }

                    currentDateTime = currentDateTime.AddMinutes(1);
                    timeService.SetCurrentDateTime(currentDateTime);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Handle Integration Event: BacktestingDataCreatedIntegrationEvent.");
                Console.WriteLine("Result: Failure.");
                Console.WriteLine("Error Message: " + ex.Message);
            }

            /*currentDateTime = currentDateTime.AddMinutes(-1);
             * timeService.SetCurrentDateTime(currentDateTime);*/

            var toFinishedTrace = await this._traceRepository.GetByTraceIdAsync(traceId);

            toFinishedTrace.CloseTracing(timeService);

            this._traceRepository.Update(toFinishedTrace);
            await this._traceRepository.UnitOfWork.SaveEntitiesAsync();
        }
        public async Task Handle(TraceDataRequestedIntegrationEvent @event)
        {
            try
            {
                var exchangeId    = @event.ExchangeId;
                var baseCurrency  = @event.BaseCurrency;
                var quoteCurrency = @event.QuoteCurrency;
                var period        = CandlePeriod.FromName(@event.CandlePeriod);

                //DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
                var from = @event.From;
                var to   = @event.To;

                var result = new List <CryptoTrading.Services.ExchangeAccess.API.Application.Models.Candle>();


                var candleChart = await _candleChartRepository.GetByCurrencyPairAsync(baseCurrency, quoteCurrency, exchangeId, period);

                if (candleChart != null)
                {
                    var      updatedChart          = candleChart;
                    DateTime fromWithWarmingPeriod = from;


                    if (!candleChart.HasCompleteCandlesBetween(fromWithWarmingPeriod, to))
                    {
                        var candles = await this._exchangeAccessService.GetCandlesData(
                            exchangeId,
                            baseCurrency,
                            quoteCurrency,
                            period,
                            fromWithWarmingPeriod,
                            to);

                        foreach (var candle in candles)
                        {
                            candleChart.UpdateCandle(candle.Timestamp, candle.High, candle.Low, candle.Open, candle.Close, candle.Volume);
                        }

                        updatedChart = this._candleChartRepository.Update(candleChart);
                        await this._candleChartRepository.UnitOfWork.SaveEntitiesAsync();
                    }

                    var candlesData = updatedChart.GetCandles(fromWithWarmingPeriod, to);



                    foreach (var candle in candlesData)
                    {
                        result.Add(new CryptoTrading.Services.ExchangeAccess.API.Application.Models.Candle
                        {
                            Timestamp = candle.Timestamp,
                            Open      = candle.Open,
                            Close     = candle.Close,
                            High      = candle.High,
                            Low       = candle.Low,
                            Volume    = candle.Volume
                        });
                    }
                }


                await this._exchangeAccessIntegrationEventService.PublishThroughEventBusAsync(
                    new PaperTradeDataCreatedIntegrationEvent(
                        @event.TraceId,
                        @event.StrategyId,
                        @event.CandlePeriod,
                        @event.ExchangeId,
                        @event.BaseCurrency,
                        @event.QuoteCurrency,
                        result));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Handle Integration Event: TraceDataRequestedIntegrationEvent.");
                Console.WriteLine("Result: Failure.");
                Console.WriteLine("Error Message: " + ex.Message);
            }
        }
Example #7
0
        private CandlePeriod CalculateIdealCandlePeriod()
        {
            int oneMin      = 0;
            int fiveMins    = 0;
            int fifteenMins = 0;
            int thirtyMins  = 0;
            int oneHour     = 0;
            int twoHours    = 0;
            int fourHours   = 0;
            int oneDay      = 0;
            int oneWeek     = 0;

            foreach (var strategy in this._tradeStrategies)
            {
                var min  = GetPeriodMinute(strategy.GetIdealPeriod());
                var hour = GetPeriodHour(strategy.GetIdealPeriod());
                var day  = GetPeriodDay(strategy.GetIdealPeriod());
                var week = GetPeriodWeek(strategy.GetIdealPeriod());

                if (min != 0)
                {
                    if (min == 1)
                    {
                        oneMin += strategy.Weight;
                    }
                    else if (min == 5)
                    {
                        fiveMins += strategy.Weight;
                    }
                    else if (min == 15)
                    {
                        fifteenMins += strategy.Weight;
                    }
                    else if (min == 30)
                    {
                        thirtyMins += strategy.Weight;
                    }
                }
                else if (hour != 0)
                {
                    if (hour == 1)
                    {
                        oneHour += strategy.Weight;
                    }
                    else if (hour == 2)
                    {
                        twoHours += strategy.Weight;
                    }
                    else if (hour == 4)
                    {
                        fourHours += strategy.Weight;
                    }
                }
                else if (day != 0)
                {
                    if (day == 1)
                    {
                        oneDay += strategy.Weight;
                    }
                }
                else if (week != 0)
                {
                    if (week == 1)
                    {
                        oneWeek += strategy.Weight;
                    }
                }
            }

            var dic = new Dictionary <string, int>();

            dic.Add(CandlePeriod.OneMinute.Name, oneMin);
            dic.Add(CandlePeriod.FiveMinutes.Name, fiveMins);
            dic.Add(CandlePeriod.FifteenMinutes.Name, fifteenMins);
            dic.Add(CandlePeriod.ThirtyMinutes.Name, thirtyMins);
            dic.Add(CandlePeriod.OneHour.Name, oneHour);
            dic.Add(CandlePeriod.TwoHours.Name, twoHours);
            dic.Add(CandlePeriod.FourHours.Name, fourHours);
            dic.Add(CandlePeriod.OneDay.Name, oneDay);
            dic.Add(CandlePeriod.OneWeek.Name, oneWeek);

            var orderedDic = dic.OrderBy(p => p.Value);

            var largest = orderedDic.Last();


            return(CandlePeriod.FromName(largest.Key));
        }