コード例 #1
0
 public CreateHasSuggestionsEvent(long orderId, Guid shopId, OrderSuggestion orderSuggestion)
 {
     DomainEventDate = DateTime.Now;
     OrderId         = orderId;
     ShopId          = shopId;
     OrderSuggestion = orderSuggestion;
 }
コード例 #2
0
        private IOrderSuggestionItemTypeCountDto GetOrderSuggestionItemTypeCount(OrderSuggestion orderSuggestion)
        {
            var result = new OrderSuggestionItemTypeCountDto
            {
                AcceptedCount    = orderSuggestion.OrderSuggestionItems.OfType <HasProductSuggestionItem>().Count(),
                RejectedCount    = orderSuggestion.OrderSuggestionItems.OfType <NoProductSuggestionItem>().Count(),
                AlternativeCount = orderSuggestion.OrderSuggestionItems.OfType <AlternativeProductSuggestionItem>().Count()
            };

            return(result);
        }
コード例 #3
0
        private decimal CalcTotalPrice(OrderSuggestion orderSuggestion)
        {
            decimal totalPrice = 0;

            foreach (var item in orderSuggestion.OrderSuggestionItems)
            {
                if (item is AlternativeProductSuggestionItem)
                {
                    var alternativeProductSuggestionItem = (AlternativeProductSuggestionItem)item;
                    totalPrice += alternativeProductSuggestionItem.Price * alternativeProductSuggestionItem.Quantity;
                }
                if (item is HasProductSuggestionItem)
                {
                    var hasProductSuggestionItem = (HasProductSuggestionItem)item;
                    totalPrice += hasProductSuggestionItem.Price * hasProductSuggestionItem.Quantity;
                }
            }
            return(decimal.Round(totalPrice));
        }
コード例 #4
0
        /// <summary>
        /// </summary>
        /// <param name="currentBar">Current bar of the simulation</param>
        public override void OnBarUpdate(int currentBar)
        {
            base.OnBarUpdate(currentBar);

            // Give the indicators some time to warm up.
            if (currentBar < 50)
            {
                return;
            }

            _stdDev = UtilityMethods.StdDev(Data.Close, currentBar, 10);

            string foundStrategyName = "";
            double buyDirection      = 0.0;

            if (ShouldBuy(currentBar))
            {
                if (ShouldBuyLong(currentBar))
                {
                    buyDirection      = Order.OrderType.Long;
                    foundStrategyName = "BullDmiStrategy";
                }
                //else if (ShouldBuyShort(currentBar))
                //{
                //	buyDirection = Order.OrderType.Short;
                //	foundStrategyName = "BearDmiStrategy";
                //}
            }

            if (buyDirection != 0.0)
            {
                CalculateTargets(buyDirection, currentBar);

                int sizeOfOrder = CalculateOrderSize(buyDirection, currentBar);
                if (sizeOfOrder > 0)
                {
                    List <Indicator> dependentIndicators = GetDependentIndicators();

                    Order placedOrder = EnterOrder(foundStrategyName, currentBar, buyDirection, sizeOfOrder,
                                                   dependentIndicators, GetBuyConditions(), GetSellConditions());

                    if (placedOrder != null)
                    {
                        // Get things like win/loss percent up to the point this order was started.
                        StrategyStatistics orderStats = Simulator.Orders.GetStrategyStatistics(placedOrder.StrategyName,
                                                                                               placedOrder.Type,
                                                                                               placedOrder.Ticker.TickerAndExchange,
                                                                                               currentBar,
                                                                                               Simulator.Config.MaxLookBackBars);

                        AddExtraOrderInfo(placedOrder, currentBar);

                        //if (orderStats.WinPercent >= Simulator.Config.GavalasPercentForBuy && orderStats.Gain > Simulator.Config.GavalasGainForBuy)
                        if (_riskRatio >= Simulator.Config.ChannelMinRiskRatio && _expectedGainPercent >= Simulator.Config.ChannelMinExpectedGain)
                        {
                            Bars[currentBar] = new OrderSuggestion(
                                orderStats.WinPercent,
                                orderStats.Gain,
                                foundStrategyName,
                                buyDirection,
                                sizeOfOrder,
                                dependentIndicators,
                                new List <StrategyStatistics>()
                            {
                                orderStats
                            },
                                GetBuyConditions(),
                                GetSellConditions(),
                                placedOrder.ExtraInfo);
                        }
                    }
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// </summary>
        /// <param name="currentBar">Current bar of the simulation</param>
        public override void OnBarUpdate(int currentBar)
        {
            base.OnBarUpdate(currentBar);

            // Save this so we can use it to set the zigzag deviation.
            _lastAtrValue = ((Atr)_dependents[5]).Value[currentBar];

            if (currentBar < 2)
            {
                return;
            }

            _stdDev = UtilityMethods.StdDev(Data.Close, currentBar, 10);

            GavalasZones zones = (GavalasZones)_dependents[0];

            if (zones.DidBarTouchZone(Data.Low[currentBar], Data.High[currentBar], currentBar) == true)
            {
                _barLastZoneHit       = currentBar;
                _lastZoneHitDirection = zones.BuyDirection[currentBar];
            }

            string foundStrategyName = "";
            double buyDirection      = 0.0;

            // See if we hit one of our buy zones.
            if (ShouldBuy(currentBar))
            {
                if (ShouldBuyLong(currentBar))
                {
                    buyDirection      = Order.OrderType.Long;
                    foundStrategyName = "BullGavalasStrategy";
                }
                else if (ShouldBuyShort(currentBar))
                {
                    buyDirection      = Order.OrderType.Short;
                    foundStrategyName = "BearGavalasStrategy";
                }
            }

            if (buyDirection != 0.0)
            {
                CalculateTargets(buyDirection, currentBar);

                List <Indicator> dependentIndicators = GetDependentIndicators();

                Order placedOrder = EnterOrder(foundStrategyName, currentBar, buyDirection, Simulator.Config.GavalasMaxRiskAmount,
                                               dependentIndicators, GetBuyConditions(), GetSellConditions());

                if (placedOrder != null)
                {
                    // Get things like win/loss percent up to the point this order was started.
                    StrategyStatistics orderStats = Simulator.Orders.GetStrategyStatistics(placedOrder.StrategyName,
                                                                                           placedOrder.Type,
                                                                                           placedOrder.Ticker.TickerAndExchange,
                                                                                           currentBar,
                                                                                           Simulator.Config.MaxLookBackBars);

                    AddExtraOrderInfo(placedOrder, currentBar);

                    // Size of order = max amount we'll risk / (current low - stop)
                    double lossPerShare = buyDirection > 0 ? Data.Low[currentBar] - _stopPrice : _stopPrice - Data.High[currentBar];
                    int    sizeOfOrder  = Convert.ToInt32(Simulator.Config.GavalasMaxRiskAmount / lossPerShare);

                    //if (orderStats.WinPercent >= Simulator.Config.GavalasPercentForBuy && orderStats.Gain > Simulator.Config.GavalasGainForBuy)
                    if (sizeOfOrder > 0)
                    {
                        Bars[currentBar] = new OrderSuggestion(
                            orderStats.WinPercent,
                            orderStats.Gain,
                            foundStrategyName,
                            buyDirection,
                            sizeOfOrder,
                            dependentIndicators,
                            new List <StrategyStatistics>()
                        {
                            orderStats
                        },
                            GetBuyConditions(),
                            GetSellConditions(),
                            placedOrder.ExtraInfo);
                    }
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// </summary>
        /// <param name="currentBar">Current bar of the simulation</param>
        public override void OnBarUpdate(int currentBar)
        {
            base.OnBarUpdate(currentBar);

            if (currentBar < 2)
            {
                return;
            }

            ElliotWaves waves = (ElliotWaves)_dependents[0];

            double buyDirection      = 0.0;
            string foundStrategyName = "";

            // If we're in a 5th wave, see if the price touched one of the retracement zones.
            if (DataSeries.IsAbove(waves.FifthWaveValue, 0.0, currentBar, 2) != -1 && IsBarInZone(currentBar))
            {
                buyDirection = waves.FifthWaveDirection[currentBar] * -1.0;

                // Verify with the mechanical buy signal.
                DtOscillator dtosc = (DtOscillator)_dependents[2];
                if (buyDirection > 0.0 && Data.HigherTimeframeTrend[currentBar] < 0.0)
                {
                    if (dtosc.SD[currentBar] <= 25.0 && dtosc.SK[currentBar] <= 25.0)
                    {
                        foundStrategyName = "BullElliotWavesStrategy";
                    }
                }
                else if (buyDirection < 0.0 && Data.HigherTimeframeTrend[currentBar] > 0.0)
                {
                    if (dtosc.SD[currentBar] >= 75.0 && dtosc.SK[currentBar] >= 75.0)
                    {
                        foundStrategyName = "BearElliotWavesStrategy";
                    }
                }
            }

            if (foundStrategyName.Length > 0)
            {
                List <Indicator> dependentIndicators = GetDependentIndicators();

                Order placedOrder = EnterOrder(foundStrategyName, currentBar, buyDirection, 10000,
                                               dependentIndicators, GetBuyConditions(), GetSellConditions());

                if (placedOrder != null)
                {
                    // Get things like win/loss percent up to the point this order was started.
                    StrategyStatistics orderStats = Simulator.Orders.GetStrategyStatistics(placedOrder.StrategyName,
                                                                                           placedOrder.Type,
                                                                                           placedOrder.Ticker.TickerAndExchange,
                                                                                           currentBar,
                                                                                           Simulator.Config.MaxLookBackBars);

                    Bars[currentBar] = new OrderSuggestion(
                        100.0,
                        orderStats.Gain,
                        foundStrategyName,
                        buyDirection,
                        10000,
                        dependentIndicators,
                        new List <StrategyStatistics>()
                    {
                        orderStats
                    },
                        GetBuyConditions(),
                        GetSellConditions(),
                        null);
                }
            }
        }
コード例 #7
0
 public static IOrderSuggestionDto ToDo(this OrderSuggestion src)
 {
     return(Mapper.Map <IOrderSuggestionDto>(src));
 }
コード例 #8
0
        private decimal CalcDiscountTotalPrice(OrderSuggestion orderSuggestion)
        {
            decimal totalPrice = 0;

            foreach (var item in orderSuggestion.OrderSuggestionItems)
            {
                if (item is AlternativeProductSuggestionItem alternativeProductSuggestionItem)
                {
                    if (alternativeProductSuggestionItem.OrderItem.Discount != null)
                    {
                        if (alternativeProductSuggestionItem.OrderItem.Discount is OrderItemPercentDiscount percentDiscount)
                        {
                            if (alternativeProductSuggestionItem.OrderItem.Discount.HasDiscountValid())
                            {
                                var price = alternativeProductSuggestionItem.Price * (100 - orderSuggestion.Discount) / 100;
                                totalPrice += price * (decimal)(100 - percentDiscount.Percent) / 100;

                                if (alternativeProductSuggestionItem.Quantity - 1 > 0)
                                {
                                    var price1 = alternativeProductSuggestionItem.Price * (100 - orderSuggestion.Discount) /
                                                 100;
                                    totalPrice += price1 * (alternativeProductSuggestionItem.Quantity - 1);
                                }
                            }
                            else
                            {
                                var price = alternativeProductSuggestionItem.Price * (100 - orderSuggestion.Discount) / 100;
                                totalPrice += price * alternativeProductSuggestionItem.Quantity;
                            }
                        }
                        else
                        {
                            var price = alternativeProductSuggestionItem.Price * (100 - orderSuggestion.Discount) / 100;
                            totalPrice += price * alternativeProductSuggestionItem.Quantity;
                        }
                    }
                    else
                    {
                        var price = alternativeProductSuggestionItem.Price * (100 - orderSuggestion.Discount) / 100;
                        totalPrice += price * alternativeProductSuggestionItem.Quantity;
                    }
                }
                if (item is HasProductSuggestionItem hasProductSuggestionItem)
                {
                    if (hasProductSuggestionItem.OrderItem.Discount != null)
                    {
                        if (hasProductSuggestionItem.OrderItem.Discount is OrderItemPercentDiscount percentDiscount)
                        {
                            if (hasProductSuggestionItem.OrderItem.Discount.HasDiscountValid())
                            {
                                var price = hasProductSuggestionItem.Price * (100 - orderSuggestion.Discount) / 100;
                                totalPrice += price * (decimal)(100 - percentDiscount.Percent) / 100;

                                if (hasProductSuggestionItem.Quantity - 1 > 0)
                                {
                                    var price1 = hasProductSuggestionItem.Price * (100 - orderSuggestion.Discount) /
                                                 100;
                                    totalPrice += price1 * (hasProductSuggestionItem.Quantity - 1);
                                }
                            }
                            else
                            {
                                var price = hasProductSuggestionItem.Price * (100 - orderSuggestion.Discount) / 100;
                                totalPrice += price * hasProductSuggestionItem.Quantity;
                            }
                        }
                        else
                        {
                            var price = hasProductSuggestionItem.Price * (100 - orderSuggestion.Discount) / 100;
                            totalPrice += price * hasProductSuggestionItem.Quantity;
                        }
                    }
                    else
                    {
                        var price = hasProductSuggestionItem.Price * (100 - orderSuggestion.Discount) / 100;
                        totalPrice += price * hasProductSuggestionItem.Quantity;
                    }
                }
            }
            return(decimal.Round(totalPrice));
        }
コード例 #9
0
        public async Task <CreateOrderSuggestionCommandResponse> Handle(CreateOrderSuggestionCommand command)
        {
            _applicationSettingDomainService.CheckDiscountInRangeSetting(command.Discount);
            _applicationSettingDomainService.CheckShippingTime(command.ShippingTime);
            if (_repository.AsQuery().Any(p => p.OrderId == command.OrderId))
            {
                throw new DomainException("پیشنهاد بروی این سفارش زده شده است");
            }
            var order = _orderRepository.AsQuery().SingleOrDefault(p => p.Id == command.OrderId);

            if (order == null)
            {
                throw new DomainException("سفارش یافت نشد");
            }

            if (order.OrderStatus == OrderStatus.Cancel)
            {
                throw new DomainException("این سفارش توسط مشتری لغو شده است");
            }
            _applicationSettingDomainService.CheckOrderExpireTime(order.CreationTime);
            if (order.ResponseExpireTime < DateTime.Now)
            {
                throw new DomainException("زمان پاسخ گویی شما به پایان رسیده است");
            }

            var shop = _personRepository.AsQuery().OfType <Shop>().SingleOrDefault(p => p.UserId == command.UserId);

            if (shop == null)
            {
                throw new DomainException("فروشگاه یافت نشد");
            }

            var appSetting = _applicationSettingRepository.AsQuery().SingleOrDefault();

            if (appSetting == null)
            {
                throw new Exception();
            }

            if (command.Discount < appSetting.MinimumDiscount || command.Discount > appSetting.MaximumDiscount)
            {
                throw new DomainException("تخفیف وارد شده در بازه تخفیفات معتبر نمی باشد");
            }
            if (command.ShippingTime > appSetting.MaximumDeliveryTime)
            {
                throw new DomainException("زمان ارسال سفارش از حداکثر زمان ارسال معتبر بیشتر می باشد");
            }

            var orderId         = order is AreaOrder areaOrder ? areaOrder.PrivateOrder.Id : order.Id;
            var orderSuggestion = new OrderSuggestion(Guid.NewGuid(), orderId, command.Discount, command.Description, shop, command.ShippingTime)
            {
                OrderSuggestionItems = new List <OrderSuggestionItemBase>()
            };
            decimal totalPrice = 0;

            foreach (var item in command.OrderSuggestionItems)
            {
                var orderItem = order.OrderItems.SingleOrDefault(p => p.Id == item.OrderItemId);
                if (orderItem == null)
                {
                    throw new DomainException("آیتم سفارش یافت نشد");
                }
                var findProduct = _productRepository.Find(item.ProductId);
                switch (item.OrderSuggestionItemType)
                {
                case OrderSuggestionItemType.AlternativeProduct:
                    if (findProduct == null)
                    {
                        throw new DomainException("کالای ارسالی جایگزین نامعتبر می باشد");
                    }
                    var alternativeProduct =
                        new AlternativeProductSuggestion(findProduct.Id, findProduct.Name, findProduct.MainImage,
                                                         findProduct.Brand.Id, findProduct.Brand.Name);
                    orderItem.Discount = null;
                    var alternativeProductSuggestionItem = new AlternativeProductSuggestionItem(Guid.NewGuid(),
                                                                                                orderItem, item.Quantity, item.Description, item.Price, alternativeProduct,
                                                                                                orderItem.Quantity != item.Quantity);
                    orderSuggestion.OrderSuggestionItems.Add(alternativeProductSuggestionItem);
                    totalPrice = totalPrice + (item.Price * item.Quantity);
                    break;

                case OrderSuggestionItemType.NoProduct:
                    var noProduct = new NoProductSuggestionItem(Guid.NewGuid(), orderItem);
                    orderSuggestion.OrderSuggestionItems.Add(noProduct);
                    break;

                case OrderSuggestionItemType.HasProduct:
                    if (orderItem.Discount != null)
                    {
                        if (!orderItem.Discount.HasDiscountValid())
                        {
                            orderItem.Discount = null;
                        }
                    }
                    var hasProduct = new HasProductSuggestionItem(Guid.NewGuid(), orderItem, item.Quantity,
                                                                  item.Description, item.Price, orderItem.Quantity != item.Quantity);
                    orderSuggestion.OrderSuggestionItems.Add(hasProduct);
                    totalPrice = totalPrice + (item.Price * item.Quantity);
                    break;
                }
            }
            _repository.Add(orderSuggestion);


            //todo order check it
            var expireMinutes = order.ExpireOpenTime.Subtract(DateTime.Now).TotalMinutes;

            order.ExpireOpenTime = order.ExpireOpenTime.AddMinutes(appSetting.OrderSuggestionExpireTime - expireMinutes);
            order.SuggestionTime = DateTime.Now.AddMinutes(appSetting.OrderSuggestionExpireTime);
            DomainEventDispatcher.Raise(new TheOrderStatusWentToHasSuggestionEvent(order));
            if (order is AreaOrder area)
            {
                area.PrivateOrder.SuggestionTime = DateTime.Now.AddMinutes(appSetting.OrderSuggestionExpireTime);
                DomainEventDispatcher.Raise(new TheOrderStatusWentToHasSuggestionEvent(area.PrivateOrder));
            }
            DomainEventDispatcher.Raise(new CreateHasSuggestionsEvent(order.Id, shop.Id, orderSuggestion));
            await _fcmNotification.SendToIds(order.Customer.GetPushTokens(),
                                             "پیشنهاد سفارش",
                                             $"برای سفارش شما با شناسه {order.Id} یک پیشنهاد ثبت شد",
                                             NotificationType.OrderSuggestionAdded,
                                             AppType.Customer, NotificationSound.Shopper);

            return(new CreateOrderSuggestionCommandResponse());
        }