示例#1
0
		private void UpdateProvider(ISecurityProvider provider)
		{
			if (_securityProvider == provider)
				return;

			if (_securityProvider != null)
			{
				_securityProvider.Added -= AddSecurities;
				_securityProvider.Removed -= RemoveSecurities;
				_securityProvider.Cleared -= ClearSecurities;

				SecurityTextBox.ItemsSource = Enumerable.Empty<Security>();
				_itemsSource = null;
			}

			_securityProvider = provider;

			if (_securityProvider == null)
				return;

			var itemsSource = new ObservableCollectionEx<Security>();

			_itemsSource = new ThreadSafeObservableCollection<Security>(itemsSource);
			_itemsSource.AddRange(_securityProvider.LookupAll());

			_securityProvider.Added += AddSecurities;
			_securityProvider.Removed += RemoveSecurities;
			_securityProvider.Cleared += ClearSecurities;

			SecurityTextBox.ItemsSource = itemsSource;
		}
 public NotesController(IMyDiaryData data,
                         IUserIdProvider userIdProvider)
     : base(data)
 {
     this.userIdProvider = userIdProvider;
     this.securityProvider = new SecurityProvider();
 }
示例#3
0
        public static ISecurityProvider CreateInstance()
        {
            if (_instance == null)
                _instance = new MiniSecurity();

            return _instance;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SecurityIdentity"/> class.
        /// </summary>
        /// <param name="provider">An <see cref="ISecurityProvider"/> of the user.</param>
        /// <exception cref="ArgumentNullException">Value specified for <paramref name="provider"/> is null.</exception>
        public SecurityIdentity(ISecurityProvider provider)
        {
            if ((object)provider == null)
                throw new ArgumentNullException(nameof(provider));

            m_provider = provider;
        }
示例#5
0
		/// <summary>
		/// To get the underlying asset by the derivative.
		/// </summary>
		/// <param name="derivative">The derivative.</param>
		/// <param name="provider">The provider of information about instruments.</param>
		/// <returns>Underlying asset.</returns>
		public static Security GetUnderlyingAsset(this Security derivative, ISecurityProvider provider)
		{
			if (derivative == null)
				throw new ArgumentNullException("derivative");

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

			if (derivative.Type == SecurityTypes.Option)
			{
				derivative.CheckOption();

				return _underlyingSecurities.SafeAdd(derivative, key =>
				{
					var underlyingSecurity = provider.LookupById(key.UnderlyingSecurityId);

					if (underlyingSecurity == null)
						throw new InvalidOperationException(LocalizedStrings.Str704Params.Put(key.UnderlyingSecurityId));

					return underlyingSecurity;
				});
			}
			else
			{
				return provider.LookupById(derivative.UnderlyingSecurityId);
			}
		}
示例#6
0
        public AccountManager(
            ISecurityProvider securityProvider,
            IAccountRepository accountRepository,
            IAccountValidator accountValidator,
            ITimeSource timeSource,
            int accountSessionCollectionCapacity,
            ISessionRepository sessionRepository,
            IActionRightResolver actionRightResolver/*,
            Func<TBizAccountRegistrationData, TBizAccount> accountRegistrationDataToAccount*/)
        {
            // todo1[ak] check args
            _securityProvider = securityProvider;
            _accountRepository = accountRepository;
            _accountValidator = accountValidator;
            _timeSource = timeSource;

            _sessionManager = new SessionManager(
                _securityProvider,
                _timeSource,
                accountSessionCollectionCapacity,
                sessionRepository);

            _actionRightResolver = actionRightResolver;
            //_accountRegistrationDataToAccount = accountRegistrationDataToAccount;
        }
示例#7
0
		/// <summary>
		/// Initializes a new instance of the <see cref="BlackScholes"/>.
		/// </summary>
		/// <param name="option">Options contract.</param>
		/// <param name="securityProvider">The provider of information about instruments.</param>
		/// <param name="dataProvider">The market data provider.</param>
		public BlackScholes(Security option, ISecurityProvider securityProvider, IMarketDataProvider dataProvider)
			: this(securityProvider, dataProvider)
		{
			if (option == null)
				throw new ArgumentNullException(nameof(option));

			Option = option;
		}
示例#8
0
        /// <summary>
        ///     Creates the brokerage under test and connects it
        /// </summary>
        /// <returns>A connected brokerage instance</returns>
        protected override IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider)
        {
            var environment = Config.Get("oanda-environment").ConvertTo<Environment>();
            var accessToken = Config.Get("oanda-access-token");
            var accountId = Config.Get("oanda-account-id");

            return new OandaBrokerage(orderProvider, securityProvider, environment, accessToken, accountId);
        }
        public MembershipProviderManagementService(IPersonRepository personRepository,
                                                   ISecurityProvider securityProvider)
        {
            Check.Require(personRepository != null, "userRepository may not be null");

            _personRepository = personRepository;
            _securityProvider = securityProvider;
        }
示例#10
0
 public void SetSecurityProvider(ISecurityProvider provider)
 {
     if (_securityProvider != null) return;
     lock (_locker)
     {
         if (_securityProvider != null) return;
         _securityProvider = provider;
     }
 }
 public UserController(
     ISecurityProvider securityProvider,
     ICommercialRepository repositoryCommerce,
     IMailProvider mailProvider)
 {
     _securityProvider = securityProvider;
     _repositoryCommerce = repositoryCommerce;
     _mailProvider = mailProvider;
 }
示例#12
0
        /// <summary>
        /// Creates the brokerage under test
        /// </summary>
        /// <returns>A connected brokerage instance</returns>
        protected override IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider)
        {
            var server = Config.Get("fxcm-server");
            var terminal = Config.Get("fxcm-terminal");
            var userName = Config.Get("fxcm-user-name");
            var password = Config.Get("fxcm-password");
            var accountId = Config.Get("fxcm-account-id");

            return new FxcmBrokerage(orderProvider, securityProvider, server, terminal, userName, password, accountId);
        }
示例#13
0
		/// <summary>
		/// Initializes a new instance of the <see cref="Synthetic"/>.
		/// </summary>
		/// <param name="security">The instrument (the option or the underlying asset).</param>
		/// <param name="provider">The provider of information about instruments.</param>
		public Synthetic(Security security, ISecurityProvider provider)
		{
			if (security == null)
				throw new ArgumentNullException(nameof(security));

			if (provider == null)
				throw new ArgumentNullException(nameof(provider));

			_security = security;
			_provider = provider;
		}
示例#14
0
		/// <summary>
		/// Initialize <see cref="BlackScholes"/>.
		/// </summary>
		/// <param name="securityProvider">The provider of information about instruments.</param>
		/// <param name="dataProvider">The market data provider.</param>
		protected BlackScholes(ISecurityProvider securityProvider, IMarketDataProvider dataProvider)
		{
			if (securityProvider == null)
				throw new ArgumentNullException(nameof(securityProvider));

			if (dataProvider == null)
				throw new ArgumentNullException(nameof(dataProvider));

			SecurityProvider = securityProvider;
			DataProvider = dataProvider;
		}
示例#15
0
 /// <summary>
 /// Creates a new instance of the <see cref="FxcmBrokerage"/> class
 /// </summary>
 /// <param name="orderProvider">The order provider</param>
 /// <param name="securityProvider">The holdings provider</param>
 /// <param name="server">The url of the server</param>
 /// <param name="terminal">The terminal name</param>
 /// <param name="userName">The user name (login id)</param>
 /// <param name="password">The user password</param>
 /// <param name="accountId">The account id</param>
 public FxcmBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider, string server, string terminal, string userName, string password, string accountId)
     : base("FXCM Brokerage")
 {
     _orderProvider = orderProvider;
     _securityProvider = securityProvider;
     _server = server;
     _terminal = terminal;
     _userName = userName;
     _password = password;
     _accountId = accountId;
 }
示例#16
0
			public StrategyConnector(StrategyContainer strategy, DateTimeOffset startDate, DateTimeOffset stopDate, TimeSpan useCandlesTimeFrame, bool onlyInitialize)
			{
				if (strategy == null)
					throw new ArgumentNullException(nameof(strategy));

				UpdateSecurityLastQuotes = false;
				UpdateSecurityByLevel1 = false;

				var entityRegistry = ConfigManager.GetService<IStudioEntityRegistry>();

				_strategy = strategy;
				_useCandlesTimeFrame = useCandlesTimeFrame;
				_onlyInitialize = onlyInitialize;
				_sessionStrategy = entityRegistry.ReadSessionStrategyById(strategy.Strategy.Id);

				if (_sessionStrategy == null)
					throw new InvalidOperationException("sessionStrategy = null");

				Id = strategy.Id;
				Name = strategy.Name + " Connector";

				_realConnector = (StudioConnector)ConfigManager.GetService<IStudioConnector>();
				_realConnector.NewMessage += RealConnectorNewMessage;

				_securityProvider = new StudioSecurityProvider();

				var storageRegistry = new StudioStorageRegistry { MarketDataSettings = strategy.MarketDataSettings };

				//EntityFactory = new StorageEntityFactory(entityRegistry, storageRegistry);

				Adapter.InnerAdapters.Add(_historyMessageAdapter = new HistoryMessageAdapter(TransactionIdGenerator, _securityProvider)
				{
					StartDate = startDate,
					StopDate = stopDate,
					StorageRegistry = storageRegistry
				});
				//_historyMessageAdapter.UpdateCurrentTime(startDate);
				var transactionAdapter = new PassThroughMessageAdapter(TransactionIdGenerator);
				transactionAdapter.AddTransactionalSupport();
				Adapter.InnerAdapters.Add(transactionAdapter);

				_historyMessageAdapter.MarketTimeChangedInterval = useCandlesTimeFrame;

				// при инициализации по свечкам, время меняется быстрее и таймаут должен быть больше 30с.
				ReConnectionSettings.TimeOutInterval = TimeSpan.MaxValue;

				//_historyMessageAdapter.BasketStorage.InnerStorages.AddRange(GetExecutionStorages());

				this.LookupById(strategy.Security.Id);

				new ChartAutoRangeCommand(true).Process(_strategy);
			}
示例#17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OandaBrokerage"/> class.
        /// </summary>
        /// <param name="orderProvider">The order provider.</param>
        /// <param name="securityProvider">The holdings provider.</param>
        /// <param name="environment">The Oanda environment (Trade or Practice)</param>
        /// <param name="accessToken">The Oanda access token (can be the user's personal access token or the access token obtained with OAuth by QC on behalf of the user)</param>
        /// <param name="accountId">The account identifier.</param>
        public OandaBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider, Environment environment, string accessToken, int accountId)
            : base("Oanda Brokerage")
        {
            _orderProvider = orderProvider;
            _securityProvider = securityProvider;

            if (environment != Environment.Trade && environment != Environment.Practice)
                throw new NotSupportedException("Oanda Environment not supported: " + environment);

            _environment = environment;
            _accessToken = accessToken;
            _accountId = accountId;
        }
示例#18
0
 protected override IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider)
 {
     if (!_manualGatewayControl && !_gatewayLaunched)
     {
         _gatewayLaunched = true;
         InteractiveBrokersGatewayRunner.Start(Config.Get("ib-controller-dir"),
             Config.Get("ib-tws-dir"),
             Config.Get("ib-user-name"),
             Config.Get("ib-password"),
             Config.GetBool("ib-use-tws")
             );
     }
     return new InteractiveBrokersBrokerage(orderProvider, securityProvider);
 }
示例#19
0
        /// <summary>
        /// Creates a new instance of the <see cref="FxcmBrokerage"/> class
        /// </summary>
        /// <param name="orderProvider">The order provider</param>
        /// <param name="securityProvider">The holdings provider</param>
        /// <param name="server">The url of the server</param>
        /// <param name="terminal">The terminal name</param>
        /// <param name="userName">The user name (login id)</param>
        /// <param name="password">The user password</param>
        /// <param name="accountId">The account id</param>
        public FxcmBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider, string server, string terminal, string userName, string password, string accountId)
            : base("FXCM Brokerage")
        {
            _orderProvider = orderProvider;
            _securityProvider = securityProvider;
            _server = server;
            _terminal = terminal;
            _userName = userName;
            _password = password;
            _accountId = accountId;

            HistoryResponseTimeout = 5000;
            MaximumHistoryRetryAttempts = 1;
        }
示例#20
0
		/// <summary>
		/// Инициализировать <see cref="BasketStrike"/>.
		/// </summary>
		/// <param name="underlyingAsset">Базовый актив.</param>
		/// <param name="securityProvider">Поставщик информации об инструментах.</param>
		/// <param name="dataProvider">Поставщик маркет-данных.</param>
		protected BasketStrike(Security underlyingAsset, ISecurityProvider securityProvider, IMarketDataProvider dataProvider)
		{
			if (underlyingAsset == null)
				throw new ArgumentNullException("underlyingAsset");

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

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

			UnderlyingAsset = underlyingAsset;
			SecurityProvider = securityProvider;
			DataProvider = dataProvider;
		}
示例#21
0
        internal SessionManager(ISecurityProvider securityProvider, ITimeSource timeSource, int accountSessionCollectionCapacity, ISessionRepository sessionRepository)
        {
            // todo1[ak] check args

            _securityProvider = securityProvider;
            _timeSource = timeSource;

            _accountSessionCollectionCapacity = accountSessionCollectionCapacity;
            _accountSessions = new Dictionary<string, IAccountSessionCollection>();

            _lock = new object();
            _allSessions = new Dictionary<string, BizSession>();

            _sessionRepository = sessionRepository;
        }
示例#22
0
        public FakeAccountRepository(IEnumerable<BizAccountRegistrationData> initialRegDatas, ISecurityProvider securityProvider)
        {
            _accounts = new Dictionary<long, AccountRec>();

            if (initialRegDatas != null)
            {
                foreach (var rd in initialRegDatas)
                {
                    BizAccount acc = WagenBackendHelper.AccountRegistrationDataToAccount(rd);
                    string hash = securityProvider.GetPasswordHashString(rd.Password);

                    this.AddAccount(acc, hash);
                }
            }
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="FilterableSecurityProvider"/>.
		/// </summary>
		/// <param name="provider">Security meta info provider.</param>
		/// <param name="ownProvider"><see langword="true"/> to leave the <paramref name="provider"/> open after the <see cref="FilterableSecurityProvider"/> object is disposed; otherwise, <see langword="false"/>.</param>
		///// <param name="excludeFilter">Filter for instruments exclusion.</param>
		public FilterableSecurityProvider(ISecurityProvider provider, bool ownProvider = false/*, Func<Security, bool> excludeFilter = null*/)
		{
			if (provider == null)
				throw new ArgumentNullException(nameof(provider));

			_provider = provider;
			_ownProvider = ownProvider;

			//ExcludeFilter = excludeFilter;

			_provider.Added += AddSecurities;
			_provider.Removed += RemoveSecurities;
			_provider.Cleared += ClearSecurities;

			AddSecurities(_provider.LookupAll());
		}
示例#24
0
        /// <summary>
        /// Creates the brokerage under test
        /// </summary>
        /// <returns>A connected brokerage instance</returns>
        protected override IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider)
        {
            var accountID = TradierBrokerageFactory.Configuration.AccountID;
            var tradier = new TradierBrokerage(orderProvider, securityProvider, accountID);

            var qcUserID = TradierBrokerageFactory.Configuration.QuantConnectUserID;
            var tokens = TradierBrokerageFactory.GetTokens();
            tradier.SetTokens(qcUserID, tokens.AccessToken, tokens.RefreshToken, tokens.IssuedAt, TimeSpan.FromSeconds(tokens.ExpiresIn));

            // keep the tokens up to date in the event of a refresh
            tradier.SessionRefreshed += (sender, args) =>
            {
                File.WriteAllText(TradierBrokerageFactory.TokensFile, JsonConvert.SerializeObject(args, Formatting.Indented));
            };

            return tradier;
        }
示例#25
0
        public static void Init(
            ISecurityProvider securityProvider,
            bool alwaysCheck,
            IUpdateHandler updateHandler,
            ISourceProvider[] sourceProviders)
        {
            if (securityProvider == null || updateHandler == null)
            {
                throw new ArgumentException("Parameters missed!");
            }

            var sp = new List<ISourceProvider> { new WebApiSourceProvider(securityProvider) };
            if (sourceProviders != null && sourceProviders.Any())
            {
                sp.AddRange(sourceProviders);
            }

            var updateManager = new UpdateManager(updateHandler, sp);
            updateManager.InitialCheck();
            if (alwaysCheck)
            {
                updateManager.Subscribe();
            }
        }
示例#26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HistoryEmulationConnector"/>.
 /// </summary>
 /// <param name="securityProvider">The provider of information about instruments.</param>
 /// <param name="portfolioProvider">The portfolio to be used to register orders. If value is not given, the portfolio with default name Simulator will be created.</param>
 /// <param name="storageRegistry">Market data storage.</param>
 /// <param name="exchangeInfoProvider">Exchanges and trading boards provider.</param>
 public HistoryEmulationConnector(ISecurityProvider securityProvider, IPortfolioProvider portfolioProvider, IExchangeInfoProvider exchangeInfoProvider, IStorageRegistry storageRegistry)
     : this(new HistoryMessageAdapter(new IncrementalIdGenerator(), securityProvider) { StorageRegistry = storageRegistry }, true, new InMemoryMessageChannel(new MessageByLocalTimeQueue(), "Emulator in", err => err.LogError()), securityProvider, portfolioProvider, exchangeInfoProvider)
 {
 }
示例#27
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="service"></param>
 /// <param name="securityProvider"></param>
 public AESKeyGeneratorController(ISecurityProvider securityProvider)
     : base(securityProvider)
 {
 }
示例#28
0
文件: Black.cs 项目: hbwjz/StockSharp
		// http://riskencyclopedia.com/articles/black_1976/

		/// <summary>
		/// Initializes a new instance of the <see cref="Black"/>.
		/// </summary>
		/// <param name="option">Options contract.</param>
		/// <param name="securityProvider">The provider of information about instruments.</param>
		/// <param name="dataProvider">The market data provider.</param>
		public Black(Security option, ISecurityProvider securityProvider, IMarketDataProvider dataProvider)
			: base(option, securityProvider, dataProvider)
		{
		}
示例#29
0
        // http://riskencyclopedia.com/articles/black_1976/

        /// <summary>
        /// Initializes a new instance of the <see cref="Black"/>.
        /// </summary>
        /// <param name="option">Options contract.</param>
        /// <param name="securityProvider">The provider of information about instruments.</param>
        /// <param name="dataProvider">The market data provider.</param>
        public Black(Security option, ISecurityProvider securityProvider, IMarketDataProvider dataProvider)
            : base(option, securityProvider, dataProvider)
        {
        }
 public ChatMessageRepository(IPersistenceContext <ChatMessage> dbContext, ISecurityProvider <ChatMessage> securityProvider, ChatUserSessionRepository chatUserSessionRepository, MessageBus messageBus = null) : base(dbContext, messageBus)
 {
     ChatUserSessionRepository = chatUserSessionRepository;
     SecurityProvider          = securityProvider;
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="service"></param>
 /// <param name="securityProvider"></param>
 public PasswordHashGeneratorController(ISecurityProvider securityProvider)
     : base(securityProvider)
 {
 }
示例#32
0
        static WebAppConfig()
        {
            string appClassName = ConfigurationManager.AppSettings["WebAppClassName"];

            _version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            _templateCacheDuration = Convert.ToInt32(ConfigurationManager.AppSettings["TemplateCacheDuration"]);
            _templateFileEncoding  = string.IsNullOrEmpty(ConfigurationManager.AppSettings["TemplateFileEncoding"]) ? Encoding.Default : Encoding.GetEncoding(ConfigurationManager.AppSettings["TemplateFileEncoding"]);

            bool.TryParse(ConfigurationManager.AppSettings["EnabledHttpCompress"], out _enabledHttpCompress);

            string enabledPermission = ConfigurationManager.AppSettings["EnabledPermission"];

            string defaultLanguageCode = ConfigurationManager.AppSettings["DefaultLanguageCode"];

            if (defaultLanguageCode != null && defaultLanguageCode.Length >= 2)
            {
                _defaultLanguageCode = defaultLanguageCode;
            }

            _extension = ConfigurationManager.AppSettings["Extension"] ?? string.Empty;

            _appKey    = ConfigurationManager.AppSettings["AppKey"];
            _appSecret = ConfigurationManager.AppSettings["AppSecret"];
            _oAuthUri  = ConfigurationManager.AppSettings["OAuthUri"];

            //if (string.IsNullOrEmpty(_appKey))
            //    throw new CException("AppKey not found, please check the Web.config's configuration/appSettings.");

            //if (string.IsNullOrEmpty(_appSecret))
            //    throw new CException("AppSecret not found, please check the Web.config's configuration/appSettings.");

            //if (string.IsNullOrEmpty(_oAuthUri))
            //    throw new CException("OAuthUri not found, please check the Web.config's configuration/appSettings.");

            //if (string.IsNullOrEmpty(_publicKey))
            //    throw new CException("PublicKey not found, please check the Web.config's configuration/appSettings.");

            //if (string.IsNullOrEmpty(_privateKey))
            //    throw new CException("PrivateKey not found, please check the Web.config's configuration/appSettings.");

            if (!string.IsNullOrEmpty(enabledPermission))
            {
                bool.TryParse(enabledPermission, out _enabledPermission);
            }

            if (string.IsNullOrEmpty(appClassName))
            {
                throw new CException("WebAppClassName not found, please check the Web.config's configuration/appSettings.");
            }

            Type appType = Type.GetType(appClassName, false);

            if (appType == null)
            {
                throw new CException("Can not load the type of WebAppClassName '" + appClassName + "'");
            }

            MethodInfo initMethod = appType.GetMethod("Init", new Type[0]);

            if (initMethod == null || !initMethod.IsStatic)
            {
                throw new CException("Can not found the static Init method of " + appType.FullName);
            }

            RegisterAssembly(appType.Assembly);

            initMethod.Invoke(null, null);

            if (_sessionType == null)
            {
                throw new CException("WebAppConfig.SessionType is null.");
            }

            if (_securityType == null)
            {
                throw new CException("WebAppConfig.SecurityType is null.");
            }

            LoadControllerClasses();

            if (_timeProvider == null)
            {
                _timeProvider = new RealTimeProvider();
            }

            if (_deserializeProvider == null)
            {
                _deserializeProvider = new JSONDeserializer();
            }

            if (_serializeProvider == null)
            {
                _serializeProvider = new JSONSerializer();
            }

            if (_securityProvider == null)
            {
                _securityProvider = MiniSecurity.CreateInstance();
            }

            if (_stringFilterProvider == null)
            {
                _stringFilterProvider = new MFilter();
            }
        }
示例#33
0
            public StrategyConnector(StrategyContainer strategy, DateTimeOffset startDate, DateTimeOffset stopDate, TimeSpan useCandlesTimeFrame, bool onlyInitialize)
            {
                if (strategy == null)
                {
                    throw new ArgumentNullException("strategy");
                }

                UpdateSecurityLastQuotes = false;
                UpdateSecurityByLevel1   = false;

                var entityRegistry = ConfigManager.GetService <IStudioEntityRegistry>();

                _strategy            = strategy;
                _useCandlesTimeFrame = useCandlesTimeFrame;
                _onlyInitialize      = onlyInitialize;
                _sessionStrategy     = entityRegistry.ReadSessionStrategyById(strategy.Strategy.Id);

                if (_sessionStrategy == null)
                {
                    throw new InvalidOperationException("sessionStrategy = null");
                }

                Id   = strategy.Id;
                Name = strategy.Name + " Connector";

                _realConnector             = (StudioConnector)ConfigManager.GetService <IStudioConnector>();
                _realConnector.NewMessage += RealConnectorNewMessage;

                EntityFactory = new StudioConnectorEntityFactory();

                _securityProvider = new StudioSecurityProvider();

                var session = new HistorySessionHolder(TransactionIdGenerator, _securityProvider)
                {
                    StartDate = startDate,
                    StopDate  = stopDate,
                };

                session.UpdateCurrentTime(startDate);

                var storageRegistry = new StudioStorageRegistry {
                    MarketDataSettings = strategy.MarketDataSettings
                };

                MarketDataAdapter = _historyMessageAdapter = new HistoryMessageAdapter(session)
                {
                    StorageRegistry = storageRegistry
                };
                TransactionAdapter = new PassThroughMessageAdapter(session);

                _historyMessageAdapter.SessionHolder.MarketTimeChangedInterval = useCandlesTimeFrame;
                // при инициализации по свечкам, время меняется быстрее и таймаут должен быть больше 30с.
                _historyMessageAdapter.SessionHolder.ReConnectionSettings.TimeOutInterval = TimeSpan.MaxValue;

                _historyMessageAdapter.BasketStorage.InnerStorages.AddRange(GetExecutionStorages());

                ApplyMessageProcessor(MessageDirections.In, true, true);
                ApplyMessageProcessor(MessageDirections.Out, true, true);

                this.LookupById(strategy.Security.Id);

                new ChartAutoRangeCommand(true).Process(_strategy);
            }
示例#34
0
 public DatabaseFileRepository(IPersistenceContext <DatabaseFile> dbContext, FileService fileService, ISecurityProvider <DatabaseFile> securityProvider = null, MessageBus messageBus = null) : base(dbContext, messageBus)
 {
     this.SecurityProvider = securityProvider;
     this.FileService      = fileService;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="RealTimeEmulationTrader{T}"/>.
        /// </summary>
        /// <param name="underlyngMarketDataAdapter"><see cref="IMessageAdapter"/>, through which market data will be got.</param>
        /// <param name="securityProvider">The provider of information about instruments.</param>
        /// <param name="portfolioProvider">The portfolio to be used to register orders. If value is not given, the portfolio with default name Simulator will be created.</param>
        /// <param name="ownAdapter">Track the connection <paramref name="underlyngMarketDataAdapter" /> lifetime.</param>
        public RealTimeEmulationTrader(TUnderlyingMarketDataAdapter underlyngMarketDataAdapter, ISecurityProvider securityProvider, IPortfolioProvider portfolioProvider, bool ownAdapter = true)
            : base(new EmulationMessageAdapter(underlyngMarketDataAdapter, new InMemoryMessageChannel(new MessageByOrderQueue(), "Emulator in", err => err.LogError()), false, securityProvider, portfolioProvider) { OwnInnerAdapter = ownAdapter }, ownAdapter)
        {
            UpdateSecurityByLevel1   = false;
            UpdateSecurityLastQuotes = false;

            UnderlyngMarketDataAdapter = underlyngMarketDataAdapter;

            Adapter.IgnoreExtraAdapters = true;
        }
示例#36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OandaRestApiV1"/> class.
 /// </summary>
 /// <param name="symbolMapper">The symbol mapper.</param>
 /// <param name="orderProvider">The order provider.</param>
 /// <param name="securityProvider">The holdings provider.</param>
 /// <param name="environment">The Oanda environment (Trade or Practice)</param>
 /// <param name="accessToken">The Oanda access token (can be the user's personal access token or the access token obtained with OAuth by QC on behalf of the user)</param>
 /// <param name="accountId">The account identifier.</param>
 /// <param name="agent">The Oanda agent string</param>
 public OandaRestApiV1(OandaSymbolMapper symbolMapper, IOrderProvider orderProvider, ISecurityProvider securityProvider, Environment environment, string accessToken, string accountId, string agent)
     : base(symbolMapper, orderProvider, securityProvider, environment, accessToken, accountId, agent)
 {
 }
 public ChatSessionRepository(ChatUserSessionRepository chatUserSessionRepository, IPersistenceContext <ChatSession> dbContext, ISecurityProvider <ChatSession> securityProvider = null, IUserSession userSession = null, MessageBus messageBus = null) : base(dbContext, messageBus)
 {
     ChatUserSessionRepository = chatUserSessionRepository;
     SecurityProvider          = securityProvider;
     UserSession = userSession;
 }
示例#38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CustomHistoryMessageAdapter"/>.
 /// </summary>
 /// <param name="innerAdapter">Underlying adapter.</param>
 /// <param name="securityProvider">The provider of information about instruments.</param>
 public CustomHistoryMessageAdapter(IMessageAdapter innerAdapter, ISecurityProvider securityProvider)
     : this(innerAdapter)
 {
     _securityProvider = securityProvider ?? throw new ArgumentNullException(nameof(securityProvider));
 }
示例#39
0
 /// <summary>
 /// To get at the money options (ATM).
 /// </summary>
 /// <param name="underlyingAsset">Underlying asset.</param>
 /// <param name="securityProvider">The provider of information about instruments.</param>
 /// <param name="dataProvider">The market data provider.</param>
 /// <returns>At the money options.</returns>
 public static IEnumerable <Security> GetAtTheMoney(this Security underlyingAsset, ISecurityProvider securityProvider, IMarketDataProvider dataProvider)
 {
     return(underlyingAsset.GetAtTheMoney(dataProvider, underlyingAsset.GetDerivatives(securityProvider)));
 }
示例#40
0
 /// <summary>
 /// Creates a new InteractiveBrokersBrokerage using values from configuration:
 ///     ib-account (required)
 ///     ib-host (optional, defaults to LOCALHOST)
 ///     ib-port (optional, defaults to 4001)
 ///     ib-agent-description (optional, defaults to Individual)
 /// </summary>
 /// <param name="orderProvider">An instance of IOrderProvider used to fetch Order objects by brokerage ID</param>
 /// <param name="securityProvider">The security provider used to give access to algorithm securities</param>
 public InteractiveBrokersBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider)
     : this(
         orderProvider,
         securityProvider,
         Config.Get("ib-account"),
         Config.Get("ib-host", "LOCALHOST"),
         Config.GetInt("ib-port", 4001),
         Config.GetValue("ib-agent-description", IB.AgentDescription.Individual)
         )
 {
 }
示例#41
0
 /// <summary>
 /// To get the main strike.
 /// </summary>
 /// <param name="underlyingAsset">Underlying asset.</param>
 /// <param name="securityProvider">The provider of information about instruments.</param>
 /// <param name="dataProvider">The market data provider.</param>
 /// <param name="expirationDate">The options expiration date.</param>
 /// <param name="optionType">Option type.</param>
 /// <returns>The main strike.</returns>
 public static Security GetCentralStrike(this Security underlyingAsset, ISecurityProvider securityProvider, IMarketDataProvider dataProvider, DateTimeOffset expirationDate, OptionTypes optionType)
 {
     return(underlyingAsset.GetCentralStrike(dataProvider, underlyingAsset.GetDerivatives(securityProvider, expirationDate).Filter(optionType)));
 }
 public EmulationEntityFactory(ISecurityProvider securityProvider, IEnumerable <Portfolio> portfolios)
 {
     _securityProvider = securityProvider ?? throw new ArgumentNullException(nameof(securityProvider));
     _portfolios       = portfolios.ToDictionary(p => p.Name, p => p, StringComparer.InvariantCultureIgnoreCase);
 }
示例#43
0
 public NodeMessageRoutesRequestHandler(ISecurityProvider securityProvider,
                                        INodeRoutesRegistrar nodeRoutesRegistrar)
 {
     this.securityProvider    = securityProvider;
     this.nodeRoutesRegistrar = nodeRoutesRegistrar;
 }
示例#44
0
 /// <summary>
 /// Creates the brokerage under test and connects it
 /// </summary>
 /// <returns>A connected brokerage instance</returns>
 protected abstract IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider);
示例#45
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="service"></param>
 /// <param name="logoutService"></param>
 /// <param name="securityProvider"></param>
 public LoginController(IDomainLoginService service, IDomainLogoutService logoutService, ISecurityProvider securityProvider)
     : base(securityProvider)
 {
     _service       = service;
     _logoutService = logoutService;
 }
示例#46
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OandaRestApiV20"/> class.
        /// </summary>
        /// <param name="symbolMapper">The symbol mapper.</param>
        /// <param name="orderProvider">The order provider.</param>
        /// <param name="securityProvider">The holdings provider.</param>
        /// <param name="aggregator">Consolidate ticks.</param>
        /// <param name="environment">The Oanda environment (Trade or Practice)</param>
        /// <param name="accessToken">The Oanda access token (can be the user's personal access token or the access token obtained with OAuth by QC on behalf of the user)</param>
        /// <param name="accountId">The account identifier.</param>
        /// <param name="agent">The Oanda agent string</param>
        public OandaRestApiV20(OandaSymbolMapper symbolMapper, IOrderProvider orderProvider, ISecurityProvider securityProvider, IDataAggregator aggregator, Environment environment, string accessToken, string accountId, string agent)
            : base(symbolMapper, orderProvider, securityProvider, aggregator, environment, accessToken, accountId, agent)
        {
            var basePathRest = environment == Environment.Trade ?
                               "https://api-fxtrade.oanda.com/v3" :
                               "https://api-fxpractice.oanda.com/v3";

            var basePathStreaming = environment == Environment.Trade ?
                                    "https://stream-fxtrade.oanda.com/v3" :
                                    "https://stream-fxpractice.oanda.com/v3";

            _apiRest = new DefaultApi(basePathRest);
            _apiRest.Configuration.AddDefaultHeader(OandaAgentKey, Agent);

            _apiStreaming = new DefaultApi(basePathStreaming);
        }
示例#47
0
        private static void Configure(ISecurityProvider security, IConfigurationRoot configuration, string connectionstringName = "default")
        {
            #region License

            var licensefile = "license.key";
            if (File.Exists(licensefile))
            {
                try
                {
                    var licenseText = File.ReadAllText(licensefile);
                    DWKitRuntime.RegisterLicense(licenseText);
                }
                catch
                {
                    //TODO add write to log
                }
            }

            #endregion

#if (DEBUG)
            DWKitRuntime.UseMetadataCache = false;
            //CodeActionsCompiler.DebugMode = true;
#elif (RELEASE)
            DWKitRuntime.UseMetadataCache = true;
#endif

            DWKitRuntime.ConnectionStringData = configuration[$"ConnectionStrings:{connectionstringName}"];
            DWKitRuntime.DbProvider           = AutoDetectProvider();
            DWKitRuntime.Security             = security;


            var path = configuration["Metadata:path"];

            if (string.IsNullOrEmpty(path))
            {
                path = "Metadata/metadata.json";
            }

            DWKitRuntime.Metadata = new DefaultMetadataProvider(path, "Metadata/Forms", "Metadata/Localization");

            if (configuration["DWKit:BlockMetadataChanges"] == "True")
            {
                DWKitRuntime.Metadata.BlockMetadataChanges = true;
            }

            if (configuration["DWKit:BlockMetadataChanges"] == "True")
            {
                DWKitRuntime.Metadata.BlockMetadataChanges = true;
                DWKitRuntime.Metadata.ResourceFolder       = configuration["DWKit:ResourceFolder"];
            }

            if (!string.IsNullOrWhiteSpace(configuration["DWKit:CodeActionsDebugMode"]))
            {
                DWKitRuntime.CodeActionsDebugMode = bool.Parse(configuration["DWKit:CodeActionsDebugMode"]);
            }

            CodeActionsCompiler.RegisterAssembly(typeof(WorkflowRuntime).Assembly);
            //It is necessary to have this assembly for compile code with dynamic
            CodeActionsCompiler.RegisterAssembly(typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly);
            DWKitRuntime.CompileAllCodeActionsAsync().Wait();
            DWKitRuntime.ServerActions.RegisterUsersProvider("filters", new Filters());
            DWKitRuntime.ServerActions.RegisterUsersProvider("triggers", new Triggers());

            //Initial inbox/outbox notifiers
            DWKitRuntime.AddClientNotifier(typeof(ClientNotificationHub), ClientNotifiers.NotifyClientsAboutInboxStatus);
            //Remove process after the document was removed
            DynamicEntityOperationNotifier.SubscribeToDeleteByTableName("Document", "WorkflowDelete", (e, c) =>
            {
                Func <Task> task = async() => { await ClientNotifiers.DeleteWokflowAndNotifyClients(e, c); };
                task.FireAndForgetWithDefaultExceptionLogger();
            });

            //Forcing the creation of a WF runtime to initialize timers and the Flow.
            try
            {
                WorkflowInit.ForceInit();
            }
            catch (Exception e)
            {
                if (Debugger.IsAttached)
                {
                    var info         = ExceptionUtils.GetExceptionInfo(e);
                    var errorBuilder = new StringBuilder();
                    errorBuilder.AppendLine("Workflow engine start failed.");
                    errorBuilder.AppendLine($"Message: {info.Message}");
                    errorBuilder.AppendLine($"Exceptions: {info.Exeptions}");
                    errorBuilder.Append($"StackTrace: {info.StackTrace}");
                    Debug.WriteLine(errorBuilder);
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RealTimeEmulationTrader{T}"/>.
 /// </summary>
 /// <param name="underlyngMarketDataAdapter"><see cref="IMessageAdapter"/>, through which market data will be got.</param>
 /// <param name="securityProvider">The provider of information about instruments.</param>
 /// <param name="portfolio">The portfolio to be used to register orders. If value is not given, the portfolio with default name Simulator will be created.</param>
 /// <param name="ownAdapter">Track the connection <paramref name="underlyngMarketDataAdapter" /> lifetime.</param>
 public RealTimeEmulationTrader(TUnderlyingMarketDataAdapter underlyngMarketDataAdapter, ISecurityProvider securityProvider, Portfolio portfolio, bool ownAdapter = true)
     : this(underlyngMarketDataAdapter, securityProvider, new CollectionPortfolioProvider(new[] { portfolio }), ownAdapter)
 {
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="HistoryEmulationConnector"/>.
		/// </summary>
		/// <param name="securityProvider">The provider of information about instruments.</param>
		/// <param name="portfolios">Portfolios, the operation will be performed with.</param>
		/// <param name="storageRegistry">Market data storage.</param>
		public HistoryEmulationConnector(ISecurityProvider securityProvider, IEnumerable<Portfolio> portfolios, IStorageRegistry storageRegistry)
		{
			if (securityProvider == null)
				throw new ArgumentNullException(nameof(securityProvider));

			if (portfolios == null)
				throw new ArgumentNullException(nameof(portfolios));

			if (storageRegistry == null)
				throw new ArgumentNullException(nameof(storageRegistry));

			// чтобы каждый раз при повторной эмуляции получать одинаковые номера транзакций
			TransactionIdGenerator = new IncrementalIdGenerator();

			_initialMoney = portfolios.ToDictionary(pf => pf, pf => pf.BeginValue);
			EntityFactory = new EmulationEntityFactory(securityProvider, _initialMoney.Keys);

			InMessageChannel = new PassThroughMessageChannel();
			OutMessageChannel = new PassThroughMessageChannel();

			LatencyManager = null;
			RiskManager = null;
			CommissionManager = null;
			PnLManager = null;
			SlippageManager = null;

			HistoryMessageAdapter = new HistoryMessageAdapter(TransactionIdGenerator, securityProvider) { StorageRegistry = storageRegistry };
			_historyChannel = new InMemoryMessageChannel("History Out", SendOutError);

			Adapter = new HistoryBasketMessageAdapter(this);
			Adapter.InnerAdapters.Add(EmulationAdapter);
			Adapter.InnerAdapters.Add(new ChannelMessageAdapter(HistoryMessageAdapter, new InMemoryMessageChannel("History In", SendOutError), _historyChannel));

			// при тестировании по свечкам, время меняется быстрее и таймаут должен быть больше 30с.
			ReConnectionSettings.TimeOutInterval = TimeSpan.MaxValue;

			MaxMessageCount = 1000;

			TradesKeepCount = 0;
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="RealTimeEmulationTrader{T}"/>.
 /// </summary>
 /// <param name="underlyngMarketDataAdapter"><see cref="IMessageAdapter"/>, through which market data will be got.</param>
 /// <param name="securityProvider">The provider of information about instruments.</param>
 public RealTimeEmulationTrader(TUnderlyingMarketDataAdapter underlyngMarketDataAdapter, ISecurityProvider securityProvider)
     : this(underlyngMarketDataAdapter, securityProvider, Portfolio.CreateSimulator())
 {
 }
示例#51
0
        private static void InitializeUsersWithRoutes(
            JoggingTrackerDbContext context,
            ISecurityProvider securityProvider,
            IServerTime serverTime)
        {
            const string userUsernamePrefix = "User";

            if (context.Users.Any(user => user.Username.StartsWith(userUsernamePrefix)))
            {
                return;
            }

            var random = new Random();

            for (int userOrdinal = 1; userOrdinal <= 20; userOrdinal++)
            {
                var userUsername = $"{userUsernamePrefix}{userOrdinal}";
                var year         = 1995 - userOrdinal;
                var month        = userOrdinal % 12;
                month = month == 0 ? userOrdinal : month;
                var day = userOrdinal % 27;
                day = day == 0 ? userOrdinal : day;
                var gender = (Gender)random.Next(0, 1);

                var userId = Guid.NewGuid();
                var user   = new User()
                {
                    Id               = userId,
                    Username         = userUsername,
                    Password         = securityProvider.CalculatePasswordHash($"{123}{userUsername}"),
                    Email            = $"{userUsername}@jogging-tracker.com",
                    RegistrationDate = serverTime.UtcNow,
                    Name             = userUsername,
                    Surname          = userUsername,
                    BirthDate        = new DateTime(year, month, day),
                    Gender           = gender
                };

                context.Users.Add(user);
                context.UserRoles.Add(new UserRole()
                {
                    Role = context.Roles.Single(role => role.Name == Role.UserRole),
                    User = user
                });

                var      runningStartDate = new DateTime(serverTime.UtcNow.Year - 1, user.BirthDate.Month, user.BirthDate.Day);
                DateTime?previous         = null;

                for (int routeOrdinal = 0; routeOrdinal < 15; routeOrdinal++)
                {
                    var distance = random.NextDouble() * 25;
                    distance = distance == 0 ? 1 : distance;

                    var hours   = random.Next(0, 24);
                    var minutes = random.Next(0, 60);
                    var seconds = random.Next(0, 60);

                    if (previous == null)
                    {
                        previous = runningStartDate;
                    }
                    else
                    {
                        previous.Value.AddDays(random.Next(1, 3));
                    }

                    var startTime = previous.Value.Add(new TimeSpan(hours, minutes, seconds));
                    var endTime   = startTime.AddMinutes(random.Next(15, 120));
                    endTime = endTime.AddSeconds(random.Next(0, 60));

                    var joggingRoute = new JoggingRoute()
                    {
                        Id                 = Guid.NewGuid(),
                        UserId             = userId,
                        DistanceKilometers = (decimal)distance,
                        StartTime          = startTime,
                        EndTime            = endTime,
                        Date               = startTime.Date
                    };

                    context.JoggingRoutes.Add(joggingRoute);

                    previous = endTime;
                }
            }

            context.SaveChanges();
        }
示例#52
0
 /// <summary>
 /// Создать <see cref="BasketBlackScholes"/>.
 /// </summary>
 /// <param name="securityProvider">Поставщик информации об инструментах.</param>
 /// <param name="dataProvider">Поставщик маркет-данных.</param>
 public BasketBlackScholes(ISecurityProvider securityProvider, IMarketDataProvider dataProvider)
     : base(securityProvider, dataProvider)
 {
     _innerModels = new InnerModelList(this);
 }
示例#53
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HistoryEmulationConnector"/>.
        /// </summary>
        /// <param name="innerAdapter">Underlying adapter.</param>
        /// <param name="ownInnerAdapter">Control <paramref name="innerAdapter"/> lifetime.</param>
        /// <param name="inChannel">Incoming messages channel.</param>
        /// <param name="securityProvider">The provider of information about instruments.</param>
        /// <param name="portfolioProvider">The portfolio to be used to register orders. If value is not given, the portfolio with default name Simulator will be created.</param>
        /// <param name="exchangeInfoProvider">Exchanges and trading boards provider.</param>
        public HistoryEmulationConnector(IMessageAdapter innerAdapter, bool ownInnerAdapter, IMessageChannel inChannel, ISecurityProvider securityProvider, IPortfolioProvider portfolioProvider, IExchangeInfoProvider exchangeInfoProvider)
            : base(new EmulationMessageAdapter(innerAdapter, inChannel, true, securityProvider, portfolioProvider, exchangeInfoProvider) { OwnInnerAdapter = ownInnerAdapter }, false, false)
        {
            MarketTimeChangedInterval = HistoryMessageAdapter.MarketTimeChangedInterval;

            Adapter.LatencyManager    = null;
            Adapter.CommissionManager = null;
            Adapter.PnLManager        = null;
            Adapter.SlippageManager   = null;

            Adapter.IsSupportTransactionLog = false;
            Adapter.SupportSecurityAll      = false;

            Adapter.SendFinishedCandlesImmediatelly = true;

            InMessageChannel  = new PassThroughMessageChannel();
            OutMessageChannel = new PassThroughMessageChannel();

            // при тестировании по свечкам, время меняется быстрее и таймаут должен быть больше 30с.
            //ReConnectionSettings.TimeOutInterval = TimeSpan.MaxValue;

            //MaxMessageCount = 1000;

            //Adapter.SupportCandlesCompression = false;
            Adapter.SupportBuildingFromOrderLog          = false;
            Adapter.SupportPartialDownload               = false;
            Adapter.SupportLookupTracking                = false;
            Adapter.SupportOrderBookTruncate             = false;
            Adapter.ConnectDisconnectEventOnFirstAdapter = false;

            MarketTimeChanged += OnMarketTimeChanged;
            Disconnected      += OnDisconnected;
        }
示例#54
0
 public UserService(ISecurityProvider securityProvider, DataContext context, IServiceProvider serviceProvider, IClaimsPrincipalProvider principalProvider, ILoggerFactory loggerFactory, IMapper mapper)
     : base(context, serviceProvider, principalProvider, loggerFactory)
 {
     SecurityProvider = securityProvider;
     _mapper          = mapper;
 }
示例#55
0
        /// <summary>
        /// Creates a new InteractiveBrokersBrokerage from the specified values
        /// </summary>
        /// <param name="orderProvider">An instance of IOrderProvider used to fetch Order objects by brokerage ID</param>
        /// <param name="securityProvider">The security provider used to give access to algorithm securities</param>
        /// <param name="account">The Interactive Brokers account name</param>
        /// <param name="host">host name or IP address of the machine where TWS is running. Leave blank to connect to the local host.</param>
        /// <param name="port">must match the port specified in TWS on the Configure&gt;API&gt;Socket Port field.</param>
        /// <param name="agentDescription">Used for Rule 80A describes the type of trader.</param>
        public InteractiveBrokersBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider, string account, string host, int port, IB.AgentDescription agentDescription = IB.AgentDescription.Individual)
            : base("Interactive Brokers Brokerage")
        {
            _orderProvider = orderProvider;
            _securityProvider = securityProvider;
            _account = account;
            _host = host;
            _port = port;
            _clientID = IncrementClientID();
            _agentDescription = agentDescription;
            _client = new IB.IBClient();

            // set up event handlers
            _client.UpdatePortfolio += HandlePortfolioUpdates;
            _client.OrderStatus += HandleOrderStatusUpdates;
            _client.UpdateAccountValue += HandleUpdateAccountValue;
            _client.Error += HandleError;
            _client.TickPrice += HandleTickPrice;
            _client.TickSize += HandleTickSize;
            _client.CurrentTime += HandleBrokerTime;

            // we need to wait until we receive the next valid id from the server
            _client.NextValidId += (sender, e) =>
            {
                // only grab this id when we initialize, and we'll manually increment it here to avoid threading issues
                if (_nextValidID == 0)
                {
                    _nextValidID = e.OrderId;
                    _waitForNextValidID.Set();
                }
                Log.Trace("InteractiveBrokersBrokerage.HandleNextValidID(): " + e.OrderId);
            };
        }
 public AccountController(AWSProvider aWSProvider,
                          ApplicationDbContext db,
                          ISecurityProvider securityProvider) : base(db, securityProvider)
 {
 }
 protected override IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider)
 {
     return(new InteractiveBrokersBrokerage(new QCAlgorithm(), orderProvider, securityProvider));
 }
示例#58
0
 /// <summary>
 /// To get Put for the underlying futures.
 /// </summary>
 /// <param name="future">Underlying futures.</param>
 /// <param name="provider">The provider of information about instruments.</param>
 /// <param name="strike">Strike.</param>
 /// <param name="expirationDate">The date of the option expiration.</param>
 /// <returns>The Put option.</returns>
 public static Security GetPut(this Security future, ISecurityProvider provider, decimal strike, DateTimeOffset expirationDate)
 {
     return(future.GetOption(provider, strike, expirationDate, OptionTypes.Put));
 }
示例#59
0
  public SecurityController(ISecurityProvider securityProvider)
 {
     _securityProvider = securityProvider;
 }
 public EmulationEntityFactory(ISecurityProvider securityProvider, IEnumerable <Portfolio> portfolios)
 {
     _securityProvider = securityProvider;
     _portfolios       = portfolios.ToDictionary(p => p.Name, p => p, StringComparer.InvariantCultureIgnoreCase);
 }