/// <summary> /// Reinitialises the proxy if the user changes the API authentication settings for this proxy /// </summary> /// <param name="m"></param> private void OnSecuredDataChanged(SecuredDataChanged m) { if (m.DataKey == _selectedPair.Exchange.InternalCode) { _proxy = ExchangeProxyFactory.GetProxy(m.DataKey); } }
public void SetUp() { mockBuilder = new MockBuilder(); advancedBus = mockBuilder.Bus.Advanced; exchange = advancedBus.ExchangeDeclare("my_exchange", ExchangeType.Direct, passive:true); }
public void Bind(IExchange destination, IExchange source, params string[] topics) { foreach (var topic in topics) { _model.ExchangeBind(destination.Name, source.Name, topic); } }
/// <summary> /// Called when the main screen's exchange changes /// </summary> /// <param name="message"></param> private void OnExchangeSelected(ExchangeSelected message) { if (message.SelectorType == SelectorType.Main) { _proxy = ExchangeProxyFactory.GetProxy(message.InternalCode); } }
public Index(string isin, string symbol, string name, IExchange exchange) { this.isin = isin; this.symbol = symbol; this.name = name; this.exchange = exchange; }
public MessagePublisher(IAdvancedBus bus, ILogger logger, IExchange exchange, IQueue queue) { _bus = bus; _logger = logger; _exchange = exchange; _queue = queue; }
private bool Compare(IExchange exchange1, IExchange exchange2) { var quote1 = exchange1.GetLastQuote(); var quote2 = exchange2.GetLastQuote(); if (quote1 == null || quote2 == null) return false; if (quote1.Bid <= quote2.Ask) return false; #region -- Prepare -- string desc = string.Format("Arb detected, buy {1} sell {0}", quote1.SourceExchange, quote2.SourceExchange); Console.WriteLine(desc); decimal qty = 1; //Determine this based on how much cash is left #endregion #region -- Execution -- var trade = new Trade(desc); /* trade.Transactions.Add(new MarketOrderBuyBTCTransaction(exchange1, qty, quote1.Bid)); trade.Transactions.Add(new MarketOrderSellBTCTransaction(exchange2, qty, quote1.Bid)); */ //notificationEngine.TradeSignal(quote1, quote2); notificationEngine.TradeSignal(trade); #endregion return true; }
public DerivativeMaster(string name, SecCategories secCategory, IExchange exchange) : this() { this.Name = name; this.SecCategory = secCategory; this.Exchange = exchange; }
public void PublishRaw(IExchange exchange, byte[] body, string route) { var properties = _model.CreateBasicProperties(); properties.Persistent = true; _model.BasicPublish(exchange.Name, route, properties, body); }
public PercentageFeeCurrencyWallet(decimal entryPercentFee, decimal exitPercentFee, CurrencyType currencyWallet, IExchange exchange) { _exchange = exchange; _entryPercentFee = entryPercentFee; _exitPercentFee = exitPercentFee; Currency = currencyWallet; }
public FixedFeeCurrencyWallet(decimal entryFixedFee, decimal exitFixedFee, CurrencyType currencyType, IExchange exchange) { _entryFixedFee = entryFixedFee; _exitFixedFee = exitFixedFee; Currency = currencyType; _exchange = exchange; }
public Security(string isin, string symbol, string name, string type, bool visible, bool suspended, IExchange exchange) { this.isin = isin; this.symbol = symbol; this.name = name; this.exchange = exchange; this.visible = visible; this.suspended = suspended; }
public Index(XmlRpcStruct index) { IDataAccess data = DataAccessFactory.GetDataAccess(); this.isin = (string)index["ISIN"]; this.symbol = (string)index["SYMBOL"]; this.name = (string)index["NAME"]; this.exchange = data.GetExchangeBySymbol((string)index["EXCHANGE"]); }
public Binding(IBindable bindable, IExchange exchange, string routingKey) { Preconditions.CheckNotNull(bindable, "bindable"); Preconditions.CheckNotNull(exchange, "exchange"); Preconditions.CheckNotNull(routingKey, "routingKey"); Bindable = bindable; Exchange = exchange; RoutingKey = routingKey; }
public SubscriptionResult(IExchange exchange, IQueue queue, IDisposable consumerCancellation) { Preconditions.CheckNotNull(exchange, "exchange"); Preconditions.CheckNotNull(queue, "queue"); Preconditions.CheckNotNull(consumerCancellation, "consumerCancellation"); Exchange = exchange; Queue = queue; ConsumerCancellation = consumerCancellation; }
public RabbitQueue(IExchange exchange) { _exchange = exchange; _bindings = new List<AmqpBinding>(); _isDisposing = false; _queueName = string.Format("{0}_{1}", exchange.Name, Process.GetCurrentProcess().ProcessName); this.StartListening(); this.WaitUntilStarted(); }
protected virtual void InitMessageBusTopology() { RoutedEventExchange = Exchange.DeclareTopic(RoutedEventExchangeName); RoutedEventQueue = Queue.DeclareTransient(GetRoutedEventQueueName(Application.Current.ApplicationId)); RoutedEventQueue.BindTo(RoutedEventExchange, AllAppScopeRoutingKey, //全局范围的消息路由关键字 GetAppIdScopeRoutingKey(Application.Current.ApplicationId), //当前应用Id范围的消息路由关键字 GetAppTypeScopeRoutingKey(Application.Current.ApplicationType), //当前应用类型范围的消息路由关键字 GetAppGroupScopeRoutingKey(Application.Current.ApplicationGroup //当前应用分组范围的消息路由关键字 )); }
public Binding(IBindable bindable, IExchange exchange, params string[] routingKeys) { Preconditions.CheckNotNull(bindable, "bindable"); Preconditions.CheckNotNull(exchange, "exchange"); Preconditions.CheckAny(routingKeys, "routingKeys", "There must be at least one routingKey"); Preconditions.CheckFalse(routingKeys.Any(string.IsNullOrEmpty), "routingKeys", "RoutingKey is null or empty"); Bindable = bindable; Exchange = exchange; RoutingKeys = routingKeys; }
public Security(XmlRpcStruct security) { IDataAccess data = DataAccessFactory.GetDataAccess(); this.isin = (string)security["ISIN"]; this.symbol = (string)security["SYMBOL"]; this.name = (string)security["NAME"]; this.exchange = data.GetExchangeBySymbol((string)security["EXCHANGE"]); this.visible = (Convert.ToInt32(security["VISIBLE"]) == 1) ? true : false; this.suspended = (Convert.ToInt32(security["SUSPENDED"]) == 1) ? true : false; this.latestQuote = null; }
/// <summary> /// Returns a route depending on its link with a specific exchange /// </summary> /// <param name="session">Data access object</param> /// <param name="exchange">The exchange of interest</param> /// <returns>route object</returns> public static IRoute GetRouteByExchange(IDalSession session, IExchange exchange) { IRoute route = null; List<ICriterion> expressions = new List<ICriterion>(); expressions.Add(Expression.Eq("Exchange.Key", exchange.Key)); IList list = session.GetList(typeof(Route), expressions); if (list != null && list.Count > 0) { route = (IRoute)list[0]; } return route; }
private static void SendAuthResponse(IAdvancedBus advancedBus, IExchange exchange) { // Send auth success // TODO: Check the actual authentication stuff var responseEvent = new Event(); responseEvent.Type = Event.EventType.response; var response = new AuthenticationResponse(); response.Success = true; responseEvent.Content = response; var responseMessage = new Message<Event>(responseEvent); advancedBus.Publish(exchange, "Have.Auth.v1", false, false, responseMessage); }
public override void StartListening() { _exchange = Exchange.DeclareFanout(Configuration.ExchangeName); _queue = Configuration.QueueName == null ? Queue.DeclareTransient() : Queue.DeclareTransient(Configuration.QueueName); _queue.BindTo(_exchange, "#"); _bus.Subscribe<RabbitMqMessageWrapper>(_queue, (msg, messageReceivedInfo) => Task.Factory.StartNew(() => OnMessage(msg.Body))); }
public void DeclareExchange(IExchange exchange) { var args = new Dictionary<string, object>(); if (exchange.AlternateExchange != null) { // http://www.rabbitmq.com/ae.html args.Add("alternate-exchange", exchange.AlternateExchange.Name); } _model.ExchangeDeclare(exchange.Name, "topic", true, false, args); }
public void SetUp() { exchangeDeclareCount = 0; publishExchangeDeclareStrategy = new PublishExchangeDeclareStrategy(); advancedBus = MockRepository.GenerateStub<IAdvancedBus>(); exchange = new Exchange(exchangeName); exchangeTask = TaskHelpers.FromResult(exchange); advancedBus .Stub(x => x.ExchangeDeclareAsync(exchangeName, "topic")) .Return(exchangeTask) .WhenCalled(x => exchangeDeclareCount++); }
public void BindTo(IExchange exchange, params string[] routingKeys) { Preconditions.CheckNotNull(exchange, "exchange"); Preconditions.CheckAny(routingKeys, "routingKeys", "There must be at least one routingKey"); Preconditions.CheckFalse(routingKeys.Any(string.IsNullOrEmpty), "routingKeys", "RoutingKey is null or empty"); if (exchange is DefaultExchange) { throw new Exception("All queues are bound automatically to the default exchange, do bind manually."); } var binding = new Binding(this, exchange, routingKeys); bindings.Add(binding); }
public MessageSubscriber(IAdvancedBus bus, IMessageConsumer messageConsumer, ILogger logger, IEnvironment environment, IExchange exchange, IQueue queue) { _messageConsumer = messageConsumer; _bus = bus; _logger = logger; _environment = environment; _exchange = exchange; _queue = queue; }
/// <summary> /// Initialises a new instance of the class /// </summary> /// <param name="settings">the strategy settings</param> /// <param name="tradingIndicator">The indicator to use</param> public BaseTradingStrategy(StrategySettings settings, ITradingIndicator tradingIndicator) { _settings = settings; _tradingIndicator = tradingIndicator; _pair = settings.Pair; Actions = new List<MarketAction>(); // Only do back testing trading for now _proxy = new FakeExchange(); if (_proxy is FakeExchange) { (_proxy as FakeExchange).Init(settings.InitialItem1Balance, settings.InitialItem2Balance, settings.BuyFee, settings.SellFee); } }
public void BindTo(IExchange exchange, params string[] routingKeys) { if (exchange == null) { throw new ArgumentNullException("exchange"); } if (routingKeys.Any(string.IsNullOrEmpty)) { throw new ArgumentException("RoutingKey is null or empty"); } if (routingKeys.Length == 0) { throw new ArgumentException("There must be at least one routingKey"); } var binding = new Binding(this, exchange, routingKeys); bindings.Add(binding); }
public BitstampTrader(TimeSpan interval) { // Ninject var kernel = new StandardKernel(); kernel.Load(Assembly.GetExecutingAssembly()); _minMaxLogRepository = kernel.Get <IRepository <MinMaxLog> >(); _orderRepository = kernel.Get <IRepository <Order> >(); _currencyPairRepository = kernel.Get <IRepository <CurrencyPair> >(); _exchange = kernel.Get <IExchange>(); if (_currencyPairRepository.GetType() == typeof(MockRepository <CurrencyPair>)) { GenerateMockData(); } Interval = interval; }
public override void StartListening() { _receiveexchange = _bus.ExchangeDeclare(Configuration.ExchangeName, ExchangeType.Fanout); _stampExchange = _bus.ExchangeDeclare(Configuration.StampExchangeName, "x-stamp"); _queue = Configuration.QueueName == null ? _bus.QueueDeclare() : _bus.QueueDeclare(Configuration.QueueName); _bus.Bind( _receiveexchange, _queue, "#"); _bus.Consume<RabbitMqMessageWrapper>(_queue, (msg, messageReceivedInfo) => { var message = msg.Body; message.Id = (ulong)Convert.ToInt64(msg.Properties.Headers["stamp"]); return Task.Factory.StartNew(() => OnMessage(message)); }); }
public void TestQueueWay3() { IAdvancedBus bus = RabbitHutch.CreateBus(ConfigurationAppSetting.RabbitMQHost, reg => reg.Register <IEasyNetQLogger>(log => new Log4NetLogger())).Advanced; IExchange ex = bus.ExchangeDeclare("JinRi.Notify.Test.TestQueueWay3Ex", "direct"); IQueue qu1 = bus.QueueDeclare("JinRi.Notify.Test.TestQueueWay3Queue1"); IQueue qu2 = bus.QueueDeclare("JinRi.Notify.Test.TestQueueWay3Queue2"); IQueue qu3 = bus.QueueDeclare("JinRi.Notify.Test.TestQueueWay3Queue3"); IBinding bi1 = bus.Bind(ex, qu1, "0"); IBinding bi2 = bus.Bind(ex, qu2, "1"); IBinding bi3 = bus.Bind(ex, qu3, "2"); for (int i = 0; i < 100; i++) { int md = i % 3; bus.Publish <string>(ex, md.ToString(), false, false, new Message <string>(i.ToString())); } Thread.Sleep(5000); }
private IExchange DeclareVersionedExchanges(MessageVersionStack messageVersions, string exchangeType) { IExchange destinationExchange = null; while (!messageVersions.IsEmpty()) { var messageType = messageVersions.Pop(); var exchangeName = conventions.ExchangeNamingConvention(messageType); var sourceExchange = DeclareExchange(exchangeName, exchangeType); if (destinationExchange != null) { advancedBus.Bind(sourceExchange, destinationExchange, "#"); } destinationExchange = sourceExchange; } return(destinationExchange); }
public override void StartListening() { _receiveexchange = _bus.ExchangeDeclare(Configuration.ExchangeName, ExchangeType.Fanout); _stampExchange = _bus.ExchangeDeclare(Configuration.StampExchangeName, "x-stamp"); _queue = Configuration.QueueName == null ? _bus.QueueDeclare() : _bus.QueueDeclare(Configuration.QueueName); _bus.Bind(_receiveexchange, _queue, "#"); _bus.Consume <RabbitMqMessageWrapper>(_queue, (msg, messageReceivedInfo) => { var message = msg.Body; message.Id = (ulong)Convert.ToInt64(msg.Properties.Headers["stamp"]); return(Task.Factory.StartNew(() => OnMessage(message))); }); }
public async Task Add(IExchange exchange) { using (var context = ContextFactory.CreateDbContext(null)) { var entity = new ExchangeEntity { Id = (int)exchange.Name, Name = exchange.Name.ToString() }; if (await context.Exchange.FindAsync(entity.Id) == null) { await context.Exchange.AddAsync(entity); await context.SaveChangesAsync(); } } }
public virtual void Publish <T>(IExchange exchange, string routingKey, IMessage <T> message, Action <IAdvancedPublishConfiguration> configure) { Preconditions.CheckNotNull(exchange, "exchange"); Preconditions.CheckNotNull(routingKey, "routingKey"); Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(configure, "configure"); var typeName = advancedBus.SerializeType(typeof(T)); var messageBody = advancedBus.Serializer.MessageToBytes(message.Body); message.Properties.Type = typeName; message.Properties.CorrelationId = string.IsNullOrEmpty(message.Properties.CorrelationId) ? advancedBus.GetCorrelationId() : message.Properties.CorrelationId; Publish(exchange, routingKey, message.Properties, messageBody, configure); }
/// <summary> /// Initializes RabbitMQ Queue /// </summary> private IQueue InitializeQueue(IExchange exchange, string queueName, string routingKey) { try { // Initialize specified Queue //IQueue queue = Queue.Declare(false, true, false, queueName, null); IQueue queue = _rabbitBus.QueueDeclare(queueName, false, false, true, true); // Bind Queue to already initialized Exchange with the specified Routing Key //queue.BindTo(exchange, routingKey); _rabbitBus.Bind(exchange, queue, routingKey); return(queue); } catch (Exception exception) { Logger.Error(exception, _type.FullName, "InitializeQueue"); return(null); } }
public static void SalvaDatiExchange(IExchange exchange) { ConfigurationManager.RefreshSection("appSettings"); var configurazione = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location); string nomeClasse = exchange.GetType().FullName; string valori = exchange.ChiavePubblica + ";" + exchange.ChiavePrivata; string valoriCifrati = CifraStringa(valori, configPassword); if (configurazione.AppSettings.Settings[nomeClasse] == null) { configurazione.AppSettings.Settings.Add(nomeClasse, valoriCifrati); } else { configurazione.AppSettings.Settings[nomeClasse].Value = valoriCifrati; } configurazione.Save(); }
public void IntitializeMqServices() { try { // Create Rabbit MQ Hutch string connectionString = ReadConfigSettings("ConnectionString"); if (!string.IsNullOrEmpty(connectionString)) { // Initialize Rabbit MQ Hutch InitializeRabbitHutch(connectionString); // Get Exchange Name from Config File string exchangeName = ReadConfigSettings("Exchange"); string positionExchangeName = ReadConfigSettings("PositionExchange"); if (!string.IsNullOrEmpty(exchangeName)) { // Use the Exchange Name to Initialize Rabbit Exchange _exchange = InitializeExchange(exchangeName); if (_exchange != null) { // Initialize required queues RegisterQueues(_exchange); } } if (!string.IsNullOrEmpty(positionExchangeName)) { // Use the Exchange Name to Initialize Rabbit Exchange _positionExchange = InitializeExchange(positionExchangeName); if (_positionExchange != null) { // Initialize required queues RegisterPositionQueues(_positionExchange); } } } } catch (Exception exception) { Logger.Error(exception, _type.FullName, "IntitializeMqServices"); } }
/// <summary> /// Initializes the required parameters and fields for the Rabbit MQ service /// </summary> private void IntitializeMqServices() { try { string connectionString; if (!_mqConfigParameters.TryGetValue("ConnectionString", out connectionString)) { return; } if (!string.IsNullOrEmpty(connectionString)) { // Initialize EasyNetQ Rabbit Hutch InitializeRabbitHutch(connectionString); // Initialize Native RabbitMQ Parameters InitializeNativeRabbitMq(connectionString); // Get Exchange Name from Config File string exchangeName; if (!_mqConfigParameters.TryGetValue("Exchange", out exchangeName)) { return; } if (!string.IsNullOrEmpty(exchangeName)) { // Use the Exchange Name to Initialize Rabbit Exchange _exchange = InitializeExchange(exchangeName); if (_exchange != null) { // Initialize required queues RegisterQueues(_exchange); } } } } catch (Exception exception) { Logger.Error(exception, _type.FullName, "IntitializeMqServices"); } }
public void Setup() { var settings = File.ReadAllText("binance_settings.json"); var obj = JObject.Parse(settings); if (File.Exists("binance_settings.Development.json")) { settings = File.ReadAllText("binance_settings.Development.json"); var obj2 = JObject.Parse(settings); obj.Merge(obj2); } var apiKey = obj["Key"].ToString(); var apiSecret = obj["Secret"].ToString(); exchange = new ExchangeBuilder() .UseBinance() .SetCredentials(apiKey, apiSecret) .Build(); }
public IQueue CreateQueue(IExchange exchange, string queueName) { //Check it doesn't exist in the cache first IQueue queue = _cachedQueues.SingleOrDefault(q => q.Key.Name == queueName).Key; //Create it if (queue == null) { //Flakey queue creation - when loads of bus operations are going on queue creation sometimes results in //The definition of stupidity is repeatedly doing the same thing and expecting a different result - so lets do it 2 more times if it fails ExceptionHandling.RetryForExceptionType <Exception>(() => queue = CreateQueueInternal(exchange, queueName), 3, 500); //Add it to cache and return _cachedQueues.TryAdd(queue, 0); return(queue); } return(queue); }
/// <summary> Subscribes this object. </summary> public void Subscribe() { Bus = RabbitHutch.CreateBus("host=localhost", x => { x.Register <IConventions, AttributeBasedConventions>(); x.EnableMessageVersioning(); }); IExchange exchange = Bus.Advanced.ExchangeDeclare("EvolvedAI", ExchangeType.Topic); IQueue queue = Bus.Advanced.QueueDeclare("Deployments"); Bus.Advanced.Bind(exchange, queue, ""); Bus.Subscribe <DeploymentStartMessage>("Deployment.Start", msg => { ProcessDeploymentStartMessage(msg); }, config => config.WithTopic("Deployments")); Bus.Subscribe <DeploymentStopMessage>("Deployment.Stop", msg => { ProcessDeploymentStopMessage(msg); }, config => config.WithTopic("Deployments")); }
private async Task <IExchange> DeclareVersionedExchangesAsync(MessageVersionStack messageVersions, string exchangeType) { IExchange destinationExchange = null; while (!messageVersions.IsEmpty()) { var messageType = messageVersions.Pop(); var exchangeName = conventions.ExchangeNamingConvention(messageType); var sourceExchange = await DeclareExchangeAsync(exchangeName, exchangeType).ConfigureAwait(false); if (destinationExchange != null) { await advancedBus.BindAsync(sourceExchange, destinationExchange, "#").ConfigureAwait(false); } destinationExchange = sourceExchange; } return(destinationExchange); }
public void Start() { var infExchanger = _bus.ExchangeDeclare(ExchangerNames.InformationResource, ExchangeType.Topic); var demoExchanger = _bus.ExchangeDeclare(ExchangerNames.DemoPicture, ExchangeType.Topic); var quickLookExchanger = _bus.ExchangeDeclare(ExchangerNames.QuickLook, ExchangeType.Topic); _finishedProductsExchange = _bus.ExchangeDeclare(_settings.FinishedProductExchanger, ExchangeType.Fanout); var queue = _bus.QueueDeclare("CheckProductReadyQueue"); _bus.Bind(infExchanger, queue, "*"); _bus.Bind(demoExchanger, queue, "*"); _bus.Bind(quickLookExchanger, queue, "*"); _bus.Consume(queue, registration => registration .Add <MessageMetadata>((message, info) => { ConsumeAndProcess(message.Body); }) ); }
public virtual void BindTo(IExchange exchange, params string[] routingKeys) { if (exchange == null) { throw new ArgumentNullException("exchange"); } if (routingKeys.Any(string.IsNullOrEmpty)) { throw new ArgumentException("RoutingKey is null or empty"); } if (routingKeys.Length == 0) { throw new ArgumentException("There must be at least one routingKey"); } var binding = new Binding(this, exchange, routingKeys); bindings.Add(binding); }
public IQueue CreateQueue(IExchange exchange) { IQueue q = null; lock (_exchangeQueues) { if (_exchangeQueues.ContainsKey(exchange)) { q = _exchangeQueues[exchange]; } else { q = new RabbitQueue(exchange); _exchangeQueues.Add(exchange, q); } } return q; }
private void SubscribeInternal(IExchange exchange, string queueName) { var queue = GetQueue(exchange, queueName); IDisposable subscription; if (_queueSubscriptions.TryGetValue(queueName, out subscription)) { subscription.Dispose(); _queueSubscriptions.Remove(queueName); } lock (_locker) { subscription = _advancedBus.Consume(queue, regHandler => AddHandlers(regHandler, queue)); } _queueSubscriptions.Add(queueName, subscription); }
private RabbitConfig.IBinding DeclareConsumerBindings( string name, string routingKey, IConsumerOptions options, IExchange exchange, bool partitioned, Queue queue) { var consumerProperties = Options.GetRabbitConsumerOptions(options.BindingName); if (partitioned) { return(PartitionedBinding(name, exchange, queue, routingKey, consumerProperties, options.InstanceIndex)); } else { return(NotPartitionedBinding(exchange, queue, routingKey, consumerProperties)); } }
/// <summary> /// 订阅消息 /// </summary> /// <typeparam name="TAccept"></typeparam> /// <param name="Args"></param> public static void Subscriber <TAccept, T>(AcceptEntity Args) where TAccept : IAccept, new() where T : new() { if (Bus == null) { CreateMQ(); } if (string.IsNullOrEmpty(Args.ExchangeName)) { return; } Expression <Action <IAccept> > methodCall; IExchange EX = null; if (Args.SendType == MQEnum.Sub) { EX = Bus.Advanced.ExchangeDeclare(Args.ExchangeName, ExchangeType.Fanout); } if (Args.SendType == MQEnum.Push) { EX = Bus.Advanced.ExchangeDeclare(Args.ExchangeName, ExchangeType.Direct); } if (Args.SendType == MQEnum.Top) { EX = Bus.Advanced.ExchangeDeclare(Args.ExchangeName, ExchangeType.Topic); } IQueue queue = Bus.Advanced.QueueDeclare(Args.QueeName ?? null); Bus.Advanced.Bind(EX, queue, Args.RouteName); Bus.Advanced.Consume(queue, (body, properties, info) => Task.Factory.StartNew(() => { try { var message = Encoding.UTF8.GetString(body); //处理消息 methodCall = job => job.AcceptMQ <T>(message); methodCall.Compile()(new TAccept()); } catch (Exception ex) { throw ex; } })); }
public async Task Publish <TEvent>(SendContext <TEvent> context) where TEvent : class, IEvent { var topic = this.bus.Advanced.Conventions.TopicNamingConvention(typeof(TEvent)); if (context.Message is IHaveTopic message) { topic = message.Topic; } var messageType = typeof(TEvent); var easyNetQMessage = this.CreateEasyNetQMessage(context); easyNetQMessage.Properties.DeliveryMode = this.messageDeliveryModeStrategy.GetDeliveryMode(messageType); IExchange exchange = await this.publishExchangeDeclareStrategy.DeclareExchangeAsync(messageType, "topic").ConfigureAwait(false); await this.bus.Advanced.PublishAsync(exchange, topic, false, easyNetQMessage).ConfigureAwait(false); }
public async Task OnCreate() { if (IsValid()) { var dr = _mbs.ShowQuestion($"Do you really want to create {View.NumberOfBotsToCreate} Bots now?"); if (dr == DialogResult.Yes) { View.SetCreateInProgress(true); IExchange exchange = null; if (View.IsBinanceSelected) { exchange = new ExchangeLayer.Implementations.Binance(_keys); } else if (View.IsHuobiSelected) { exchange = new ExchangeLayer.Implementations.Huobi(_keys); } var botMgr = new BotManager(_logger, new XCommasClient(_keys, View.UsePaperTrading), exchange); try { _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; await botMgr.CreateBots(View.NumberOfBotsToCreate, View.Enable, _settings, cancellationToken); View.SetCreateInProgress(false); _mbs.ShowInformation("Operation finished! See output section for details."); } catch (Exception exception) { _logger.LogError(exception.Message); _mbs.ShowError("Error: " + exception); } finally { View.SetCreateInProgress(false); } } } }
private static void HandleTickerUpdate(IExchange instance, TickerData data) { if (!AlertsByTicker.ContainsKey(data.Ticker)) { return; } bool modified = false; foreach (var alert in AlertsByTicker[data.Ticker].ToList()) { switch (alert.Type) { case AlertType.Higher: if (data.LastTrade > alert.Value) { Program.SendMessage(string.Format("{0}: ticker {1}'s current value, {2}, is higher than the value you specified, {3}.", alert.Nick, alert.TickerName, data.LastTrade, alert.Value), Config.GetString("monitor.ptoken")); AlertsByTicker[data.Ticker].Remove(alert); Alerts.Remove(alert); modified = true; } break; case AlertType.Lower: if (data.LastTrade < alert.Value) { Program.SendMessage(string.Format("{0}: ticker {1}'s current value, {2}, is lower than the value you specified, {3}.", alert.Nick, alert.TickerName, data.LastTrade, alert.Value), Config.GetString("monitor.ptoken")); AlertsByTicker[data.Ticker].Remove(alert); Alerts.Remove(alert); modified = true; } break; } } if (modified) { Save(); } }
public IDisposable Subscribe <T, TMessage>( ISubscription subscription, IExchange exchange = null, IQueue queue = null, IEnumerable <IBinding> bindings = null) where T : ISubscriberHandler <TMessage> { using var channel = Connect().CreateModel(); exchange?.Declare(channel); queue?.Declare(channel); bindings?.Bind(channel); var consumer = new Consumer <TMessage>(Connect(), subscription, _provider); _consumers.Add(consumer); return(new UnSubscriber(() => { _consumers.Remove(consumer); consumer.Dispose(); })); }
public When_an_exchange_is_declared() { mockBuilder = new MockBuilder(); advancedBus = mockBuilder.Bus.Advanced; mockBuilder.NextModel.WhenForAnyArgs(x => x.ExchangeDeclare(null, null, false, false, null)) .Do(x => { arguments = x[4] as IDictionary; }); exchange = advancedBus.ExchangeDeclare( "my_exchange", ExchangeType.Direct, false, false, true, true, "my.alternate.exchange"); }
/// <summary> /// 发布消息队列同步 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="Param"></param> /// <param name="Bus"></param> public void SendMQ <T>(PushEntity <T> Param, IBus Bus) where T : class { //one to one var msg = new Message <T>(Param.BodyData); IExchange EX = null; if (Param.SendType == MQEnum.Sub) { EX = Bus.Advanced.ExchangeDeclare(Param.ExchangeName, ExchangeType.Fanout); } if (Param.SendType == MQEnum.Push) { EX = Bus.Advanced.ExchangeDeclare(Param.ExchangeName, ExchangeType.Direct); } if (Param.SendType == MQEnum.Top) { EX = Bus.Advanced.ExchangeDeclare(Param.ExchangeName, ExchangeType.Topic); } Bus.Advanced.Publish(EX, Param.RouteName, false, msg); }
public void Subscribe <T>(IExchange exchange, string queueName, Action <T, MessageReceivedInfo> handler) where T : class { //Need to handle our subscribes differently as we're translating the message objects to/from DTOs //So we need to intercept message/translate and then pass to handlers //So add our own handlers to consume - then call convert and invoke the handler passed in here with the result var messageType = typeof(T); var entityType = messageType.GetGenericArguments().Single(); var requestType = messageType.GetGenericTypeDefinition(); Debug.WriteLine(string.Format("Subscribing to queue {0} for message type {1}", queueName, messageType.FullName)); //Add the handler passed in to our handlerManager //Filtered by type _handlerManager.AddHandler(new QueueMessageHandler <T> { QueueName = queueName, Handler = handler }); //Subscribe to bus internally SubscribeInternal(exchange, queueName); }
private void InsertBalanceSnapshot(IExchange baseExchange, string currency, decimal price, Dictionary <string, ICurrencyBalance> baseBalances, Dictionary <string, ICurrencyBalance> counterBalances, int processId = 0) { decimal total = 0m; if (baseBalances.ContainsKey(currency)) { total += baseBalances[currency].Available + baseBalances[currency].Held; } if (counterBalances.ContainsKey(currency)) { total += counterBalances[currency].Available + counterBalances[currency].Held; } if (total < 0.01m) { total = 0m; } dbService.InsertBalanceSnapshot(currency, baseExchange.Name, counterExchange.Name, total, price, processId); }
/// <summary> Subscribes this object. </summary> private void Subscribe() { Bus = RabbitHutch.CreateBus("host=localhost", x => { x.Register <IConventions, AttributeBasedConventions>(); x.EnableMessageVersioning(); }); IExchange exchange = Bus?.Advanced?.ExchangeDeclare("EvolvedAI", ExchangeType.Topic); IQueue queue = Bus?.Advanced?.QueueDeclare("Speech"); Bus?.Advanced?.Bind(exchange, queue, ""); Bus?.Subscribe <SpeechRequestMessage>(Environment.MachineName, msg => ProcessSpeechRequestMessage(msg), config => config?.WithTopic("Speech")); Bus?.Subscribe <WikipediaSearchMessage>(Environment.MachineName, msg => ProcessWikipediaSearchMessage(msg), config => config?.WithTopic("Speech")); }
private IExchange DeclareVersionedExchanges(IAdvancedBus advancedBus, IConventions conventions, MessageVersionStack messageVersions, string exchangeType) { // This works because the message version stack is LIFO from most superseded message type to the actual message type IExchange destinationExchange = null; while (!messageVersions.IsEmpty()) { var messageType = messageVersions.Pop(); var exchangeName = conventions.ExchangeNamingConvention(messageType); var sourceExchange = DeclareExchange(advancedBus, exchangeName, exchangeType); if (destinationExchange != null) { advancedBus.Bind(sourceExchange, destinationExchange, "#"); } destinationExchange = sourceExchange; } return(destinationExchange); }
public async Task OnPreview() { if (IsValid()) { View.SetCreateInProgress(true); _logger.LogInformation("PREVIEW BEGIN"); IExchange exchange = null; if (View.IsBinanceSelected) { exchange = new ExchangeLayer.Implementations.Binance(_keys); } else if (View.IsHuobiSelected) { exchange = new ExchangeLayer.Implementations.Huobi(_keys); } var botMgr = new BotManager(_logger, new XCommasClient(_keys, View.UsePaperTrading), exchange); try { _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; await botMgr.PreviewBotsCreation(View.NumberOfBotsToCreate, _settings, cancellationToken); View.SetCreateInProgress(false); _mbs.ShowInformation("Operation finished! See output section for details."); } catch (Exception exception) { _logger.LogError(exception.Message); _mbs.ShowError("Error: " + exception); } finally { View.SetCreateInProgress(false); } _logger.LogInformation("PREVIEW END"); } }