Exemple #1
0
 public Position(Portfolio portfolio, Instrument instrument)
 {
     Portfolio = portfolio;
     Instrument = instrument;
     PortfolioId = portfolio.Id;
     InstrumentId = instrument.Id;
 }
        public static Portfolio GenerateDefaultPortfolio()
        {
            Security goog = new Security {Symbol = "goog"};
            Security msft = new Security {Symbol = "msft"};
            Security aapl = new Security {Symbol = "aapl"};

            Portfolio portfolio = new Portfolio
            {
                Name = "po' boy"
            };

            Account mandingo = new Account
            {
                Name = "mandingo",
                Portfolio = portfolio
            };
            AddPosition(mandingo, goog, 100M, 12.34M);
            AddPosition(mandingo, aapl, 200M, 23.45M);
            portfolio.Accounts.Add(mandingo);

            Account took = new Account
            {
                Name = "took",
                Portfolio = portfolio
            };
            AddPosition(took, msft, 100M, 34.56M);
            portfolio.Accounts.Add(took);

            return portfolio;
        }
        private static IDictionary<DateTime, IDictionary<IDomainEntity, decimal>> GetValues(Portfolio portfolio, IDictionary<DateTime, IDictionary<string, decimal>> priceDates)
        {
            var results = new Dictionary<DateTime, IDictionary<IDomainEntity, decimal>>();

            foreach (var date in priceDates.Keys)
            {
                var values = new Dictionary<IDomainEntity, decimal>();
                results[date] = values;
                var prices = priceDates[date];

                foreach (var account in portfolio.Accounts)
                {
                    foreach (var position in account.Positions)
                    {
                        try
                        {
                            var price = prices[position.Security.Symbol];
                            var value = price*position.Shares;
                            values.Add(position, value);
                        }
                        catch (KeyNotFoundException)
                        {
                            values.Add(position, -1M);
                        }
                    }
                }
            }

            return results;
        }
        public VMEditingPortfolio(Portfolio portfolio,  int userId, List<Project> projectCatalog = null)
        {
            Title = portfolio.Title;
            Description = portfolio.Description;
            Projects = new List<VMProject>();
            if (portfolio.Projects != null && portfolio.Projects.Count > 0)
            {
                foreach (Project u in portfolio.Projects)
                {
                    Projects.Add(new VMProject(u, portfolio.UserId));
                }
            }
            ProjectCatalog = new List<VMProject>();
            if (projectCatalog != null && projectCatalog.Count > 0)
            {
                foreach (Project u in projectCatalog)
                {
                    //Projects.Add(new VMProject(u, userId));
                    ProjectCatalog.Add(new VMProject(u, userId));
                }
            }
            Visibility = (VisibilityType)portfolio.Visibility;

            UserId = portfolio.UserId;
            Id = portfolio.Id;
            IsMainPortfolio = portfolio.IsMainPortfolio;
        }
        private static IDictionary<string, decimal> CalculateValues(Portfolio portfolio, IDictionary<string, decimal> quotes)
        {
            var results = new Dictionary<string, decimal>();

            foreach (var account in portfolio.Accounts)
            {
                foreach (var position in account.Positions)
                {
                    try
                    {
                        var price = quotes[position.Security.Symbol];
                        var value = price * position.Shares;
                        if (results.ContainsKey(position.Security.Symbol))
                            results[position.Security.Symbol] += value;
                        else
                            results.Add(position.Security.Symbol, value);
                    }
                    catch (KeyNotFoundException)
                    {
                        results.Add(position.Security.Symbol, -1M);
                    }
                }
            }

            return results;
        }
 public void LoadPortfolio(int pPortfolioId)
 {
     Portfolio portfolio = new Portfolio(pPortfolioId);
     txtProjectName.Text = portfolio.ProjectName;
     txtProjectDescription.Text = portfolio.ProjectDescription;
     String toolsAndTechnique = portfolio.ToolsAndTechniques;
     String[] toolsAndTechniquesArr = toolsAndTechnique.Split(new Char[] {','}, StringSplitOptions.RemoveEmptyEntries);
     //Int32[] tools = toolsAndTechniquesArr.ToArray<Int32>();
     //for (int i = 0; i < toolsAndTechnique.Length; i++)
     //{
     //    tools[i] = Int32.Parse(toolsAndTechniquesArr[i]);
     //}
     BindToolsAndTechniques();
     ArrayList l = new ArrayList();
     for (int i = 0; i < toolsAndTechniquesArr.Length; i++)
     {
         l.Add(Int32.Parse(toolsAndTechniquesArr[i]));
     }
     foreach (ListItem item in chkBoxList1.Items)
     {
         if(l.Contains(Int32.Parse(item.Value)))
         {
             item.Selected = true;
         }
     }
     txtProjectURL.Text = portfolio.ProjectURL;
 }
        public string GetReport(Portfolio portfolio, IEnumerable<Category> categories, IEnumerable<CategoryWeight> weights)
        {
            var reportBuilder = new StringBuilder();
            var quotes = GetQuotes(portfolio);
            var valuesDict = CalculateValues(portfolio, quotes);
            var weightsList = weights.ToList();

            //DebugPrint(reportBuilder, valuesDict);

            var total = valuesDict.Values.Where(v => v > 0M).Sum();
            reportBuilder.AppendLine(string.Format("Portfolio: {0}", portfolio.Name));
            foreach (var category in categories)
            {
                Dictionary<string, decimal> calculations = new Dictionary<string, decimal>();

                foreach (var kvpair in valuesDict)
                {
                    var weight = weightsList.Single(w => w.Security.Symbol.Equals(kvpair.Key) && w.Value.Category == category);
                    if (calculations.ContainsKey(weight.Value.Name))
                        calculations[weight.Value.Name] += kvpair.Value;
                    else
                        calculations.Add(weight.Value.Name, kvpair.Value);
                }

                reportBuilder.AppendLine(string.Format("\r\n{0}", category.Name));
                foreach (var kvpair in calculations.OrderByDescending(kv => kv.Value))
                {
                    reportBuilder.AppendLine(String.Format("{0}: {1:N1}%", kvpair.Key, kvpair.Value / total * 100M));
                }
            }

            return reportBuilder.ToString();
        }
        public void UpdatePortfolio(Portfolio.Portfolio portfolio, Ranking[] previousRankings, Ranking[] currentRankings)
        {
            // check whether we should sell the stock
            Ranking previousTop = previousRankings.First();
            Ranking currentTop = currentRankings.First();

            // let's give ourselves some money
            portfolio.Cash += portfolio.MonthlyIncrease;

            if (String.Equals(previousTop.Stock.Ticker, currentTop.Stock.Ticker, StringComparison.OrdinalIgnoreCase))
            {
                // same stock so just buy
                portfolio.BuyStock(currentTop.Stock, portfolio.MonthlyIncrease);
            }
            else
            {
                // have to sell first
                // we look for the stock to sell
                Stock previousTopRightNow = currentRankings.
                    First(ranking => String.Equals(ranking.Stock.Ticker, previousTop.Stock.Ticker, StringComparison.OrdinalIgnoreCase))
                    .Stock;

                // sell all of it
                portfolio.SellStock(previousTopRightNow, portfolio.GetStockShares(previousTopRightNow));

                // time to buy all
                portfolio.BuyStock(currentTop.Stock, portfolio.TotalValue);
            }
        }
Exemple #9
0
        private TradingResult PerformBackTesting( SystemResult systemResult )
        {
            if ( systemResult.Prices.Empty() || systemResult.Signals.Empty() )
            {
                return null;
            }

            const int InitialCash = 10000;
            var tradingLog = new TradingLog();
            var portfolio = new Portfolio( InitialCash, Broker, tradingLog );

            foreach ( var signal in systemResult.Signals )
            {
                if ( signal.Value.Type == SignalType.Buy )
                {
                    var price = systemResult.Prices[ signal.Time ];
                    portfolio.Buy( signal.Time, price.Value );
                }
                else if ( signal.Value.Type == SignalType.Sell )
                {
                    var price = systemResult.Prices[ signal.Time ];
                    portfolio.Sell( signal.Time, price.Value );
                }
            }

            return new TradingResult( systemResult )
            {
                TradingTimeSpan = systemResult.Prices.Last().Time - systemResult.Prices.First().Time,
                TradingLog = tradingLog,
                InitialCash = InitialCash,
                PortfolioValue = portfolio.GetValue( systemResult.Prices.Last().Value )
            };
        }
 public ActionResult PortfolioCreateEdit(int id = -1)
 {
     if (RouteData.Values["id"] != null)
     {
         if (int.TryParse(RouteData.Values["id"].ToString(), out id)) { }
     }
     Portfolio p = new Portfolio();
     if (id != -1)
     {
         p = db.retrievePortfolio(id);
         if (p == null)
         {
             string error1 = "The Portfolio you tried to edit either does not exist or could not be found.";
             string error2 = "Portfolio Id: " + id;
             TempData["ErrorMessages"] = new string[] { error1, error2 };
             return RedirectToAction("Http404", "Error");
         }
     }
     int userId = WebSecurity.CurrentUserId;
     List<Project> projects = db.retrieveAllProjectsByUserID(userId);
     VMEditingPortfolio vmEdit;
     if (projects != null)
     {
         vmEdit = new VMEditingPortfolio(p, userId, projects);
     }
     else
     {
         vmEdit = new VMEditingPortfolio(p, userId);
     }
     return View(vmEdit);
 }
Exemple #11
0
		private void Init(string name, Portfolio portfolio, bool reportEnabled, List<Parameter> parameters)
		{
			this.Name = name;
			this.Portfolio = portfolio;
			this.Performance = new Performance(portfolio);
			this.ReportEnabled = reportEnabled;
			this.Parameters = new ParameterSet(parameters);
		}
Exemple #12
0
 public void OnPositionOpened(Portfolio portfolio, Position position, bool queued)
 {
     var e = new OnPositionOpened(portfolio, position);
     if (queued)
         this.queue.Enqueue(e);
     else
         OnEvent(e);
 }
        /// <summary>
        /// Just buy stock that ranks first
        /// </summary>
        /// <param name="portfolio"></param>
        /// <param name="rankings"></param>
        public void SetUpPortFolio(Portfolio.Portfolio portfolio, Ranking[] rankings)
        {
            // top ranked
            Ranking topRanked = rankings.First();

            // buy the stock that rank first
            portfolio.BuyStock(topRanked.Stock, portfolio.Cash);
        }
Exemple #14
0
 public Portfolio getDeltaPortfolio(DateTime t)
 {
     List<IAsset> list_asset = new List<IAsset>();
     list_asset.Add(underlying);
     Portfolio port = new Portfolio(list_asset);
     port.addAsset(underlying, this.getDelta(t));
     return port;
 }
 private IDictionary<string, decimal> GetQuotes(Portfolio portfolio)
 {
     var securities = new List<Security>();
     foreach (var account in portfolio.Accounts)
     {
         securities.AddRange(account.Positions.Select(p => p.Security));
     }
     return _quoter.GetQuotes(securities.Distinct());
 }
        void Download13F(object args)
        {
            this.portfolio = new Portfolio();
            foreach (Form13F form in Edgar.FetchForm13Fs(args as string, 6))
            {
                portfolio.Add(form);
            }

            this.Invoke(new EnableDelegate(this.Enable));
        }
 private void Init(Portfolio portfolio)
 {
     portfolio.IsLoaded = true;
     portfolio.Init(this.framework);
     this.framework.PortfolioManager.Add(portfolio, true);
     foreach (Portfolio p in portfolio.Children)
     {
         Init(p);
         p.Parent = portfolio;
     }
 }
        public string Get2DReport(Portfolio portfolio, Category x, Category y, IEnumerable<CategoryWeight> weights)
        {
            var reportBuilder = new StringBuilder();
            var quotes = GetQuotes(portfolio);
            var valuesDict = CalculateValues(portfolio, quotes);
            var weightsList = weights.ToList();

            var total = valuesDict.Values.Where(v => v > 0M).Sum();

            return reportBuilder.ToString();
        }
Exemple #19
0
		private void Init(string name, Portfolio portfolio, DateTime startDate, DateTime stopDate, double cash, bool reportEnabled, List<Project> projects)
		{
			this.Name = name;
			this.Portfolio = portfolio;
			this.Performance = new Performance(portfolio);
			this.StartDate = startDate;
			this.StopDate = stopDate;
			this.Cash = cash;
			this.ReportEnabled = reportEnabled;
			this.Projects = new ProjectList(projects);
		}
        public static void LoadOMSTrades(object[,] objArray, Portfolio pf)
        {
            Dictionary<string, OMSTrade> omsTrades = new Dictionary<string, OMSTrade>();
            ReflectionFactory.LoadObjArrayByReflection<OMSTrade>(objArray, omsTrades);

            foreach (OMSTrade omsTrade in omsTrades.Values)
            {
                omsTrade.PostConstruct();
                pf.Trades.Add(omsTrade.Dnum, omsTrade); // you cannot do List<ParentClass> x = new List<DerivedClassA> bec. then you cannot add any DerivedClassB objects anymore... makes sense 
            }
        }
Exemple #21
0
 public static Portfolio GetOrCreatePortfolio(this Framework framework, string name, bool emitEvent = true)
 {
     Portfolio portfolio;
     if (framework.PortfolioManager.Portfolios.Contains(name))
         portfolio  = framework.PortfolioManager.Portfolios.GetByName(name);
     else
     {
         portfolio = new Portfolio(framework, name);
         framework.PortfolioManager.Add(portfolio, emitEvent);
     }
     return portfolio;
 }
 public void OnInit(string name, Portfolio portfolioControl)
 {
   this.name = name;
   this.portfolioControl = portfolioControl;
   this.portfolio = Framework.Current.PortfolioManager[name];
   this.PositionViewItems.Clear();
   this.ltvPositions.Items.Clear();
   this.TransactionsViewItems.Clear();
   this.ltvTransactions.VirtualListSize = this.TransactionsViewItems.Count;
   this.ltvPortfolio.Items.Clear();
   this.ltvPortfolio.Items.Add(new ListViewItem(new string[this.ltvPortfolio.Columns.Count]));
 }
 public ActionResult AddDummyPortfolio()
 {
     int ID = int.Parse(RouteData.Values["id"].ToString());
     Portfolio p = new Portfolio
     {
         Title = RandomTitle(),
         Visibility = (int)VisibilityType.Public,
         Description = RandomDescription(),
     };
     data.addPortfolio(p, ID);
     return RedirectToAction("AllUsers", "Admin");
 }
        public Portfolio.Portfolio BackTest(Indicator.GenericIndicator indicator, HistoricalDataSet dataSet, Portfolio.Portfolio portfolio)
        {
            Ranking[][] rankingTable = dataSet.GetRankingTable(indicator);

            SetUpPortFolio(portfolio, rankingTable[0]);

            for(int i = 1; i < rankingTable.Length; i += 1)
            {
                UpdatePortfolio(portfolio, rankingTable[i-1], rankingTable[i]);
            }

            return portfolio;
        }
Exemple #25
0
 public TradeDetector(TradeDetectionType type, Portfolio portfolio)
 {
     this.portfolio_0 = portfolio;
     if (type == TradeDetectionType.FIFO)
     {
         this.interface0_0 = new QueueFillSet();
     }
     else
     {
         this.interface0_0 = new StackFillSet();
     }
     this.list_0 = new List<TradeInfo>();
     this.timeSeries_0 = new TimeSeries();
 }
 public VMPortfolio(Portfolio portfolio)
 {
     Title = portfolio.Title;
     Description = portfolio.Description;
     Projects = new List<VMProject>();
     if (portfolio.Projects != null && portfolio.Projects.Count > 0)
     {
         foreach (Project u in portfolio.Projects)
         {
             Projects.Add(new VMProject(u, portfolio.UserId));
         }
     }
     Visibility = (VisibilityType)portfolio.Visibility;
     Id = portfolio.Id;
     UserId = portfolio.UserId;
 }
        public void Add(Portfolio portfolio, bool emitEvent = true)
        {
            if (portfolio.Id == -1)
                portfolio.Id = this.counter++;
            else
            {
                if (Portfolios.Contains(portfolio.Id))
                    Console.WriteLine($"PortfolioManager::Add portfolio {portfolio.Name} error. Portfolio with Id {portfolio.Id} already added.");
                if (portfolio.Id >= this.counter)
                    this.counter = portfolio.Id + 1;
            }

            Portfolios.Add(portfolio);
            if (emitEvent)
                this.framework.EventServer.OnPortfolioAdded(portfolio);
        }
 public ActionResult Portfolio(int id=-1)
 {
     if (RouteData.Values["id"] != null)
     {
         if (int.TryParse(RouteData.Values["id"].ToString(), out id)) { }
     }
     Portfolio p = new Portfolio();
     if (id != -1)
     {
         p = db.retrievePortfolio(id);
         if (p == null)
         {
             string error1 = "The Portfolio you tried to view either does not exist or could not be found.";
             string error2 = "Portfolio Id: " + id;
             TempData["ErrorMessages"] = new string[] { error1, error2 };
             return RedirectToAction("Http404", "Error");
         }
     }
     VMPortfolio portfolio = new VMPortfolio(p);
     return View(model: portfolio);
 }
        public string GetReport(Portfolio portfolio, DateTime start, DateTime end, Period period)
        {
            var reportBuilder = new StringBuilder();
            var prices = GetPrices(portfolio, start, end, period);
            var values = GetValues(portfolio, prices);
            var columnOrder = values.Keys.OrderBy(d => d.Date);

            // print header
            reportBuilder.Append("\t\t");
            foreach (var date in columnOrder)
            {
                reportBuilder.AppendFormat("| {0} ", date.ToString("d"));
            }
            reportBuilder.AppendLine();
            reportBuilder.Append("----------------");
            for (var i = 0; i < columnOrder.Count(); ++i)
                reportBuilder.Append("-------------");
            reportBuilder.AppendLine();

            foreach (var account in portfolio.Accounts)
            {
                reportBuilder.AppendLine(string.Format("{0,-16}", account.Name));
                foreach (var position in account.Positions)
                {
                    reportBuilder.AppendFormat("{0,-16}", position.Security.Symbol);
                    foreach (var date in columnOrder)
                    {
                        var rowValues = values[date];
                        var value = rowValues[position];
                        if (value < 0M)
                            reportBuilder.AppendFormat("| {0,10} ", " !*v*! ");
                        else
                            reportBuilder.AppendFormat("| {0,10} ", value.ToString("##.00"));
                    }
                    reportBuilder.AppendLine();
                }
            }

            return reportBuilder.ToString();
        }
        public static Portfolio GenerateEmptyPortfolio()
        {
            Portfolio portfolio = new Portfolio
            {
                Name = "po' boy"
            };
            Account mandingo = new Account
            {
                Name = "mandingo",
                Portfolio = portfolio
            };
            portfolio.Accounts.Add(mandingo);

            Account took = new Account
            {
                Name = "took",
                Portfolio = portfolio
            };
            portfolio.Accounts.Add(took);

            return portfolio;
        }
Exemple #31
0
 /// <inheritdoc />
 public Position GetPosition(Portfolio portfolio, Security security, string strategyId, Sides?side, string clientCode = "", string depoName = "", TPlusLimits?limitType = null)
 {
     return(_positions.TryGetValue(CreateKey(portfolio, security, strategyId, side, clientCode, depoName, limitType)));
 }
Exemple #32
0
 private void NewPortfolioHandler(Portfolio portfolio)
 {
     AddGuiAction(() => NewPortfolio.SafeInvoke(portfolio));
 }
Exemple #33
0
        static void Main()
        {
            try
            {
                Console.Write(LocalizedStrings.Str2992);
                var account1 = Console.ReadLine();

                Console.Write(LocalizedStrings.Str2993);
                var account2 = Console.ReadLine();

                using (var quikTrader1 = new QuikTrader {
                    LuaFixServerAddress = "127.0.0.1:5001".To <EndPoint>()
                })
                    using (var quikTrader2 = new QuikTrader {
                        LuaFixServerAddress = "127.0.0.1:5002".To <EndPoint>()
                    })
                    {
                        // подписываемся на событие ошибок обработки данных и разрыва соединения
                        //
                        quikTrader1.Error += OnError;
                        quikTrader2.Error += OnError;

                        quikTrader1.ConnectionError += OnError;
                        quikTrader2.ConnectionError += OnError;


                        var portfoliosWait = new ManualResetEvent(false);

                        Action <Portfolio> newPortfolio = portfolio =>
                        {
                            if (_portfolio1 == null && portfolio.Name == account1)
                            {
                                _portfolio1 = portfolio;
                            }

                            if (_portfolio2 == null && portfolio.Name == account2)
                            {
                                _portfolio2 = portfolio;
                            }

                            // если оба инструмента появились
                            if (_portfolio1 != null && _portfolio2 != null)
                            {
                                portfoliosWait.Set();
                            }
                        };

                        // подписываемся на события новых портфелей
                        quikTrader1.NewPortfolio += newPortfolio;
                        quikTrader2.NewPortfolio += newPortfolio;


                        var securitiesWait = new ManualResetEvent(false);

                        // подписываемся на события новых инструментов
                        quikTrader1.NewSecurity += security =>
                        {
                            if (_lkoh == null && security.Code == "LKOH")
                            {
                                _lkoh = security;
                            }

                            // если оба инструмента появились
                            if (_lkoh != null && _ri != null)
                            {
                                securitiesWait.Set();
                            }
                        };
                        quikTrader2.NewSecurity += security =>
                        {
                            if (_ri == null && security.Code == "RIZ7")
                            {
                                _ri = security;
                            }

                            // если оба инструмента появились
                            if (_lkoh != null && _ri != null)
                            {
                                securitiesWait.Set();
                            }
                        };


                        // запускаем экспорты в Quik-ах, когда получим событие об успешном соединении
                        //
                        quikTrader1.Connected += () =>
                        {
                            Console.WriteLine(LocalizedStrings.Str2994Params.Put(quikTrader1.LuaFixServerAddress));
                        };
                        quikTrader2.Connected += () =>
                        {
                            Console.WriteLine(LocalizedStrings.Str2994Params.Put(quikTrader2.LuaFixServerAddress));
                        };

                        // производим подключение каждого из QuikTrader-а
                        //
                        quikTrader1.Connect();
                        quikTrader2.Connect();

                        Console.WriteLine(LocalizedStrings.Str2995);
                        portfoliosWait.WaitOne();
                        securitiesWait.WaitOne();

                        Console.WriteLine(LocalizedStrings.Str2996);
                        if (_lkoh.BestBid == null || _ri.BestBid == null)
                        {
                            throw new Exception(LocalizedStrings.Str2990);
                        }

                        quikTrader1.RegisterOrder(new Order
                        {
                            Portfolio = _portfolio1,
                            Volume    = 1,
                            Security  = _lkoh,
                            Price     = _lkoh.BestBid.Price
                        });
                        Console.WriteLine(LocalizedStrings.Str2997);

                        quikTrader2.RegisterOrder(new Order
                        {
                            Portfolio = _portfolio2,
                            Volume    = 1,
                            Security  = _ri,
                            Price     = _ri.BestBid.Price
                        });
                        Console.WriteLine(LocalizedStrings.Str2998);
                    }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Exemple #34
0
 /// <summary>
 /// Получить позицию по портфелю и инструменту.
 /// </summary>
 /// <param name="portfolio">Портфель, по которому нужно найти позицию.</param>
 /// <param name="security">Инструмент, по которому нужно найти позицию.</param>
 /// <param name="depoName">Название депозитария, где находится физически ценная бумага.
 /// По-умолчанию передается пустая строка, что означает суммарную позицию по всем депозитариям.</param>
 /// <returns>Позиция.</returns>
 public Position GetPosition(Portfolio portfolio, Security security, string depoName = "")
 {
     return(Connector.GetPosition(portfolio, security, depoName));
 }
Exemple #35
0
 public EmulationEntityFactory(Portfolio portfolio, Connector connector)
 {
     _portfolio = portfolio;
     _connector = connector;
 }
Exemple #36
0
 /// <summary>
 /// Отменить группу заявок на бирже по фильтру.
 /// </summary>
 /// <param name="transactionId">Идентификатор транзакции отмены.</param>
 /// <param name="isStopOrder"><see langword="true"/>, если нужно отменить только стоп-заявки, false - если только обычный и null - если оба типа.</param>
 /// <param name="portfolio">Портфель. Если значение равно null, то портфель не попадает в фильтр снятия заявок.</param>
 /// <param name="direction">Направление заявки. Если значение равно null, то направление не попадает в фильтр снятия заявок.</param>
 /// <param name="board">Торговая площадка. Если значение равно null, то площадка не попадает в фильтр снятия заявок.</param>
 /// <param name="security">Инструмент. Если значение равно null, то инструмент не попадает в фильтр снятия заявок.</param>
 protected override void OnCancelOrders(long transactionId, bool?isStopOrder = null, Portfolio portfolio = null, Sides?direction = null, ExchangeBoard board = null, Security security = null)
 {
     if (security != null && portfolio != null && security.Type == SecurityTypes.Future && !security.UnderlyingSecurityId.IsEmpty())
     {
         base.OnCancelOrders(transactionId, isStopOrder, portfolio, direction, board, security);
     }
     else
     {
         this.CancelOrders(Orders, isStopOrder, portfolio, direction, board);
     }
 }
        public async Task UpdatePortfolio()
        {
            var lowRiskStocks = new Category
            {
                Name   = "Low Risk Stocks",
                Stocks = new List <StockAllocation>
                {
                    new StockAllocation {
                        Symbol = "DIS", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 2m, CurrentShares = 2
                    },                                                                                                                                //1.75
                    new StockAllocation {
                        Symbol = "MSFT", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 2m, CurrentShares = 2
                    },                                                                                                                                 //1.75
                    new StockAllocation {
                        Symbol = "V", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 1.75m, CurrentShares = 1
                    }                                                                                                                                 //1.75
                }
            };
            var mediumRiskStocks = new Category
            {
                Name   = "Medium Risk Stocks",
                Stocks = new List <StockAllocation>
                {
                    new StockAllocation {
                        Symbol = "SQ", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 1m, CurrentShares = 2
                    },                                                                                                                               //1
                    new StockAllocation {
                        Symbol = "PTON", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = .5m, CurrentShares = 2
                    },                                                                                                                                  //1
                    new StockAllocation {
                        Symbol = "QCOM", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 1m, CurrentShares = 2
                    }                                                                                                                                 //1
                }
            };

            var techEtFs = new Category
            {
                Name   = "Tech",
                Stocks = new List <StockAllocation>
                {
                    new StockAllocation {
                        Symbol = "SOXL", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 5m, CurrentShares = 3
                    },                                                                                                                                 //5
                    new StockAllocation {
                        Symbol = "CIBR", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 3m, CurrentShares = 14
                    },                                                                                                                                  //3
                    new StockAllocation {
                        Symbol = "LIT", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 2.9m, CurrentShares = 16
                    }                                                                                                                                   //2.5
                }
            };

            var cannabisEtFs = new Category
            {
                Name   = "Cannabis",
                Stocks = new List <StockAllocation>
                {
                    new StockAllocation {
                        Symbol = "MJ", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 2.95m, CurrentShares = 25
                    }                                                                                                                                   //3
                }
            };

            var energyEtFs = new Category
            {
                Name   = "Energy",
                Stocks = new List <StockAllocation>
                {
                    new StockAllocation {
                        Symbol = "TAN", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 4m, CurrentShares = 20
                    },                                                                                                                                 //4
                    new StockAllocation {
                        Symbol = "ICLN", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 4.1m, CurrentShares = 53
                    }                                                                                                                                    //4
                }
            };

            var bioEtFs = new Category
            {
                Name   = "BioTech",
                Stocks = new List <StockAllocation>
                {
                    new StockAllocation {
                        Symbol = "XBI", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 3.2m, CurrentShares = 5
                    },                                                                                                                                  //4
                    new StockAllocation {
                        Symbol = "ARKG", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 3.2m, CurrentShares = 13
                    }                                                                                                                                    //4
                }
            };

            var financeEtFs = new Category
            {
                Name   = "Finance",
                Stocks = new List <StockAllocation>
                {
                    new StockAllocation
                    {
                        Symbol = "XLF", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 4m, CurrentShares = 19 //4
                    }
                }
            };

            var indexes = new Category
            {
                Name   = "Indexes",
                Stocks = new List <StockAllocation>
                {
                    new StockAllocation {
                        Symbol = "SPY", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 14m, CurrentShares = 6
                    },                                                                                                                                 //14
                    new StockAllocation {
                        Symbol = "QQQ", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 14m, CurrentShares = 9
                    },                                                                                                                                 //14
                    new StockAllocation {
                        Symbol = "DIA", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 12m, CurrentShares = 5
                    },                                                                                                                                 //12
                    new StockAllocation {
                        Symbol = "VIXY", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 3.95m, CurrentShares = 40
                    }                                                                                                                                     //3
                }
            };

            var bonds = new Category
            {
                Name   = "Bonds",
                Stocks = new List <StockAllocation>
                {
                    new StockAllocation {
                        Symbol = "TLT", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = 14.2m, CurrentShares = 14
                    }                                                                                                                                    //14
                }
            };

            var highRisk = new Category
            {
                Name   = "High Risk Stocks",
                Stocks = new List <StockAllocation>
                {
                    new StockAllocation {
                        Symbol = "I", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = .21m, CurrentShares = 10
                    },                                                                                                                                 //.25
                    new StockAllocation {
                        Symbol = "SLRX", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = .26m, CurrentShares = 14
                    },                                                                                                                                    //.25
                    new StockAllocation {
                        Symbol = "TRXC", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = .26m, CurrentShares = 413
                    },                                                                                                                                     //.25
                    new StockAllocation {
                        Symbol = "EROS", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = .26m, CurrentShares = 23
                    },                                                                                                                                    //.25
                    new StockAllocation {
                        Symbol = "TRNX", DesiredAmountType = AllocationTypeEnum.Percentage, DesiredAmount = .26m, CurrentShares = 46
                    }                                                                                                                                     //.25
                }
            };

            Portfolio portfolio = new Portfolio
            {
                Id         = "5d80d0587d2d4657d8e1fe8f",
                Name       = "Default",
                CashOnHand = .18m,
                Categories = new List <Category>
                {
                    lowRiskStocks,
                    mediumRiskStocks,
                    new Category
                    {
                        Name       = "ETFs",
                        Categories = new List <Category>
                        {
                            techEtFs,
                            cannabisEtFs,
                            energyEtFs,
                            bioEtFs,
                            financeEtFs
                        }
                    },
                    indexes,
                    bonds,
                    highRisk
                }
            };

            var result = await _portfolioDataAccess.SavePortfolios(new List <Portfolio> {
                portfolio
            });

            Console.WriteLine($"Portfolio Id: {result.First().Id}");
            Console.WriteLine($"Portfolio Percent: {portfolio.AllStocks.Sum(s => s.DesiredAmount)}%");
        }
 private void RaisePortfolioChanged(Portfolio portfolio)
 {
     PortfolioChanged?.Invoke(portfolio);
     PortfoliosChanged?.Invoke(new[] { portfolio });
 }
        public void StepOneQE(string locators)
        {
            CacheHelper.CreateTCRegion_Pool <object, object>(QERegionName, true, true,
                                                             null, locators, "__TESTPOOL1_", true);
            IRegion <object, object> region = CacheHelper.GetVerifyRegion <object, object>(QERegionName);

            string[] /*sta*/ cnm = { "C#aaa", "C#bbb", "C#ccc", "C#ddd" };
            //CacheableStringArray cnm = CacheableStringArray.Create(sta);
            Portfolio p1 = new Portfolio(1, 2, cnm);
            Portfolio p2 = new Portfolio(2, 2, cnm);
            Portfolio p3 = new Portfolio(3, 2, cnm);
            Portfolio p4 = new Portfolio(4, 2, cnm);

            region["1"] = p1;
            region["2"] = p2;
            region["3"] = p3;
            region["4"] = p4;

            QueryService <object, object> qs = null;

            qs = PoolManager /*<object, object>*/.Find("__TESTPOOL1_").GetQueryService <object, object>();
            Query <object>          qry     = qs.NewQuery("select * from /" + QERegionName + "  p where p.ID!=3");
            ISelectResults <object> results = qry.Execute();

            Util.Log("Results size {0}.", results.Size);

            SelectResultsIterator <object> iter = results.GetIterator();

            while (iter.HasNext)
            {
                /*IGFSerializable*/ object item = iter.Next();
                Portfolio port = item as Portfolio;
                if (port == null)
                {
                    Position pos = item as Position;
                    if (pos == null)
                    {
                        //CacheableString cs = item as CacheableString;
                        string cs = item as string;
                        if (cs == null)
                        {
                            Util.Log("Query got other/unknown object.");
                        }
                        else
                        {
                            Util.Log("Query got string : {0}.", cs);
                        }
                    }
                    else
                    {
                        Util.Log("Query got Position object with secId {0}, shares {1}.", pos.SecId, pos.SharesOutstanding);
                    }
                }
                else
                {
                    Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid);
                }
            }
            // Bring down the region
            region.GetLocalView().DestroyRegion();
        }
Exemple #40
0
        /// <summary>
        /// It creates a portfolio from the transactions.
        /// First line of fileStream has to be the initial balance.
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="portfolioname"></param>
        /// <param name="fileStream">It expects a CSV file. First line has to be the initial balance</param>
        /// <returns></returns>
        public bool CreatePortfolio(string userName, string portfolioname, Stream fileStream, bool firstRowIsInitalBalance, bool overrideIfExists, out Portfolio portfolio, out string message)
        {
            List <string[]> transactionsList = new List <string[]>();

            User user = portfoliosContext.GetUser(userName);

            if (user == null)
            {
                portfolio = null;
                message   = $"User '{userName}' doesn't exist.";
                return(false);
            }

            portfolio = portfoliosContext.GetPortfoliosByUserNameAndPortfolioName(userName, portfolioname);
            int portfolioId;

            if (overrideIfExists && portfolio != null)
            {
                portfoliosContext.DeletePortfolio(portfolio);
                portfolio = null;
            }

            if (portfolio == null)
            {
                portfolio   = portfoliosContext.CreatePortfolio(user, portfolioname);
                portfolioId = portfolio.Id;
            }
            else
            {
                portfolioId = portfolio.Id;
            }

            fileStream.Position = 0;
            using (StreamReader reader = new StreamReader(fileStream, System.Text.Encoding.UTF8, true))
            {
                //First row is Header
                if (reader.Peek() >= 0)
                {
                    string line = reader.ReadLine();
                }

                if (firstRowIsInitalBalance)
                {
                    if (reader.Peek() >= 0)
                    {
                        string           line   = reader.ReadLine();
                        string[]         fields = line.Split(',');
                        PortfolioBalance pb     = PortfolioBalance.From(fields);
                        if (portfolio.Balances.Where(b => b.TransactionCode == pb.TransactionCode).Any() == false)
                        {
                            pb.PortfolioId = portfolioId;
                            portfoliosContext.AddBalance(pb);//And it also adds the balance to the balances collection of the portfolio
                            portfolio.InitialBalance = pb.NetCashBalance;
                        }
                    }
                }
                else
                {
                    //TODO: Get InitialBalance from DataBase
                }

                //Second to end row are the transactions
                while (reader.Peek() >= 0)
                {
                    string   line   = reader.ReadLine();
                    string[] fields = line.Split(',');
                    transactionsList.Add(fields);
                    Transaction newTransaction = Transaction.From(fields);
                    if (newTransaction != null && portfolio.Transactions.Where(t => t.TransactionCode == newTransaction.TransactionCode).Any() == false)
                    {
                        newTransaction.UserId      = user.Id;
                        newTransaction.PortfolioId = portfolioId;
                        if (TryGetAsset(newTransaction.Symbol, out AssetBase asset))
                        {
                            if (string.IsNullOrEmpty(newTransaction.Symbol))
                            {
                                newTransaction.Symbol = asset.Ticker;
                            }
                            newTransaction.Asset = asset;
                        }
                        else
                        {
                            newTransaction.Asset = null;
                        }
                        portfolio.Transactions.Add(newTransaction);
                        //portfoliosContext.AddTransaction(newTransaction);//And it also adds the transaction to the transactions collection of the portfolio
                    }
                    else
                    {
                        //TODO: Inform to user that transaction wasn't saved
                    }
                }
            }

            CalculateAssetAllocations(portfolio);
            portfoliosContext.Update(portfolio);

            message = $"Portfilio '{portfolioname}' created successfuly.";
            return(true);
        }
Exemple #41
0
        /// <summary>
        /// прорисовать портфель
        /// </summary>
        private static void PaintPortfolio(Portfolio portfolio)
        {
            try
            {
                DataGridViewRow secondRow = new DataGridViewRow();
                secondRow.Cells.Add(new DataGridViewTextBoxCell());
                secondRow.Cells[0].Value = portfolio.Number;

                secondRow.Cells.Add(new DataGridViewTextBoxCell());
                secondRow.Cells[1].Value = portfolio.ValueBegin;

                secondRow.Cells.Add(new DataGridViewTextBoxCell());
                secondRow.Cells[2].Value = portfolio.ValueCurrent;

                secondRow.Cells.Add(new DataGridViewTextBoxCell());
                secondRow.Cells[3].Value = portfolio.ValueBlocked;

                _gridPosition.Rows.Add(secondRow);

                List <PositionOnBoard> positionsOnBoard = portfolio.GetPositionOnBoard();

                if (positionsOnBoard == null || positionsOnBoard.Count == 0)
                {
                    DataGridViewRow nRow = new DataGridViewRow();
                    nRow.Cells.Add(new DataGridViewTextBoxCell());
                    nRow.Cells.Add(new DataGridViewTextBoxCell());
                    nRow.Cells.Add(new DataGridViewTextBoxCell());
                    nRow.Cells.Add(new DataGridViewTextBoxCell());
                    nRow.Cells.Add(new DataGridViewTextBoxCell());
                    nRow.Cells[nRow.Cells.Count - 1].Value = "Нет позиций";

                    _gridPosition.Rows.Add(nRow);
                }
                else
                {
                    for (int i = 0; i < positionsOnBoard.Count; i++)
                    {
                        DataGridViewRow nRow = new DataGridViewRow();
                        nRow.Cells.Add(new DataGridViewTextBoxCell());
                        nRow.Cells.Add(new DataGridViewTextBoxCell());
                        nRow.Cells.Add(new DataGridViewTextBoxCell());
                        nRow.Cells.Add(new DataGridViewTextBoxCell());

                        nRow.Cells.Add(new DataGridViewTextBoxCell());
                        nRow.Cells[4].Value = positionsOnBoard[i].SecurityNameCode;

                        nRow.Cells.Add(new DataGridViewTextBoxCell());
                        nRow.Cells[5].Value = positionsOnBoard[i].ValueBegin;

                        nRow.Cells.Add(new DataGridViewTextBoxCell());
                        nRow.Cells[6].Value = positionsOnBoard[i].ValueCurrent;

                        nRow.Cells.Add(new DataGridViewTextBoxCell());
                        nRow.Cells[7].Value = positionsOnBoard[i].ValueBlocked;

                        _gridPosition.Rows.Add(nRow);
                    }
                }
            }
            catch (Exception error)
            {
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
            }
        }
Exemple #42
0
        private void ClientOnUpdatePortfolio(BalanceResponse portf)
        {
            try
            {
                if (portf == null ||
                    portf.eur_balance == null)
                {
                    return;
                }

                if (_portfolios == null)
                {
                    _portfolios = new List <Portfolio>();
                }

                Portfolio osPortEur = _portfolios.Find(p => p.Number == "eurPortfolio");

                if (osPortEur == null)
                {
                    osPortEur        = new Portfolio();
                    osPortEur.Number = "eurPortfolio";
                    _portfolios.Add(osPortEur);
                }

                osPortEur.ValueBegin   = Convert.ToDecimal(portf.eur_balance.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                osPortEur.ValueBlocked = Convert.ToDecimal(portf.eur_reserved.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);

                Portfolio osPortUsd = _portfolios.Find(p => p.Number == "usdPortfolio");

                if (osPortUsd == null)
                {
                    osPortUsd        = new Portfolio();
                    osPortUsd.Number = "usdPortfolio";
                    _portfolios.Add(osPortUsd);
                }

                osPortUsd.ValueBegin   = Convert.ToDecimal(portf.usd_balance.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                osPortUsd.ValueBlocked = Convert.ToDecimal(portf.usd_reserved.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);


                Portfolio osPortBtc = _portfolios.Find(p => p.Number == "btcPortfolio");

                if (osPortBtc == null)
                {
                    osPortBtc        = new Portfolio();
                    osPortBtc.Number = "btcPortfolio";
                    _portfolios.Add(osPortBtc);
                }

                osPortBtc.ValueBegin   = Convert.ToDecimal(portf.btc_balance.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);
                osPortBtc.ValueBlocked = Convert.ToDecimal(portf.btc_reserved.Replace(",", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator), CultureInfo.InvariantCulture);

                if (PortfolioEvent != null)
                {
                    PortfolioEvent(_portfolios);
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }
Exemple #43
0
        public PortfolioDetailPage(Portfolio portfolio)
        {
            InitializeComponent();

            BindingContext = portfolio;
        }
Exemple #44
0
 /// <summary>
 /// Остановить получение новой информации по портфелю.
 /// </summary>
 /// <param name="portfolio">Портфель, по которому необходимо остановить получение новой информации.</param>
 public void UnRegisterPortfolio(Portfolio portfolio)
 {
     Connector.UnRegisterPortfolio(portfolio);
 }
Exemple #45
0
        private void StartBtnClick(object sender, RoutedEventArgs e)
        {
            InitChart();

            if (HistoryPath.Text.IsEmpty() || !Directory.Exists(HistoryPath.Text))
            {
                MessageBox.Show(this, LocalizedStrings.Str3014);
                return;
            }

            if (_connectors.Any(t => t.State != EmulationStates.Stopped))
            {
                MessageBox.Show(this, LocalizedStrings.Str3015);
                return;
            }

            var secIdParts = SecId.Text.Split('@');

            if (secIdParts.Length != 2)
            {
                MessageBox.Show(this, LocalizedStrings.Str3016);
                return;
            }

            var timeFrame = TimeSpan.FromMinutes(5);

            // создаем настройки для тестирования
            var settings = new[]
            {
                Tuple.Create(
                    TicksCheckBox,
                    TicksTestingProcess,
                    TicksParameterGrid,
                    // тест только на тиках
                    new EmulationInfo {
                    CurveColor = Colors.DarkGreen, StrategyName = LocalizedStrings.Str3017
                }),

                Tuple.Create(
                    TicksAndDepthsCheckBox,
                    TicksAndDepthsTestingProcess,
                    TicksAndDepthsParameterGrid,
                    // тест на тиках + стаканы
                    new EmulationInfo {
                    UseMarketDepth = true, CurveColor = Colors.Red, StrategyName = LocalizedStrings.Str3018
                }),

                Tuple.Create(
                    CandlesCheckBox,
                    CandlesTestingProcess,
                    CandlesParameterGrid,
                    // тест на свечах
                    new EmulationInfo {
                    UseCandleTimeFrame = timeFrame, CurveColor = Colors.DarkBlue, StrategyName = LocalizedStrings.Str3019
                }),

                Tuple.Create(
                    CandlesAndDepthsCheckBox,
                    CandlesAndDepthsTestingProcess,
                    CandlesAndDepthsParameterGrid,
                    // тест на свечах + стаканы
                    new EmulationInfo {
                    UseMarketDepth = true, UseCandleTimeFrame = timeFrame, CurveColor = Colors.Cyan, StrategyName = LocalizedStrings.Str3020
                }),

                Tuple.Create(
                    OrderLogCheckBox,
                    OrderLogTestingProcess,
                    OrderLogParameterGrid,
                    // тест на логе заявок
                    new EmulationInfo {
                    UseOrderLog = true, CurveColor = Colors.CornflowerBlue, StrategyName = LocalizedStrings.Str3021
                })
            };

            // хранилище, через которое будет производиться доступ к тиковой и котировочной базе
            var storageRegistry = new StorageRegistry
            {
                // изменяем путь, используемый по умолчанию
                DefaultDrive = new LocalMarketDataDrive(HistoryPath.Text)
            };

            var startTime = (DateTime)From.Value;
            var stopTime  = (DateTime)To.Value;

            // ОЛ необходимо загружать с 18.45 пред дня, чтобы стаканы строились правильно
            if (OrderLogCheckBox.IsChecked == true)
            {
                startTime = startTime.Subtract(TimeSpan.FromDays(1)).AddHours(18).AddMinutes(45).AddTicks(1);
            }

            // задаем шаг ProgressBar
            var progressStep = ((stopTime - startTime).Ticks / 100).To <TimeSpan>();

            // в реальности период может быть другим, и это зависит от объема данных,
            // хранящихся по пути HistoryPath,
            TicksTestingProcess.Maximum = TicksAndDepthsTestingProcess.Maximum = CandlesTestingProcess.Maximum = 100;
            TicksTestingProcess.Value   = TicksAndDepthsTestingProcess.Value = CandlesTestingProcess.Value = 0;

            var logManager      = new LogManager();
            var fileLogListener = new FileLogListener("sample.log");

            logManager.Listeners.Add(fileLogListener);
            //logManager.Listeners.Add(new DebugLogListener());	// чтобы смотреть логи в отладчике - работает медленно.

            var generateDepths = GenDepthsCheckBox.IsChecked == true;
            var maxDepth       = MaxDepth.Text.To <int>();
            var maxVolume      = MaxVolume.Text.To <int>();

            var secCode = secIdParts[0];
            var board   = ExchangeBoard.GetOrCreateBoard(secIdParts[1]);

            foreach (var set in settings)
            {
                if (set.Item1.IsChecked == false)
                {
                    continue;
                }

                var progressBar   = set.Item2;
                var statistic     = set.Item3;
                var emulationInfo = set.Item4;

                // создаем тестовый инструмент, на котором будет производится тестирование
                var security = new Security
                {
                    Id    = SecId.Text,                  // по идентификатору инструмента будет искаться папка с историческими маркет данными
                    Code  = secCode,
                    Board = board,
                };

                var level1Info = new Level1ChangeMessage
                {
                    SecurityId = security.ToSecurityId(),
                    ServerTime = startTime,
                }
                .TryAdd(Level1Fields.PriceStep, 10m)
                .TryAdd(Level1Fields.StepPrice, 6m)
                .TryAdd(Level1Fields.MinPrice, 10m)
                .TryAdd(Level1Fields.MaxPrice, 1000000m)
                .TryAdd(Level1Fields.MarginBuy, 10000m)
                .TryAdd(Level1Fields.MarginSell, 10000m);

                // тестовый портфель
                var portfolio = new Portfolio
                {
                    Name       = "test account",
                    BeginValue = 1000000,
                };

                // создаем подключение для эмуляции
                // инициализируем настройки (инструмент в истории обновляется раз в секунду)
                var connector = new HistoryEmulationConnector(
                    new[] { security },
                    new[] { portfolio })
                {
                    StorageRegistry = storageRegistry,

                    MarketEmulator =
                    {
                        Settings                =
                        {
                            // использовать свечи
                            UseCandlesTimeFrame = emulationInfo.UseCandleTimeFrame,

                            // сведение сделки в эмуляторе если цена коснулась нашей лимитной заявки.
                            // Если выключено - требуется "прохождение цены сквозь уровень"
                            // (более "суровый" режим тестирования.)
                            MatchOnTouch        = false,
                        }
                    },

                    //UseExternalCandleSource = true,
                    CreateDepthFromOrdersLog  = emulationInfo.UseOrderLog,
                    CreateTradesFromOrdersLog = emulationInfo.UseOrderLog,
                };

                connector.MarketDataAdapter.SessionHolder.MarketTimeChangedInterval = timeFrame;

                ((ILogSource)connector).LogLevel = DebugLogCheckBox.IsChecked == true ? LogLevels.Debug : LogLevels.Info;

                logManager.Sources.Add(connector);

                connector.NewSecurities += securities =>
                {
                    //подписываемся на получение данных после получения инструмента

                    if (securities.All(s => s != security))
                    {
                        return;
                    }

                    // отправляем данные Level1 для инструмента
                    connector.MarketDataAdapter.SendOutMessage(level1Info);

                    // тест подразумевает наличие стаканов
                    if (emulationInfo.UseMarketDepth)
                    {
                        connector.RegisterMarketDepth(security);

                        if (
                            // если выбрана генерация стаканов вместо реальных стаканов
                            generateDepths ||
                            // для свечей генерируем стаканы всегда
                            emulationInfo.UseCandleTimeFrame != TimeSpan.Zero
                            )
                        {
                            // если история по стаканам отсутствует, но стаканы необходимы для стратегии,
                            // то их можно сгенерировать на основании цен последних сделок или свечек.
                            connector.RegisterMarketDepth(new TrendMarketDepthGenerator(connector.GetSecurityId(security))
                            {
                                Interval           = TimeSpan.FromSeconds(1),                       // стакан для инструмента в истории обновляется раз в секунду
                                MaxAsksDepth       = maxDepth,
                                MaxBidsDepth       = maxDepth,
                                UseTradeVolume     = true,
                                MaxVolume          = maxVolume,
                                MinSpreadStepCount = 2,                                 // минимальный генерируемый спред - 2 минимальных шага цены
                                MaxSpreadStepCount = 5,                                 // не генерировать спрэд между лучшим бид и аск больше чем 5 минимальных шагов цены - нужно чтобы при генерации из свечей не получалось слишком широкого спреда.
                                MaxPriceStepCount  = 3                                  // максимальное количество шагов между ценами,
                            });
                        }
                    }
                    else if (emulationInfo.UseOrderLog)
                    {
                        connector.RegisterOrderLog(security);
                    }
                };

                // соединяемся с трейдером и запускаем экспорт,
                // чтобы инициализировать переданными инструментами и портфелями необходимые свойства EmulationTrader
                connector.Connect();
                connector.StartExport();

                var candleManager = new CandleManager(connector);
                var series        = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame);

                _shortMa = new SimpleMovingAverage {
                    Length = 10
                };
                _shortElem = new ChartIndicatorElement
                {
                    Color          = Colors.Coral,
                    ShowAxisMarker = false,
                    FullTitle      = _shortMa.ToString()
                };
                _bufferedChart.AddElement(_area, _shortElem);

                _longMa = new SimpleMovingAverage {
                    Length = 80
                };
                _longElem = new ChartIndicatorElement
                {
                    ShowAxisMarker = false,
                    FullTitle      = _longMa.ToString()
                };
                _bufferedChart.AddElement(_area, _longElem);

                // создаем торговую стратегию, скользящие средние на 80 5-минуток и 10 5-минуток
                var strategy = new SmaStrategy(_bufferedChart, _candlesElem, _tradesElem, _shortMa, _shortElem, _longMa, _longElem, series)
                {
                    Volume    = 1,
                    Portfolio = portfolio,
                    Security  = security,
                    Connector = connector,
                    LogLevel  = DebugLogCheckBox.IsChecked == true ? LogLevels.Debug : LogLevels.Info,

                    // по-умолчанию интервал равен 1 минут,
                    // что для истории в диапазон от нескольких месяцев излишне
                    UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To <TimeSpan>()
                };

                // комиссия в 1 копейку за сделку
                connector.MarketEmulator.SendInMessage(new CommissionRuleMessage
                {
                    Rule = new CommissionPerTradeRule {
                        Value = 0.01m
                    }
                });

                logManager.Sources.Add(strategy);

                // копируем параметры на визуальную панель
                statistic.Parameters.Clear();
                statistic.Parameters.AddRange(strategy.StatisticManager.Parameters);

                var pnlCurve           = Curve.CreateCurve("P&L " + emulationInfo.StrategyName, emulationInfo.CurveColor, EquityCurveChartStyles.Area);
                var unrealizedPnLCurve = Curve.CreateCurve(LocalizedStrings.PnLUnreal + emulationInfo.StrategyName, Colors.Black);
                var commissionCurve    = Curve.CreateCurve(LocalizedStrings.Str159 + " " + emulationInfo.StrategyName, Colors.Red, EquityCurveChartStyles.DashedLine);
                var posItems           = PositionCurve.CreateCurve(emulationInfo.StrategyName, emulationInfo.CurveColor);
                strategy.PnLChanged += () =>
                {
                    var pnl = new EquityData
                    {
                        Time  = strategy.CurrentTime,
                        Value = strategy.PnL - strategy.Commission ?? 0
                    };

                    var unrealizedPnL = new EquityData
                    {
                        Time  = strategy.CurrentTime,
                        Value = strategy.PnLManager.UnrealizedPnL
                    };

                    var commission = new EquityData
                    {
                        Time  = strategy.CurrentTime,
                        Value = strategy.Commission ?? 0
                    };

                    pnlCurve.Add(pnl);
                    unrealizedPnLCurve.Add(unrealizedPnL);
                    commissionCurve.Add(commission);
                };

                strategy.PositionChanged += () => posItems.Add(new EquityData {
                    Time = strategy.CurrentTime, Value = strategy.Position
                });

                var nextTime = startTime + progressStep;

                // и подписываемся на событие изменения времени, чтобы обновить ProgressBar
                connector.MarketTimeChanged += d =>
                {
                    if (connector.CurrentTime < nextTime && connector.CurrentTime < stopTime)
                    {
                        return;
                    }

                    var steps = (connector.CurrentTime - startTime).Ticks / progressStep.Ticks + 1;
                    nextTime = startTime + (steps * progressStep.Ticks).To <TimeSpan>();
                    this.GuiAsync(() => progressBar.Value = steps);
                };

                connector.StateChanged += () =>
                {
                    if (connector.State == EmulationStates.Stopped)
                    {
                        candleManager.Stop(series);
                        strategy.Stop();

                        logManager.Dispose();
                        _connectors.Clear();

                        SetIsEnabled(false);

                        this.GuiAsync(() =>
                        {
                            if (connector.IsFinished)
                            {
                                progressBar.Value = progressBar.Maximum;
                                MessageBox.Show(LocalizedStrings.Str3024 + (DateTime.Now - _startEmulationTime));
                            }
                            else
                            {
                                MessageBox.Show(LocalizedStrings.cancelled);
                            }
                        });
                    }
                    else if (connector.State == EmulationStates.Started)
                    {
                        SetIsEnabled(true);

                        // запускаем стратегию когда эмулятор запустился
                        strategy.Start();
                        candleManager.Start(series);
                    }
                };

                if (ShowDepth.IsChecked == true)
                {
                    MarketDepth.UpdateFormat(security);

                    connector.NewMessage += (message, dir) =>
                    {
                        var quoteMsg = message as QuoteChangeMessage;

                        if (quoteMsg != null)
                        {
                            MarketDepth.UpdateDepth(quoteMsg);
                        }
                    };
                }

                _connectors.Add(connector);
            }

            _startEmulationTime = DateTime.Now;

            // запускаем эмуляцию
            foreach (var connector in _connectors)
            {
                // указываем даты начала и конца тестирования
                connector.Start(startTime, stopTime);
            }

            TabControl.Items.Cast <TabItem>().First(i => i.Visibility == Visibility.Visible).IsSelected = true;
        }
        private void StartBtnClick(object sender, RoutedEventArgs e)
        {
            if (_connectors.Count > 0)
            {
                foreach (var connector in _connectors)
                {
                    connector.Start();
                }

                return;
            }

            if (HistoryPath.Folder.IsEmpty() || !Directory.Exists(HistoryPath.Folder))
            {
                MessageBox.Show(this, LocalizedStrings.Str3014);
                return;
            }

            if (_connectors.Any(t => t.State != EmulationStates.Stopped))
            {
                MessageBox.Show(this, LocalizedStrings.Str3015);
                return;
            }

            var id = SecId.Text.ToSecurityId();

            //if (secIdParts.Length != 2)
            //{
            //	MessageBox.Show(this, LocalizedStrings.Str3016);
            //	return;
            //}

            var timeFrame = TimeSpan.FromMinutes(TimeFrame.SelectedIndex == 0 ? 1 : 5);

            var secCode = id.SecurityCode;
            var board   = _exchangeInfoProvider.GetOrCreateBoard(id.BoardCode);

            // create test security
            var security = new Security
            {
                Id    = SecId.Text,              // sec id has the same name as folder with historical data
                Code  = secCode,
                Board = board,
            };

            // create backtesting modes
            var settings = new[]
            {
                Tuple.Create(
                    TicksCheckBox,
                    TicksProgress,
                    TicksParameterGrid,
                    // ticks
                    new EmulationInfo
                {
                    UseTicks     = true,
                    CurveColor   = Colors.DarkGreen,
                    StrategyName = LocalizedStrings.Ticks
                },
                    TicksChart,
                    TicksEquity,
                    TicksPosition),

                Tuple.Create(
                    TicksAndDepthsCheckBox,
                    TicksAndDepthsProgress,
                    TicksAndDepthsParameterGrid,
                    // ticks + order book
                    new EmulationInfo
                {
                    UseTicks       = true,
                    UseMarketDepth = true,
                    CurveColor     = Colors.Red,
                    StrategyName   = LocalizedStrings.XamlStr757
                },
                    TicksAndDepthsChart,
                    TicksAndDepthsEquity,
                    TicksAndDepthsPosition),

                Tuple.Create(
                    DepthsCheckBox,
                    DepthsProgress,
                    DepthsParameterGrid,
                    // order book
                    new EmulationInfo
                {
                    UseMarketDepth = true,
                    CurveColor     = Colors.OrangeRed,
                    StrategyName   = LocalizedStrings.MarketDepths
                },
                    DepthsChart,
                    DepthsEquity,
                    DepthsPosition),

                Tuple.Create(
                    CandlesCheckBox,
                    CandlesProgress,
                    CandlesParameterGrid,
                    // candles
                    new EmulationInfo
                {
                    UseCandleTimeFrame = timeFrame,
                    CurveColor         = Colors.DarkBlue,
                    StrategyName       = LocalizedStrings.Candles
                },
                    CandlesChart,
                    CandlesEquity,
                    CandlesPosition),

                Tuple.Create(
                    CandlesAndDepthsCheckBox,
                    CandlesAndDepthsProgress,
                    CandlesAndDepthsParameterGrid,
                    // candles + orderbook
                    new EmulationInfo
                {
                    UseMarketDepth     = true,
                    UseCandleTimeFrame = timeFrame,
                    CurveColor         = Colors.Cyan,
                    StrategyName       = LocalizedStrings.XamlStr635
                },
                    CandlesAndDepthsChart,
                    CandlesAndDepthsEquity,
                    CandlesAndDepthsPosition),

                Tuple.Create(
                    OrderLogCheckBox,
                    OrderLogProgress,
                    OrderLogParameterGrid,
                    // order log
                    new EmulationInfo
                {
                    UseOrderLog  = true,
                    CurveColor   = Colors.CornflowerBlue,
                    StrategyName = LocalizedStrings.OrderLog
                },
                    OrderLogChart,
                    OrderLogEquity,
                    OrderLogPosition),

                Tuple.Create(
                    Level1CheckBox,
                    Level1Progress,
                    Level1ParameterGrid,
                    // order log
                    new EmulationInfo
                {
                    UseLevel1    = true,
                    CurveColor   = Colors.Aquamarine,
                    StrategyName = LocalizedStrings.Level1
                },
                    Level1Chart,
                    Level1Equity,
                    Level1Position),

                Tuple.Create(
                    FinamCandlesCheckBox,
                    FinamCandlesProgress,
                    FinamCandlesParameterGrid,
                    // candles
                    new EmulationInfo
                {
                    UseCandleTimeFrame   = timeFrame,
                    CustomHistoryAdapter = g => new FinamMessageAdapter(g),
                    CurveColor           = Colors.DarkBlue,
                    StrategyName         = LocalizedStrings.FinamCandles
                },
                    FinamCandlesChart,
                    FinamCandlesEquity,
                    FinamCandlesPosition),

                Tuple.Create(
                    YahooCandlesCheckBox,
                    YahooCandlesProgress,
                    YahooCandlesParameterGrid,
                    // candles
                    new EmulationInfo
                {
                    UseCandleTimeFrame   = timeFrame,
                    CustomHistoryAdapter = g => new YahooMessageAdapter(g),
                    CurveColor           = Colors.DarkBlue,
                    StrategyName         = LocalizedStrings.YahooCandles
                },
                    YahooCandlesChart,
                    YahooCandlesEquity,
                    YahooCandlesPosition),
            };

            // storage to historical data
            var storageRegistry = new StorageRegistry
            {
                // set historical path
                DefaultDrive = new LocalMarketDataDrive(HistoryPath.Folder)
            };

            var startTime = ((DateTime)From.EditValue).UtcKind();
            var stopTime  = ((DateTime)To.EditValue).UtcKind();

            // (ru only) ОЛ необходимо загружать с 18.45 пред дня, чтобы стаканы строились правильно
            if (OrderLogCheckBox.IsChecked == true)
            {
                startTime = startTime.Subtract(TimeSpan.FromDays(1)).AddHours(18).AddMinutes(45).AddTicks(1).ApplyTimeZone(TimeHelper.Moscow).UtcDateTime;
            }

            // ProgressBar refresh step
            var progressStep = ((stopTime - startTime).Ticks / 100).To <TimeSpan>();

            // set ProgressBar bounds
            _progressBars.ForEach(p =>
            {
                p.Value   = 0;
                p.Maximum = 100;
            });

            var logManager      = new LogManager();
            var fileLogListener = new FileLogListener("sample.log");

            logManager.Listeners.Add(fileLogListener);
            //logManager.Listeners.Add(new DebugLogListener());	// for track logs in output window in Vusial Studio (poor performance).

            var generateDepths = GenDepthsCheckBox.IsChecked == true;
            var maxDepth       = MaxDepth.Text.To <int>();
            var maxVolume      = MaxVolume.Text.To <int>();
            var secId          = security.ToSecurityId();

            SetIsEnabled(false, false, false);

            foreach (var set in settings)
            {
                if (set.Item1.IsChecked == false)
                {
                    continue;
                }

                var title = (string)set.Item1.Content;

                InitChart(set.Item5, set.Item6, set.Item7);

                var progressBar   = set.Item2;
                var statistic     = set.Item3;
                var emulationInfo = set.Item4;

                var level1Info = new Level1ChangeMessage
                {
                    SecurityId = secId,
                    ServerTime = startTime,
                }
                .TryAdd(Level1Fields.PriceStep, secCode == "RIZ2" ? 10m : 1)
                .TryAdd(Level1Fields.StepPrice, 6m)
                .TryAdd(Level1Fields.MinPrice, 10m)
                .TryAdd(Level1Fields.MaxPrice, 1000000m)
                .TryAdd(Level1Fields.MarginBuy, 10000m)
                .TryAdd(Level1Fields.MarginSell, 10000m);

                // test portfolio
                var portfolio = Portfolio.CreateSimulator();

                // create backtesting connector
                var connector = new HistoryEmulationConnector(
                    new[] { security },
                    new[] { portfolio })
                {
                    EmulationAdapter =
                    {
                        Emulator             =
                        {
                            Settings         =
                            {
                                // match order if historical price touched our limit order price.
                                // It is terned off, and price should go through limit order price level
                                // (more "severe" test mode)
                                MatchOnTouch = false,
                            }
                        }
                    },

                    //UseExternalCandleSource = emulationInfo.UseCandleTimeFrame != null,

                    //CreateDepthFromOrdersLog = emulationInfo.UseOrderLog,
                    //CreateTradesFromOrdersLog = emulationInfo.UseOrderLog,

                    HistoryMessageAdapter =
                    {
                        StorageRegistry             = storageRegistry,

                        OrderLogMarketDepthBuilders =
                        {
                            {
                                secId,
                                new OrderLogMarketDepthBuilder(secId)
                            }
                        }
                    },

                    // set market time freq as time frame
                    MarketTimeChangedInterval = timeFrame,
                };

                ((ILogSource)connector).LogLevel = DebugLogCheckBox.IsChecked == true ? LogLevels.Debug : LogLevels.Info;

                logManager.Sources.Add(connector);

                var series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame)
                {
                    BuildCandlesMode = emulationInfo.UseCandleTimeFrame == null ? MarketDataBuildModes.Build : MarketDataBuildModes.Load,
                    BuildCandlesFrom = emulationInfo.UseOrderLog ? (MarketDataTypes?)MarketDataTypes.OrderLog : null,
                };

                _shortMa = new SimpleMovingAverage {
                    Length = 10
                };
                _shortElem = new ChartIndicatorElement
                {
                    Color          = Colors.Coral,
                    ShowAxisMarker = false,
                    FullTitle      = _shortMa.ToString()
                };

                var chart = set.Item5;

                chart.AddElement(_area, _shortElem);

                _longMa = new SimpleMovingAverage {
                    Length = 80
                };
                _longElem = new ChartIndicatorElement
                {
                    ShowAxisMarker = false,
                    FullTitle      = _longMa.ToString()
                };
                chart.AddElement(_area, _longElem);

                // create strategy based on 80 5-min и 10 5-min
                var strategy = new SmaStrategy(chart, _candlesElem, _tradesElem, _shortMa, _shortElem, _longMa, _longElem, series)
                {
                    Volume    = 1,
                    Portfolio = portfolio,
                    Security  = security,
                    Connector = connector,
                    LogLevel  = DebugLogCheckBox.IsChecked == true ? LogLevels.Debug : LogLevels.Info,

                    // by default interval is 1 min,
                    // it is excessively for time range with several months
                    UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To <TimeSpan>()
                };

                logManager.Sources.Add(strategy);

                if (emulationInfo.CustomHistoryAdapter != null)
                {
                    connector.Adapter.InnerAdapters.Remove(connector.MarketDataAdapter);
                    connector.Adapter.InnerAdapters.Add(new CustomHistoryMessageAdapter(emulationInfo.CustomHistoryAdapter(connector.TransactionIdGenerator)));
                }

                // set history range
                connector.HistoryMessageAdapterEx.StartDate = startTime;
                connector.HistoryMessageAdapterEx.StopDate  = stopTime;

                connector.NewSecurity += s =>
                {
                    if (s != security)
                    {
                        return;
                    }

                    // fill level1 values
                    connector.HistoryMessageAdapterEx.SendOutMessage(level1Info);

                    if (emulationInfo.UseMarketDepth)
                    {
                        connector.SubscribeMarketDepth(security);

                        if (
                            // if order book will be generated
                            generateDepths ||
                            // or backtesting will be on candles
                            emulationInfo.UseCandleTimeFrame != TimeSpan.Zero
                            )
                        {
                            // if no have order book historical data, but strategy is required,
                            // use generator based on last prices
                            connector.RegisterMarketDepth(new TrendMarketDepthGenerator(connector.GetSecurityId(security))
                            {
                                Interval           = TimeSpan.FromSeconds(1),                       // order book freq refresh is 1 sec
                                MaxAsksDepth       = maxDepth,
                                MaxBidsDepth       = maxDepth,
                                UseTradeVolume     = true,
                                MaxVolume          = maxVolume,
                                MinSpreadStepCount = 2,                                 // min spread generation is 2 pips
                                MaxSpreadStepCount = 5,                                 // max spread generation size (prevent extremely size)
                                MaxPriceStepCount  = 3                                  // pips size,
                            });
                        }
                    }

                    if (emulationInfo.UseOrderLog)
                    {
                        connector.SubscribeOrderLog(security);
                    }

                    if (emulationInfo.UseTicks)
                    {
                        connector.SubscribeTrades(security);
                    }

                    if (emulationInfo.UseLevel1)
                    {
                        connector.SubscribeLevel1(security);
                    }

                    // start strategy before emulation started
                    strategy.Start();

                    // start historical data loading when connection established successfully and all data subscribed
                    connector.Start();
                };

                // fill parameters panel
                statistic.Parameters.Clear();
                statistic.Parameters.AddRange(strategy.StatisticManager.Parameters);

                var equity = set.Item6;

                var pnlCurve           = equity.CreateCurve(LocalizedStrings.PnL + " " + emulationInfo.StrategyName, Colors.Green, Colors.Red, ChartIndicatorDrawStyles.Area);
                var unrealizedPnLCurve = equity.CreateCurve(LocalizedStrings.PnLUnreal + " " + emulationInfo.StrategyName, Colors.Black, ChartIndicatorDrawStyles.Line);
                var commissionCurve    = equity.CreateCurve(LocalizedStrings.Str159 + " " + emulationInfo.StrategyName, Colors.Red, ChartIndicatorDrawStyles.DashedLine);

                strategy.PnLChanged += () =>
                {
                    var data = new ChartDrawData();

                    data
                    .Group(strategy.CurrentTime)
                    .Add(pnlCurve, strategy.PnL - strategy.Commission ?? 0)
                    .Add(unrealizedPnLCurve, strategy.PnLManager.UnrealizedPnL ?? 0)
                    .Add(commissionCurve, strategy.Commission ?? 0);

                    equity.Draw(data);
                };

                var posItems = set.Item7.CreateCurve(emulationInfo.StrategyName, emulationInfo.CurveColor, ChartIndicatorDrawStyles.Line);

                strategy.PositionChanged += () =>
                {
                    var data = new ChartDrawData();

                    data
                    .Group(strategy.CurrentTime)
                    .Add(posItems, strategy.Position);

                    set.Item7.Draw(data);
                };

                var nextTime = startTime + progressStep;

                // handle historical time for update ProgressBar
                connector.MarketTimeChanged += d =>
                {
                    if (connector.CurrentTime < nextTime && connector.CurrentTime < stopTime)
                    {
                        return;
                    }

                    var steps = (connector.CurrentTime - startTime).Ticks / progressStep.Ticks + 1;
                    nextTime = startTime + (steps * progressStep.Ticks).To <TimeSpan>();
                    this.GuiAsync(() => progressBar.Value = steps);
                };

                connector.StateChanged += () =>
                {
                    if (connector.State == EmulationStates.Stopped)
                    {
                        strategy.Stop();

                        SetIsChartEnabled(chart, false);

                        if (_connectors.All(c => c.State == EmulationStates.Stopped))
                        {
                            logManager.Dispose();
                            _connectors.Clear();

                            SetIsEnabled(true, false, false);
                        }

                        this.GuiAsync(() =>
                        {
                            if (connector.IsFinished)
                            {
                                progressBar.Value = progressBar.Maximum;
                                MessageBox.Show(this, LocalizedStrings.Str3024.Put(DateTime.Now - _startEmulationTime), title);
                            }
                            else
                            {
                                MessageBox.Show(this, LocalizedStrings.cancelled, title);
                            }
                        });
                    }
                    else if (connector.State == EmulationStates.Started)
                    {
                        if (_connectors.All(c => c.State == EmulationStates.Started))
                        {
                            SetIsEnabled(false, true, true);
                        }

                        SetIsChartEnabled(chart, true);
                    }
                    else if (connector.State == EmulationStates.Suspended)
                    {
                        if (_connectors.All(c => c.State == EmulationStates.Suspended))
                        {
                            SetIsEnabled(true, false, true);
                        }
                    }
                };

                if (ShowDepth.IsChecked == true)
                {
                    MarketDepth.UpdateFormat(security);

                    connector.NewMessage += message =>
                    {
                        if (message is QuoteChangeMessage quoteMsg)
                        {
                            MarketDepth.UpdateDepth(quoteMsg);
                        }
                    };
                }

                _connectors.Add(connector);

                progressBar.Value = 0;
            }

            _startEmulationTime = DateTime.Now;

            // start emulation
            foreach (var connector in _connectors)
            {
                // raise NewSecurities and NewPortfolio for full fill strategy properties
                connector.Connect();

                // 1 cent commission for trade
                connector.SendInMessage(new CommissionRuleMessage
                {
                    Rule = new CommissionPerTradeRule {
                        Value = 0.01m
                    }
                });
            }

            TabControl.Items.Cast <TabItem>().First(i => i.Visibility == Visibility.Visible).IsSelected = true;
        }
 public PortfolioModel(Portfolio portfolio)
 {
     Id       = portfolio.Id;
     UserId   = portfolio.UserId;
     Equities = EquityModelHelpers.MapToModelCollection(portfolio.Equities);
 }
Exemple #48
0
 /// <summary>
 /// Unsubscribe from the portfolio changes.
 /// </summary>
 /// <param name="portfolio">Portfolio for unsubscription.</param>
 public void UnRegisterPortfolio(Portfolio portfolio)
 {
     _subscriptionManager.UnRegisterPortfolio(portfolio);
 }
 public PositionEventArgs(Portfolio portfolio, Position position) : base(portfolio)
 {
     this.Position = position;
 }
Exemple #50
0
        static void Main()
        {
            try
            {
                // для теста выбираем бумагу Лукойл
                const string secCode = "LKOH";

                var quikPath = QuikTerminal.GetDefaultPath();

                if (quikPath.IsEmpty())
                {
                    Console.WriteLine(LocalizedStrings.Str2984);
                    return;
                }

                Console.WriteLine(LocalizedStrings.Str2985 + quikPath);

                Console.Write(LocalizedStrings.Str2986);
                var account = Console.ReadLine();

                using (var waitHandle = new AutoResetEvent(false))
                {
                    // создаем подключение к Quik-у
                    using (var trader = new QuikTrader(quikPath)
                    {
                        IsDde = true
                    })
                    {
                        // необходимо раскомментировать, если идет работа с РТС Стандарт
                        //trader.FormatTransaction += builder => builder.RemoveInstruction(Transaction.TimeInForce);

                        // подписываемся на событие успешного подключения
                        // все действия необходимо производить только после подключения
                        trader.Connected += () =>
                        {
                            Console.WriteLine(LocalizedStrings.Str2169);

                            // извещаем об успешном соединени
                            waitHandle.Set();
                        };

                        Console.WriteLine(LocalizedStrings.Str2170);

                        trader.DdeTables = new[] { trader.SecuritiesTable, trader.MyTradesTable, trader.EquityPositionsTable,
                                                   trader.EquityPortfoliosTable, trader.OrdersTable };

                        trader.Connect();

                        // дожидаемся события об успешном соединении
                        waitHandle.WaitOne();

                        trader.NewPortfolios += portfolios =>
                        {
                            if (_portfolio == null)
                            {
                                // находим нужный портфель и присваиваем его переменной _portfolio
                                _portfolio = portfolios.FirstOrDefault(p => p.Name == account);

                                if (_portfolio != null)
                                {
                                    Console.WriteLine(LocalizedStrings.Str2171Params, account);

                                    // если инструмент и стакан уже появились,
                                    // то извещаем об этом основной поток для выставления заявки
                                    if (_lkoh != null && _depth != null)
                                    {
                                        waitHandle.Set();
                                    }
                                }
                            }
                        };

                        // подписываемся на событие появление инструментов
                        trader.NewSecurities += securities =>
                        {
                            if (_lkoh == null)
                            {
                                // находим Лукойл и присваиваем ее переменной lkoh
                                _lkoh = securities.FirstOrDefault(sec => sec.Code == secCode);

                                if (_lkoh != null)
                                {
                                    Console.WriteLine(LocalizedStrings.Str2987);

                                    // запускаем экспорт стакана
                                    trader.RegisterMarketDepth(_lkoh);

                                    if (_portfolio != null && _depth != null)
                                    {
                                        waitHandle.Set();
                                    }
                                }
                            }
                        };

                        // подписываемся на событие появления моих новых сделок
                        trader.NewMyTrades += myTrades =>
                        {
                            foreach (var myTrade in myTrades)
                            {
                                var trade = myTrade.Trade;
                                Console.WriteLine(LocalizedStrings.Str2173Params, trade.Id, trade.Price, trade.Security.Code, trade.Volume, trade.Time);
                            }
                        };

                        // подписываемся на событие обновления стакана
                        trader.MarketDepthsChanged += depths =>
                        {
                            if (_depth == null && _lkoh != null)
                            {
                                _depth = depths.FirstOrDefault(d => d.Security == _lkoh);

                                if (_depth != null)
                                {
                                    Console.WriteLine(LocalizedStrings.Str2988);

                                    // если портфель и инструмент уже появился, то извещаем об этом основной поток для выставления заявки
                                    if (_portfolio != null && _lkoh != null)
                                    {
                                        waitHandle.Set();
                                    }
                                }
                            }
                        };

                        Console.WriteLine(LocalizedStrings.Str2989Params.Put(account));

                        // дожидаемся появления портфеля и инструмента
                        waitHandle.WaitOne();

                        // 0.1% от изменения цены
                        const decimal delta = 0.001m;

                        // запоминаем первоначальное значение середины спреда
                        var firstMid = _lkoh.BestPair.SpreadPrice / 2;
                        if (_lkoh.BestBid == null || firstMid == null)
                        {
                            throw new Exception(LocalizedStrings.Str2990);
                        }

                        Console.WriteLine(LocalizedStrings.Str2991Params, _lkoh.BestBid.Price + firstMid);

                        while (true)
                        {
                            var mid = _lkoh.BestPair.SpreadPrice / 2;

                            // если спред вышел за пределы нашего диапазона
                            if (mid != null &&
                                ((firstMid + firstMid * delta) <= mid ||
                                 (firstMid - firstMid * delta) >= mid)
                                )
                            {
                                var order = new Order
                                {
                                    Portfolio = _portfolio,
                                    Price     = _lkoh.ShrinkPrice(_lkoh.BestBid.Price + mid.Value),
                                    Security  = _lkoh,
                                    Volume    = 1,
                                    Direction = Sides.Buy,
                                };
                                trader.RegisterOrder(order);
                                Console.WriteLine(LocalizedStrings.Str1157Params, order.Id);
                                break;
                            }
                            else
                            {
                                Console.WriteLine(LocalizedStrings.Str2176Params, _lkoh.BestBid.Price + mid);
                            }

                            // ждем 1 секунду
                            Thread.Sleep(1000);
                        }

                        // останавливаем подключение
                        trader.Disconnect();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
 public IList <Entities.PortfolioSecurity> GetPortfolioSecurityList(ISession session, Portfolio portfolio)
 {
     return(session.QueryOver <Entities.PortfolioSecurity>()
            .Fetch(SelectMode.ChildFetch, p => p.Portfolio)
            .Fetch(SelectMode.ChildFetch, p => p.Security)
            .Where(p => p.Portfolio.PortfolioId == portfolio.PortfolioId)
            .List());
 }
Exemple #52
0
 /// <summary>
 /// Отменить группу заявок на бирже по фильтру.
 /// </summary>
 /// <param name="isStopOrder"><see langword="true"/>, если нужно отменить только стоп-заявки, false - если только обычный и null - если оба типа.</param>
 /// <param name="portfolio">Портфель. Если значение равно null, то портфель не попадает в фильтр снятия заявок.</param>
 /// <param name="direction">Направление заявки. Если значение равно null, то направление не попадает в фильтр снятия заявок.</param>
 /// <param name="board">Торговая площадка. Если значение равно null, то площадка не попадает в фильтр снятия заявок.</param>
 /// <param name="security">Инструмент. Если значение равно null, то инструмент не попадает в фильтр снятия заявок.</param>
 public void CancelOrders(bool?isStopOrder = null, Portfolio portfolio = null, Sides?direction = null, ExchangeBoard board = null, Security security = null)
 {
     Connector.CancelOrders(isStopOrder, portfolio, direction, board, security);
 }
 public override void LookupPortfolios(Portfolio criteria)
 {
     _realConnector.LookupPortfolios(criteria);
 }
Exemple #54
0
        /// <summary>
        /// Runs after algorithm, used to check our portfolio and orders
        /// </summary>
        public override void OnEndOfAlgorithm()
        {
            if (!Portfolio.ContainsKey(_optionBuy.Symbol) || !Portfolio.ContainsKey(_optionBuy.Symbol.Underlying) || !Portfolio.ContainsKey(_equityBuy.Symbol))
            {
                throw new Exception("Portfolio does not contain the Symbols we purchased");
            }

            //Check option holding, should not be invested since it expired, profit should be -400
            var optionHolding = Portfolio[_optionBuy.Symbol];

            if (optionHolding.Invested || optionHolding.Profit != -400)
            {
                throw new Exception("Options holding does not match expected outcome");
            }

            //Check the option underlying symbol since we should have bought it at exercise
            //Quantity should be 100, AveragePrice should be option strike price
            var optionExerciseHolding = Portfolio[_optionBuy.Symbol.Underlying];

            if (!optionExerciseHolding.Invested || optionExerciseHolding.Quantity != 100 || optionExerciseHolding.AveragePrice != _optionBuy.Symbol.ID.StrikePrice)
            {
                throw new Exception("Equity holding for exercised option does not match expected outcome");
            }

            //Check equity holding, should be invested, profit should be
            //Quantity should be 50, AveragePrice should be ticket AverageFillPrice
            var equityHolding = Portfolio[_equityBuy.Symbol];

            if (!equityHolding.Invested || equityHolding.Quantity != 50 || equityHolding.AveragePrice != _equityBuy.AverageFillPrice)
            {
                throw new Exception("Equity holding does not match expected outcome");
            }
        }
 private void RaiseNewPortfolio(Portfolio portfolio)
 {
     NewPortfolio?.Invoke(portfolio);
     NewPortfolios?.Invoke(new[] { portfolio });
 }
Exemple #56
0
        private void StartBtnClick(object sender, RoutedEventArgs e)
        {
            // if process was already started, will stop it now
            if (_connector != null && _connector.State != EmulationStates.Stopped)
            {
                _strategy.Stop();
                _connector.Disconnect();
                _logManager.Sources.Clear();

                _connector = null;
                return;
            }

            // create test security
            var security = new Security
            {
                Id    = "AAPL@NASDAQ",
                Code  = "AAPL",
                Name  = "AAPL Inc",
                Board = ExchangeBoard.Nasdaq,
            };

            var startTime = new DateTime(2009, 6, 1);
            var stopTime  = new DateTime(2009, 9, 1);

            var level1Info = new Level1ChangeMessage
            {
                SecurityId = security.ToSecurityId(),
                ServerTime = startTime,
            }
            .TryAdd(Level1Fields.PriceStep, 10m)
            .TryAdd(Level1Fields.StepPrice, 6m)
            .TryAdd(Level1Fields.MinPrice, 10m)
            .TryAdd(Level1Fields.MaxPrice, 1000000m)
            .TryAdd(Level1Fields.MarginBuy, 10000m)
            .TryAdd(Level1Fields.MarginSell, 10000m);

            // test portfolio
            var portfolio = new Portfolio
            {
                Name       = "test account",
                BeginValue = 1000000,
            };

            var timeFrame = TimeSpan.FromMinutes(5);

            // create backtesting connector
            _connector = new HistoryEmulationConnector(
                new[] { security },
                new[] { portfolio })
            {
                HistoryMessageAdapter =
                {
                    // set history range
                    StartDate = startTime,
                    StopDate  = stopTime,
                },

                // set market time freq as time frame
                MarketTimeChangedInterval = timeFrame,
            };

            _logManager.Sources.Add(_connector);

            var candleManager = new CandleManager(_connector);

            var series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame);

            // create strategy based on 80 5-min и 10 5-min
            _strategy = new SmaStrategy(candleManager, series, new SimpleMovingAverage {
                Length = 80
            }, new SimpleMovingAverage {
                Length = 10
            })
            {
                Volume    = 1,
                Security  = security,
                Portfolio = portfolio,
                Connector = _connector,
            };

            _connector.NewSecurities += securities =>
            {
                if (securities.All(s => s != security))
                {
                    return;
                }

                // fill level1 values
                _connector.SendInMessage(level1Info);

                _connector.RegisterTrades(new RandomWalkTradeGenerator(_connector.GetSecurityId(security)));
                _connector.RegisterMarketDepth(new TrendMarketDepthGenerator(_connector.GetSecurityId(security))
                {
                    GenerateDepthOnEachTrade = false
                });

                // start strategy before emulation started
                _strategy.Start();
                candleManager.Start(series);

                // start historical data loading when connection established successfully and all data subscribed
                _connector.Start();
            };

            // fill parameters panel
            ParameterGrid.Parameters.Clear();
            ParameterGrid.Parameters.AddRange(_strategy.StatisticManager.Parameters);

            _strategy.PnLChanged += () =>
            {
                var data = new EquityData
                {
                    Time  = _strategy.CurrentTime,
                    Value = _strategy.PnL,
                };

                this.GuiAsync(() => _curveItems.Add(data));
            };

            _logManager.Sources.Add(_strategy);

            // ProgressBar refresh step
            var progressStep = ((stopTime - startTime).Ticks / 100).To <TimeSpan>();
            var nextTime     = startTime + progressStep;

            TestingProcess.Maximum = 100;
            TestingProcess.Value   = 0;

            // handle historical time for update ProgressBar
            _connector.MarketTimeChanged += diff =>
            {
                if (_connector.CurrentTime < nextTime && _connector.CurrentTime < stopTime)
                {
                    return;
                }

                var steps = (_connector.CurrentTime - startTime).Ticks / progressStep.Ticks + 1;
                nextTime = startTime + (steps * progressStep.Ticks).To <TimeSpan>();
                this.GuiAsync(() => TestingProcess.Value = steps);
            };

            _connector.StateChanged += () =>
            {
                if (_connector.State == EmulationStates.Stopped)
                {
                    this.GuiAsync(() =>
                    {
                        Report.IsEnabled = true;

                        if (_connector.IsFinished)
                        {
                            TestingProcess.Value = TestingProcess.Maximum;
                            MessageBox.Show(this, LocalizedStrings.Str3024.Put(DateTime.Now - _startEmulationTime));
                        }
                        else
                        {
                            MessageBox.Show(this, LocalizedStrings.cancelled);
                        }
                    });
                }
            };

            _curveItems.Clear();

            Report.IsEnabled = false;

            _startEmulationTime = DateTime.Now;

            // raise NewSecurities and NewPortfolio for full fill strategy properties
            _connector.Connect();
        }
Exemple #57
0
        public RootObject GetAccountView(int memberId)
        {
            RootObject rootObject = new RootObject();

            var member = _context.Members.Select(item => item).Where(item => item.Id == memberId).SingleOrDefault();

            rootObject.MemberId        = member.Id;
            rootObject.LastLogin       = member.LastLogin;
            rootObject.MemberName      = member.MemberName;
            rootObject.loanEligibility = member.LoanEligibility;
            member.LastLogin           = DateTime.Now.ToString();
            _context.SaveChanges();

            rootObject.AccountView = new List <Portfolio>();
            Portfolio accountView = null;

            var result = _context.AccountDetails.Select(item => item).Where(item => item.MembersId == memberId);

            if (result.Any())
            {
                var resultList = result.ToList();
                foreach (AccountDetails detail in resultList)
                {
                    var primaryMemberId       = _context.AccountDetails.Select(item => item).Where(item => item.AccountsId == detail.AccountsId && item.AccountTypesId == 1).SingleOrDefault().MembersId;
                    var primaryMemberName     = _context.Members.Select(item => item).Where(item => item.Id == primaryMemberId).SingleOrDefault().MemberName;
                    var memberLoanEligibility = _context.Members.Select(item => item).Where(item => item.Id == primaryMemberId).SingleOrDefault().LoanEligibility;
                    var jointMember           = _context.AccountDetails.Select(item => item).Where(item => item.AccountsId == detail.AccountsId && item.AccountTypesId == 2).SingleOrDefault();

                    string jointMemberName = null;
                    if (jointMember != null)
                    {
                        jointMemberName = _context.Members.Select(item => item).Where(item => item.Id == jointMember.MembersId).SingleOrDefault().MemberName;
                    }

                    var accountNumbers = _context.Accounts.Select(item => item).Where(item => item.Id == detail.AccountsId).ToList();

                    accountView = new Portfolio();

                    /* fixing response format */
                    // accountView.loanEligibility = memberLoanEligibility;
                    accountView.account = accountNumbers[0].AccountNumber;
                    accountView.Primary = primaryMemberName;
                    accountView.Joint   = jointMemberName;
                    var shareList = _context.Shares.Select(item => item).Where(item => item.AccountsId == detail.AccountsId).ToList();
                    var loanList  = _context.Loans.Select(item => item).Where(item => item.AccountsId == detail.AccountsId).ToList();
                    accountView.shares = new List <Share>();
                    accountView.loans  = new List <Loan>();

                    foreach (Shares share in shareList)
                    {
                        accountView.shares.Add(new Share()
                        {
                            id = share.ShareNumber, balance = Convert.ToDouble(share.Balance), description = share.Description
                        });
                        accountView.shares_total = accountView.shares_total + Convert.ToDouble(share.Balance);
                    }
                    foreach (Loans loan in loanList)
                    {
                        accountView.loans.Add(new Loan()
                        {
                            id = loan.Id, balance = Convert.ToDouble(loan.Balance), description = loan.Description, emiDue = loan.EmiDue, emiDueDate = loan.EmiDueDate
                        });
                        accountView.loans_total = accountView.loans_total + Convert.ToDouble(loan.Balance);
                    }

                    /* get transactions */
                    accountView.transactionList = new List <TransactionList>();
                    accountView.transactionList = GetTransactions(accountNumbers[0].Id);
                    /* get transactions */

                    /*get cards */
                    var cardDetails = _context.Cards.Select(item => item).Where(item => item.AccountsId == detail.AccountsId).ToList();
                    accountView.card                = new Card();
                    accountView.card.Account        = accountNumbers[0].AccountNumber;
                    accountView.card.CardNumber     = cardDetails[0].CardNumber;
                    accountView.card.PaymentDue     = cardDetails[0].PaymentDue;
                    accountView.card.PaymentDueDate = cardDetails[0].PaymentDueDate;
                    accountView.card.Type           = cardDetails[0].Type;

                    /*get cards*/
                    rootObject.AccountView.Add(accountView);
                    accountView.message = accountView.shares.Count + " shares and " + accountView.loans.Count + " loans";
                }
            }

            return(rootObject);
        }
Exemple #58
0
        private void StartBtnClick(object sender, RoutedEventArgs e)
        {
            if (HistoryPath.Text.IsEmpty() || !Directory.Exists(HistoryPath.Text))
            {
                MessageBox.Show(this, LocalizedStrings.Str3014);
                return;
            }

            if (Math.Abs(TestingProcess.Value - 0) > double.Epsilon)
            {
                MessageBox.Show(this, LocalizedStrings.Str3015);
                return;
            }

            var logManager      = new LogManager();
            var fileLogListener = new FileLogListener("sample.log");

            logManager.Listeners.Add(fileLogListener);

            // SMA periods
            var periods = new[]
            {
                new Tuple <int, int, Color>(80, 10, Colors.DarkGreen),
                new Tuple <int, int, Color>(70, 8, Colors.Red),
                new Tuple <int, int, Color>(60, 6, Colors.DarkBlue)
            };

            // storage to historical data
            var storageRegistry = new StorageRegistry
            {
                // set historical path
                DefaultDrive = new LocalMarketDataDrive(HistoryPath.Text)
            };

            var timeFrame = TimeSpan.FromMinutes(5);

            // create test security
            var security = new Security
            {
                Id    = "RIZ2@FORTS",              // sec id has the same name as folder with historical data
                Code  = "RIZ2",
                Name  = "RTS-12.12",
                Board = ExchangeBoard.Forts,
            };

            var startTime = new DateTime(2012, 10, 1);
            var stopTime  = new DateTime(2012, 10, 31);

            var level1Info = new Level1ChangeMessage
            {
                SecurityId = security.ToSecurityId(),
                ServerTime = startTime,
            }
            .TryAdd(Level1Fields.PriceStep, 10m)
            .TryAdd(Level1Fields.StepPrice, 6m)
            .TryAdd(Level1Fields.MinPrice, 10m)
            .TryAdd(Level1Fields.MaxPrice, 1000000m)
            .TryAdd(Level1Fields.MarginBuy, 10000m)
            .TryAdd(Level1Fields.MarginSell, 10000m);

            // test portfolio
            var portfolio = new Portfolio
            {
                Name       = "test account",
                BeginValue = 1000000,
            };

            // create backtesting connector
            var batchEmulation = new BatchEmulation(new[] { security }, new[] { portfolio }, storageRegistry)
            {
                EmulationSettings =
                {
                    MarketTimeChangedInterval = timeFrame,
                    StartTime = startTime,
                    StopTime  = stopTime,

                    // count of parallel testing strategies
                    BatchSize                 = periods.Length,
                }
            };

            // handle historical time for update ProgressBar
            batchEmulation.ProgressChanged += (curr, total) => this.GuiAsync(() => TestingProcess.Value = total);

            batchEmulation.StateChanged += (oldState, newState) =>
            {
                if (batchEmulation.State != EmulationStates.Stopped)
                {
                    return;
                }

                this.GuiAsync(() =>
                {
                    if (batchEmulation.IsFinished)
                    {
                        TestingProcess.Value = TestingProcess.Maximum;
                        MessageBox.Show(LocalizedStrings.Str3024.Put(DateTime.Now - _startEmulationTime));
                    }
                    else
                    {
                        MessageBox.Show(LocalizedStrings.cancelled);
                    }
                });
            };

            // получаем подключение для эмуляции
            var connector = batchEmulation.EmulationConnector;

            logManager.Sources.Add(connector);

            connector.NewSecurities += securities =>
            {
                if (securities.All(s => s != security))
                {
                    return;
                }

                // fill level1 values
                connector.SendOutMessage(level1Info);

                connector.RegisterMarketDepth(new TrendMarketDepthGenerator(connector.GetSecurityId(security))
                {
                    // order book freq refresh is 1 sec
                    Interval = TimeSpan.FromSeconds(1),
                });
            };

            TestingProcess.Maximum = 100;
            TestingProcess.Value   = 0;

            _startEmulationTime = DateTime.Now;

            var strategies = periods
                             .Select(period =>
            {
                var series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame);

                // create strategy based SMA
                var strategy = new SmaStrategy(series, new SimpleMovingAverage {
                    Length = period.Item1
                }, new SimpleMovingAverage {
                    Length = period.Item2
                })
                {
                    Volume    = 1,
                    Security  = security,
                    Portfolio = portfolio,
                    Connector = connector,

                    // by default interval is 1 min,
                    // it is excessively for time range with several months
                    UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To <TimeSpan>()
                };

                strategy.SetCandleManager(new CandleManager(connector));

                var curveItems       = Curve.CreateCurve(LocalizedStrings.Str3026Params.Put(period.Item1, period.Item2), period.Item3);
                strategy.PnLChanged += () =>
                {
                    var data = new EquityData
                    {
                        Time  = strategy.CurrentTime,
                        Value = strategy.PnL,
                    };

                    this.GuiAsync(() => curveItems.Add(data));
                };

                Stat.AddStrategies(new[] { strategy });

                return(strategy);
            })
                             .ToEx(periods.Length);

            // start emulation
            batchEmulation.Start(strategies);
        }
Exemple #59
0
 /// <summary>
 /// Найти портфели, соответствующие фильтру <paramref name="criteria"/>.
 /// Найденные портфели будут переданы через событие <see cref="LookupPortfoliosResult"/>.
 /// </summary>
 /// <param name="criteria">Портфель, поля которого будут использоваться в качестве фильтра.</param>
 public void LookupPortfolios(Portfolio criteria)
 {
     Connector.LookupPortfolios(criteria);
 }
Exemple #60
0
 private void PortfolioChangedHandler(Portfolio portfolio)
 {
     AddGuiAction(() => PortfolioChanged.SafeInvoke(portfolio));
 }