当前位置: 首页>>代码示例>>C#>>正文


C# BusinessEntities.Portfolio类代码示例

本文整理汇总了C#中StockSharp.BusinessEntities.Portfolio的典型用法代码示例。如果您正苦于以下问题:C# Portfolio类的具体用法?C# Portfolio怎么用?C# Portfolio使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Portfolio类属于StockSharp.BusinessEntities命名空间,在下文中一共展示了Portfolio类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: PortfolioCommand

		public PortfolioCommand(Portfolio portfolio, bool isNew)
		{
			if (portfolio == null)
				throw new ArgumentNullException("portfolio");

			Portfolio = portfolio;
			IsNew = isNew;
		}
开发者ID:reddream,项目名称:StockSharp,代码行数:8,代码来源:PortfolioCommand.cs

示例2: EMAStrategyOptimizer

        public EMAStrategyOptimizer(Security security, StorageRegistry storage, Portfolio portfolio, DateTime startTime, DateTime stopTime)
        {
            _startTime = startTime;
            _stopTime = stopTime;

            _security = security;
            _portfolio = portfolio;

            _storage = storage;

            this.Volume = 1;
            this.UseQuoting = true;
        }
开发者ID:akramarev,项目名称:SampleSMA,代码行数:13,代码来源:EMAStrategyOptimizer.cs

示例3: Main

		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<IEnumerable<Portfolio>> newPortfolios = portfolios =>
					{
						if (_portfolio1 == null)
							_portfolio1 = portfolios.FirstOrDefault(p => p.Name == account1);

						if (_portfolio2 == null)
							_portfolio2 = portfolios.FirstOrDefault(p => p.Name == account2);

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

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


					var securitiesWait = new ManualResetEvent(false);

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

						// если оба инструмента появились
						if (_lkoh != null && _riz0 != null)
							securitiesWait.Set();
					};
					quikTrader2.NewSecurities += securities =>
					{
						if (_riz0 == null)
							_riz0 = securities.FirstOrDefault(s => s.Code == "RIZ0");

						// если оба инструмента появились
						if (_lkoh != null && _riz0 != 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 || _riz0.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
					{
//.........这里部分代码省略.........
开发者ID:reddream,项目名称:StockSharp,代码行数:101,代码来源:Program.cs

示例4: LookupPortfolios

			public override void LookupPortfolios(Portfolio criteria)
			{
				_realConnector.LookupPortfolios(criteria);
			}
开发者ID:jsonbao,项目名称:StockSharp,代码行数:4,代码来源:StrategyService.cs

示例5: SendPortfolio

		private void SendPortfolio(Portfolio portfolio)
		{
			SendInMessage(portfolio.ToMessage());

			var money = _initialMoney[portfolio];

			SendInMessage(
				EmulationAdapter
					.CreatePortfolioChangeMessage(portfolio.Name)
						.Add(PositionChangeTypes.BeginValue, money)
						.Add(PositionChangeTypes.CurrentValue, money)
						.Add(PositionChangeTypes.BlockedValue, 0m));
		}
开发者ID:qiujoe,项目名称:StockSharp,代码行数:13,代码来源:HistoryEmulationConnector.cs

示例6: Clone

		/// <summary>
		/// Создать копию объекта <see cref="Portfolio"/>.
		/// </summary>
		/// <returns>Копия объекта.</returns>
		public Portfolio Clone()
		{
			var clone = new Portfolio();
			CopyTo(clone);
			return clone;
		}
开发者ID:rudrp,项目名称:StockSharp,代码行数:10,代码来源:Portfolio.cs

示例7: OnCancelOrders

		/// <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 (Version == SmartComVersions.V2 && isStopOrder == null && portfolio == null && direction == null && board == null && security == null)
				base.OnCancelOrders(transactionId);
			else
				this.CancelOrders(Orders, isStopOrder, portfolio, direction, board, security);
		}
开发者ID:neosb,项目名称:StockSharp,代码行数:16,代码来源:SmartTrader.cs

示例8: Button_Click

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			var wnd = new PortfolioPickerWindow();

			if (Portfolios != null)
				wnd.Portfolios = Portfolios;

			if (wnd.ShowModal(this))
			{
				SelectedPortfolio = wnd.SelectedPortfolio;
			}
		}
开发者ID:zjxbetter,项目名称:StockSharp,代码行数:12,代码来源:PortfolioEditor.xaml.cs

示例9: OnCancelOrders

		/// <summary>
		/// Отменить группу заявок на бирже по фильтру.
		/// </summary>
		/// <param name="transactionId">Идентификатор транзакции отмены.</param>
		/// <param name="isStopOrder"><see langword="true"/>, если нужно отменить только стоп-заявки, <see langword="false"/> - если только обычный и <see langword="null"/> - если оба типа.</param>
		/// <param name="portfolio">Портфель. Если значение равно <see langword="null"/>, то портфель не попадает в фильтр снятия заявок.</param>
		/// <param name="direction">Направление заявки. Если значение равно <see langword="null"/>, то направление не попадает в фильтр снятия заявок.</param>
		/// <param name="board">Торговая площадка. Если значение равно <see langword="null"/>, то площадка не попадает в фильтр снятия заявок.</param>
		/// <param name="security">Инструмент. Если значение равно <see langword="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);
		}
开发者ID:RakotVT,项目名称:StockSharp,代码行数:16,代码来源:QuikTrader.cs

示例10: ChangePosition

		private void ChangePosition(Security security, Portfolio portfolio, decimal diff)
		{
			if (security == null)
				throw new ArgumentNullException("security");

			if (portfolio == null)
				throw new ArgumentNullException("portfolio");

			bool isNew;
			var position = _positions.SafeAdd(Tuple.Create(security, portfolio),
			    key => new Position { Security = key.Item1, Portfolio = key.Item2 }, out isNew);

			position.CurrentValue += diff;

			if (isNew)
				NewPosition.SafeInvoke(position);
			else
				PositionChanged.SafeInvoke(position);
		}
开发者ID:rudrp,项目名称:StockSharp,代码行数:19,代码来源:PositionManager.cs

示例11: StartEmulation

		private void StartEmulation()
		{
			if (_connector != null && _connector.State != EmulationStates.Stopped)
				throw new InvalidOperationException(LocalizedStrings.Str3015);

			if (Strategy == null)
				throw new InvalidOperationException("Strategy not selected.");

			var strategy = (EmulationDiagramStrategy)Strategy;
			var settings = strategy.EmulationSettings;

			if (settings.MarketDataSettings == null)
				throw new InvalidOperationException(LocalizedStrings.Str3014);

			new SetDefaultEmulationSettingsCommand(settings).Process(this);

			strategy
				.Composition
				.Parameters
				.ForEach(p =>
				{
					if (p.Type == typeof(Security) && p.Value == null)
						throw new InvalidOperationException(LocalizedStrings.Str1380);
				});

			strategy.Reset();
			Reset();

			var securityId = "[email protected]";
			var secGen = new SecurityIdGenerator();
			var secIdParts = secGen.Split(securityId);
			var secCode = secIdParts.SecurityCode;
			var board = ExchangeBoard.GetOrCreateBoard(secIdParts.BoardCode);
			var timeFrame = settings.CandlesTimeFrame;
			var useCandles = settings.MarketDataSource == MarketDataSource.Candles;

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

			// storage to historical data
			var storageRegistry = new StudioStorageRegistry
			{
				MarketDataSettings = settings.MarketDataSettings
			};

			var startTime = settings.StartDate.ChangeKind(DateTimeKind.Utc);
			var stopTime = settings.StopDate.ChangeKind(DateTimeKind.Utc);

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

			// set ProgressBar bounds
			TicksAndDepthsProgress.Value = 0;
			TicksAndDepthsProgress.Maximum = 100;

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

			var securityProvider = ConfigManager.GetService<ISecurityProvider>();

			// create backtesting connector
			_connector = new HistoryEmulationConnector(securityProvider, new[] { portfolio }, new StorageRegistry())
			{
				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 = settings.MatchOnTouch, 
							IsSupportAtomicReRegister = settings.IsSupportAtomicReRegister,
							Latency = settings.EmulatoinLatency,
						}
					}
				},

				UseExternalCandleSource = useCandles,

				HistoryMessageAdapter =
				{
					StorageRegistry = storageRegistry,
					StorageFormat = settings.StorageFormat,

					// set history range
					StartDate = startTime,
					StopDate = stopTime,
				},

//.........这里部分代码省略.........
开发者ID:noreentry,项目名称:StockSharp,代码行数:101,代码来源:StrategyControl.xaml.cs

示例12: StartBtnClick

		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 = "[email protected]", // 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(this, LocalizedStrings.Str3024.Put(DateTime.Now - _startEmulationTime));
					}
					else
						MessageBox.Show(this, LocalizedStrings.cancelled);
				});
			};

//.........这里部分代码省略.........
开发者ID:reddream,项目名称:StockSharp,代码行数:101,代码来源:MainWindow.xaml.cs

示例13: Connect

        public void Connect()
        {
            trader = new IQFeedTrader();
            trader.Connected += () => SetConnectionStatus(0);
            trader.Disconnected += () => SetConnectionStatus(1);
            trader.ConnectionError += error => SetConnectionStatus(error);

            trader.Connect();

            var monitor = new MonitorWindow();
            monitor.Show();

            logManager.Listeners.Add(new GuiLogListener(monitor));
            logManager.Sources.Add(trader);

            var address = IPAddress.Parse("72.5.42.156");

            Trader = new BlackwoodTrader();
            logManager.Sources.Add(Trader);

            Trader.Login = "FUSDEMO09";
            Trader.Password = "m6e533";
            Trader.ExecutionAddress = new IPEndPoint(address, BlackwoodAddresses.ExecutionPort);
            Trader.MarketDataAddress = new IPEndPoint(address, BlackwoodAddresses.MarketDataPort);
            Trader.HistoricalDataAddress = new IPEndPoint(address, BlackwoodAddresses.HistoricalDataPort);

            Trader.Connected += Trader_Connected;
            Trader.ConnectionError += Trader_ConnectionError;
            Trader.Disconnected += Trader_Disconnected;

            Trader.NewPortfolios += portfolios =>
            {
                foreach (var portfolio in portfolios)
                {
                    Portfolio = portfolio;
                    Debug.Print("Portfolio name {0}", portfolio.Name);
                    Debug.Print("Portfolio RealizedPnL {0}", portfolio.RealizedPnL);
                    Debug.Print("Portfolio UnrealizedPnL {0}", portfolio.UnrealizedPnL);
                }
            };

            Trader.NewCandles += Trader_NewCandles;

            Trader.NewOrders += Trader_NewOrders;
            Trader.NewPositions += Trader_NewPositions;
            Trader.Connect();
        }
开发者ID:AlexandrKalinovskiy,项目名称:Quasar,代码行数:47,代码来源:Worker.cs

示例14: GetOptContext

        public KeyValuePair<OptVarItem, EMAEventModelStrategy> GetOptContext(OptVarItem optVarItem)
        {
            // clone doesn't work for some reason
            var security = new Security
            {
                Id = _security.Id,
                Code = _security.Code,
                Name = _security.Name,
                MinStepSize = _security.MinStepSize,
                MinStepPrice = _security.MinStepPrice,
                ExchangeBoard = _security.ExchangeBoard,
                MaxPrice = 99999,
                MinPrice = 1
            };

            // Create local Storage to make it disposable after optimization
            var storage = new StorageRegistry();
            ((LocalMarketDataDrive) storage.DefaultDrive).Path = ((LocalMarketDataDrive) _storage.DefaultDrive).Path;
            ((LocalMarketDataDrive) storage.DefaultDrive).UseAlphabeticPath = true;

            var portfolio = new Portfolio { BeginValue = _portfolio.BeginValue };

            EmulationTrader trader = new EmulationTrader(
                new[] { security },
                new[] { portfolio })
            {
                MarketTimeChangedInterval = optVarItem.TimeFrame,
                StorageRegistry = storage,
                UseMarketDepth = true,
                //UseCandlesTimeFrame = optVarItem.TimeFrame
            };

            if (trader.UseMarketDepth)
            {
                trader.MarketEmulator.Settings.DepthExpirationTime = TimeSpan.FromMinutes(5); // Default: TimeSpan.FromDays(1);
                var marketDepthGenerator = new TrendMarketDepthGenerator(security)
                {
                    // стакан для инструмента в истории обновляется раз в 10 секунд
                    Interval = TimeSpan.FromSeconds(10),
                    //MaxAsksDepth = 5,
                    //MaxBidsDepth = 5
                };

                trader.RegisterMarketDepth(marketDepthGenerator);

                trader.StateChanged += (oldState, newState) =>
                {
                    if (trader.State == EmulationStates.Stopped)
                    {
                        trader.UnRegisterMarketDepth(marketDepthGenerator);
                        marketDepthGenerator = null;
                    }
                };
            }

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

            var series = new CandleSeries(typeof(TimeFrameCandle), trader.Securities.First(), optVarItem.TimeFrame);
            var candleManager = new CandleManager(trader);
            candleManager.Start(series);

            var strategy = new EMAEventModelStrategy(series,
                new ExponentialMovingAverage { Length = optVarItem.FilterOptPeriod },
                new ExponentialMovingAverage { Length = optVarItem.LongOptPeriods },
                new ExponentialMovingAverage { Length = optVarItem.ShortOptPeriods },
                optVarItem.TakeProfitUnit, optVarItem.StopLossUnit)
            {
                Volume = this.Volume,
                Portfolio = portfolio,
                Security = security,
                Trader = trader,
                UseQuoting = this.UseQuoting
            };

            trader.StateChanged += (oldState, newState) =>
            {
                if (trader.State == EmulationStates.Started)
                {
                    strategy.Start();
                }
                else if (trader.State == EmulationStates.Stopped)
                {
                    strategy.Stop();
                    candleManager = null;
                    storage = null;
                }
            };

            var result = new KeyValuePair<OptVarItem, EMAEventModelStrategy>(optVarItem, strategy);
            return result;
        }
开发者ID:akramarev,项目名称:SampleSMA,代码行数:94,代码来源:EMAStrategyOptimizer.cs

示例15: CreatePosition

		/// <summary>
		/// Create position.
		/// </summary>
		/// <param name="portfolio">Portfolio.</param>
		/// <param name="security">Security.</param>
		/// <returns>Created position.</returns>
		public override Position CreatePosition(Portfolio portfolio, Security security)
		{
			return _entityRegistry.Positions.ReadBySecurityAndPortfolio(security, portfolio)
			       ?? base.CreatePosition(portfolio, security);
		}
开发者ID:vikewoods,项目名称:StockSharp,代码行数:11,代码来源:StorageEntityFactory.cs


注:本文中的StockSharp.BusinessEntities.Portfolio类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。