public void SetUp()
        {
            subscribedTopics = new List<string>();
            unsubscribedTopics = new List<string>();

            topicEvaluatorMock = new Mock<ITopicEvaluator>();
            testee = new SubscriptionManager(topicEvaluatorMock.Object);
        }
 public DirectSubscriptionProvider(string sourceID, SubscriptionManager subscriptionManager, IRecipientProvider recipientProvider)
 {
     if (string.IsNullOrEmpty(sourceID)) throw new ArgumentNullException("sourceID");
     if (subscriptionManager == null) throw new ArgumentNullException("subscriptionManager");
     if (recipientProvider == null) throw new ArgumentNullException("recipientProvider");
     
     this.sourceID = sourceID;
     this.subscriptionManager = subscriptionManager;
     this.recipientProvider = recipientProvider;
 }
        public void DeleteVM()
        {
            var result = new SubscriptionManager("82f8e1cd-ee8d-414e-b6a5-be7b18a1fa89")
                .GetVirtualMachinesManager()
                .AddPublishSettingsFromXml(Publishsettings)
                .DeleteVirtualMachine("HostedService", "DeploymentName", "RoleName")
                .ToString();

            result.Should().NotBeNullOrEmpty();
            Console.WriteLine(result);
        }
 public Publisher(SubscriptionManager.DataLayer.DataTables.Publisher publisherDl)
 {
     if (publisherDl != null)
     {
         this.HasData = true;
         this.PublisherId = publisherDl.PublisherId;
         this.PublisherName = publisherDl.PublisherName;
     }
     else
     {
         throw new ArgumentException("Invalid Publisher");
     }
 }
Example #5
0
    public ConsorsGate(Logger l)
    {
        _log=l;
        _log.info("ConsorsGate::ConsorsGate", "constructing.");
        _quit=false;
        _thread=new Thread(new ThreadStart(Run));
        _thread.Start();

        //initializing the core elements

        _sm = new SubscriptionManager(_log, this);
        _qs = new QuoteSystem(_log, this);
    }
        private void FillProperties(SubscriptionManager.DataLayer.DataTables.ComicBookSeries series)
        {
            HasData = true;

            ComicBookSeriesId = series.ComicBookSeriesId;
            PublisherId = series.PublisherId;
            ComicBookSeriesTitle = series.ComicBookSeriesTitle;
            IsActive = series.IsActive;
            CreateDate = series.CreateDate;
            CreateUserId = series.CreateUserId;
            ChangeUserId = series.ChangeUserId;
            ChangeDate = series.ChangeDate;
            DeleteDate = series.DeleteDate;
        }
        private void FillProperties(SubscriptionManager.DataLayer.DataTables.Store store)
        {
            HasData = true;

            if (store != null)
            {
                StoreId = store.StoreId;
                StoreName = store.StoreName;
                AddressOne = store.AddressOne;
                AddressTwo = store.AddressTwo;
                City = store.City;
                State = store.State;
                ZipCode = store.ZipCode;
                PhoneNumber = store.PhoneNumber;
                EmailAddress = store.EmailAddress;
            }
        }
        public void CreateVm()
        {
            var vm = new SubscriptionManager("82f8e1cd-ee8d-414e-b6a5-be7b18a1fa89")
                .GetVirtualMachinesManager()
                .AddPublishSettingsFromXml(Publishsettings)
                .CreateVirtualMachineDeployment()
                .AddToExistingCloudServiceWithName("CloudServiceName")
                .WithAdminPassword("Password")
                .WithDeploymentType(Commands.VirtualMachines.VirtualMachineTemplates.SqlServer2012)
                .WithMachineName("ServerName")
                .WithRoleName("NewRole")
                .WithStorageAccountForVhds("StorageAccount")
                .WithVmOfSize(Types.VmSize.ExtraLarge);

            var result = vm.ToString();
            result.Should().NotBeNullOrEmpty();
            Console.WriteLine(result);
        }
        public void CreateCustomImage()
        {
            var result = new SubscriptionManager("82f8e1cd-ee8d-414e-b6a5-be7b18a1fa89")
                .GetVirtualMachinesManager()
                .AddPublishSettingsFromXml(Publishsettings)
                .CreateVirtualMachineDeployment()
                .WithDeploymentType("ImageShortName")
                .AddInputEndpoint("Web2", Types.VirtualMachines.Protocol.TCP, 8080, 8080)
                .AddInputEndpoint(InputEndpoint.GetDefaultWebSettings())
                .AddToExistingCloudServiceWithName("CloudService")
                .WithAdminPassword("Password")
                .WithMachineName("NewMachine")
                .WithRoleName("NewRole")
                .WithStorageAccountForVhds("accountName")
                .WithVmOfSize(Types.VmSize.ExtraLarge);

            result.ToString().Should().NotBeNullOrEmpty();
            Console.WriteLine(result);
        }
Example #10
0
        private Framework(string name, FrameworkMode mode, bool createServers, EventBus externalBus, InstrumentServer instrumentServer, DataServer dataServer, string fileServerPath)
        {
            Name = name;
            this.mode = mode;
            LoadConfiguration();

            // Setup events compoents setup
            EventBus = new EventBus(this);
            OutputManager = new OutputManager(this, Configuration.IsOutputLogEnabled ? Configuration.OutputLogFileName : null);
            Clock = new Clock(this, ClockType.Local, false);
            EventBus.LocalClockEventQueue = Clock.ReminderQueue;
            ExchangeClock = new Clock(this, ClockType.Exchange, false);
            EventBus.ExchangeClockEventQueue = ExchangeClock.ReminderQueue;
            externalBus?.Attach(EventBus);
            EventServer = new EventServer(this, EventBus);
            EventManager = new EventManager(this, EventBus);

            // Setup streamers
            StreamerManager = new StreamerManager();
            StreamerManager.AddDefaultStreamers();

            // Create Servers
            var iServer = instrumentServer ?? new FileInstrumentServer(this, Configuration.InstrumentFileName);
            var dServer = dataServer ?? new FileDataServer(this, Configuration.DataFileName);
            var oServer = new FileOrderServer(this, Configuration.OrderFileName);
            var pServer = new FilePortfolioServer(this, Configuration.PortfolioFileName);

            InstrumentManager = new InstrumentManager(this, iServer);
            InstrumentServer = iServer;
            InstrumentManager.Load();
            DataManager = new DataManager(this, dServer);
            DataServer = dServer;
            OrderManager = new OrderManager(this, oServer);
            OrderServer = oServer;
            PortfolioManager = new PortfolioManager(this, pServer);
            PortfolioServer = pServer;
            UserServer = new XmlUserServer(this);
            UserManager = new UserManager(this, UserServer);
            UserManager.Load();

            // Create Providers
            ProviderManager = new ProviderManager(this);

            // Other stuff
            EventLoggerManager = new EventLoggerManager();
            SubscriptionManager = new SubscriptionManager(this);
            ScenarioManager = new ScenarioManager(this);
            StrategyManager = new StrategyManager(this);
            StatisticsManager = new StatisticsManager(this);
            GroupManager = new GroupManager(this);
            AccountDataManager = new AccountDataManager(this);
            LicenseManager = new LicenseManager();
            CurrencyConverter = new CurrencyConverter(this);
            DataFileManager = new DataFileManager(Installation.DataDir.FullName);

            instance = instance ?? this;
        }
 public SingleSecurity_Second_BenchmarkTest()
 {
     SubscriptionManager.SetDataManager(new DataManager());
 }
Example #12
0
		public MessageDestination(IService service, DestinationDefinition destinationDefinition)
			: base(service, destinationDefinition) {
			_subscriptionManager = new SubscriptionManager(this);
		}
        private void FillProperties(SubscriptionManager.DataLayer.DataTables.Customer customer)
        {
            HasData = true;

            if (customer != null)
            {
                CustomerId = customer.CustomerId;
                StoreId = customer.StoreId;
                FirstName = customer.FirstName;
                LastName = customer.LastName;
                PhoneNumber = customer.PhoneNumber;
                EmailAddress = customer.EmailAddress;
                City = customer.City;
                State = customer.State;
                ZipCode = customer.ZipCode;
                SubscriptionCount = customer.SubscriptionCount;
                CreateDate = customer.CreateDate;
                CreateUserId = customer.CreateUserId;
                ChangeUserId = customer.ChangeUserId;
                ChangeDate = customer.ChangeDate;
                DeleteDate = customer.DeleteDate;
            }
        }
 public Customer(SubscriptionManager.DataLayer.DataTables.Customer customer)
 {
     FillProperties(customer);
 }
Example #15
0
        /// <summary>
        /// Ensures that we have a data feed to convert this currency into the base currency.
        /// This will add a <see cref="SubscriptionDataConfig"/> and create a <see cref="Security"/> at the lowest resolution if one is not found.
        /// </summary>
        /// <param name="securities">The security manager</param>
        /// <param name="subscriptions">The subscription manager used for searching and adding subscriptions</param>
        /// <param name="marketMap">The market map that decides which market the new security should be in</param>
        /// <param name="changes">Will be used to consume <see cref="SecurityChanges.AddedSecurities"/></param>
        /// <param name="securityService">Will be used to create required new <see cref="Security"/></param>
        /// <param name="accountCurrency">The account currency</param>
        /// <param name="defaultResolution">The default resolution to use for the internal subscriptions</param>
        /// <returns>Returns the added <see cref="SubscriptionDataConfig"/>, otherwise null</returns>
        public List <SubscriptionDataConfig> EnsureCurrencyDataFeed(SecurityManager securities,
                                                                    SubscriptionManager subscriptions,
                                                                    IReadOnlyDictionary <SecurityType, string> marketMap,
                                                                    SecurityChanges changes,
                                                                    ISecurityService securityService,
                                                                    string accountCurrency,
                                                                    Resolution defaultResolution = Resolution.Minute
                                                                    )
        {
            // this gets called every time we add securities using universe selection,
            // so must of the time we've already resolved the value and don't need to again
            if (CurrencyConversion != null)
            {
                return(null);
            }

            if (Symbol == accountCurrency)
            {
                _isBaseCurrency    = true;
                CurrencyConversion = null;
                ConversionRate     = 1.0m;
                return(null);
            }

            // existing securities
            var securitiesToSearch = securities.Select(kvp => kvp.Value)
                                     .Concat(changes.AddedSecurities)
                                     .Where(s => s.Type == SecurityType.Forex || s.Type == SecurityType.Cfd || s.Type == SecurityType.Crypto);

            // Create a SecurityType to Market mapping with the markets from SecurityManager members
            var markets = securities.Select(x => x.Key)
                          .GroupBy(x => x.SecurityType)
                          .ToDictionary(x => x.Key, y => y.Select(symbol => symbol.ID.Market).ToHashSet());

            if (markets.ContainsKey(SecurityType.Cfd) && !markets.ContainsKey(SecurityType.Forex))
            {
                markets.Add(SecurityType.Forex, markets[SecurityType.Cfd]);
            }
            if (markets.ContainsKey(SecurityType.Forex) && !markets.ContainsKey(SecurityType.Cfd))
            {
                markets.Add(SecurityType.Cfd, markets[SecurityType.Forex]);
            }

            var forexEntries  = GetAvailableSymbolPropertiesDatabaseEntries(SecurityType.Forex, marketMap, markets);
            var cfdEntries    = GetAvailableSymbolPropertiesDatabaseEntries(SecurityType.Cfd, marketMap, markets);
            var cryptoEntries = GetAvailableSymbolPropertiesDatabaseEntries(SecurityType.Crypto, marketMap, markets);

            var potentialEntries = forexEntries
                                   .Concat(cfdEntries)
                                   .Concat(cryptoEntries)
                                   .ToList();

            if (!potentialEntries.Any(x =>
                                      Symbol == x.Key.Symbol.Substring(0, x.Key.Symbol.Length - x.Value.QuoteCurrency.Length) ||
                                      Symbol == x.Value.QuoteCurrency))
            {
                // currency not found in any tradeable pair
                Log.Error($"No tradeable pair was found for currency {Symbol}, conversion rate to account currency ({accountCurrency}) will be set to zero.");
                CurrencyConversion = null;
                ConversionRate     = 0m;
                return(null);
            }

            // Special case for crypto markets without direct pairs (They wont be found by the above)
            // This allows us to add cash for "StableCoins" that are 1-1 with our account currency without needing a conversion security.
            // Check out the StableCoinsWithoutPairs static var for those that are missing their 1-1 conversion pairs
            if (marketMap.TryGetValue(SecurityType.Crypto, out var market)
                &&
                (Currencies.StableCoinsWithoutPairs.Contains(QuantConnect.Symbol.Create(Symbol + accountCurrency, SecurityType.Crypto, market)) ||
                 Currencies.StableCoinsWithoutPairs.Contains(QuantConnect.Symbol.Create(accountCurrency + Symbol, SecurityType.Crypto, market))))
            {
                CurrencyConversion = null;
                ConversionRate     = 1.0m;
                return(null);
            }

            var requiredSecurities = new List <SubscriptionDataConfig>();

            var potentials = potentialEntries
                             .Select(x => QuantConnect.Symbol.Create(x.Key.Symbol, x.Key.SecurityType, x.Key.Market));

            var minimumResolution = subscriptions.Subscriptions.Select(x => x.Resolution).DefaultIfEmpty(defaultResolution).Min();

            var makeNewSecurity = new Func <Symbol, Security>(symbol =>
            {
                var securityType = symbol.ID.SecurityType;

                // use the first subscription defined in the subscription manager
                var type       = subscriptions.LookupSubscriptionConfigDataTypes(securityType, minimumResolution, false).First();
                var objectType = type.Item1;
                var tickType   = type.Item2;

                // set this as an internal feed so that the data doesn't get sent into the algorithm's OnData events
                var config = subscriptions.SubscriptionDataConfigService.Add(symbol,
                                                                             minimumResolution,
                                                                             fillForward: true,
                                                                             extendedMarketHours: false,
                                                                             isInternalFeed: true,
                                                                             subscriptionDataTypes: new List <Tuple <Type, TickType> >
                {
                    new Tuple <Type, TickType>(objectType, tickType)
                }).First();

                var newSecurity = securityService.CreateSecurity(symbol,
                                                                 config,
                                                                 addToSymbolCache: false);

                Log.Trace($"Cash.EnsureCurrencyDataFeed(): Adding {symbol.Value} for cash {Symbol} currency feed");

                securities.Add(symbol, newSecurity);
                requiredSecurities.Add(config);

                return(newSecurity);
            });

            CurrencyConversion = SecurityCurrencyConversion.LinearSearch(Symbol,
                                                                         accountCurrency,
                                                                         securitiesToSearch.ToList(),
                                                                         potentials,
                                                                         makeNewSecurity);

            return(requiredSecurities);
        }
        public VideoPlayerPageViewModel(
            ILoggerFactory loggerFactory,
            IScheduler scheduler,
            IPlayerView playerView,
            NiconicoSession niconicoSession,
            SubscriptionManager subscriptionManager,
            NicoVideoProvider nicoVideoProvider,
            ChannelProvider channelProvider,
            MylistProvider mylistProvider,
            AppearanceSettings appearanceSettings,
            PlayerSettings playerSettings,
            VideoCacheSettings_Legacy cacheSettings,
            ApplicationLayoutManager applicationLayoutManager,
            LocalMylistManager localMylistManager,
            LoginUserOwnedMylistManager userMylistManager,
            PageManager pageManager,
            QueuePlaylist queuePlaylist,
            HohoemaPlaylistPlayer hohoemaPlaylistPlayer,
            MediaPlayer mediaPlayer,
            VideoTogglePlayPauseCommand videoTogglePlayPauseCommand,
            NotificationService notificationService,
            DialogService dialogService,
            AddSubscriptionCommand addSubscriptionCommand,
            LocalPlaylistCreateCommand createLocalMylistCommand,
            MylistAddItemCommand addMylistCommand,
            LocalPlaylistAddItemCommand localPlaylistAddItemCommand,
            MylistCreateCommand createMylistCommand,
            VideoStreamingOriginOrchestrator videoStreamingOriginOrchestrator,
            VideoCommentPlayer commentPlayer,
            CommentCommandEditerViewModel commentCommandEditerViewModel,
            KeepActiveDisplayWhenPlaying keepActiveDisplayWhenPlaying,
            ObservableMediaPlayer observableMediaPlayer,
            VideoEndedRecommendation videoEndedRecommendation,
            PrimaryViewPlayerManager primaryViewPlayerManager,
            TogglePlayerDisplayViewCommand togglePlayerDisplayViewCommand,
            ShowPrimaryViewCommand showPrimaryViewCommand,
            MediaPlayerSoundVolumeManager soundVolumeManager,
            OpenLinkCommand openLinkCommand,
            CopyToClipboardCommand copyToClipboardCommand,
            ChangeVideoQualityCommand changeVideoQualityCommand,
            CopyToClipboardWithShareTextCommand copyToClipboardWithShareTextCommand,
            OpenShareUICommand openShareUICommand,
            PlaylistSidePaneContentViewModel playlistSidePaneContentViewModel,
            SettingsSidePaneContentViewModel settingsSidePaneContentViewModel,
            VideoCommentSidePaneContentViewModel videoCommentSidePaneContent,
            RelatedVideosSidePaneContentViewModel relatedVideosSidePaneContentViewModel
            )
        {
            _logger = loggerFactory.CreateLogger <VideoPlayerPageViewModel>();
            CurrentPlayerDisplayView = appearanceSettings
                                       .ObserveProperty(x => x.PlayerDisplayView)
                                       .ToReadOnlyReactivePropertySlim()
                                       .AddTo(_CompositeDisposable);

            _scheduler                             = scheduler;
            PlayerView                             = playerView;
            NiconicoSession                        = niconicoSession;
            SubscriptionManager                    = subscriptionManager;
            NicoVideoProvider                      = nicoVideoProvider;
            ChannelProvider                        = channelProvider;
            MylistProvider                         = mylistProvider;
            PlayerSettings                         = playerSettings;
            CacheSettings                          = cacheSettings;
            ApplicationLayoutManager               = applicationLayoutManager;
            LocalMylistManager                     = localMylistManager;
            UserMylistManager                      = userMylistManager;
            PageManager                            = pageManager;
            _queuePlaylist                         = queuePlaylist;
            _hohoemaPlaylistPlayer                 = hohoemaPlaylistPlayer;
            _NotificationService                   = notificationService;
            _HohoemaDialogService                  = dialogService;
            AddSubscriptionCommand                 = addSubscriptionCommand;
            CreateLocalMylistCommand               = createLocalMylistCommand;
            AddMylistCommand                       = addMylistCommand;
            LocalPlaylistAddItemCommand            = localPlaylistAddItemCommand;
            CreateMylistCommand                    = createMylistCommand;
            _videoStreamingOriginOrchestrator      = videoStreamingOriginOrchestrator;
            CommentPlayer                          = commentPlayer;
            CommentCommandEditerViewModel          = commentCommandEditerViewModel;
            PrimaryViewPlayerManager               = primaryViewPlayerManager;
            TogglePlayerDisplayViewCommand         = togglePlayerDisplayViewCommand;
            ShowPrimaryViewCommand                 = showPrimaryViewCommand;
            SoundVolumeManager                     = soundVolumeManager;
            OpenLinkCommand                        = openLinkCommand;
            CopyToClipboardCommand                 = copyToClipboardCommand;
            ChangeVideoQualityCommand              = changeVideoQualityCommand;
            CopyToClipboardWithShareTextCommand    = copyToClipboardWithShareTextCommand;
            OpenShareUICommand                     = openShareUICommand;
            _playlistSidePaneContentViewModel      = playlistSidePaneContentViewModel;
            _settingsSidePaneContentViewModel      = settingsSidePaneContentViewModel;
            _videoCommentSidePaneContentViewModel  = videoCommentSidePaneContent;
            _relatedVideosSidePaneContentViewModel = relatedVideosSidePaneContentViewModel;
            ObservableMediaPlayer                  = observableMediaPlayer
                                                     .AddTo(_CompositeDisposable);
            VideoEndedRecommendation = videoEndedRecommendation
                                       .AddTo(_CompositeDisposable);
            _keepActiveDisplayWhenPlaying = keepActiveDisplayWhenPlaying
                                            .AddTo(_CompositeDisposable);
            MediaPlayer = mediaPlayer;
            VideoTogglePlayPauseCommand = videoTogglePlayPauseCommand;
            SeekCommand            = new MediaPlayerSeekCommand(MediaPlayer);
            SetPlaybackRateCommand = new MediaPlayerSetPlaybackRateCommand(MediaPlayer);
            ToggleMuteCommand      = new MediaPlayerToggleMuteCommand(MediaPlayer);
            VolumeUpCommand        = new MediaPlayerVolumeUpCommand(SoundVolumeManager);
            VolumeDownCommand      = new MediaPlayerVolumeDownCommand(SoundVolumeManager);

            PlayNextCommand = _hohoemaPlaylistPlayer.GetCanGoNextOrPreviewObservable()
                              .SelectMany(async x => await _hohoemaPlaylistPlayer.CanGoNextAsync())
                              .ToAsyncReactiveCommand()
                              .AddTo(_CompositeDisposable);

            PlayNextCommand.Subscribe(async() => await _hohoemaPlaylistPlayer.GoNextAsync(NavigationCancellationToken))
            .AddTo(_CompositeDisposable);

            PlayPreviousCommand = _hohoemaPlaylistPlayer.GetCanGoNextOrPreviewObservable()
                                  .SelectMany(async x => await _hohoemaPlaylistPlayer.CanGoPreviewAsync())
                                  .ToAsyncReactiveCommand()
                                  .AddTo(_CompositeDisposable);

            PlayPreviousCommand.Subscribe(async() => await _hohoemaPlaylistPlayer.GoPreviewAsync(NavigationCancellationToken))
            .AddTo(_CompositeDisposable);

            IsLoopingEnabled = PlayerSettings.ToReactivePropertyAsSynchronized(x => x.IsCurrentVideoLoopingEnabled, raiseEventScheduler: scheduler)
                               .AddTo(_CompositeDisposable);
            IsLoopingEnabled.Subscribe(x => mediaPlayer.IsLoopingEnabled = x)
            .AddTo(_CompositeDisposable);

            IsPlaylistShuffleRequeted = PlayerSettings.ToReactivePropertyAsSynchronized(x => x.IsShuffleEnable, _scheduler)
                                        .AddTo(_CompositeDisposable);

            IsAvailablePlaylistRepeatOrShuffle = _hohoemaPlaylistPlayer.ObserveProperty(x => x.IsShuffleAndRepeatAvailable)
                                                 .ToReadOnlyReactiveProperty();
        }
Example #17
0
        /// <summary>
        /// Ensures that we have a data feed to convert this currency into the base currency.
        /// This will add a <see cref="SubscriptionDataConfig"/> and create a <see cref="Security"/> at the lowest resolution if one is not found.
        /// </summary>
        /// <param name="securities">The security manager</param>
        /// <param name="subscriptions">The subscription manager used for searching and adding subscriptions</param>
        /// <param name="marketMap">The market map that decides which market the new security should be in</param>
        /// <param name="changes">Will be used to consume <see cref="SecurityChanges.AddedSecurities"/></param>
        /// <param name="securityService">Will be used to create required new <see cref="Security"/></param>
        /// <param name="accountCurrency">The account currency</param>
        /// <returns>Returns the added <see cref="SubscriptionDataConfig"/>, otherwise null</returns>
        public SubscriptionDataConfig EnsureCurrencyDataFeed(SecurityManager securities,
                                                             SubscriptionManager subscriptions,
                                                             IReadOnlyDictionary <SecurityType, string> marketMap,
                                                             SecurityChanges changes,
                                                             ISecurityService securityService,
                                                             string accountCurrency
                                                             )
        {
            // this gets called every time we add securities using universe selection,
            // so must of the time we've already resolved the value and don't need to again
            if (ConversionRateSecurity != null)
            {
                return(null);
            }

            AccountCurrency = accountCurrency;

            if (Symbol == AccountCurrency)
            {
                ConversionRateSecurity = null;
                _isBaseCurrency        = true;
                ConversionRate         = 1.0m;
                return(null);
            }

            // we require a security that converts this into the base currency
            string normal             = Symbol + AccountCurrency;
            string invert             = AccountCurrency + Symbol;
            var    securitiesToSearch = securities.Select(kvp => kvp.Value)
                                        .Concat(changes.AddedSecurities)
                                        .Where(s => s.Type == SecurityType.Forex || s.Type == SecurityType.Cfd || s.Type == SecurityType.Crypto);

            foreach (var security in securitiesToSearch)
            {
                if (security.Symbol.Value == normal)
                {
                    ConversionRateSecurity = security;
                    return(null);
                }
                if (security.Symbol.Value == invert)
                {
                    ConversionRateSecurity = security;
                    _invertRealTimePrice   = true;
                    return(null);
                }
            }
            // if we've made it here we didn't find a security, so we'll need to add one

            // Create a SecurityType to Market mapping with the markets from SecurityManager members
            var markets = securities.Select(x => x.Key).GroupBy(x => x.SecurityType).ToDictionary(x => x.Key, y => y.First().ID.Market);

            if (markets.ContainsKey(SecurityType.Cfd) && !markets.ContainsKey(SecurityType.Forex))
            {
                markets.Add(SecurityType.Forex, markets[SecurityType.Cfd]);
            }
            if (markets.ContainsKey(SecurityType.Forex) && !markets.ContainsKey(SecurityType.Cfd))
            {
                markets.Add(SecurityType.Cfd, markets[SecurityType.Forex]);
            }

            var potentials = Currencies.CurrencyPairs.Select(fx => CreateSymbol(marketMap, fx, markets, SecurityType.Forex))
                             .Concat(Currencies.CfdCurrencyPairs.Select(cfd => CreateSymbol(marketMap, cfd, markets, SecurityType.Cfd)))
                             .Concat(Currencies.CryptoCurrencyPairs.Select(crypto => CreateSymbol(marketMap, crypto, markets, SecurityType.Crypto)));

            var minimumResolution = subscriptions.Subscriptions.Select(x => x.Resolution).DefaultIfEmpty(Resolution.Minute).Min();

            foreach (var symbol in potentials)
            {
                if (symbol.Value == normal || symbol.Value == invert)
                {
                    _invertRealTimePrice = symbol.Value == invert;
                    var securityType = symbol.ID.SecurityType;

                    // use the first subscription defined in the subscription manager
                    var type       = subscriptions.LookupSubscriptionConfigDataTypes(securityType, minimumResolution, false).First();
                    var objectType = type.Item1;
                    var tickType   = type.Item2;

                    // set this as an internal feed so that the data doesn't get sent into the algorithm's OnData events
                    var config = subscriptions.SubscriptionDataConfigService.Add(symbol,
                                                                                 minimumResolution,
                                                                                 fillForward: true,
                                                                                 extendedMarketHours: false,
                                                                                 isInternalFeed: true,
                                                                                 subscriptionDataTypes: new List <Tuple <Type, TickType> > {
                        new Tuple <Type, TickType>(objectType, tickType)
                    }).First();

                    var security = securityService.CreateSecurity(symbol,
                                                                  config,
                                                                  addToSymbolCache: false);

                    ConversionRateSecurity = security;
                    securities.Add(config.Symbol, security);
                    Log.Trace("Cash.EnsureCurrencyDataFeed(): Adding " + symbol.Value + " for cash " + Symbol + " currency feed");
                    return(config);
                }
            }

            // if this still hasn't been set then it's an error condition
            throw new ArgumentException(string.Format("In order to maintain cash in {0} you are required to add a subscription for Forex pair {0}{1} or {1}{0}", Symbol, AccountCurrency));
        }
 public TestAlgorithm(Action beforePostInitializeAction = null)
 {
     _beforePostInitializeAction = beforePostInitializeAction;
     SubscriptionManager.SetDataManager(new DataManagerStub(this, new MockDataFeed(), liveMode: true));
 }
 /// <summary>
 /// Used to deploy a cloud service package to Azure 
 /// </summary>
 public void DeployServiceToAzure(PaaSDeploymentSettings settings)
 {
     var manager = new SubscriptionManager(SubscriptionId);
     manager.GetDeploymentManager()
         .AddCertificate(ManagementCertificate)
         .ForNewDeployment(settings.CloudServiceName)
         .SetCspkgEndpoint(settings.CspkgStorageEndpoint, settings.CscfgConfig)
         .WithNewHostedService(settings.CloudServiceName)
         .WithStorageAccount(settings.StorageAccountName)
         .AddEnvironment(DeploymentSlot.Production)
         .AddLocation(settings.Location)
         .AddParams(DeploymentParams.StartImmediately)
         .WaitUntilAllRoleInstancesAreRunning()
         .Go()
         .Commit();
 }
Example #20
0
 /// <summary>
 /// Removes the specified configuration
 /// </summary>
 /// <param name="dataConfig">Subscription config to be removed</param>
 public void Unsubscribe(SubscriptionDataConfig dataConfig)
 {
     SubscriptionManager.Unsubscribe(dataConfig);
     _aggregator.Remove(dataConfig);
 }
Example #21
0
    /// <summary>
    /// This will be called when Unity IAP has finished initialising.
    /// </summary>
    public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
    {
        m_Controller                   = controller;
        m_AppleExtensions              = extensions.GetExtension <IAppleExtensions>();
        m_SamsungExtensions            = extensions.GetExtension <ISamsungAppsExtensions>();
        m_MicrosoftExtensions          = extensions.GetExtension <IMicrosoftExtensions>();
        m_TransactionHistoryExtensions = extensions.GetExtension <ITransactionHistoryExtensions>();
        m_GooglePlayStoreExtensions    = extensions.GetExtension <IGooglePlayStoreExtensions>();
        // Sample code for expose product sku details for google play store
        // Key is product Id (Sku), value is the skuDetails json string
        //Dictionary<string, string> google_play_store_product_SKUDetails_json = m_GooglePlayStoreExtensions.GetProductJSONDictionary();
        // Sample code for manually finish a transaction (consume a product on GooglePlay store)
        //m_GooglePlayStoreExtensions.FinishAdditionalTransaction(productId, transactionId);
        m_GooglePlayStoreExtensions.SetLogLevel(0); // 0 == debug, info, warning, error. 1 == warning, error only.

        InitUI(controller.products.all);

        // On Apple platforms we need to handle deferred purchases caused by Apple's Ask to Buy feature.
        // On non-Apple platforms this will have no effect; OnDeferred will never be called.
        m_AppleExtensions.RegisterPurchaseDeferredListener(OnDeferred);

#if SUBSCRIPTION_MANAGER
        Dictionary <string, string> introductory_info_dict = m_AppleExtensions.GetIntroductoryPriceDictionary();
#endif
        // Sample code for expose product sku details for apple store
        //Dictionary<string, string> product_details = m_AppleExtensions.GetProductDetails();


        Debug.Log("Available items:");
        foreach (var item in controller.products.all)
        {
            if (item.availableToPurchase)
            {
                Debug.Log(string.Join(" - ",
                                      new[]
                {
                    item.metadata.localizedTitle,
                    item.metadata.localizedDescription,
                    item.metadata.isoCurrencyCode,
                    item.metadata.localizedPrice.ToString(),
                    item.metadata.localizedPriceString,
                    item.transactionID,
                    item.receipt
                }));
#if INTERCEPT_PROMOTIONAL_PURCHASES
                // Set all these products to be visible in the user's App Store according to Apple's Promotional IAP feature
                // https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StoreKitGuide/PromotingIn-AppPurchases/PromotingIn-AppPurchases.html
                m_AppleExtensions.SetStorePromotionVisibility(item, AppleStorePromotionVisibility.Show);
#endif

#if SUBSCRIPTION_MANAGER
                // this is the usage of SubscriptionManager class
                if (item.receipt != null)
                {
                    if (item.definition.type == ProductType.Subscription)
                    {
                        if (checkIfProductIsAvailableForSubscriptionManager(item.receipt))
                        {
                            string intro_json        = (introductory_info_dict == null || !introductory_info_dict.ContainsKey(item.definition.storeSpecificId)) ? null : introductory_info_dict[item.definition.storeSpecificId];
                            SubscriptionManager p    = new SubscriptionManager(item, intro_json);
                            SubscriptionInfo    info = p.getSubscriptionInfo();
                            Debug.Log("product id is: " + info.getProductId());
                            Debug.Log("purchase date is: " + info.getPurchaseDate());
                            Debug.Log("subscription next billing date is: " + info.getExpireDate());
                            Debug.Log("is subscribed? " + info.isSubscribed().ToString());
                            Debug.Log("is expired? " + info.isExpired().ToString());
                            Debug.Log("is cancelled? " + info.isCancelled());
                            Debug.Log("product is in free trial peroid? " + info.isFreeTrial());
                            Debug.Log("product is auto renewing? " + info.isAutoRenewing());
                            Debug.Log("subscription remaining valid time until next billing date is: " + info.getRemainingTime());
                            Debug.Log("is this product in introductory price period? " + info.isIntroductoryPricePeriod());
                            Debug.Log("the product introductory localized price is: " + info.getIntroductoryPrice());
                            Debug.Log("the product introductory price period is: " + info.getIntroductoryPricePeriod());
                            Debug.Log("the number of product introductory price period cycles is: " + info.getIntroductoryPricePeriodCycles());
                        }
                        else
                        {
                            Debug.Log("This product is not available for SubscriptionManager class, only products that are purchase by 1.19+ SDK can use this class.");
                        }
                    }
                    else
                    {
                        Debug.Log("the product is not a subscription product");
                    }
                }
                else
                {
                    Debug.Log("the product should have a valid receipt");
                }
#endif
            }
        }

        // Populate the product menu now that we have Products
        AddProductUIs(m_Controller.products.all);

        LogProductDefinitions();
    }
 public Series(SubscriptionManager.DataLayer.DataTables.ComicBookSeries series)
 {
     FillProperties(series);
 }
Example #23
0
        /// <summary>
        /// Starts data generation
        /// </summary>
        public void Run()
        {
            var tickTypesPerSecurityType = SubscriptionManager.DefaultDataTypes();
            // can specify a seed value in this ctor if determinism is desired
            var random = new Random();
            var randomValueGenerator = new RandomValueGenerator();

            if (_settings.RandomSeedSet)
            {
                random = new Random(_settings.RandomSeed);
                randomValueGenerator = new RandomValueGenerator(_settings.RandomSeed);
            }

            var symbolGenerator = BaseSymbolGenerator.Create(_settings, randomValueGenerator);

            var maxSymbolCount = symbolGenerator.GetAvailableSymbolCount();

            if (_settings.SymbolCount > maxSymbolCount)
            {
                Log.Error($"RandomDataGenerator.Run(): Limiting Symbol count to {maxSymbolCount}, we don't have more {_settings.SecurityType} tickers for {_settings.Market}");
                _settings.SymbolCount = maxSymbolCount;
            }

            Log.Trace($"RandomDataGenerator.Run(): Begin data generation of {_settings.SymbolCount} randomly generated {_settings.SecurityType} assets...");

            // iterate over our randomly generated symbols
            var count         = 0;
            var progress      = 0d;
            var previousMonth = -1;

            foreach (var(symbolRef, currentSymbolGroup) in symbolGenerator.GenerateRandomSymbols()
                     .GroupBy(s => s.HasUnderlying ? s.Underlying : s)
                     .Select(g => (g.Key, g.OrderBy(s => s.HasUnderlying).ToList())))
            {
                Log.Trace($"RandomDataGenerator.Run(): Symbol[{++count}]: {symbolRef} Progress: {progress:0.0}% - Generating data...");

                var      tickGenerators     = new List <IEnumerator <Tick> >();
                var      tickHistories      = new Dictionary <Symbol, List <Tick> >();
                Security underlyingSecurity = null;
                foreach (var currentSymbol in currentSymbolGroup)
                {
                    if (!_securityManager.TryGetValue(currentSymbol, out var security))
                    {
                        security = _securityManager.CreateSecurity(
                            currentSymbol,
                            new List <SubscriptionDataConfig>(),
                            underlying: underlyingSecurity);
                        _securityManager.Add(security);
                    }

                    underlyingSecurity ??= security;

                    tickGenerators.Add(
                        new TickGenerator(_settings, tickTypesPerSecurityType[currentSymbol.SecurityType].ToArray(), security, randomValueGenerator)
                        .GenerateTicks()
                        .GetEnumerator());

                    tickHistories.Add(
                        currentSymbol,
                        new List <Tick>());
                }

                using var sync = new SynchronizingEnumerator(tickGenerators);
                while (sync.MoveNext())
                {
                    var dataPoint = sync.Current;
                    if (!_securityManager.TryGetValue(dataPoint.Symbol, out var security))
                    {
                        Log.Error($"RandomDataGenerator.Run(): Could not find security for symbol {sync.Current.Symbol}");
                        continue;
                    }

                    tickHistories[security.Symbol].Add(dataPoint as Tick);
                    security.Update(new List <BaseData> {
                        dataPoint
                    }, dataPoint.GetType(), false);
                }

                foreach (var(currentSymbol, tickHistory) in tickHistories)
                {
                    var symbol = currentSymbol;

                    // This is done so that we can update the Symbol in the case of a rename event
                    var delistDate     = GetDelistingDate(_settings.Start, _settings.End, randomValueGenerator);
                    var willBeDelisted = randomValueGenerator.NextBool(1.0);

                    // Companies rarely IPO then disappear within 6 months
                    if (willBeDelisted && tickHistory.Select(tick => tick.Time.Month).Distinct().Count() <= 6)
                    {
                        willBeDelisted = false;
                    }

                    var dividendsSplitsMaps = new DividendSplitMapGenerator(
                        symbol,
                        _settings,
                        randomValueGenerator,
                        symbolGenerator,
                        random,
                        delistDate,
                        willBeDelisted);

                    // Keep track of renamed symbols and the time they were renamed.
                    var renamedSymbols = new Dictionary <Symbol, DateTime>();

                    if (_settings.SecurityType == SecurityType.Equity)
                    {
                        dividendsSplitsMaps.GenerateSplitsDividends(tickHistory);

                        if (!willBeDelisted)
                        {
                            dividendsSplitsMaps.DividendsSplits.Add(new CorporateFactorRow(new DateTime(2050, 12, 31), 1m, 1m));

                            if (dividendsSplitsMaps.MapRows.Count > 1)
                            {
                                // Remove the last element if we're going to have a 20501231 entry
                                dividendsSplitsMaps.MapRows.RemoveAt(dividendsSplitsMaps.MapRows.Count - 1);
                            }
                            dividendsSplitsMaps.MapRows.Add(new MapFileRow(new DateTime(2050, 12, 31), dividendsSplitsMaps.CurrentSymbol.Value));
                        }

                        // If the Symbol value has changed, update the current Symbol
                        if (symbol != dividendsSplitsMaps.CurrentSymbol)
                        {
                            // Add all Symbol rename events to dictionary
                            // We skip the first row as it contains the listing event instead of a rename event
                            foreach (var renameEvent in dividendsSplitsMaps.MapRows.Skip(1))
                            {
                                // Symbol.UpdateMappedSymbol does not update the underlying security ID Symbol, which
                                // is used to create the hash code. Create a new equity Symbol from scratch instead.
                                symbol = Symbol.Create(renameEvent.MappedSymbol, SecurityType.Equity, _settings.Market);
                                renamedSymbols.Add(symbol, renameEvent.Date);

                                Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {symbol} will be renamed on {renameEvent.Date}");
                            }
                        }
                        else
                        {
                            // This ensures that ticks will be written for the current Symbol up until 9999-12-31
                            renamedSymbols.Add(symbol, new DateTime(9999, 12, 31));
                        }

                        symbol = dividendsSplitsMaps.CurrentSymbol;

                        // Write Splits and Dividend events to directory factor_files
                        var factorFile = new CorporateFactorProvider(symbol.Value, dividendsSplitsMaps.DividendsSplits, _settings.Start);
                        var mapFile    = new MapFile(symbol.Value, dividendsSplitsMaps.MapRows);

                        factorFile.WriteToFile(symbol);
                        mapFile.WriteToCsv(_settings.Market, symbol.SecurityType);

                        Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {symbol} Dividends, splits, and map files have been written to disk.");
                    }
                    else
                    {
                        // This ensures that ticks will be written for the current Symbol up until 9999-12-31
                        renamedSymbols.Add(symbol, new DateTime(9999, 12, 31));
                    }

                    // define aggregators via settings
                    var    aggregators    = CreateAggregators(_settings, tickTypesPerSecurityType[currentSymbol.SecurityType].ToArray()).ToList();
                    Symbol previousSymbol = null;
                    var    currentCount   = 0;
                    var    monthsTrading  = 0;

                    foreach (var renamed in renamedSymbols)
                    {
                        var previousRenameDate    = previousSymbol == null ? new DateTime(1, 1, 1) : renamedSymbols[previousSymbol];
                        var previousRenameDateDay = new DateTime(previousRenameDate.Year, previousRenameDate.Month, previousRenameDate.Day);
                        var renameDate            = renamed.Value;
                        var renameDateDay         = new DateTime(renameDate.Year, renameDate.Month, renameDate.Day);

                        foreach (var tick in tickHistory.Where(tick => tick.Time >= previousRenameDate && previousRenameDateDay != TickDay(tick)))
                        {
                            // Prevents the aggregator from being updated with ticks after the rename event
                            if (TickDay(tick) > renameDateDay)
                            {
                                break;
                            }

                            if (tick.Time.Month != previousMonth)
                            {
                                Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: Month: {tick.Time:MMMM}");
                                previousMonth = tick.Time.Month;
                                monthsTrading++;
                            }

                            foreach (var item in aggregators)
                            {
                                tick.Value = tick.Value / dividendsSplitsMaps.FinalSplitFactor;
                                item.Consolidator.Update(tick);
                            }

                            if (monthsTrading >= 6 && willBeDelisted && tick.Time > delistDate)
                            {
                                Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {renamed.Key} delisted at {tick.Time:MMMM yyyy}");
                                break;
                            }
                        }

                        // count each stage as a point, so total points is 2*Symbol-count
                        // and the current progress is twice the current, but less one because we haven't finished writing data yet
                        progress = 100 * (2 * count - 1) / (2.0 * _settings.SymbolCount);

                        Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {renamed.Key} Progress: {progress:0.0}% - Saving data in LEAN format");

                        // persist consolidated data to disk
                        foreach (var item in aggregators)
                        {
                            var writer = new LeanDataWriter(item.Resolution, renamed.Key, Globals.DataFolder, item.TickType);

                            // send the flushed data into the writer. pulling the flushed list is very important,
                            // lest we likely wouldn't get the last piece of data stuck in the consolidator
                            // Filter out the data we're going to write here because filtering them in the consolidator update phase
                            // makes it write all dates for some unknown reason
                            writer.Write(item.Flush().Where(data => data.Time > previousRenameDate && previousRenameDateDay != DataDay(data)));
                        }

                        // update progress
                        progress = 100 * (2 * count) / (2.0 * _settings.SymbolCount);
                        Log.Trace($"RandomDataGenerator.Run(): Symbol[{count}]: {symbol} Progress: {progress:0.0}% - Symbol data generation and output completed");

                        previousSymbol = renamed.Key;
                        currentCount++;
                    }
                }
            }

            Log.Trace("RandomDataGenerator.Run(): Random data generation has completed.");

            DateTime TickDay(Tick tick) => new(tick.Time.Year, tick.Time.Month, tick.Time.Day);
            DateTime DataDay(BaseData data) => new(data.Time.Year, data.Time.Month, data.Time.Day);
        }