Beispiel #1
0
 private void SetCumulativePnL(Deal deal)
 {
     if (Deals.Count > 0)
     {
         deal.CumulativePnL = deal.PnL + Deals.Last().CumulativePnL;
         if (deal.IsProfit == Deals.Last().IsProfit)
         {
             deal.InSeries    = Deals.Last().InSeries + 1;
             deal.InSeriesMax = deal.InSeries;
             Deals.Last().InSeriesMax = 0;
         }
         else
         {
             deal.InSeries    = 1;
             deal.InSeriesMax = 1;
         }
     }
     else
     {
         deal.CumulativePnL = deal.PnL;
         deal.InSeries      = 1;
         deal.InSeriesMax   = 1;
     }
 }
Beispiel #2
0
        /// <summary>
        /// Функция завершения сделки
        /// </summary>
        /// <param name="deal">Принимает объект с полями класса Deals</param>
        /// <returns>Возращает True - если удачно, False - если не удачно</returns>
        public bool StopDeal(Deals _deal)
        {
            using (RealEstateAgencyEntities db = new RealEstateAgencyEntities())
            {
                try
                {
                    Deals deal = db.Deals.Where(x => x.ID == _deal.ID).FirstOrDefault();
                    deal.DateEnd  = DateTime.Now;
                    deal.StatusID = new Guid("38BD2342-D0C8-4E65-B124-B73A09BF27B7");

                    Objects obj = db.Objects.Where(x => x.ID == deal.ObjectID).FirstOrDefault();
                    obj.Status = new Guid("F764E303-473F-4A2A-A5E7-584BA0CAA852");

                    db.SaveChanges();

                    return(true);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Произошла ошибка при редактирование пользователя. \n {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return(false);
                }
            }
        }
Beispiel #3
0
        public bool Parse(string log)
        {
            var lines = new List <string>();

            using (StringReader reader = new StringReader(log))
            {
                string rline;
                while ((rline = reader.ReadLine()) != null)
                {
                    // Do something with the line
                    lines.Add(rline);
                }
            }

            if (lines.Count < 1)
            {
                return(false);
            }

            var line = lines[0];

            if (line != "[begin]")
            {
                return(false);
            }

            var dealLines = lines.Select(x => x).Where(x => x.StartsWith("[deal]") || x.StartsWith("\t(flower)"))
                            .ToArray();

            // [deal](A)(hand):1万,2万,3万,1筒,2筒,3筒,8筒,8筒,8筒,1条,2条,3条,7条,
            //  (flower):
            if (dealLines.Length % 2 != 0)
            {
                return(false);
            }

            string          pattern;
            Regex           rgx;
            MatchCollection matches;
            Match           match;

            for (var j = 0; j < dealLines.Length - 1; j += 2)
            {
                var xhand   = dealLines[j];
                var xflower = dealLines[j + 1];

                pattern = @"^\[.+\]\((?<name>.+)\)\(.+\):(?<tiles>.+)$";
                rgx     = new Regex(pattern, RegexOptions.IgnoreCase);
                matches = rgx.Matches(xhand);
                if (matches.Count != 1)
                {
                    return(false);
                }
                match = matches[0];
                var name  = match.Groups["name"].Value;
                var tiles = match.Groups["tiles"].Value;

                if (string.IsNullOrWhiteSpace(name) ||
                    string.IsNullOrWhiteSpace(tiles))
                {
                    return(false);
                }

                pattern = @"^\s*\(.+\):(?<flowers>.*)$";
                rgx     = new Regex(pattern, RegexOptions.IgnoreCase);
                matches = rgx.Matches(xflower);
                if (matches.Count != 1)
                {
                    return(false);
                }
                match = matches[0];
                var flowers = match.Groups["flowers"].Value;
                if (string.IsNullOrWhiteSpace(flowers))
                {
                    flowers = "";
                }

                var deal = new Deal()
                {
                    Name = name, HandTiles = tiles, FlowerTiles = flowers
                };

                Deals.Add(deal);
            }

            var drawLines = lines.Select(x => x).Where(x => x.StartsWith("[draw]"));

            foreach (var drawLine in drawLines)
            {
                //[draw](A):南
                pattern = @".+:(?<tname>.*)$";
                rgx     = new Regex(pattern, RegexOptions.IgnoreCase);
                matches = rgx.Matches(drawLine);
                if (matches.Count != 1)
                {
                    return(false);
                }

                match = matches[0];
                var tileName = match.Groups["tname"].Value;
                Draws.Add(tileName);
            }

            ActionLines.AddRange(lines.Select(x => x).Where(IsActionLine));

            var banker = lines.Find(x => x.StartsWith("[bank]"));
            var wind   = lines.Find(x => x.StartsWith("[wind]"));

            if (!string.IsNullOrWhiteSpace(banker))
            {
                var begin = banker.IndexOf(":", StringComparison.Ordinal);
                var bname = banker.Substring(begin + 1);
                Banker = bname;
            }
            if (!string.IsNullOrWhiteSpace(wind))
            {
                var begin = wind.IndexOf(":", StringComparison.Ordinal);
                var bname = wind.Substring(begin + 1);
                Wind = bname;
            }

            Deals.Sort((x, y) => x.Name[0] - y.Name[0]);
            var i = 0;

            for (; i < Deals.Count; ++i)
            {
                if (Deals[i].HandTileCount == 14)
                {
                    break;
                }
            }
            var newList = new List <Deal>();
            var length  = Deals.Count;

            for (var k = 0; k < length; ++k)
            {
                newList.Add(Deals[(i + k) % length]);
            }
            Deals.Clear();
            Deals.AddRange(newList);
            return(true);
        }
Beispiel #4
0
 public DealWasDeleted(Deals deals) : base($"The following deal have been deleted: {deals.Name} ")
 {
 }
Beispiel #5
0
 public DealWasAdded(Deals deal) : base($"{deal.Name} has been created")
 {
 }
Beispiel #6
0
        public static List <Deals> getAmazonOffers()
        {
            string NAMESPACE = "http://webservices.amazon.com/AWSECommerceService/2011-08-01";


            SignedRequestHelper s = new SignedRequestHelper("//Your Associate Key Id //",
                                                            "//Your Associate Secret Key //",
                                                            "webservices.amazon.in");
            IDictionary <string, string> r1 = new Dictionary <string, string>();

            r1["Service"] = "AWSECommerceService";

            r1["Operation"]    = "ItemSearch";
            r1["AssociateTag"] = "//Your Associate Tag ";

            r1["SearchIndex"] = "All";

            r1["ResponseGroup"] = "Images,ItemAttributes,Offers,PromotionSummary";
            r1["Keywords"]      = " ";
            r1["Version"]       = "2011-08-01";



            // http://webservices.amazon.in/onca/xml?Service=AWSECommerceService


            //   AssociateTag = buyhatk - 21 &
            //Product p = new Product();

            string      signedUrl = s.Sign(r1);
            WebRequest  request   = HttpWebRequest.Create(signedUrl);
            WebResponse response  = request.GetResponse();

            XmlDocument doc = new XmlDocument();

            doc.Load(response.GetResponseStream());
            var nsmgr = new XmlNamespaceManager(doc.NameTable);

            nsmgr.AddNamespace("app", "http://webservices.amazon.com/AWSECommerceService/2011-08-01");
            List <Deals> lisAmazonOffer = new List <Deals>();

            for (int i = 0; i < 9; i++)

            {
                Deals p = new Deals();

                XmlNode idNode          = doc.GetElementsByTagName("ASIN", NAMESPACE).Item(i);
                XmlNode productTypeNode = doc.GetElementsByTagName("ProductGroup", NAMESPACE).Item(i);
                XmlNode titleNode       = doc.GetElementsByTagName("Title", NAMESPACE).Item(i);
                XmlNode ImageUrlNode    = doc.GetElementsByTagName("ImageSets", NAMESPACE).Item(i);
                XmlNode priceNodeRaw    = doc.GetElementsByTagName("LowestNewPrice", NAMESPACE).Item(i);
                XmlNode PRICENODE       = priceNodeRaw.LastChild;

                XmlNode urlNode   = doc.GetElementsByTagName("DetailPageURL", NAMESPACE).Item(i);
                XmlNode ImageNode = ImageUrlNode.FirstChild.LastChild.FirstChild;

                XmlNode priceNode = priceNodeRaw.FirstChild;
                p.id             = idNode.InnerText;
                p.title          = titleNode.InnerText;
                p.url            = urlNode.InnerText;
                p.imgurl_default = ImageNode.InnerText;
                p.price          = PRICENODE.InnerText;
                p.category       = productTypeNode.InnerText;
                p.website        = "Amazon";
                p.imgsrc         = p.imgurl_default;

                lisAmazonOffer.Add(p);
                p.Equals(null);
            }


            return(lisAmazonOffer);
        }
Beispiel #7
0
 public void Remove(Deal entity) => Deals.Remove(entity);
Beispiel #8
0
        static void Main(string[] args)
        {
            Deals d      = new Deals();
            var   hubKey = System.Configuration.ConfigurationManager.AppSettings["hubKey"];
            var   api    = new HubSpotApi(hubKey);


            // ids(1434839429)(1441579255)(1463049837)
            var deals = api.Deal.List <DealHubSpotModel>(true,
                                                         new ListRequestOptions {
                PropertiesToInclude = new List <string> {
                    "dealId"
                }
            }).Deals;

            int contDeals = 0;

            foreach (DealHubSpotModel de in deals)
            {
                var deal   = api.Deal.GetById <DealHubSpotModel>((long)de.Id);
                var owners = api.Owner.GetAll <OwnerHubSpotModel>();
                var owner  = owners.First(o => o.Id == deal.OwnerId);

                string namefull = $"{owner.FirstName} {owner.LastName}";
                d.ResponsavelNegocio = namefull;
                d.ValorNegocio       = (double)deal.Amount;
                d.DataNegocio        = deal.CloseDate;

                if (deal.DealType == "newbusiness")
                {
                    d.TipoNegocio = "New Business";
                }
                else if (deal.DealType == "existingbusiness")
                {
                    d.TipoNegocio = "Existing Business";
                }
                else if (deal.DealType == null)
                {
                    d.TipoNegocio = null;
                }

                using (var context = new DbContext())
                {
                    context.deals.Add(d);
                    context.SaveChanges();
                    d.Id = 0;
                }
                contDeals++;
            }

            Console.WriteLine($"Foram salvos {contDeals} Deals." +
                              "\nFim!!!");

            /*Console.WriteLine("Digite um Id disponivel: ");
             * string id;
             * id = Console.ReadLine();
             * Console.WriteLine($"\nO Id selecionado foi: {id}");
             * try
             * {
             *  long dealId = long.Parse(id);
             *
             *  var deal = api.Deal.GetById<DealHubSpotModel>(dealId);
             *  var owners = api.Owner.GetAll<OwnerHubSpotModel>();
             *  var owner = owners.First(o => o.Id == deal.OwnerId);
             *
             *  string namefull = $"{owner.FirstName} {owner.LastName}";
             *  d.ResponsavelNegocio = namefull;
             *  d.ValorNegocio = (double)deal.Amount;
             *  d.DataNegocio = deal.CloseDate;
             *
             *  if (deal.DealType == "newbusiness")
             *  {
             *      d.VendaNova = "New Business";
             *      d.Recompra = null;
             *  }
             *  else if (deal.DealType == "existingbusiness")
             *  {
             *      d.Recompra = "Existing Business";
             *      d.VendaNova = null;
             *  }
             *
             *  Console.WriteLine($"Responsavel pelo Negócio: {namefull}" +
             *      $"\nValor do Negócio: {d.ValorNegocio}" +
             *      $"\nData do Negócio: {d.DataNegocio}" +
             *      $"\nVenda Nova: {d.VendaNova}" +
             *      $"\nRecompra: {d.Recompra}");
             * }
             * catch (Exception e)
             * {
             *  Console.WriteLine("o Id digitado não existe" +
             *      "\nFim!!!");
             * }
             * finally
             * {
             *  try
             *  {
             *      using (var context = new DbContext())
             *      {
             *          context.deals.Add(d);
             *          context.SaveChanges();
             *          Console.WriteLine("\nFim!!!");
             *      }
             *  }
             *  catch(Exception e)
             *  {
             *      Console.WriteLine($"A Conexão com banco falhou!!!!!!!" +
             *          "\nFim!!!");
             *  }
             * }*/
            Console.ReadLine();
        }
 int ICollectionModifier <Deal> .Add(Deal entity) => Deals.Add(entity).Id;
Beispiel #10
0
        private void lstbx_Deals_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Deals chosenDeal = (Deals)lstbx_Deals.SelectedItem;

            NavigationService.Navigate(new ViewDealDetails(chosenDeal.DealsID));
        }
Beispiel #11
0
        // Made by Mikkel E.R. Glerup
        /// <summary>
        /// Creates a deal for a category
        /// </summary>
        /// <param name="deal"></param>
        /// <returns></returns>
        public static bool InsertDealCategory(Deals deal)
        {
            DBInsert dBInsert = new DBInsert();

            return(dBInsert.InsertDealCategory(deal));
        }
Beispiel #12
0
        // Made by Mikkel E.R. Glerup
        /// <summary>
        /// Creates a deal for a product
        /// </summary>
        /// <param name="deal"></param>
        /// <returns></returns>
        public static bool InsertDealProduct(Deals deal)
        {
            DBInsert dBInsert = new DBInsert();

            return(dBInsert.InsertDealProduct(deal));
        }
Beispiel #13
0
        public void OnItemAdded(Trade item)
        {
            if (Portfolio != item.Portfolio)
            {
                return;
            }
            if (Symbol != item.Symbol)
            {
                return;
            }
            //разобрать трейд по модулю лота, т.е. на максимальнео количество частей
            //определить направление трейда
            //проверить очередь противоположного направления, на наличие соответсвующего открывающего трейда
            //если есть соответсвующий открывающий трейд, извлекаем
            //определяем направление закрытой позиции
            //определяем результат закрытой позиции
            //если нет соответствия, помещаем в очередь своего направления

            //определить направление трейда
            int count = (int)System.Math.Abs(item.Amount);

            if (item.Action == TradeAction.Buy)
            {
                //разобрать трейд по модулю лота, т.е. на максимальнео количество частей
                for (int i = 0; i < count; i++)
                {
                    Trade tradeBuy = new Trade(item);
                    tradeBuy.Amount = 1;
                    //проверить очередь противоположного направления, на наличие соответсвующего открывающего трейда
                    if (SellTrades.Any())
                    {
                        //если есть соответсвующий открывающий трейд, извлекаем
                        Trade tradeSell_1 = SellTrades.Dequeue();
                        //определяем направление закрытой позиции
                        //определяем результат закрытой позиции
                        Deal deal = new Deal(TradeAction.Sell, tradeBuy, tradeSell_1);
                        SetCumulativePnL(deal);
                        Deals.Add(deal);
                    }
                    else
                    {
                        //если нет соответствия, помещаем в очередь своего направления
                        BuyTrades.Enqueue(tradeBuy);
                    }
                }
            }
            else
            if (item.Action == TradeAction.Sell)
            {
                for (int i = 0; i < count; i++)
                {
                    Trade tradeSell = new Trade(item);
                    tradeSell.Amount = -1;
                    if (BuyTrades.Any())
                    {
                        Trade tradeBuy_1 = BuyTrades.Dequeue();
                        Deal  deal       = new Deal(TradeAction.Buy, tradeBuy_1, tradeSell);
                        SetCumulativePnL(deal);
                        Deals.Add(deal);
                    }
                    else
                    {
                        SellTrades.Enqueue(tradeSell);
                    }
                }
            }
        }
Beispiel #14
0
 public void Add(Deal entity) => Deals.Add(entity);
Beispiel #15
0
 static void TestingOrgs()
 {
     Deals.LoadNewOrg(@"\\MCRAESERVER-PC\McRae Files\PipeDrive\XML\1789.xml");
     Deals.CreateOrg();
 }
Beispiel #16
0
 public void Add(Deal deal) => Deals.Add(deal);
Beispiel #17
0
 public bool Equals(Stock other)
 {
     return(other != null &&
            IsStarted == other.IsStarted &&
            TickerID == other.TickerID &&
            Ticker == other.Ticker &&
            Type == other.Type &&
            FullName == other.FullName &&
            Prefix == other.Prefix &&
            Currency == other.Currency &&
            ISIN == other.ISIN &&
            Name == other.Name &&
            ShortName == other.ShortName &&
            ChartName == other.ChartName &&
            Decimals == other.Decimals &&
            ForgDecimals == other.ForgDecimals &&
            Open == other.Open &&
            Close == other.Close &&
            Last == other.Last &&
            LastHTML == other.LastHTML &&
            LastSize == other.LastSize &&
            LastTime == other.LastTime &&
            LastHtmlTime == other.LastHtmlTime &&
            Change == other.Change &&
            ChangePercentage == other.ChangePercentage &&
            Min == other.Min &&
            Max == other.Max &&
            DealsCount == other.DealsCount &&
            Deals.SequenceEqual(other.Deals) &&
            Traffic == other.Traffic &&
            TrafficCount == other.TrafficCount &&
            OpenInterest == other.OpenInterest &&
            Status == other.Status &&
            PanelJS == other.PanelJS &&
            ID == other.ID &&
            RealTime == other.RealTime &&
            Pe2000 == other.Pe2000 &&
            Pe2001 == other.Pe2001 &&
            CloseOneMonth == other.CloseOneMonth &&
            CloseOneMonthInterval.Equals(other.CloseOneMonthInterval) &&
            CloseThreeMonth == other.CloseThreeMonth &&
            CloseThreeMonthInterval.Equals(other.CloseThreeMonthInterval) &&
            CloseOneYear == other.CloseOneYear &&
            CloseOneYearInterval.Equals(other.CloseOneYearInterval) &&
            OneMonthVolatility == other.OneMonthVolatility &&
            ThreeMonthVolatility == other.ThreeMonthVolatility &&
            OneYearVolatility == other.OneYearVolatility &&
            Eps2000 == other.Eps2000 &&
            Eps2001 == other.Eps2001 &&
            MinOneYear == other.MinOneYear &&
            MinOneYearAt == other.MinOneYearAt &&
            MaxOneYear == other.MaxOneYear &&
            MaxOneYearAt == other.MaxOneYearAt &&
            MinOfAllTime == other.MinOfAllTime &&
            MinOfAllTimeAt == other.MinOfAllTimeAt &&
            MaxOfAllTime == other.MaxOfAllTime &&
            MaxOfAllTimeAt == other.MaxOfAllTimeAt &&
            CloseMinOneYear == other.CloseMinOneYear &&
            CloseMinOneYearAt == other.CloseMinOneYearAt &&
            CloseMaxOneYear == other.CloseMaxOneYear &&
            CloseMaxOneYearAt == other.CloseMaxOneYearAt &&
            CloseMinAllTime == other.CloseMinAllTime &&
            CloseMinAllTimeAt == other.CloseMinAllTimeAt &&
            CloseMaxOfAllTime == other.CloseMaxOfAllTime &&
            CloseMaxAllTimeAt == other.CloseMaxAllTimeAt &&
            TrafficAvgInSixMonth == other.TrafficAvgInSixMonth &&
            TrafficAvgInOneYear == other.TrafficAvgInOneYear &&
            StartCount == other.StartCount &&
            Kapit == other.Kapit &&
            BuxKapit == other.BuxKapit &&
            ChangeInOneMonth == other.ChangeInOneMonth &&
            ChangeInThreeMonth == other.ChangeInThreeMonth &&
            ChangeInOneYear == other.ChangeInOneYear &&
            StartPrice == other.StartPrice &&
            MinInOneYear == other.MinInOneYear &&
            MaxInOneYear == other.MaxInOneYear &&
            ImageData == other.ImageData);
 }
Beispiel #18
0
 public int Add(Deal entity) => Deals.Add(entity).Id;
 void ICollectionModifier <Deal> .Remove(Deal entity) => Deals.Remove(entity);
        async void BindDeals()
        {
            try
            {
                Deals objRedeemDeal = await App.TodoManager.GetDeals();

                if (objRedeemDeal != null)
                {
                    if (objRedeemDeal.data != null)
                    {
                        foreach (DealsDatum d in objRedeemDeal.data.data)
                        {
                            #region DashBoardItems
                            Thickness objThickness = new Thickness(0, 0, 0, 0);
                            var       TapGasture   = new TapGestureRecognizer();
                            var       frame        = new Frame();
                            var       stack        = new StackLayout();
                            var       Label        = new Label()
                            {
                                FontSize = 14, TextColor = Color.FromHex("#000"), VerticalOptions = LayoutOptions.Center, HorizontalTextAlignment = TextAlignment.Center, FontAttributes = FontAttributes.None, Text = d.name
                            };
                            BoxView bx = new BoxView()
                            {
                                HeightRequest = 1, HorizontalOptions = LayoutOptions.FillAndExpand, Margin = new Thickness(0, 5), BackgroundColor = Color.Gray
                            };
                            Label lbl = new Label()
                            {
                                Text = d.points.ToString() + " KOINS", TextColor = Color.FromHex("#f44337"), VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center, HorizontalTextAlignment = TextAlignment.Center
                            };
                            Image I = new Image {
                                Source = "http://squareboat.testing.kyor.com/deals/photo/" + d.photo.name, HeightRequest = 70, WidthRequest = 70, Aspect = Aspect.AspectFit, BackgroundColor = Color.Transparent
                            };
                            var stack2 = new StackLayout();
                            stack2.Orientation = StackOrientation.Vertical;
                            stack2.Children.Add(I);
                            stack2.Children.Add(Label);
                            stack2.Children.Add(bx);
                            stack2.Children.Add(lbl);


                            stack.VerticalOptions = LayoutOptions.FillAndExpand;
                            stack.Orientation     = StackOrientation.Vertical;

                            stack.Padding = objThickness;

                            TapGasture.Tapped += (s, e) => { Navigation.PushAsync(new RedeemSingleDeal(d)); };
                            stack.GestureRecognizers.Add(TapGasture);
                            stack.Children.Add(stack2);

                            frame.BackgroundColor = Color.FromHex("#f8f8f8");
                            frame.HasShadow       = true;
                            frame.Content         = stack;
                            LoginGrid.Children.Add(frame, Column, Row);

                            #endregion DashBoardItems
                        }
                    }
                }
            }
            catch (Exception)
            {
                DependencyService.Get <IMessage>().LongAlert();
            }
        }