private static void RegisterTopologyConfiguration(ContainerBuilder builder)
        {
            var evtsExchange = new ExchangeConfig(EventsExchangeName, "fanout");

            builder
                .Register(c => evtsExchange)
                .As<ExchangeConfig>();

            builder
                .Register(c => new QueueConfig(CommandsQueueName))
                .As<QueueConfig>();

            builder
                .Register(c => new QueueConfig("WhiteRabbit.SampleApp.Events.Testing", string.Empty, evtsExchange))
                .As<QueueConfig>();
        }
Пример #2
0
        public async Task <ExchangeConfig> Update(ExchangeConfig entity, IDbConnection connection, IDbTransaction transaction = null)
        {
            string query = @"update
								ExchangeConfig
							set
								updated = @updated,
								isEnabled = @enabled,
								apiKey = @apiKey,
								apiSecret = @apiSecret
							where
								exchangeCode = @exchangeCode;
						"                        ;

            return(await connection.QueryFirstOrDefaultAsync <ExchangeConfig>(query,
                                                                              new
            {
                updated = DateTime.UtcNow,
                isEnabled = entity.IsEnabled,
                apiKey = entity.ApiKey,
                apiSecret = entity.ApiSecret
            }, transaction));
        }
Пример #3
0
        public async Task <long> Create(ExchangeConfig entity, IDbConnection connection, IDbTransaction transaction = null)
        {
            string query = @"
					insert into 
						ExchangeConfigs
						(
							id,
							created,
							updated,
							isEnabled,
							isDeleted,
							exchangeCode,
							apiKey,
							apiSecret,
						)
					values
						(
							default,
							@created,
							null,
							true,
							false,
							@exchangeCode,
							@key,
							@secret
						)
					returning id
					on conflict (exchangeCode) do nothing;"                    ;

            return(await connection.QuerySingleAsync <long>(query,
                                                            new
            {
                created = DateTime.UtcNow,
                exchangeCode = entity.ExchangeCode,
                key = entity.ApiKey,
                secret = entity.ApiSecret
            }, transaction));
        }
        public async Task SendTopicAsync <T>(T message, string routeKey = "", bool isMandatory = false) where T : class
        {
            var exchange = new ExchangeConfig();

            if (!_bus.IsConnected)
            {
                string errorMessage = "";
                _logger.LogError(errorMessage);
                throw new Exception("");
            }

            _advancedBus.ExchangeDeclare(exchange.Name, exchange.Type);

            var policy = Policy.Handle <Exception>().WaitAndRetryAsync(_retryAttempts, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, _retryAttempts)), (ex, time) =>
            {
                string errorMessage = "";
                _logger.LogError(errorMessage);
                throw new Exception("");
            });

            await policy.ExecuteAsync(async() =>
                                      await _advancedBus.PublishAsync(exchange, routeKey, isMandatory, new Message <T>(message)).ConfigureAwait(false)
                                      ).ConfigureAwait(false);
        }
Пример #5
0
        //在联网前,读取Read本地缓存文件,如果没有文件,hashcode为"",第一行是hashcode
        //加载Load hashcode,数据,到内存
        //登录,比较新hashcode,相同则跳过;不同,则申请新的hashcode
        //申请的结果和运行时动态更新都是收到服务端的ResponseTextConfig,加载hashcode,数据,到内存,组装新文件替换缓存

        /// <summary>
        /// 从硬盘读取bytes加载到内存。每次刚运行时调用
        /// </summary>
        public static void ReadCacheAndLoadAllLargeConfigs()
        {
            for (int i = 0; i < Configs.Length; i++)
            {
                var configType = (ConfigType)i;

                var    path  = GetFilePath(configType);
                byte[] bytes = null;
                if (File.Exists(path))
                {
                    try
                    {
                        //bytes = File.ReadAllBytes(path);
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);
                    }
                }
                if (bytes != null)
                {
                    IReceiveable configCmd = null;
                    switch (configType)
                    {
                    case ConfigType.CoreConfig:
                        configCmd = new CoreConfig();
                        break;

                    case ConfigType.RechargeConfig:
                        configCmd = new RechargeConfig();
                        break;

                    case ConfigType.SkillConfig:
                        configCmd = new SkillConfig();
                        break;

                    case ConfigType.SkillParameterConfig:
                        configCmd = new SkillParameterConfig();
                        break;

                    case ConfigType.ExchangeConfig:
                        configCmd = new ExchangeConfig();
                        break;

                    case ConfigType.VegetableConfig:
                        configCmd = new VegetableConfig();
                        break;

                    case ConfigType.ChallengeLevelConfig:
                        configCmd = new ChallengeLevelConfig();
                        break;

                    case ConfigType.SkillIntroTextConfig:
                        configCmd = new SkillIntroTextConfig();
                        break;

                    case ConfigType.SkillLevelDetailTextConfig:
                        configCmd = new SkillLevelDetailTextConfig();
                        break;

                    case ConfigType.VegetableIntroTextConfig:
                        configCmd = new VegetableIntroTextConfig();
                        break;

                    case ConfigType.WaitHintTextConfig:
                        configCmd = new WaitHintTextConfig();
                        break;

                    case ConfigType.CharacterConfig:
                        configCmd = new CharacterConfig();
                        break;

                    case ConfigType.EquipConfig:
                        configCmd = new EquipConfig();
                        break;

                    case ConfigType.MajorLevelIntroTextConfig:
                        configCmd = new MajorLevelIntroTextConfig();
                        break;

                    case ConfigType.EquipIntroTextConfig:
                        configCmd = new EquipIntroTextConfig();
                        break;

                    case ConfigType.CharacterIntroTextConfig:
                        configCmd = new CharacterIntroTextConfig();
                        break;

                    case ConfigType.OAuthParamConfig:
                        configCmd = new OAuthParamConfig();
                        break;

                    default:
                        Debug.LogError("遇到新的ConfigType,需添加代码。type:" + configType);
                        break;
                    }
                    if (configCmd != null)
                    {
                        configCmd.ParseFrom(bytes);
                        SetConfig(configType, configCmd);
                    }
                }
            }
        }
Пример #6
0
 public Hopper(IModelFactory modelFactory, ISerializerFactory serializerFactory, ExchangeConfig exchange, Action <string> logAction, IDictionary <Type, Func <object> > typeFactory,
               TimeSpan delayBetweenRuns, TimeSpan messageTimeout)
 {
     _modelFactory      = modelFactory;
     _serializerFactory = serializerFactory;
     _exchange          = exchange;
     _logAction         = logAction;
     _typeFactory       = typeFactory;
     _delayBetweenRuns  = delayBetweenRuns;
     _messageTimeout    = messageTimeout;
 }
Пример #7
0
 public ExchangeFacade(IChannelProvider channelProvider, ExchangeConfig config) : base(channelProvider)
 {
     Config = config;
 }
Пример #8
0
 public GdaxSocket(ExchangeConfig config)
 {
     _gdax   = new Gdax(config);
     _config = config;
     name    = config.Name;
 }
Пример #9
0
 /// <summary>
 /// Создать точку обмена сообщениями с типом "Direct".
 /// </summary>
 /// <param name="exchangeConfig">Свойства точки обмена сообщениями.</param>
 public void CreateExchangeTopic(ExchangeConfig exchangeConfig)
 {
     CreateExchange(ExchangeType.Topic, exchangeConfig);
 }
Пример #10
0
 /// <summary>
 /// Создать точку обмена сообщениями с типом "Direct".
 /// </summary>
 /// <param name="exchangeConfig">Свойства точки обмена сообщениями.</param>
 public void CreateExchangeDirect(ExchangeConfig exchangeConfig)
 {
     CreateExchange(ExchangeType.Direct, exchangeConfig);
 }
Пример #11
0
 public TDMExchange(ExchangeConfig config)
     : base(config)
 {
     InstrumentList = new Dictionary <string, List <TDM_Instrument> >();
 }
Пример #12
0
        public async Task <IActionResult> Edit(int id)
        {
            ExchangeConfig config = await _exchangeConfigProcessor.GetExchangeConfig(id);

            return(View(config.ToModel()));
        }
Пример #13
0
 public Binance(ExchangeConfig config)
 {
     _binance = RestClient.For <IBinanceApi>("https://api.binance.com");
     _config  = config;
     name     = config.Name;
 }
Пример #14
0
 public Okex(ExchangeConfig config)
 {
     _config = config;
     name    = config.Name;
     _okex   = RestClient.For <IOkexApi>("https://www.okex.com/");
 }
Пример #15
0
 /// <summary>
 /// Получить точку обмена сообщениями с типом "Headers".
 /// </summary>
 /// <param name="exchangeConfig">Свойства точки обмена сообщениями.</param>
 public void CreateExchangeHeaders(ExchangeConfig exchangeConfig)
 {
     CreateExchange(ExchangeType.Headers, exchangeConfig);
 }
Пример #16
0
 public BinanceSocket(ExchangeConfig config)
 {
     _binance = new Binance(config);
     _config  = config;
     name     = config.Name;
 }
Пример #17
0
 /// <summary>
 /// Создать точку обмена сообщениями с типом "Fanout".
 /// </summary>
 /// <param name="exchangeConfig">Свойства точки обмена сообщениями.</param>
 public void CreateExchangeFanout(ExchangeConfig exchangeConfig)
 {
     CreateExchange(ExchangeType.Fanout, exchangeConfig);
 }
Пример #18
0
 public OkexSocket(ExchangeConfig config)
 {
     _okex   = new Okex(config);
     _config = config;
     name    = config.Name;
 }
Пример #19
0
        public async Task <ExchangeOrder> Send(Order order, ExchangeConfig config)
        {
            ExchangeOrder exchangeOrder = null;
            PairConfig    pairConfig    = config.Pairs.FirstOrDefault(x => x.Symbol.Equals(order.Symbol));

            if (order.UpdateRequired)
            {
                using (BinanceClient client = new BinanceClient(new BinanceClientOptions()
                {
                    ApiCredentials = new ApiCredentials(config.ApiKey, config.ApiSecret)
                }))
                {
                    if (order.OrderStatusCode == OrderStatusCode.PENDING)
                    {
                        (bool success, string error, BinancePlacedOrder order)result;;
                        if (order.OrderTypeCode == OrderTypeCode.MKT.Code)
                        {
                            if (pairConfig.IsTestMode)
                            {
                                WebCallResult <BinancePlacedOrder> orderResult = await client.PlaceTestOrderAsync(order.Symbol, (OrderSide)order.OrderSideCode, OrderType.Market, order.Amount.Value, null, order.Id.ToString(), null, TimeInForce.GoodTillCancel);

                                result = (orderResult.Success, orderResult.Error.Message, orderResult.Data);
                            }
                            else
                            {
                                WebCallResult <BinancePlacedOrder> orderResult = await client.PlaceOrderAsync(order.Symbol, (OrderSide)order.OrderSideCode, OrderType.Market, order.Amount.Value, null, order.Id.ToString(), null, TimeInForce.GoodTillCancel);

                                result = (orderResult.Success, orderResult.Error.Message, orderResult.Data);
                            }
                        }
                        else if (order.OrderTypeCode == OrderTypeCode.LMT.Code)
                        {
                            if (pairConfig.IsTestMode)
                            {
                                WebCallResult <BinancePlacedOrder> orderResult = await client.PlaceTestOrderAsync(order.Symbol, (OrderSide)order.OrderSideCode, OrderType.Limit, order.Amount.Value, null, order.Id.ToString(), order.Price, TimeInForce.GoodTillCancel);

                                result = (orderResult.Success, orderResult.Error.Message, orderResult.Data);
                            }
                            else
                            {
                                WebCallResult <BinancePlacedOrder> orderResult = await client.PlaceOrderAsync(order.Symbol, (OrderSide)order.OrderSideCode, OrderType.Limit, order.Amount.Value, null, order.Id.ToString(), order.Price, TimeInForce.GoodTillCancel);

                                result = (orderResult.Success, orderResult.Error.Message, orderResult.Data);
                            }
                        }
                        else if (order.OrderTypeCode == OrderTypeCode.LST.Code)
                        {
                            if (pairConfig.IsTestMode)
                            {
                                // OCO Order can't be used in test mode
                                WebCallResult <BinancePlacedOrder> orderResult = await client.PlaceTestOrderAsync(order.Symbol, (OrderSide)order.OrderSideCode, OrderType.Limit, order.Amount.Value, null, order.Id.ToString(), order.Price, TimeInForce.GoodTillCancel);

                                result = (orderResult.Success, orderResult.Error.Message, orderResult.Data);
                            }
                            else
                            {
                                if (order.OrderSideCode == OrderSideCode.BUY.Code)
                                {
                                    // For now let's use limit standard order
                                    WebCallResult <BinancePlacedOrder> orderResult = await client.PlaceOrderAsync(order.Symbol, OrderSide.Buy, OrderType.Limit, order.Amount.Value, null, order.Id.ToString(), order.Price, TimeInForce.GoodTillCancel);

                                    result = (orderResult.Success, orderResult.Error.Message, orderResult.Data);
                                }
                                else
                                {
                                    WebCallResult <BinanceOrderList> orderResult = await client.PlaceOCOOrderAsync(order.Symbol, OrderSide.Sell, order.Amount.Value, order.Price.Value, order.StopLoss.Value);

                                    result = (orderResult.Success, orderResult.Error.Message, orderResult.Data.OrderReports.First());
                                }
                            }
                        }
                        else
                        {
                            throw new Exception($"{order.Id} selected order type isn't supported");
                        }

                        if (!result.success)
                        {
                            throw new Exception(result.error);
                        }

                        exchangeOrder = result.order.ToOrder();
                        _logger.LogInformation($"{Exchange.Description} - Order {order.Id} has been processed with status: {result.order.Status}");
                    }
                    else if (order.OrderStatusCode == OrderStatusCode.CANCELED)
                    {
                        WebCallResult <BinanceCanceledOrder> cancelResult = await client.CancelOrderAsync(order.Symbol, order.ExchangeOrderId);

                        if (!cancelResult.Success)
                        {
                            throw new Exception(cancelResult.Error.Message);
                        }

                        exchangeOrder = cancelResult.Data.ToOrder();
                        _logger.LogInformation($"{Exchange.Description} - Order {order.Id} has been processed with status: {cancelResult.Data.Status}");
                    }
                    else
                    {
                        throw new Exception($"{Exchange.Description} - Can't update update order {order.Id}: wrong status");
                    }
                }
            }

            return(exchangeOrder);
        }
        protected override async Task DoWork(PairConfig config, CancellationToken stoppingToken)
        {
            ExchangeConfig exchangeConfig = await _exchangeConfigProcessor.GetExchangeConfig(Exchange.Code);

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    string listenKey = String.Empty;
                    using (BinanceClient client = new BinanceClient())
                    {
                        listenKey = client.StartUserStream().Data;
                    }

                    using (BinanceSocketClient socketClient = new BinanceSocketClient())
                    {
                        ConnectionInfo cnInfo = new ConnectionInfo(_settings.Value.BusConnectionString);
                        using (NatsClient natsClient = new NatsClient(cnInfo))
                        {
                            if (!natsClient.IsConnected)
                            {
                                natsClient.Connect();
                            }

                            CallResult <UpdateSubscription> successAccount = socketClient.SubscribeToUserDataUpdates(listenKey,
                                                                                                                     accountData =>
                            {
                            },
                                                                                                                     async orderData =>
                            {
                                Order order = orderData.ToOrder();
                                Deal deal   = await _dealProcessor.UpdateForOrder(order, config);

                                await natsClient.PubAsJsonAsync(_settings.Value.OrdersQueueName, new Notification <Deal>()
                                {
                                    Code = ActionCode.UPDATED.Code, Payload = deal
                                });
                            },
                                                                                                                     ocoOrderData =>
                            {
                            },
                                                                                                                     async balancesData =>
                            {
                                IEnumerable <Balance> balances = balancesData.Select(x => x.ToBalance());
                                foreach (Balance balance in balances)
                                {
                                    await _balanceProcessor.UpdateOrCreate(balance);
                                }
                            },
                                                                                                                     onAccountBalanceUpdate =>
                            {
                            });

                            while (!stoppingToken.IsCancellationRequested)
                            {
                            }

                            natsClient.Disconnect();
                            await socketClient.UnsubscribeAll();
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            }
        }
Пример #21
0
 public Bittrex(ExchangeConfig config)
 {
     _bittrex = new BittrexApi(config.ApiKey, config.Secret);
     name     = config.Name;
 }
Пример #22
0
 public BitmexApi(ILogger logger, ExchangeConfig config) : base(logger, config)
 {
     _logger = logger;
 }
Пример #23
0
        static bool Initialize(string sequenceName)
        {
            _logger.Debug("Initialize ...");

            try
            {
                #region init proxy info
                _proxyCredentialToken = ConfigurationManager.AppSettings["ProxyCredentialToken"];
                _proxyHost            = ConfigurationManager.AppSettings["ProxyHost"];

                string proxyPort = ConfigurationManager.AppSettings["ProxyPort"];
                int.TryParse(proxyPort, out _proxyPort);
                #endregion

                #region init client credentials
                _ssoURL       = ConfigurationManager.AppSettings["SSO_URL"];
                _clientId     = ConfigurationManager.AppSettings["client_id"];
                _clientSecret = ConfigurationManager.AppSettings["client_secret"];
                _authType     = ConfigurationManager.AppSettings["grant_type"];

                string clientKey = ConfigurationManager.AppSettings["client_key"];
                if (!string.IsNullOrEmpty(clientKey))
                {
                    _clientSecret = EncryptionUtility.Decrypt(_clientSecret, clientKey);
                }
                else
                {
                    _clientSecret = EncryptionUtility.Decrypt(_clientSecret);
                }
                #endregion

                #region init exchange sequence and timeout
                string configPath = ConfigurationManager.AppSettings["ExchangeConfig"];

                if (!File.Exists(configPath))
                {
                    _logger.Error("Exchange Configuration not found.");
                    return(false);
                }

                ExchangeConfig config = Utility.Read <ExchangeConfig>(configPath, true);
                foreach (Sequence sequence in config)
                {
                    if (sequence.Name.ToLower() == sequenceName.ToLower())
                    {
                        _sequence = sequence;
                        break;
                    }
                }

                if (_sequence == null)
                {
                    _logger.Error("Sequence [" + sequenceName + "] does not exist in exchange configuration.");
                    return(false);
                }

                string httpRequestTimeout = ConfigurationManager.AppSettings["RequestTimeout"];
                if (!string.IsNullOrWhiteSpace(httpRequestTimeout))
                {
                    _requestTimeout = Convert.ToInt32(httpRequestTimeout);
                }
                #endregion
            }
            catch (Exception ex)
            {
                _logger.Error("Initialization failed: " + ex.Message, ex);
                return(false);
            }

            return(true);
        }