public ExchangeConnectorApplication(ExchangeFactory exchange, ILog log)
        {
            _log = log;

            _exchanges = exchange.CreateExchanges();
            _timer     = new Timer(OnHeartbeat);
        }
Esempio n. 2
0
        /// <summary>
        /// 执行TASK更新市场深度
        /// </summary>
        /// <param name="model"></param>
        public void TaskExecution(VmpConfigModel model)
        {
            //Log.Info($"执行更新市场深度TaskExecution,platformCode={platformCode};coinCode={coinCode};currencyCode={currencyCode}");
            try
            {
                ExchangeType   eType      = (ExchangeType)Enum.Parse(typeof(ExchangeType), model.PlatformCode);
                ExChangeBase   eb         = ExchangeFactory.InstanExchange(eType);
                LatePriceModel priceModel = eb.GetLatestRecord(model.CurrencyCode, model.ExCurrencyCode);
                if (priceModel.Asks == null)
                {
                    Log.Error($"执行查询集合为空,platformCode={model.PlatformCode};coinCode={model.CurrencyCode};currencyCode={model.ExCurrencyCode}");
                    return;
                }

                //更新数据库市场深度
                //UpdateLatePriceFacade latePriceFacade =new UpdateLatePriceFacade();
                //latePriceFacade.InsertLatestRecord(model, priceModel);
                //更新缓存市场深度
                UpdateDepthFacade depthFacade = new UpdateDepthFacade();
                if (!depthFacade.UpdateLatePrice(model, priceModel))
                {
                    Log.Error($"Error,更新缓存市场深度失败,platformCode={model.PlatformCode};coinCode={model.CurrencyCode};currencyCode={model.ExCurrencyCode}");
                }

                GC.Collect();
            }
            catch (Exception ex)
            {
                Log.Error("执行查询插入数据出错" + ex);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 更新24小时市场价,废弃
        /// </summary>
        /// <param name="platformId"></param>
        /// <param name="coinId"></param>
        /// <param name="exchangeId"></param>
        /// <param name="exName"></param>
        /// <param name="platformCode"></param>
        /// <param name="coinCode"></param>
        public void TaskExecution(int platformId, int coinId, int exchangeId, string exName, string platformCode, string coinCode)
        {
            Log.Info("执行TaskExecution:" + platformCode + "_" + coinCode + "_" + exName);
            try
            {
                ExchangeType   eType      = (ExchangeType)Enum.Parse(typeof(ExchangeType), platformCode);
                ExChangeBase   eb         = ExchangeFactory.InstanExchange(eType);
                BasePriceModel priceModel = eb.GetNowPrice(coinCode, exName);
                if (priceModel == null)
                {
                    return;
                }
                //得到1970年的时间戳
                DateTime timeStamp = new DateTime(1970, 1, 1);
                //注意这里有时区问题,用now就要减掉8个小时
                string timestamps = Convert.ToString((DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000);
                InsertQuotes(platformId, coinId, exchangeId, platformCode, coinCode, timestamps, priceModel);

                GC.Collect();
            }
            catch (Exception ex)
            {
                Log.Error("执行查询插入数据出错" + ex);
            }
        }
Esempio n. 4
0
        public void OpenWebSocketTest()
        {
            // Arrange
            IExchangeApi exchangeApi = ExchangeFactory.GetExchangeApi(Enumerations.ExchangesEnum.Gdax, _exchangeSettings);

            // Act
            exchangeApi.OpenSocket();
        }
Esempio n. 5
0
        public static List <IStrategy> GetConfigurations()
        {
            List <IStrategy> strategyList          = new List <IStrategy>();
            IFactory         xChangeObjectFactory  = null;
            IFactory         strategyObjectFactory = null;
            IStrategy        stratObj = null;

            //  IExchange xChangeObj = null;

            using (StreamReader file = File.OpenText(configFile))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jsonObject = (JObject)JToken.ReadFrom(reader);
                }


            var rootObject = JsonConvert.DeserializeObject <ConfigRoot>(jsonObject.ToString());

            GlobalConfig.SetRootConfig(rootObject);

            //Do Validations here.....  ************************************ NEED CONFIG VALIDATIONS HERE  *********************

            //NEED CONFIG VALIDATIONS HERE

            //******************************************************************************************************************

            foreach (ExchangeConfig xChng in rootObject.Exchanges)
            {
                if (xChng.ActiveStatus)
                {
                    xChangeObjectFactory = new ExchangeFactory();
                    //xChangeObj = xChangeObjectFactory.GetObject<IExchange>(xChng);
                    foreach (StrategyConfig strgyItem in xChng.Strategies)
                    {
                        strategyObjectFactory = new StrategyFactory();
                        if (strgyItem.ActiveStatus)
                        {
                            stratObj = strategyObjectFactory.GetObject <IStrategy>(strgyItem);
                            //xChng.UniqueStrategyId = stratObj.GetStrategyId();
                            stratObj.SetExchangeDetails(xChangeObjectFactory.GetObject <IExchange>(xChng));
                            stratObj.SetConfigPath(configFile);
                            //stratObj.SetStrategyId();
                            strategyList.Add(stratObj);
                        }
                    }
                }
            }
            return(strategyList);
        }
        public IBotProcessManager GetBotProcessManager()
        {
            var exchanges = new List <IExchange> {
                new BinanceService(SecretDataRepository)
            };

            ExchangeFactory = new ExchangeFactory(exchanges);
            var processors = new List <IBotProcessor> {
                new CoreNumberProcessor(ExchangeFactory, BotInstanceDataRepository)
            };

            BotProcessorFactory = new BotProcessorFactory(processors);
            BotProcessManager   = new BotProcessManager(ExchangeFactory, BotProcessorFactory, BotInstanceDataRepository, SecretDataRepository, TradingViewAlertServiceMock, InstanceConfigurationServiceMock);;
            return(BotProcessManager);
        }
Esempio n. 7
0
        private IExchangeApi GetExchange(Bot bot)
        {
            ApiSetting exchangeSetting = bot.User.ApiSettings.FirstOrDefault(x => x.Exchange.ExchangeId == bot.Exchange.ExchangeId);

            return
                (ExchangeFactory.GetExchangeApi((Enumerations.ExchangesEnum)bot.Exchange.ExchangeId, new ExchangeSettings
            {
                Url = exchangeSetting.Url,
                SocketUrl = exchangeSetting.SocketUrl,
                PassPhrase = exchangeSetting.Passphrase,
                ApiKey = exchangeSetting.Key,
                Secret = exchangeSetting.Secret,
                CommissionRate = exchangeSetting.ComissionRate,
                Simulate = exchangeSetting.Simulated
            }));
        }
Esempio n. 8
0
        public void GetBTCTickerTest()
        {
            // Arrange
            IExchangeApi exchangeApi = ExchangeFactory.GetExchangeApi(Enumerations.ExchangesEnum.Gdax, _exchangeSettings);

            // Act
            var response = exchangeApi.GetTicker(new Coin()
            {
                Code = "BTC"
            }, new Coin()
            {
                Code = "EUR"
            });


            // Asert
            Assert.IsNotNull(response);
        }
Esempio n. 9
0
        public async Task <HistoryResponseDto> History(string symbol, Int32 from, Int32 to, string resolution)
        {
            _exchangeApi = ExchangeFactory.GetExchangeApi(Enumerations.ExchangesEnum.Gdax, null);

            IEnumerable <Candle> candles =
                _exchangeApi.GetCandles(new Coin {
                Code = "EUR"
            }, new Coin {
                Code = "BTC"
            }, 60 * 60 * 24, UnixTimeStampToDateTime(from), UnixTimeStampToDateTime(to));

            candles = candles.OrderBy(x => x.Timestamp);

            //var asTable = ToDataTable(candles.ToList());

            var response = new HistoryResponseDto
            {
                TimeStamps = candles.Select(x => (long)CryptoUtility.UnixTimestampFromDateTimeSeconds(x.Timestamp)).ToArray(),
                Opens      = candles.Select(x => x.OpenPrice).ToArray(),
                Highs      = candles.Select(x => x.HighPrice).ToArray(),
                Lows       = candles.Select(x => x.LowPrice).ToArray(),
                Closes     = candles.Select(x => x.ClosePrice).ToArray(),
                Volumes    = candles.Select(x => Convert.ToDecimal(x.VolumeQuantity)).ToArray(),
                Status     = "ok"
            };

            return(response);

            //var json = System.IO.File.ReadAllText("D:\\Development\\CryptoBot\\CryptoBot.Api\\Data\\Sample\\history.json");
            //var result = JsonConvert.DeserializeObject<HistoryResponseDto>(json);
            //var fromDates = result.TimeStamps.Where(x => x > from);
            //var toDates = result.TimeStamps.Where(x => x < to);

            //if(!fromDates.Any() || !toDates.Any())
            //    return new HistoryResponseDto{ Status = "no_data"};

            //return JsonConvert.DeserializeObject<HistoryResponseDto>(json);
        }
Esempio n. 10
0
 public UnauthenticatedCommands()
     : base(ExchangeFactory.GetUnauthenticatedExchange(ExchangeType.BitStamp))
 {
 }
Esempio n. 11
0
 public StrategyFactory(ExchangeFactory exchangeFactory, StrategyLogService logService)
 {
     this.exchangeFactory = exchangeFactory;
     this.logService      = logService;
 }
Esempio n. 12
0
 public GdaxSetup() : base(ExchangeFactory.GetAuthenticatedExchange(ExchangeType.Gdax))
 {
 }
Esempio n. 13
0
 public BitfinexSetup() : base(ExchangeFactory.GetAuthenticatedExchange(ExchangeType.Bitfinex))
 {
 }
Esempio n. 14
0
        //dotnet publish -c Release -r win10-x64

        static void Main(string[] args)
        {
            #region config
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                          .AddEnvironmentVariables();
            IConfigurationRoot configuration = builder.Build();

            var arbitrageConfig = new ArbitrageConfig();
            configuration.GetSection("ArbitrageConfig").Bind(arbitrageConfig);

            NLog.Logger logger = LogManager.GetCurrentClassLogger();

            // Create the token source.
            var masterToken = new CancellationTokenSource();

            #endregion
            try
            {
                var dbService = new BMDbService(configuration.GetValue <string>("LocalSqlConnectionString"), arbitrageConfig.Gmail);

                var configs   = arbitrageConfig.Exchanges.ToDictionary(c => c.Name);
                var exchanges = arbitrageConfig.Exchanges.Where(c => c.Enabled).Select(c => ExchangeFactory.GetInstance(c)).ToDictionary(e => e.Name);

                var binance = new Binance(configs["Binance"]);//(Binance)exchanges["Binance"];
                var hitbtc  = (Hitbtc)exchanges["Hitbtc"];
                var gdax    = (Gdax)exchanges["Gdax"];


                var hitbtcv2 = new HitbtcSocket(configs["Hitbtc"]);

                var enginev2 = new ArbitrageEngineV2(hitbtcv2.Rest, binance, dbService);
                var bManager = new BalanceManager(dbService, hitbtcv2.Rest, binance);

                //    bManager.StartManager();

                var hitbtcBalances  = hitbtc.GetBalances().Result.ToDictionary(b => b.Currency);
                var binanceBalances = binance.GetBalances().Result.ToDictionary(b => b.Currency);

                string address = "0xf18414d9961c458a0d120ffe2f0b0da279d1aea0";
                //string tag = "24da0a5343fc7a28199edd703b8c80bc7b84ab154b1ce4416e53b8f00437f01d";
                string currency = "ETH";

                decimal hitAmount = hitbtcBalances[currency].Available;
                //decimal biAmount = binanceBalances[currency].Available;

                if (!string.IsNullOrWhiteSpace(address) && hitAmount > 0)
                {
                    logger.Trace("Withdraw {0} {1} to {2}", hitAmount, currency, address);
                    var hitRes = hitbtc.Withdraw(currency, hitAmount, address).Result;
                }

                //if (!string.IsNullOrWhiteSpace(address) && biAmount > 0)
                //{
                //    logger.Trace("Withdraw {0} {1} to {2}", biAmount, currency, address);
                //    var biRes = binance.Withdraw(currency, biAmount, address).Result;
                //}


                //var res = hitbtc.Withdraw("DOGE", 1000000m, "DDi3FWrU7RhSJ4NbYKS9gAM73ZHP8TCQTv").Result;
                //AuditOrder("XMRBTC", "8903177267", "1614791", hitbtc, binance);

                //       Console.ReadKey();

                //var result = gdax.MarketSell("BTCUSD", 0.63405632m).Result;

                //      logger.Trace("Complete");
            }
            catch (Exception e)
            {
                if (e.InnerException != null && e.InnerException.GetType() == typeof(ApiException))
                {
                    var apiE = (ApiException)e.InnerException;
                    Console.WriteLine(apiE.Content);
                }
                masterToken.Cancel();
                Console.WriteLine(e);
            }
        }
Esempio n. 15
0
 public Exceptions() : base(ExchangeFactory.GetAuthenticatedExchange(ExchangeType.BitStamp))
 {
 }
Esempio n. 16
0
 public BitfinexExceptions() : base(ExchangeFactory.GetAuthenticatedExchange(ExchangeType.Bitfinex))
 {
 }
        public async Task <bool> Run(ILogger logger)
        {
            logger.LogInformation("Running repository bootstrapper");

            try
            {
                foreach (var currency in CurrencyFactory.List())
                {
                    await CurrencyRepository.Add(currency);
                }

                foreach (var symbol in SymbolFactory.List())
                {
                    await SymbolRepository.Add(symbol);
                }

                foreach (var group in IntervalFactory.ListGroups())
                {
                    foreach (var ik in IntervalFactory.ListIntervalKeys(group.IntervalGroup))
                    {
                        await IntervalRepository.Add(ik);
                    }
                }

                foreach (var exchange in ExchangeFactory.List())
                {
                    await ExchangeRepository.Add(exchange);

                    var httpClient = exchange.GetHttpClient();

                    foreach (var symbolCode in exchange.Symbol)
                    {
                        var symbol = SymbolFactory.Get(symbolCode);

                        await SymbolRepository.Add(symbol);

                        await ExchangeRepository.AddSymbol(exchange.Name, symbolCode);

                        var tradeFilter = await HistorianRepository.GetTradeFilter(exchange.Name, symbolCode);

                        if (tradeFilter == null)
                        {
                            using (var transaction = await StorageTransactionFactory.Begin())
                            {
                                await HistorianRepository.SetTradeFilter(transaction, exchange.Name, symbolCode, httpClient.InitialTradeFilter);

                                await transaction.Commit();
                            }
                        }
                    }
                }

                foreach (var orderSide in OrderSideFactory.List())
                {
                    await OrderSideRepository.Add(orderSide);
                }

                return(true);
            }
            catch (Exception ex)
            {
                logger.LogCritical(ex, "Unable to run repository bootstrapper");

                return(false);
            }
        }
Esempio n. 18
0
 public Configuration() : base(ExchangeFactory.GetAuthenticatedExchange(ExchangeType.BitStamp))
 {
 }