Beispiel #1
0
 public Deal(string code, decimal value, DealType type, decimal minimumOrder = 0.0m)
 {
     Code         = code;
     Value        = value;
     Type         = type;
     MinimumOrder = minimumOrder;
 }
Beispiel #2
0
        private async Task <DealModifyModel> CreateDealModifyModel(DealType dealType)
        {
            var freeObjectsTask   = _dealObjectProvider.GetUserObjects(true, dealType);
            var userTask          = _userProvider.GetUser();
            var regionsTask       = _regionProvider.GetRegions();
            var deliveryTypesTask = _dealProvider.GetDeleveryTypes();

            await Task.WhenAll(freeObjectsTask, userTask, regionsTask, deliveryTypesTask);

            var user = userTask.Result.Model;

            string regionCode = String.IsNullOrEmpty(user.RegionCode) ? Constants.MOSCOW_KLADR : user.RegionCode;

            var locationTask = _regionProvider.GetLocalities(regionCode);
            var cityTask     = _regionProvider.GetLocationsByRegion(regionCode);

            await Task.WhenAll(locationTask, cityTask);

            var freeObjects   = freeObjectsTask.Result.Model;
            var locations     = locationTask.Result.Model;
            var cities        = cityTask.Result.Model;
            var regions       = regionsTask.Result.Model;
            var deliveryTypes = deliveryTypesTask.Result.Model;

            var deleveryType = AddressType.City;

            if (user.DeleveryLocationType.HasValue)
            {
                deleveryType = (AddressType)user.DeleveryLocationType;
            }

            string cityCode     = String.IsNullOrEmpty(user.CityCode) ? cities.First().Code : user.CityCode;
            string localityCode = String.IsNullOrEmpty(user.LocalityCode) ? locations.First().Code : user.LocalityCode;
            string locationCode = String.IsNullOrEmpty(user.CityCode) ? locations.First().Code : user.CityCode;

            return(new DealModifyModel
            {
                AddressModel = new AddressViewModel(nameof(SellDealModifyViewModel.AddressModel))
                {
                    Address = user.Address,
                    DeliveryLocationType = deleveryType,
                    City = new CityViewModel
                    {
                        CityCode = cityCode,
                        CityList = new SelectList(cities.OrderBy(l => l.Name), "Code", "Name", cityCode)
                    },
                    Locality = new LocalityViewModel
                    {
                        LocalityList = new SelectList(locations.OrderBy(l => l.Name), "Code", "Name", localityCode),
                        LocalityCode = user.LocalityCode,
                        LocationList = new SelectList(locations.OrderBy(l => l.Name), "Code", "Name", locationCode),
                        LocationCode = user.CityCode
                    },
                    RegionCode = regionCode,
                    RegionList = new SelectList(regions.OrderBy(l => l.Name), "Code", "Name", regionCode),
                },
                DeleveryTypes = new SelectList(deliveryTypes, "DeliveryId", "Name"),
                FreeDealObjects = new SelectList(freeObjects, "ObjectId", "Name")
            });
        }
Beispiel #3
0
    /// <summary>
    /// 提交订单完成
    /// </summary>
    private void SubmintDealComplete()
    {
        //更新显示
        UpdateShow();
        //更新主界面显示
        if (UIDealController.Instance != null)
        {
            switch (_curDealType)
            {
            case DealType.MiddleLevel:
                UIDealController.Instance.UpdateIntermediateDealNum();
                break;

            case DealType.HighLevel:
                UIDealController.Instance.UpdateAdvancedDealNum();
                break;

            default:
                UIDealController.Instance.UpdateOrdinaryDealNum();
                break;
            }

            //通知提交订单完成
            UIDealController.Instance.NotifySubmintDealComplete();
            _curDealType = DealType.None;
            //提示获取的物品
            //StaticData.OpenCommonReceiveAwardTips(StaticData.GetMultilingual(120290), StaticData.GetMultilingual(120195), "", ShowAwardCallback, null, _showAwardDatas);
        }
    }
Beispiel #4
0
 private static void DrawEnterSign(DealType side,
                                   int x, int y,
                                   Graphics g, Pen pen, Brush foreBrush)
 {
     if (side == DealType.Buy)
     {
         var points = new[]
         {
             new Point(x, y),
             new Point(x - 4, y + 6),
             new Point(x + 4, y + 6)
         };
         g.FillPolygon(foreBrush, points);
         g.DrawPolygon(pen, points);
     }
     else
     {
         var points = new[]
         {
             new Point(x, y),
             new Point(x - 4, y - 6),
             new Point(x + 4, y - 6)
         };
         g.FillPolygon(foreBrush, points);
         g.DrawPolygon(pen, points);
     }
 }
 public TradeFromSLDlg(int tradeCount, DealType side, float? sl)
 {
     InitializeComponent();
     labelCountOpen.Text = tradeCount.ToString();
     cbSide.SelectedIndex = side == DealType.Buy ? 0 : 1;
     if (sl.HasValue) tbSL.Text = sl.Value.ToStringUniform(4);
 }
Beispiel #6
0
        public async Task <DealType> CreateDealType(DealType dealType)
        {
            await _unitOfWork.DealTypes.AddAsync(dealType);

            await _unitOfWork.CommitAsync();

            return(dealType);
        }
Beispiel #7
0
        public static void Draw(DealEventSymbolType evType, DealType side,
                                double chartX, double chartY, RectangleD worldRect, Rectangle canvasRect,
                                Graphics g, Pen pen, Brush foreBrush, Brush backBrush)
        {
            var center = Conversion.WorldToScreen(new
                                                  PointD(chartX, chartY), worldRect, canvasRect);

            Draw(evType, side, (int)center.X, (int)center.Y, g, pen, foreBrush, backBrush);
        }
Beispiel #8
0
        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <param name="oldpath">原图片绝对地址</param>
        /// <param name="newpath">新图片放置的绝对地址</param>
        /// <param name="WatermarkText">水印文字</param>
        /// <param name="Watermarkimgpath">水印图片绝对地址</param>
        public bool addWaterMark(string oldpath, string newpath, DealType dealtype, WaterPos WatermarkPosition, string WatermarkText, string Watermarkimgpath)
        {
            bool re = false;

            try
            {
                System.Drawing.Image image = System.Drawing.Image.FromFile(oldpath);

                foreach (Guid guid in image.FrameDimensionsList)//判断是否是GIF动画:是-则不加水印
                {
                    FrameDimension dimension = new FrameDimension(guid);
                    if (image.GetFrameCount(dimension) > 1)
                    {
                        image.Dispose();
                        return(false);
                    }
                }

                Bitmap   b = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb);
                Graphics g = Graphics.FromImage(b);
                g.Clear(Color.White);
                g.SmoothingMode     = SmoothingMode.AntiAlias;
                g.InterpolationMode = InterpolationMode.High;

                g.DrawImage(image, 0, 0, image.Width, image.Height);

                switch (dealtype)
                {
                //是图片的话
                case DealType.WM_IMAGE:
                    this.addWatermarkImage(g, Watermarkimgpath, WatermarkPosition, image.Width, image.Height);
                    break;

                //如果是文字
                case DealType.WM_TEXT:
                    this.addWatermarkText(g, WatermarkText, WatermarkPosition, image.Width, image.Height);
                    break;
                }

                //b.Save(newpath);
                //直接save加水印后图片容量大小会成几倍增加
                EncoderParameters parameters = new EncoderParameters(1);
                parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long)80));
                b.Save(newpath, ImageHelper.GetCodecInfo("image/" + ImageHelper.GetFormat(newpath).ToString().ToLower()), parameters);

                b.Dispose();
                g.Dispose();
                image.Dispose();

                re = true;
            }
            catch
            {
                re = false;
            }
            return(re);
        }
Beispiel #9
0
        public async Task <DealType> UpdateDealType(DealType dealTypeToUpdate, DealType dealType)
        {
            dealTypeToUpdate.Name        = dealType.Name;
            dealTypeToUpdate.Description = dealType.Description;

            await _unitOfWork.CommitAsync();

            return(dealTypeToUpdate);
        }
Beispiel #10
0
    /// <summary>
    /// 获取刷新订单消耗
    /// </summary>
    /// <returns></returns>
    private GoodIDCount GetRefreshDealConsume(DealType dealType)
    {
        var curDealInf = StaticData.configExcel.Deal.Find(dealInf => dealInf.DealLevel == (int)dealType);

        if (curDealInf != null)
        {
            return(curDealInf.RefreshDealUseGoods);
        }
        return(null);
    }
Beispiel #11
0
 public DealEntity(ItemType itemType, DealType dealType, string ItemDesc, int UserID, string ClientName, double Price)
 {
     this.DealType   = dealType;
     this.ItemType   = itemType;
     this.ItemDesc   = ItemDesc;
     this.UserID     = UserID;
     this.ClientName = ClientName;
     this.DateOfBuy  = (DateTime?)DateTime.Now;
     this.Price      = Price;
 }
        private static string AugmentLongDescription(string longdescription, DealType dealType)
        {
            if (dealType == DealType.Free)
                return longdescription;

            var a = $"FEES = £0\nDEPOSIT = £0\nUP FRONT RENT = £0\n\nMove in to this property for FREE \n\n{longdescription}\n\nBest of all you can move in for Free and pay your first month's rent 2 weeks later - simple as that!\n\nTo avoid missing out call us today or email us with your name and a phone number.";
            var b = $"*NO UPFRONT RENT, FEES OR DEPOSIT*\n\n{longdescription}\n\nWith a normal agency/landlord this property could cost you over £2000 just to move in when you add up all the admin fees, deposit and upfront rent! \nLetMe charge you NOTHING!Available for viewings and ready to Let NOW!!";

            return new Random().NextDouble() >= 0.5 ? a : b;
        }
 public TradeFromSLDlg(int tradeCount, DealType side, float?sl)
 {
     InitializeComponent();
     labelCountOpen.Text  = tradeCount.ToString();
     cbSide.SelectedIndex = side == DealType.Buy ? 0 : 1;
     if (sl.HasValue)
     {
         tbSL.Text = sl.Value.ToStringUniform(4);
     }
 }
Beispiel #14
0
 public DealModel(
     int dealId,
     int?sellerUserId,
     int?buyerUserId,
     int hostUserId,
     int?checkedByUserId,
     string checkStatusName,
     string checkComment,
     int dealCurrencyId,
     bool isApprovedBySeller,
     bool isApprovedByBuyer,
     bool isApprovedByMe,
     bool isApprovedByParner,
     bool isAccepted,
     double price,
     int liveTimeInHours,
     int paymentTimeInMinutes,
     string comment,
     DateTime?closeDate,
     DateTime createDate,
     DateTime changeDate,
     DealType dealType,
     bool isMyDeal,
     bool blocked,
     int pin,
     int?accountId,
     string objects)
 {
     DealId             = dealId;
     SellerUserId       = sellerUserId;
     BuyerUserId        = buyerUserId;
     HostUserId         = hostUserId;
     CheckedByUserId    = checkedByUserId;
     CheckStatusName    = checkStatusName;
     CheckComment       = checkComment;
     DealCurrencyId     = dealCurrencyId;
     IsApprovedBySeller = isApprovedBySeller;
     IsApprovedByBuyer  = isApprovedByBuyer;
     IsApprovedByMe     = isApprovedByMe;
     IsApprovedByParner = isApprovedByParner;
     IsAccepted         = isAccepted;
     Price                = price;
     LiveTimeInHours      = liveTimeInHours;
     PaymentTimeInMinutes = paymentTimeInMinutes;
     Comment              = comment;
     CloseDate            = closeDate;
     CreateDate           = createDate;
     ChangeDate           = changeDate;
     DealType             = dealType;
     IsMyDeal             = isMyDeal;
     Blocked              = blocked;
     Pin       = pin;
     AccountId = accountId;
     Objects   = objects;
 }
Beispiel #15
0
 static string DealTypeString(DealType type)
 {
     if (type == DealType.SHORT)
     {
         return("Short");
     }
     else
     {
         return("Long");
     }
 }
        public void Shuffle(DealType deal)
        {
            switch (deal)
            {
            case DealType.SequentialSuits: { ShuffleBySuitDealSequentially(); break; }

            case DealType.RandomSuits: { ShuffleBySuitDealRandomly(); break; }

            case DealType.BandedSuits: { ShuffleBySuitDealVerticalBands(); break; }

            default: { ShuffleStandard(); break; }
            }
        }
 public bool IsEnterProhibided(DealType side)
 {
     if (!indexCalculator.lastIndexValue.HasValue) return false;
     foreach (var con in conditions)
     {
         if ((con.ProhibitionType == UserIndexFilterCondition.DealProhibitionType.ЗапретПокупок &&
             side == DealType.Sell) ||
             (con.ProhibitionType == UserIndexFilterCondition.DealProhibitionType.ЗапретПродаж &&
             side == DealType.Buy)) continue;
         if (con.IsProhibided(indexCalculator.lastIndexValue.Value)) return true;
     }
     return false;
 }
Beispiel #18
0
 private static void DrawEnterLock(DealType side,
                                   int x, int y,
                                   Graphics g, Pen pen, Brush foreBrush)
 {
     DrawEnterSign(side, x, y, g, pen, foreBrush);
     if (side == DealType.Buy)
     {
         g.DrawArc(pen, x - 4, y + 4, 8, 8, 0, 180);
     }
     else
     {
         g.DrawArc(pen, x - 4, y - 4 - 8, 8, 8, 180, 180);
     }
 }
Beispiel #19
0
        //Определение направления сделки
        private static AggressorSide DealTypeConverter(DealType dealType)
        {
            var aggressorSide = AggressorSide.None;

            if (dealType == DealType.Buy)
            {
                aggressorSide = AggressorSide.Buy;
            }
            else if (dealType == DealType.Sell)
            {
                aggressorSide = AggressorSide.Sell;
            }

            return(aggressorSide);
        }
        private void BtnOKClick(object sender, EventArgs e)
        {
            var sl = tbSL.Text.Replace(",", ".").ToFloatUniformSafe() ?? 0;

            if (sl <= 0)
            {
                MessageBox.Show("Укажите ненулевой SL");
                return;
            }
            StopLoss = sl;
            Side     = cbSide.SelectedIndex == 0 ? DealType.Buy : DealType.Sell;

            DialogResult = DialogResult.OK;
            Close();
        }
 public Simulator(ushort suitCount,
                  ushort valueCount,
                  ushort trials,
                  ushort experiments,
                  DealType deal,
                  ApproachType approach,
                  OutputType output)
 {
     SuitCount   = suitCount;
     ValueCount  = valueCount;
     Trials      = trials;
     Experiments = experiments;
     Deal        = deal;
     Approach    = approach;
     Output      = output;
 }
Beispiel #22
0
    private async void SubmintDealCallback(SCSubmintDeal sCSubmintDeal)
    {
        if (sCSubmintDeal == null)
        {
            _butSubmint.interactable = true;
            return;
        }
        _showAwardDatas.Clear();

        _curDealType = _currDeal.DealType;

        //发放奖励 道具入库
        for (int i = 0; i < _currDeal.DealAwardInfo.Count; i++)
        {
            //需要展示的物品
            CSWareHouseStruct cSWareHouseStruct = new CSWareHouseStruct();
            cSWareHouseStruct.GoodId  = _currDeal.DealAwardInfo[i].GoodId;
            cSWareHouseStruct.GoodNum = _currDeal.DealAwardInfo[i].GoodNum;
            cSWareHouseStruct.IsLock  = true;
            _showAwardDatas.Add(cSWareHouseStruct);

            var item       = StaticData.configExcel.GetGameItemByID(cSWareHouseStruct.GoodId);
            var itemSprite = await ABManager.GetAssetAsync <Sprite>(item.Icon);

            //世界坐标转换为屏幕坐标
            var pos = Camera.main.WorldToScreenPoint(transform.position);
            StaticData.OpenPickupItemEffectNew(itemSprite, 0.35f, pos, cSWareHouseStruct.GoodId, cSWareHouseStruct.GoodNum, null /*PickUpItemEffectComplete*/);
        }
        //移除需要的物品
        for (int i = 0; i < _currDeal.DealNeedGoods.Count; i++)
        {
            StaticData.UpdateWareHouseItem(_currDeal.DealNeedGoods[i].GoodId, _currDeal.DealNeedGoods[i].GoodNum * -1);
        }

        //更新完成订单数
        int dealLevel = (int)_currDeal.DealType - 1;

        dealLevel = dealLevel >= 0 ? dealLevel : 0;
        StaticData.AddDealCompleteValue(dealLevel);

        //更新订单数据
        _currDeal = sCSubmintDeal.NewDealInfo;
        StaticData.UpdateDeal(_currDeal);

        //道具入库
        ItemPropsWarehousing();
    }
Beispiel #23
0
        public DealMarker(ChartControl owner, List<DealMarker> markers,
            DealMarkerType markerType, DealType side, 
            double candleIndex, double price, DateTime time)
        {
            this.markers = markers;
            var maxId = markers.Count == 0 ? 0 : markers.Max(m => m.id);
            if (nextNumber <= maxId) nextNumber = maxId + 1;
            id = nextNumber++;

            Name = string.Format("{0} {1}", ClassName, id);
            this.owner = owner;
            MarkerType = markerType;
            this.candleIndex = candleIndex;
            Price = price;
            DateStart = time;
            this.side = side;
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return(null);
            }
            DealType dealType = (DealType)value;

            switch (dealType)
            {
            case DealType.Purchase:
                return("Alış");

            case DealType.Sale:
                return("Satış");

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Beispiel #25
0
        public DealMarker(ChartControl owner, List <DealMarker> markers,
                          DealMarkerType markerType, DealType side,
                          double candleIndex, double price, DateTime time)
        {
            this.markers = markers;
            var maxId = markers.Count == 0 ? 0 : markers.Max(m => m.id);

            if (nextNumber <= maxId)
            {
                nextNumber = maxId + 1;
            }
            id = nextNumber++;

            Name             = string.Format("{0} {1}", ClassName, id);
            this.owner       = owner;
            MarkerType       = markerType;
            this.candleIndex = candleIndex;
            Price            = price;
            DateStart        = time;
            this.side        = side;
        }
 public bool IsEnterProhibided(DealType side)
 {
     if (!indexCalculator.lastIndexValue.HasValue)
     {
         return(false);
     }
     foreach (var con in conditions)
     {
         if ((con.ProhibitionType == UserIndexFilterCondition.DealProhibitionType.ЗапретПокупок &&
              side == DealType.Sell) ||
             (con.ProhibitionType == UserIndexFilterCondition.DealProhibitionType.ЗапретПродаж &&
              side == DealType.Buy))
         {
             continue;
         }
         if (con.IsProhibided(indexCalculator.lastIndexValue.Value))
         {
             return(true);
         }
     }
     return(false);
 }
Beispiel #27
0
        public override bool Initialize(List <IProcessorInput> inputs, string parameters, ILogger logger)
        {
            dealprice   = new double[2];
            dealtime    = new DateTime[2];
            dealcounter = 0;
            this.inputs = inputs;
            this.logger = logger;
            ParametersParser parser = CreateParser(parameters);

            min_node     = parser.GetInt("MinValue");
            gap_position = parser.GetInt("GapPosition");
            if (gap_position < 0 || gap_position > Model.Project.Outputs.Count)
            {
                return(false);
            }
            Fut = parser.GetInt("Future");
            if (Fut < 0 || Fut >= inputs.Count)
            {
                return(false);
            }
            string name = parser.GetString("Name");

            file_name_profit     = Path.Combine(logPath, name + "_profit_log.txt");
            file_name_lose       = Path.Combine(logPath, name + "_lose_log.txt");
            prev_peak            = 0;
            next_value_to_change = 0;
            dealtype             = DealType.NONE;
            global_profit        = 0;
            global_lose          = 0;
            Value = 0;
//Gap = Model.Project.Proccesors[gap_position];
            //Gap.ProcessorAction += GapWorker;
            IsNewValue = false;
            return(true);
            //throw new NotImplementedException();
        }
Beispiel #28
0
        public static void Draw(DealEventSymbolType evType, DealType side,
                                int x, int y,
                                Graphics g, Pen pen, Brush foreBrush, Brush backBrush)
        {
            g.DrawLine(pen, x - 5, y, x + 5, y);
            switch (evType)
            {
            case DealEventSymbolType.Open:
                DrawEnterSign(side, x, y, g, pen, foreBrush);
                break;

            case DealEventSymbolType.Close:
                DrawClose(x, y, g, pen);
                break;

            case DealEventSymbolType.OpenLocking:
                DrawEnterLock(side, x, y, g, pen, foreBrush);
                break;

            case DealEventSymbolType.Unlock:
                DrawUnlock(x, y, g, pen);
                break;
            }
        }
Beispiel #29
0
        public static DealModel CreateDeal(
            string shortTitle = "",
            string shortDescription = "",
            string longTitle = "",
            string longDescription = "",
            string finePrint = "",
            string highlight = "",
            string canonicalUrl = "",
            string id = "",
            DealType dealType = DealType.Product)
        {
            var deal = DealModel.Create(
                shortTitle.Equals("") ? fixture.Create<string>() : shortTitle,
                shortDescription.Equals("") ? fixture.Create<string>() : shortDescription,
                longTitle.Equals("") ? fixture.Create<string>() : longTitle,
                longDescription.Equals("") ? fixture.Create<string>() : longDescription,
                finePrint.Equals("") ? fixture.Create<string>() : finePrint,
                highlight.Equals("") ? fixture.Create<string>() : highlight,
                dealType);

            deal.Key = string.IsNullOrEmpty(id) ? fixture.Create<string>() : id;

            if (!string.IsNullOrEmpty(canonicalUrl))
            {
                deal.CanonicalUrl = canonicalUrl;
            }

            var regularPrice = fixture.Create<double>();
            var specialPrice = fixture.Create<double>(regularPrice);

            deal.SetPrice(regularPrice, specialPrice);

            return deal;
        }
Beispiel #30
0
 void Deal(string logfile, DateTime time_open, DateTime time_close, double deal_price, double[] deal_prices, double global_profit, DealType type)
 {
     using (StreamWriter sw = new StreamWriter(logfile, true))
     {
         string message = String.Format(" Сделка {0} {1} / {2} : Профит {3} (открыто по цене {4} / закрыто по цене {5}. Общий профит: {6})",
                                        DealTypeString(dealtype), time_open.ToString("dd.MM hh:mm:ss:fff"), time_close.ToString("dd.MM hh:mm:ss:fff"),
                                        deal_price, deal_prices[0], deal_prices[1], global_profit);
         sw.WriteLine(message);
     }
 }
Beispiel #31
0
 private static void DrawEnterSign(DealType side,
     int x, int y,
     Graphics g, Pen pen, Brush foreBrush)
 {
     if (side == DealType.Buy)
     {
         var points = new[]
         {
             new Point(x, y),
             new Point(x - 4, y + 6),
             new Point(x + 4, y + 6)
         };
         g.FillPolygon(foreBrush, points);
         g.DrawPolygon(pen, points);
     }
     else
     {
         var points = new[]
         {
             new Point(x, y),
             new Point(x - 4, y - 6),
             new Point(x + 4, y - 6)
         };
         g.FillPolygon(foreBrush, points);
         g.DrawPolygon(pen, points);
     }
 }
Beispiel #32
0
        public override double Process(DateTime time)
        {
            double temp_value = Model.Project.Outputs[gap_position].Value;

            if (next_value_to_change == 0)
            {
                if (temp_value > min_node)
                {
                    next_peak            = temp_value;
                    peak_time            = time;
                    next_value_to_change = -min_node;
                    fut_ask = inputs[Fut].Ask;
                }
                if (temp_value < -min_node)
                {
                    next_peak            = temp_value;
                    peak_time            = time;
                    next_value_to_change = min_node;
                    fut_bid = inputs[Fut].Bid;
                }
            }
            if (next_value_to_change < 0)
            {
                if (temp_value > next_peak)
                {
                    next_peak = temp_value;
                    peak_time = time;
                    fut_ask   = inputs[Fut].Ask;
                }
                if (temp_value < -min_node)
                {
                    Value      = next_peak;
                    ValueTime  = peak_time;
                    IsNewValue = true;
                    ProcessorAction?.Invoke(new object[] { "Max", Value, fut_ask, ValueTime });
                    next_value_to_change   = min_node;
                    dealprice[dealcounter] = fut_ask;
                    dealtime[dealcounter]  = ValueTime;
                    dealcounter++;
                    if (dealtype == DealType.NONE)
                    {
                        dealtype = DealType.LONG;
                    }
                    next_peak = temp_value;
                    peak_time = time;
                    fut_ask   = inputs[Fut].Ask;
                }
            }
            if (next_value_to_change > 0)
            {
                if (temp_value < next_peak)
                {
                    next_peak = temp_value;
                    peak_time = time;
                    fut_bid   = inputs[Fut].Bid;
                }
                if (temp_value > min_node)
                {
                    Value      = next_peak;
                    ValueTime  = peak_time;
                    IsNewValue = true;
                    ProcessorAction?.Invoke(new object[] { "Min", Value, fut_bid, ValueTime });
                    next_value_to_change = -min_node;
                    //next_value_to_change = min_node;
                    dealprice[dealcounter] = fut_bid;
                    dealtime[dealcounter]  = ValueTime;
                    dealcounter++;
                    if (dealtype == DealType.NONE)
                    {
                        dealtype = DealType.SHORT;
                    }
                    next_peak = temp_value;
                    peak_time = time;
                    fut_bid   = inputs[Fut].Bid;
                }
            }
            if (dealcounter == 2)
            {
                double profit = 0;
                if (dealtype == DealType.SHORT)
                {
                    profit = dealprice[0] - dealprice[1];
                }
                else
                {
                    profit = dealprice[1] - dealprice[0];
                }
                if (profit > 0)
                {
                    global_profit += profit;
                    Deal(file_name_profit, dealtime[0], dealtime[1], profit, dealprice, global_profit, dealtype);
                }
                else
                {
                    global_lose += profit;
                    Deal(file_name_lose, dealtime[0], dealtime[1], profit, dealprice, global_lose, dealtype);
                }
                dealtime[0]  = dealtime[1];
                dealprice[0] = dealprice[1];
                dealcounter  = 1;
                if (dealtype == DealType.LONG)
                {
                    dealtype = DealType.SHORT;
                }
                else
                {
                    dealtype = DealType.LONG;
                }
            }
            return(Value);
            //throw new NotImplementedException();
        }
Beispiel #33
0
 private static void DrawEnterLock(DealType side,
     int x, int y,
     Graphics g, Pen pen, Brush foreBrush)
 {
     DrawEnterSign(side, x, y, g, pen, foreBrush);
     if (side == DealType.Buy)
         g.DrawArc(pen, x - 4, y + 4, 8, 8, 0, 180);
     else
         g.DrawArc(pen, x - 4, y - 4 - 8, 8, 8, 180, 180);
 }
Beispiel #34
0
 public static DealVM GenerateDealsJson(int value, DealType type = DealType.CardLinked)
 {
     return(new DealVM(null));
 }
Beispiel #35
0
 public void MakeTrade(DealType side, string symbol, int volume)
 {
     MakeTrade(side, symbol, volume, UserSettings.Instance.PromptFastButtonTrade);
 }
Beispiel #36
0
 public XYSaleBill(int billtype, string card_num, string token, DateTime create_time, int sheet_id, string dealer, string store, string desc, string comment, double total_cost, int oid, DealType deal_type, List<XYBillDetail> items,XYPostBillInfo postbillinfo)
 {
     this._billtype = billtype;
     this._card_num = card_num;
     this._token = token;
     this._create_time = create_time;
     this._sheet_id = sheet_id;
     this._dealer = dealer;
     this._store = store;
     this._desc = desc;
     this._comment = comment;
     this._total_cost = total_cost;
     this._oid = oid;
     this._deal_type = deal_type;
     this._items = items;
     this.postBillInfo = postbillinfo;
 }
        public override string ActivateScript(string ticker)
        {
            if (!AccountStatus.Instance.isAuthorized)
            {
                MessageBox.Show("Не авторизован");
                return "Не авторизован";
            }
            var equity = AccountStatus.Instance.AccountData.Equity;
            if (equity <= 0)
            {
                MessageBox.Show("На счете отсутствуют денежные средства");
                return "На счете отсутствуют денежные средства";
            }

            var orders = MarketOrdersStorage.Instance.MarketOrders.Where(o => o.Symbol == ticker).ToList();
            var side = orders.Count == 0 ? DealType.Buy : (DealType)orders[0].Side;
            float? sl = orders.Count == 0 ? null : orders[0].StopLoss;

            // открыть окно выбора направления входа и SL
            var dlg = new TradeFromSLDlg(orders.Count, side, sl);
            if (dlg.ShowDialog() != DialogResult.OK) return "Отменено пользователем";
            side = dlg.Side;
            var targetSl = dlg.StopLoss;

            // выставить стоп остальным ордерам
            foreach (var order in orders)
            {
                var delta = Math.Abs((order.StopLoss ?? 0) - targetSl);
                var deltaPoints = DalSpot.Instance.GetPointsValue(ticker, delta);
                if (deltaPoints < 2) continue;

                // редактировать ордер
                order.StopLoss = targetSl;
                MainForm.Instance.SendEditMarketRequestSafe(order);
            }

            // получить текущую цену
            var quotes = QuoteStorage.Instance.ReceiveAllData();
            QuoteData quote;
            quotes.TryGetValue(ticker, out quote);
            if (quote == null)
                return "Нет котировки " + ticker;

            // коэфф пересчета из контрвалюты в валюту депо
            var kCounterDepo = 1f;
            if (!ticker.EndsWith("USD"))
                kCounterDepo = 1 / ((quote.ask + quote.bid)*0.5f);
            // посчитать макс. допустимый объем входа исходя из просадки
            var ordersResult = orders.Sum(o => o.Volume * o.Side * (targetSl - o.PriceEnter) * kCounterDepo); // убыток (прибыль) по сделкам

            var priceEnter = side == DealType.Buy ? quote.ask : quote.bid;
            var orderLossAbs = ((int)side) * (decimal)(targetSl - priceEnter);
            decimal volumeMax = decimal.MaxValue;

            // от текущего баланса считать сумму потерь
            var loss = equity * lossPercent / 100;
            if (orderLossAbs < 0)
            {
                volumeMax = (decimal)kCounterDepo * (loss + (decimal)ordersResult) / (-orderLossAbs);
            }

            // вход невозможен
            if (volumeMax < 0)
            {
                var err = string.Format(
                        "Потери по уже открытым позициям для SL {0:f4} ({1:f0}) превысят допустимый процент " +
                        "потерь ({2:f1}%, {3:f0} USD)", targetSl, ordersResult, lossPercent, loss);
                MessageBox.Show(err);
                return err;
            }

            // множитель для объема
            var indexK = orders.Count;
            if (indexK >= volumePercent.Length) indexK = volumePercent.Length - 1;
            var koeffVolume = volumePercent[indexK];
            if (volumeMax < decimal.MaxValue)
                volumeMax *= (koeffVolume/100M);

            // сравнить объем с предельно допустимым
            var maxVolumeDepo = equity * LeverageMax;
            var maxVolumeBase = maxVolumeDepo / (decimal)((quote.bid + quote.ask)*0.5f);

            var volumeEnter = Math.Min(volumeMax, maxVolumeBase);

            // округлить объем
            var volume = MarketOrder.RoundDealVolume((int) volumeEnter, VolumeRound,
                                        volumeMin, volumeStep);
            if (volume == 0)
            {
                var err = string.Format("Объем входа ({0:f0}) после округления равен 0",
                                        volumeEnter);
                MessageBox.Show(err);
                return err;
            }

            // подтвердить вход)
            if (confirmTrade)
            {
                var orderLoss = volume*((int) side)*(targetSl - priceEnter);
                var lossStr = ordersResult != 0
                                  ? string.Format("{0}{1:f0} по уже открытым ордерам и {2:f0} по новому ордеру",
                                  ordersResult > 0 ? "прибыль" : "", Math.Abs(ordersResult), (-orderLoss))
                                  : (-orderLoss).ToString("f0");
                var prompt = string.Format("Будет открыта позиция: {0} {1} {2}, SL={3:f4}. Потери при SL: {4}. Продолжить?",
                                           side, volume, ticker, targetSl, lossStr);
                if (MessageBox.Show(prompt, "Подтвердить сделку", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    return "Отменено пользователем";
            }

            // войти в рынок
            MainForm.Instance.SendNewOrderRequestSafe(
                RequestUniqueId.Next(),
                AccountStatus.Instance.accountID,
                new MarketOrder
                    {
                        Volume = volume,
                        Side = (int)side,
                        Symbol = ticker,
                        StopLoss = targetSl
                    },
                    (decimal)priceEnter, 0, OrderType.Market);

            return "Операция успешна";
        }
Beispiel #38
0
        public void ParsePost(String Url, Animal Animal, DealType DealType)
        {
            this.Parsed = () =>
            {
                DateTime PostDate = DateTime.Now;

                Post NewPost = new Post();

                NewPost.Title = Elements.Where
                                    (x => (x.Name == "div" && x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("topinfo"))).ToList()[0].Descendants("h1").ToList()[0].InnerText;

                var DateNotSplitted = Elements.Where
                                          (x => (x.Name == "div" && x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("more_infome"))).ToList()[0].Descendants("span").ToList()[0]
                                      .Attributes[1].Value;
                DateNotSplitted = DateNotSplitted.Split(' ')[0] + " " + DateNotSplitted.Split(' ')[1] + ":00";
                if (!DateTime.TryParse(DateNotSplitted, out PostDate))
                {
                    return;
                }
                NewPost.Date = PostDate;

                NewPost.Information = Elements.Where
                                          (x => (x.Name == "div" && x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("message_once"))).ToList()[0].Descendants("div").ToList()[2].InnerText.Trim();

                var PriceBLock = Elements.Where
                                     (x => (x.Name == "div" && x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("once_price"))).ToList();
                if (PriceBLock.Count != 0)
                {
                    Decimal ParsedCost = 0.0M;
                    if (!Decimal.TryParse(PriceBLock[0].ChildNodes[1].ChildNodes[1].InnerText.Trim(), out ParsedCost))
                    {
                        return;
                    }
                    else
                    {
                        NewPost.Cost = ParsedCost;
                    }
                }

                //no autor block
                try
                {
                    var table = Elements.Where
                                    (x => (x.Name == "div" && x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("message_once"))).ToList()[0].Descendants("table").ToList();
                    NewPost.Autor = table[1].ChildNodes[1].ChildNodes[1].ChildNodes[1].ChildNodes[1].ChildNodes[3].InnerText;
                }
                catch { }

                //no additional block
                try
                {
                    var AdditionalUl = Elements.Where
                                           (x => (x.Name == "ul" && x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("once_list2"))).ToList()[0].Descendants("li").ToList();
                    foreach (var Element in AdditionalUl)
                    {
                        if (Element.Descendants("strong").ToList()[0].InnerText == "Телефон")
                        {
                            NewPost.Number = Element.InnerText.Replace("Телефон: ", "");
                        }
                    }
                }
                catch { }

                //no image
                try
                {
                    NewPost.ImageUrl = "http://www.zoo-zoo.ru" + Elements.Where
                                           (x => (x.Name == "div" && x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("message_images"))).ToList()[0].Descendants("table").ToList()[0]
                                       .ChildNodes[1].ChildNodes[1].ChildNodes[1].Attributes[1].Value;
                }
                catch
                {
                    NewPost.Information = Elements.Where
                                              (x => (x.Name == "div" && x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("message_once"))).ToList()[0].Descendants("div").ToList()[1].InnerText.Trim();
                }

                NewPost.DealType = DealType;
                NewPost.Type     = Animal;

                this.OnParsed(NewPost);
            };
            Parse(Url);
        }
Beispiel #39
0
 public static string ParseDealType(DealType dealType)
 {
     switch (dealType)
     {
         case DealType.Unknown:
             return "Unknown";
         case DealType.PayUpfront:
             return "Pay Upfront";
         case DealType.PayWhenRented:
             return "Pay When Rented";
         case DealType.Free:
             return "Free Listing";
         default:
             return string.Empty;
     }
 }
Beispiel #40
0
 public static void Draw(DealEventSymbolType evType, DealType side,
     double chartX, double chartY, RectangleD worldRect, Rectangle canvasRect,
     Graphics g, Pen pen, Brush foreBrush, Brush backBrush)
 {
     var center = Conversion.WorldToScreen(new
         PointD(chartX, chartY), worldRect, canvasRect);
     Draw(evType, side, (int) center.X, (int) center.Y, g, pen, foreBrush, backBrush);
 }
Beispiel #41
0
 public static void Draw(DealEventSymbolType evType, DealType side,
     int x, int y,
     Graphics g, Pen pen, Brush foreBrush, Brush backBrush)
 {
     g.DrawLine(pen, x - 5, y, x + 5, y);
     switch (evType)
     {
         case DealEventSymbolType.Open:
             DrawEnterSign(side, x, y, g, pen, foreBrush);
             break;
         case DealEventSymbolType.Close:
             DrawClose(x, y, g, pen);
             break;
         case DealEventSymbolType.OpenLocking:
             DrawEnterLock(side, x, y, g, pen, foreBrush);
             break;
         case DealEventSymbolType.Unlock:
             DrawUnlock(x, y, g, pen);
             break;
     }
 }
Beispiel #42
0
        static void Main(string[] args)
        {
            try
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

                ConfigManager.Default.Init();

                string cmd   = string.Empty;
                bool   retry = false;
Menu:
                string[] cmdArgs = args;
                if (cmdArgs.Length == 0 || retry)
                {
                    ShowMenu();
                    cmd = Console.ReadLine();
                    if (cmd.StartsWith("deal", StringComparison.OrdinalIgnoreCase) ||
                        cmd.StartsWith("recommend", StringComparison.OrdinalIgnoreCase) ||
                        cmd.StartsWith("relation", StringComparison.OrdinalIgnoreCase) ||
                        cmd.StartsWith("center", StringComparison.OrdinalIgnoreCase) ||
                        cmd.StartsWith("usercenter", StringComparison.OrdinalIgnoreCase) ||
                        cmd.StartsWith("fixservicecenter", StringComparison.OrdinalIgnoreCase))
                    {
                        cmdArgs = cmd.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    }
                    retry = false;
                }
                else
                {
                    cmd = cmdArgs[0];
                }

                Func <bool>         needContinue = () => !cmdArgs.FirstOrDefault(a => a.Equals("continue", StringComparison.OrdinalIgnoreCase)).IsNullOrEmpty();
                Func <string, bool> isCmd        = name => cmd.Equals(name, StringComparison.OrdinalIgnoreCase) || (cmdArgs.Length > 0 && cmdArgs[0].Equals(name, StringComparison.OrdinalIgnoreCase));
                // 业绩服务处理
                Action <AchievementService> actionFinish = acs =>
                {
                    acs?.Run(
                        readResult =>
                    {
                        ReadResult(readResult);
                    },
                        writeResult =>
                    {
                        WriteResult(writeResult);
                    });
                };

                if (isCmd("deal") || isCmd("recommend") || isCmd("relation") || isCmd("center") || isCmd("usercenter") || isCmd("fixservicecenter"))
                {
                    if (cmdArgs.Length < 2)
                    {
                        Console.WriteLine($"deal业务处理,需传入配置文件(放置于configs目录下,或指定全路径)");
                        goto Menu;
                    }
                    var fileName = cmdArgs[1];
                    if (fileName.IndexOf(':') == -1)
                    {
                        fileName = Path.Combine(RuntimeContext.Current.TableConfigPath, fileName);
                    }
                    if (!File.Exists(fileName))
                    {
                        Console.WriteLine($"deal业务处理,传入配置文件{fileName}不存在");
                        goto Menu;
                    }
                    bool     isContinue = needContinue();
                    DealType type       = DealType.All;

                    if (isCmd("recommend"))
                    {
                        type         = DealType.Recommend;
                        actionFinish = null;
                    }
                    else if (isCmd("relation"))
                    {
                        type = DealType.Relation;
                    }
                    else if (isCmd("center"))
                    {
                        type = DealType.Center;
                    }
                    else if (isCmd("usercenter"))
                    {
                        type = DealType.UserCenter;
                    }
                    else if (isCmd("fixservicecenter"))
                    {
                        type = DealType.FixServiceCenter;
                    }
                    else
                    {
                    }

                    if (type == DealType.Center)
                    {
                        new CenterAchievementService(fileName, isContinue).Run(
                            readResult =>
                        {
                            ReadResult(readResult);
                        },
                            writeResult =>
                        {
                            WriteResult(writeResult);
                        });
                    }
                    else
                    {
                        Deal(new DealService(fileName, isContinue), type, () => actionFinish(new AchievementService(fileName, isContinue)));
                    }
                }
                else if (cmd.Equals("all", StringComparison.OrdinalIgnoreCase))
                {
                    var config = ConfigManager.Default.TableConfigs[0];
                    Init(() => Deal(new DealService(config, false),
                                    DealType.All, () => actionFinish(new AchievementService(config, false))));
                }
                else if (cmd.IsNullOrEmpty() || cmd.Equals("init", StringComparison.OrdinalIgnoreCase))
                {
                    Init();
                }
                else
                {
                    goto Menu;
                }

                //ServiceBase<Entity> serviceFrom = new ServiceBase<Entity>(new ReadWriteRepository<Entity>(context.FromContext));
                //Entity e = serviceFrom.Get(1);
            }
            catch (Exception ex)
            {
                LoggerManager.Log("Running exception", ex);
                Console.WriteLine(ex.Message);
            }

            Console.Read();
        }
Beispiel #43
0
        static void Deal(IDealService dealService, DealType type, Action finished = null)
        {
            switch (type)
            {
            case DealType.All:
                dealService.Run(result =>
                {
                    string msg = $"Deal Running State:{result.State},{result.Message}";
                    if (result.Exception != null)
                    {
                        msg += $",Exception:{result.Exception.Message},{result.Exception.StackTrace}";
                    }
                    Console.WriteLine(msg);
                });
                break;

            case DealType.Recommend:
                dealService.RunRecommend(result =>
                {
                    string msg = $"Recommend Running State:{result.State},{result.Message}";
                    if (result.Exception != null)
                    {
                        msg += $",Exception:{result.Exception.Message},{result.Exception.StackTrace}";
                    }
                    Console.WriteLine(msg);
                });
                break;

            case DealType.Relation:
                dealService.RunRelation(result =>
                {
                    string msg = $"Relation Running State:{result.State},{result.Message}";
                    if (result.Exception != null)
                    {
                        msg += $",Exception:{result.Exception.Message},{result.Exception.StackTrace}";
                    }
                    Console.WriteLine(msg);

                    if (result.ServiceFinished)
                    {
                        finished.Invoke();
                    }
                });
                break;

            case DealType.UserCenter:
                dealService.RunUserCenter(result =>
                {
                    string msg = $"UserCenter Running State:{result.State},{result.Message}";
                    if (result.Exception != null)
                    {
                        msg += $",Exception:{result.Exception.Message},{result.Exception.StackTrace}";
                    }
                    Console.WriteLine(msg);
                });
                break;

            case DealType.FixServiceCenter:
                dealService.FixServiceCenter(ReadResult);
                break;
            }
        }
Beispiel #44
0
        public static DealModel Create(
            string shortTitle,
            string shortDescription,
            string longTitle,
            string longDescription,
            string finePrint,
            string highlight,
            DealType dealType)
        {
            var deal = new DealModel
            {
                ShortTitle = shortTitle,
                ShortDescription = shortDescription,
                LongTitle = longTitle,
                LongDescription = longDescription,
                FinePrint = finePrint,
                Highlight = highlight,
                DateAdded = DateTime.UtcNow,
                StartTime = DateTime.UtcNow,
                EndTime = DateTime.UtcNow.AddDays(7),
                IsFeatured = false,
                RegularPrice = 0,
                SpecialPrice = 0,
                Status = DealStatus.Draft,
                Key = Guid.NewGuid().ToString(),
                DealType = dealType
            };

            deal.CanonicalUrl = GenerateCanonicalUrl(deal);
            deal.SKU = GenerateSKU(deal);

            return deal;
        }
Beispiel #45
0
        public void MakeTrade(DealType side, string symbol, int volume, bool shouldPrompt)
        {
            // вывести запрос - подтверждение трейда
            if (shouldPrompt)
            {
                var request = Localizer.GetString("MessagePositionWillBeOpened") + ": " + side + " " + volume.ToStringUniformMoneyFormat()
                              + " " + symbol + ". " + Localizer.GetString("MessageContinueQuestion");
                if (MessageBox.Show(request, Localizer.GetString("TitleConfirmation"), MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question) == DialogResult.No)
                    return;
            }
            try
            {
                SendNewOrderRequestSafe(RequestUniqueId.Next(),
                                        AccountStatus.Instance.accountID,
                                        new MarketOrder
                                            {
                                                Volume = volume,
                                                Side = (int) side,
                                                Symbol = symbol,

                                            },
                                        0, 0, OrderType.Market);
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в MakeTrade: SendNewOrderRequest error: ", ex);
                MessageBox.Show(Localizer.GetString("MessageErrorSendingRequest"), Localizer.GetString("TitleError"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }