public static void AddSubscriptionToObject(string targetLocation, string subscriberLocation, string subscriptionType, string targetTypeName = null, string subscriberTypeName = null) { if(targetLocation == subscriberLocation) throw new InvalidDataException("Self-circular subscription targeting self attempted: " + targetLocation); var sub = GetSubscriptionToObject(targetLocation, subscriberLocation, subscriptionType, targetTypeName:targetTypeName, subscriberTypeName:subscriberTypeName); SubscriptionCollection subscriptionCollection = GetSubscriptions(targetLocation); if(subscriptionCollection == null) { subscriptionCollection = new SubscriptionCollection(); subscriptionCollection.SetRelativeLocationAsMetadataTo(targetLocation); } var alreadyExists = subscriptionCollection.CollectionContent.FirstOrDefault( existing => existing.SubscriberRelativeLocation == sub.SubscriberRelativeLocation && existing.SubscriptionType == sub.SubscriptionType); if(alreadyExists != null) { // If the values match, don't save when there are no changes if (alreadyExists.SubscriberInformationObjectType == sub.SubscriberInformationObjectType && alreadyExists.TargetInformationObjectType == sub.TargetInformationObjectType) return; // ... otherwise update the values alreadyExists.SubscriberInformationObjectType = sub.SubscriberInformationObjectType; alreadyExists.TargetInformationObjectType = sub.TargetInformationObjectType; } else { subscriptionCollection.CollectionContent.Add(sub); } StorageSupport.StoreInformation(subscriptionCollection); }
/// <summary> /// Initializes the data feed for the specified job and algorithm /// </summary> public void Initialize(IAlgorithm algorithm, AlgorithmNodePacket job, IResultHandler resultHandler, IMapFileProvider mapFileProvider, IFactorFileProvider factorFileProvider) { _algorithm = algorithm; _resultHandler = resultHandler; _mapFileProvider = mapFileProvider; _factorFileProvider = factorFileProvider; _subscriptions = new SubscriptionCollection(); _universeSelection = new UniverseSelection(this, algorithm, job.Controls); _cancellationTokenSource = new CancellationTokenSource(); IsActive = true; var threadCount = Math.Max(1, Math.Min(4, Environment.ProcessorCount - 3)); _controller = new ParallelRunnerController(threadCount); _controller.Start(_cancellationTokenSource.Token); var ffres = Time.OneMinute; _fillForwardResolution = Ref.Create(() => ffres, res => ffres = res); // wire ourselves up to receive notifications when universes are added/removed algorithm.UniverseManager.CollectionChanged += (sender, args) => { switch (args.Action) { case NotifyCollectionChangedAction.Add: foreach (var universe in args.NewItems.OfType<Universe>()) { var config = universe.Configuration; var start = _frontierUtc != DateTime.MinValue ? _frontierUtc : _algorithm.StartDate.ConvertToUtc(_algorithm.TimeZone); var marketHoursDatabase = MarketHoursDatabase.FromDataFolder(); var exchangeHours = marketHoursDatabase.GetExchangeHours(config); Security security; if (!_algorithm.Securities.TryGetValue(config.Symbol, out security)) { // create a canonical security object if it doesn't exist security = new Security(exchangeHours, config, _algorithm.Portfolio.CashBook[CashBook.AccountCurrency], SymbolProperties.GetDefault(CashBook.AccountCurrency)); } var end = _algorithm.EndDate.ConvertToUtc(_algorithm.TimeZone); AddSubscription(new SubscriptionRequest(true, universe, security, config, start, end)); } break; case NotifyCollectionChangedAction.Remove: foreach (var universe in args.OldItems.OfType<Universe>()) { RemoveSubscription(universe.Configuration); } break; default: throw new NotImplementedException("The specified action is not implemented: " + args.Action); } }; }
public void FillForwardResolutionIgnoresInternalFeed() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second, "AAPL", true); subscriptionColletion.TryAdd(subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 1, 0)); subscriptionColletion.TryRemove(subscription.Configuration, out subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 1, 0)); }
public void GettingSpecificSubscription() { #region Snippet:Hello_World_SpecificSubscription string subscriptionId = "your-subscription-id"; ArmClient client = new ArmClient(new DefaultAzureCredential()); SubscriptionCollection subscriptions = client.GetSubscriptions(); SubscriptionResource subscription = subscriptions.Get(subscriptionId); Console.WriteLine($"Got subscription: {subscription.Data.DisplayName}"); #endregion Snippet:Hello_World_SpecificSubscription }
public void UpdatesFillForwardResolutionSuccessfullyWhenNotAdding() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second); var fillForwardResolutio = subscriptionColletion.UpdateAndGetFillForwardResolution(subscription.Configuration); Assert.AreEqual(fillForwardResolutio.Value, new TimeSpan(0, 0, 1)); subscription.Dispose(); }
public void UpdatesFillForwardResolutionOverridesDefaultWhenNotAdding() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Daily); var fillForwardResolutio = subscriptionColletion.UpdateAndGetFillForwardResolution(subscription.Configuration); Assert.AreEqual(fillForwardResolutio.Value, new TimeSpan(1, 0, 0, 0)); subscription.Dispose(); }
public void Start() { _subscriptions = new SubscriptionCollection(_messageBus); // On Core initialization, startup all necessary Stitches _subscriptions.Subscribe <CoreEvent>(b => b .WithChannelName(CoreEvent.ChannelInitialized) .Invoke(m => _service.StartRunningStitchesOnStartup()) .OnWorkerThread()); // Upload package files _subscriptions.Listen <PackageFileUploadRequest, PackageFileUploadResponse>(l => l .WithChannelName(PackageFileUploadRequest.ChannelLocal) .Invoke(_service.UploadStitchPackageFile)); _subscriptions.Listen <PackageFileUploadRequest, PackageFileUploadResponse>(l => l .WithChannelName(PackageFileUploadRequest.ChannelFromRemote) .Invoke(_service.UploadStitchPackageFileFromRemote)); _subscriptions.Listen <LocalCreateInstanceRequest, LocalCreateInstanceResponse>(l => l .OnDefaultChannel() .Invoke(_service.CreateNewInstance)); _subscriptions.Listen <InstanceRequest, InstanceResponse>(l => l .WithChannelName(InstanceRequest.ChannelClone) .Invoke(_service.CloneInstance)); _subscriptions.Listen <InstanceRequest, InstanceResponse>(l => l .WithChannelName(InstanceRequest.ChannelStart) .Invoke(_service.StartInstance)); _subscriptions.Listen <InstanceRequest, InstanceResponse>(l => l .WithChannelName(InstanceRequest.ChannelStop) .Invoke(_service.StopInstance)); _subscriptions.Listen <InstanceRequest, InstanceResponse>(l => l .WithChannelName(InstanceRequest.ChannelDelete) .Invoke(_service.DeleteStitchInstance)); _subscriptions.Listen <InstanceInformationRequest, List <InstanceInformation> >(l => l .OnDefaultChannel() .Invoke(m => _service.GetInstanceInformation())); _subscriptions.Listen <StitchResourceUsageRequest, StitchResourceUsage>(l => l .OnDefaultChannel() .Invoke(m => _service.GetInstanceResources(m.StitchInstanceId))); _subscriptions.Subscribe <StitchDataMessage>(b => b .WithChannelName(StitchDataMessage.ChannelSendLocal) .Invoke(_service.SendDataMessageToStitch) .OnWorkerThread() .WithFilter(m => !string.IsNullOrEmpty(m.ToStitchInstanceId))); _subscriptions.Subscribe <ObjectReceivedEvent <StitchDataMessage> >(b => b .WithChannelName(ReceivedEvent.ChannelReceived) .Invoke(m => _service.SendDataMessageToStitch(m.Object))); _subscriptions.Subscribe <SendHeartbeatEvent>(b => b .OnDefaultChannel() .Invoke(m => _service.SendHeartbeat(m.HeartbeatId))); }
public void FillForwardResolutionIgnoresTick() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Tick); subscriptionColletion.TryAdd(subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 1, 0)); subscriptionColletion.TryRemove(subscription.Configuration, out subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 1, 0)); subscription.Dispose(); }
public void Stop() { if (_subscriptions == null) { return; } _subscriptions.Dispose(); _subscriptions = null; _messageBus.ThreadPool.StopDedicatedWorker(_workerThreadId); _workerThreadId = 0; }
public async Task GettingSpecificSubscriptionAsync() { #region Snippet:Hello_World_Async_SpecificSubscription string subscriptionId = "your-subscription-id"; ArmClient client = new ArmClient(new DefaultAzureCredential()); SubscriptionCollection subscriptions = client.GetSubscriptions(); SubscriptionResource subscription = await subscriptions.GetAsync(subscriptionId); Console.WriteLine(subscription.Id); #endregion Snippet:Hello_World_Async_SpecificSubscription }
public void DoesNotUpdateFillForwardResolutionWhenAddingBiggerResolution() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second); var subscription2 = CreateSubscription(Resolution.Minute); subscriptionColletion.TryAdd(subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 0, 1)); subscriptionColletion.TryAdd(subscription2); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 0, 1)); }
public StitchMonitorModule(CrossStitchCore core, NodeConfiguration configuration) { _configuration = configuration; var log = new ModuleLog(core.MessageBus, Name); var calculator = new StitchHealthCalculator(configuration.MissedHeartbeatsThreshold); var heartbeatSender = new HeartbeatSender(core.MessageBus); var healthNotifier = new StitchHealthNotifier(core.MessageBus); _heartbeatService = new StitchHeartbeatService(log, heartbeatSender, healthNotifier, calculator); _subscriptions = new SubscriptionCollection(core.MessageBus); }
private static Notification CreateNotification(SubscriptionCollection subscription, IEnumerable <FeedInfo> feed) { var matchingFeeds = feed .Where(f => Filter(f, subscription.SubscribedAnimes)) .Select( x => new SubscribedFeed(OptionUtils.UnpackOption(x.AnimeTitle.Value, string.Empty), x.Links, x.EpisodeInfo, x.PublicationDate)); return(new Notification(subscription.SubscriptionId, matchingFeeds)); }
public void Stop() { _backplane.Stop(); _backplane.MessageReceived -= MessageReceivedHandler; _backplane.ClusterMember -= ClusterMemberHandler; _backplane.ZoneMember -= ZoneMemberHandler; _subscriptions.Dispose(); _subscriptions = null; _messageBus.ThreadPool.StopDedicatedWorker(_workerThreadId); }
public ActionResult Save(Bam.Net.CoreServices.ApplicationRegistration.Dao.Subscription[] values) { try { SubscriptionCollection saver = new SubscriptionCollection(); saver.AddRange(values); saver.Save(); return(Json(new { Success = true, Message = "", Dao = "" })); } catch (Exception ex) { return(GetErrorResult(ex)); } }
public BackplaneModule(CrossStitchCore core, IClusterBackplane backplane = null, BackplaneConfiguration configuration = null) { _messageBus = core.MessageBus; _subscriptions = new SubscriptionCollection(_messageBus); _log = new ModuleLog(_messageBus, Name); _configuration = configuration ?? BackplaneConfiguration.GetDefault(); _backplane = backplane ?? new ZyreBackplane(core, _configuration); // Forward messages from the backplane to the IMessageBus _backplane.MessageReceived += MessageReceivedHandler; _backplane.ClusterMember += ClusterMemberHandler; _backplane.ZoneMember += ZoneMemberHandler; }
public MasterModule(CrossStitchCore core, NodeConfiguration configuration) { _configuration = configuration; _messageBus = core.MessageBus; _log = new ModuleLog(core.MessageBus, Name); var data = new DataHelperClient(core.MessageBus); _data = new MasterDataRepository(core.NodeId, data); var stitches = new StitchRequestHandler(core.MessageBus); var sender = new ClusterMessageSender(core.MessageBus); _service = new MasterService(core, _log, _data, stitches, sender); _subscriptions = new SubscriptionCollection(_messageBus); }
public void UpdatesFillForwardResolutionWhenRemoving() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second); var subscription2 = CreateSubscription(Resolution.Daily); subscriptionColletion.TryAdd(subscription); subscriptionColletion.TryAdd(subscription2); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 0, 1)); subscriptionColletion.TryRemove(subscription.Configuration, out subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(1, 0, 0, 0)); subscriptionColletion.TryRemove(subscription2.Configuration, out subscription2); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 1, 0)); }
/// <summary> /// Contructs a server by de-serializing its OpcUrl from the stream. /// </summary> protected TsCAeServer(SerializationInfo info, StreamingContext context) : base(info, context) { int count = (int)info.GetValue(Names.COUNT, typeof(int)); _subscriptions = new SubscriptionCollection(); for (int ii = 0; ii < count; ii++) { Ae.TsCAeSubscription subscription = (Ae.TsCAeSubscription)info.GetValue(Names.SUBSCRIPTION + ii.ToString(), typeof(Ae.TsCAeSubscription)); _subscriptions.Add(subscription); } }
public static void NotifySubscribers(string targetLocation) { var ictx = InformationContext.Current; if (ictx.IsExecutingSubscriptions) { return; } SubscriptionCollection subscriptionCollection = GetSubscriptions(targetLocation); string targetParentLocation = GetParentDirectoryTarget(targetLocation); SubscriptionCollection parentSubscriptionCollection = GetSubscriptions(targetParentLocation); if (subscriptionCollection == null && parentSubscriptionCollection == null) { return; } VirtualOwner owner = VirtualOwner.FigureOwner(targetLocation); OwnerSubscriptionItem subscriptionItem = new OwnerSubscriptionItem { Owner = owner, TargetLocation = targetLocation }; ictx.AddSubscriptionUpdateTarget(subscriptionItem); return; if (subscriptionCollection != null) { foreach (var subscription in subscriptionCollection.CollectionContent) { OperationRequest operationRequest = new OperationRequest { SubscriberNotification = subscription }; //QueueSupport.PutToOperationQueue(operationRequest); ictx.AddOperationRequestToFinalizingQueue(operationRequest); } } if (parentSubscriptionCollection != null) { foreach (var subscription in parentSubscriptionCollection.CollectionContent) { OperationRequest operationRequest = new OperationRequest { SubscriberNotification = subscription }; //QueueSupport.PutToOperationQueue(operationRequest); ictx.AddOperationRequestToFinalizingQueue(operationRequest); } } }
protected Server(SerializationInfo info, StreamingContext context) : base(info, context) { this.m_filters = 0; this.m_disposing = false; this.m_subscriptions = new SubscriptionCollection(); int num = (int)info.GetValue("CT", typeof(int)); this.m_subscriptions = new SubscriptionCollection(); for (int i = 0; i < num; i++) { Subscription subscription = (Subscription)info.GetValue("SU" + i.ToString(), typeof(Subscription)); this.m_subscriptions.Add(subscription); } }
/// <summary> /// Constructs a server by de-serializing its OpcUrl from the stream. /// </summary> protected TsCAeServer(SerializationInfo info, StreamingContext context) : base(info, context) { int count = (int)info.GetValue(Names.Count, typeof(int)); subscriptions_ = new SubscriptionCollection(); for (int ii = 0; ii < count; ii++) { var subscription = (TsCAeSubscription)info.GetValue(Names.Subscription + ii, typeof(TsCAeSubscription)); subscriptions_.Add(subscription); } }
public StitchesModule(CrossStitchCore core, StitchesConfiguration configuration = null) { configuration = configuration ?? StitchesConfiguration.GetDefault(); var log = new ModuleLog(core.MessageBus, Name); var data = new DataHelperClient(core.MessageBus); var observer = new StitchEventObserver(core.MessageBus, data, log); var fileSystem = new StitchFileSystem(configuration, new DateTimeVersionManager()); var adaptorFactory = new StitchAdaptorFactory(core, configuration, fileSystem, log, observer); var manager = new StitchInstanceManager(fileSystem, adaptorFactory); var notifier = new StitchEventNotifier(core.MessageBus); _service = new StitchesService(core, data, fileSystem, manager, log, notifier); _subscriptions = new SubscriptionCollection(core.MessageBus); }
public void AddSubscription(string groupName, List <string> tagList, DataChangedEventHandler onDataChange) { if (!_server.IsConnected) { Console.WriteLine("Connection to OPC server is not established"); return; } // Create group Opc.Da.Subscription group; Opc.Da.SubscriptionState groupState = new Opc.Da.SubscriptionState(); groupState.Name = groupName; groupState.Active = true; groupState.UpdateRate = 200; // Short circuit if group already exists SubscriptionCollection existingCollection = _server.Subscriptions; if (existingCollection.Count > 0) { for (int i = 0; i < existingCollection.Count; i++) { if (existingCollection[i].Name == groupName) { Console.WriteLine(String.Format("Subscription group {0} already exists", groupName)); return; } } } group = (Opc.Da.Subscription)_server.CreateSubscription(groupState); // Create list of items to monitor Item[] opcItems = new Item[1]; int j = 0; foreach (string tag in tagList) { opcItems[j] = new Item(); opcItems[j].ItemName = tag; j++; } // Attach items and event to group group.AddItems(opcItems); //group.DataChanged += new Opc.Da.DataChangedEventHandler(OPCSubscription_DataChanged); group.DataChanged += new Opc.Da.DataChangedEventHandler(onDataChange); }
public void SubscriptionsAreSortedWhenRemoving() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second, Futures.Metals.Gold, false, SecurityType.Future); var subscription2 = CreateSubscription(Resolution.Second, "SPY"); var subscription3 = CreateSubscription(Resolution.Second, "AAPL", false, SecurityType.Option); var subscription4 = CreateSubscription(Resolution.Second, "EURGBP"); var subscription5 = CreateSubscription(Resolution.Second, "AAPL", false, SecurityType.Option, TickType.OpenInterest); var subscription6 = CreateSubscription(Resolution.Second, "AAPL", false, SecurityType.Option, TickType.Quote); subscriptionColletion.TryAdd(subscription); subscriptionColletion.TryAdd(subscription2); subscriptionColletion.TryAdd(subscription3); subscriptionColletion.TryAdd(subscription4); subscriptionColletion.TryAdd(subscription5); subscriptionColletion.TryAdd(subscription6); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription4, subscription2, subscription3, subscription6, subscription5, subscription }); subscriptionColletion.TryRemove(subscription2.Configuration, out subscription2); Assert.AreEqual(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList(), new[] { SecurityType.Equity, SecurityType.Option, SecurityType.Option, SecurityType.Option, SecurityType.Future }); subscriptionColletion.TryRemove(subscription3.Configuration, out subscription3); Assert.AreEqual(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList(), new[] { SecurityType.Equity, SecurityType.Option, SecurityType.Option, SecurityType.Future }); subscriptionColletion.TryRemove(subscription.Configuration, out subscription); Assert.AreEqual(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList(), new[] { SecurityType.Equity, SecurityType.Option, SecurityType.Option }); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription4, subscription6, subscription5 }); subscriptionColletion.TryRemove(subscription6.Configuration, out subscription6); Assert.AreEqual(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList(), new[] { SecurityType.Equity, SecurityType.Option }); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription4, subscription5 }); subscriptionColletion.TryRemove(subscription5.Configuration, out subscription5); Assert.AreEqual(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList(), new[] { SecurityType.Equity }); subscriptionColletion.TryRemove(subscription4.Configuration, out subscription4); Assert.IsTrue(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList().IsNullOrEmpty()); subscription.Dispose(); subscription2.Dispose(); subscription3.Dispose(); subscription4.Dispose(); subscription5.Dispose(); subscription6.Dispose(); }
public void DoesNotUpdateFillForwardResolutionWhenRemovingDuplicateResolution() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second); var subscription2 = CreateSubscription(Resolution.Second, "SPY"); subscriptionColletion.TryAdd(subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 0, 1)); subscriptionColletion.TryAdd(subscription2); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 0, 1)); subscriptionColletion.TryRemove(subscription.Configuration, out subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 0, 1)); subscriptionColletion.TryRemove(subscription2.Configuration, out subscription2); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 1, 0)); subscription.Dispose(); subscription2.Dispose(); }
public void SubscriptionCollection_CreateReport_Test() { var target = new SubscriptionCollection(new MessageBus()); target.Subscribe <int>(b => b .WithTopic("test1") .Invoke(x => { })); target.Listen <int, string>(b => b .WithTopic("test2") .Invoke(x => "ok")); target.Participate <long, DateTime>(b => b .WithTopic("test3") .Invoke(x => DateTime.UtcNow)); var report = target.ReportContents(); report.Length.Should().Be(3); }
public override void Connect(URL url, ConnectData connectData) { base.Connect(url, connectData); if (this.m_subscriptions.Count != 0) { SubscriptionCollection subscriptions = new SubscriptionCollection(); foreach (Subscription subscription in this.m_subscriptions) { try { subscriptions.Add(this.EstablishSubscription(subscription)); } catch { } } this.m_subscriptions = subscriptions; } }
public void SubscriptionsAreSortedWhenAdding2() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second, "GC", false, SecurityType.Future); var subscription2 = CreateSubscription(Resolution.Second, "SPY"); var subscription3 = CreateSubscription(Resolution.Second, "AAPL", false, SecurityType.Option); var subscription4 = CreateSubscription(Resolution.Second, "EURGBP"); subscriptionColletion.TryAdd(subscription); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription }); subscriptionColletion.TryAdd(subscription2); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription2, subscription }); subscriptionColletion.TryAdd(subscription3); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription2, subscription3, subscription }); subscriptionColletion.TryAdd(subscription4); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription4, subscription2, subscription3, subscription }); Assert.AreEqual(subscriptionColletion.Select(x => x.Security.Type).ToList(), new[] { SecurityType.Equity, SecurityType.Equity, SecurityType.Option, SecurityType.Future }); }
private bool TryGetSubscriptionCollection <TEvent>(bool createIfNotExists, out SubscriptionCollection <TEvent>?subscriptionCollection) { var eventType = typeof(TEvent); if (!_subscriptionCollections.TryGetValue(eventType, out var foundCollection)) { if (!createIfNotExists) { subscriptionCollection = null; return(false); } subscriptionCollection = new SubscriptionCollection <TEvent>(); _subscriptionCollections.Add(eventType, subscriptionCollection); return(true); } subscriptionCollection = (SubscriptionCollection <TEvent>)foundCollection; return(true); }
public async Task ManageAvailabilitySetOld() { #region Snippet:Readme_ManageAvailabilitySetOld ResourceIdentifier id = new ResourceIdentifier("/subscriptions/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/resourceGroups/workshop2021-rg/providers/Microsoft.Compute/availabilitySets/ws2021availSet"); // We construct a new client to work with ArmClient client = new ArmClient(new DefaultAzureCredential()); // Next we get the collection of subscriptions SubscriptionCollection subscriptions = client.GetSubscriptions(); // Next we get the specific subscription this resource belongs to Subscription subscription = await subscriptions.GetAsync(id.SubscriptionId); // Next we get the collection of resource groups that belong to that subscription ResourceGroupCollection resourceGroups = subscription.GetResourceGroups(); // Next we get the specific resource group this resource belongs to ResourceGroup resourceGroup = await resourceGroups.GetAsync(id.ResourceGroupName); // Next we get the collection of availability sets that belong to that resource group AvailabilitySetCollection availabilitySets = resourceGroup.GetAvailabilitySets(); // Finally we get the resource itself // Note: for this last step in this example, Azure.ResourceManager.Compute is needed AvailabilitySet availabilitySet = await availabilitySets.GetAsync(id.Name); #endregion Snippet:Readme_ManageAvailabilitySetOld }
public void Start() { _subscriptions = new SubscriptionCollection(_messageBus); int heartbeatTickMultiple = (_configuration.HeartbeatIntervalMinutes * 60) / Timer.MessageTimerModule.TimerIntervalSeconds; _subscriptions.TimerSubscribe(heartbeatTickMultiple, b => b .Invoke(e => _heartbeatService.SendScheduledHeartbeat())); int monitorTickMultiple = (_configuration.StitchMonitorIntervalMinutes * 60) / Timer.MessageTimerModule.TimerIntervalSeconds; _subscriptions.TimerSubscribe(monitorTickMultiple, b => b.Invoke(e => MonitorStitchStatus())); _subscriptions.Subscribe <StitchInstanceEvent>(b => b .WithChannelName(StitchInstanceEvent.ChannelSynced) .Invoke(_heartbeatService.StitchSyncReceived)); _subscriptions.Listen <StitchHealthRequest, StitchHealthResponse>(l => l .OnDefaultChannel() .Invoke(_heartbeatService.GetStitchHealthReport)); }
/// <summary> /// Initializes the data feed for the specified job and algorithm /// </summary> public void Initialize(IAlgorithm algorithm, AlgorithmNodePacket job, IResultHandler resultHandler, IMapFileProvider mapFileProvider, IFactorFileProvider factorFileProvider) { if (!(job is LiveNodePacket)) { throw new ArgumentException("The LiveTradingDataFeed requires a LiveNodePacket."); } _cancellationTokenSource = new CancellationTokenSource(); _algorithm = algorithm; _job = (LiveNodePacket) job; _resultHandler = resultHandler; _timeProvider = GetTimeProvider(); _dataQueueHandler = GetDataQueueHandler(); _frontierTimeProvider = new ManualTimeProvider(_timeProvider.GetUtcNow()); _customExchange = new BaseDataExchange("CustomDataExchange") {SleepInterval = 10}; // sleep is controlled on this exchange via the GetNextTicksEnumerator _exchange = new BaseDataExchange("DataQueueExchange"){SleepInterval = 0}; _exchange.AddEnumerator(DataQueueHandlerSymbol, GetNextTicksEnumerator()); _subscriptions = new SubscriptionCollection(); _bridge = new BusyBlockingCollection<TimeSlice>(); _universeSelection = new UniverseSelection(this, algorithm, job.Controls); // run the exchanges Task.Run(() => _exchange.Start(_cancellationTokenSource.Token)); Task.Run(() => _customExchange.Start(_cancellationTokenSource.Token)); // this value will be modified via calls to AddSubscription/RemoveSubscription var ffres = Time.OneMinute; _fillForwardResolution = Ref.Create(() => ffres, v => ffres = v); // wire ourselves up to receive notifications when universes are added/removed var start = _timeProvider.GetUtcNow(); algorithm.UniverseManager.CollectionChanged += (sender, args) => { switch (args.Action) { case NotifyCollectionChangedAction.Add: foreach (var universe in args.NewItems.OfType<Universe>()) { var config = universe.Configuration; var marketHoursDatabase = MarketHoursDatabase.FromDataFolder(); var exchangeHours = marketHoursDatabase.GetExchangeHours(config); Security security; if (!_algorithm.Securities.TryGetValue(config.Symbol, out security)) { // create a canonical security object security = new Security(exchangeHours, config, _algorithm.Portfolio.CashBook[CashBook.AccountCurrency], SymbolProperties.GetDefault(CashBook.AccountCurrency)); } AddSubscription(new SubscriptionRequest(true, universe, security, config, start, Time.EndOfTime)); // Not sure if this is needed but left here because of this: // https://github.com/QuantConnect/Lean/commit/029d70bde6ca83a1eb0c667bb5cc4444bea05678 UpdateFillForwardResolution(); } break; case NotifyCollectionChangedAction.Remove: foreach (var universe in args.OldItems.OfType<Universe>()) { RemoveSubscription(universe.Configuration); } break; default: throw new NotImplementedException("The specified action is not implemented: " + args.Action); } }; }
/// <summary> /// Saves a set of subscriptions. /// </summary> public void Save(string filePath, IEnumerable<Subscription> subscriptions) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = false; settings.Encoding = Encoding.UTF8; XmlWriter writer = XmlWriter.Create(filePath, settings); SubscriptionCollection subscriptionList = new SubscriptionCollection(subscriptions); try { DataContractSerializer serializer = new DataContractSerializer(typeof(SubscriptionCollection)); serializer.WriteObject(writer, subscriptionList); } finally { writer.Close(); } }