Example #1
0
 public GenericTradeManager(IExchangeApi api, ITradingStrategy strat, INotificationManager notificationManager, Action <string> log)
 {
     _api          = api;
     _strategy     = strat;
     _log          = log;
     _notification = notificationManager;
 }
Example #2
0
        public LiveTradeManager(IExchangeApi api, ITradingStrategy strategy, INotificationManager notificationManager, ILogger logger, TradeOptions settings, IDataStore dataStore)
        {
            _api          = api;
            _strategy     = strategy;
            _logger       = logger;
            _notification = notificationManager;
            _dataStore    = dataStore;
            _settings     = settings;

            if (_api == null)
            {
                throw new ArgumentException("Invalid exchange provided...");
            }
            if (_strategy == null)
            {
                throw new ArgumentException("Invalid strategy provided...");
            }
            if (_dataStore == null)
            {
                throw new ArgumentException("Invalid data store provided...");
            }
            if (_settings == null)
            {
                throw new ArgumentException("Invalid settings provided...");
            }
            if (_logger == null)
            {
                throw new ArgumentException("Invalid logger provided...");
            }
        }
Example #3
0
        public void GdaxIntegrationBuyTest()
        {
            Bot bot = _dbContext
                      .Bots
                      .Include("BaseCoin")
                      .Include("Coin")
                      .Single(x => x.BotId == 1);

            ExchangeSettings exchangeSettings = _mapper.Map <ApiSetting, ExchangeSettings>(
                _user.ApiSettings.Single(x => x.Exchange.ExchangeId == bot.Exchange.ExchangeId),
                new ExchangeSettings());

            exchangeSettings.Simulate = false;

            _exchangeApi = ExchangeEngine.ExchangeFactory.GetExchangeApi(
                (Enumerations.ExchangesEnum)bot.Exchange.ExchangeId, exchangeSettings);

            Ticker ticker = _exchangeApi.GetTicker(bot.BaseCoin, bot.Coin);

            bot.Amount = 10m; // 3 euros

            OrderManager orderManager = new OrderManager(bot, new Trader(_logger), _dbContext, _logger, _mapper, _messagingApp);

            orderManager.Buy(new Candle()
            {
                ClosePrice = ticker.Ask, Timestamp = DateTime.Now
            });
        }
 public ExchangeDataProvider(IExchangeApi exchangeApi)
 {
     if (exchangeApi == null)
     {
         throw new ArgumentNullException(nameof(exchangeApi), "Значение 'null' не допустимо для параметра");
     }
     _exchangeApi = exchangeApi;
 }
Example #5
0
        public void OpenWebSocketTest()
        {
            // Arrange
            IExchangeApi exchangeApi = ExchangeFactory.GetExchangeApi(Enumerations.ExchangesEnum.Gdax, _exchangeSettings);

            // Act
            exchangeApi.OpenSocket();
        }
Example #6
0
        public BitmexService(ILogger logger, ExchangeConfig config)
        {
            _logger        = logger;
            ExchangeConfig = config;

            _exchangeApi = new BitmexApi(logger, ExchangeConfig);
            _openOrders  = new List <OrderDto>();
        }
Example #7
0
 public NotifyOnlyTradeManager(IExchangeApi api, ITradingStrategy strategy, INotificationManager notificationManager, string buyMessage, string sellMessage, ILogger logger, TradeOptions settings)
 {
     _api          = api;
     _strategy     = strategy;
     _logger       = logger;
     _notification = notificationManager;
     _buyMessage   = buyMessage;
     _sellMessage  = sellMessage;
     _settings     = settings;
 }
Example #8
0
        public SymbolSubscriptionCache(string symbol, int limit, TradeView.Core.Model.CandlestickInterval candlestickInterval, IExchangeApi exchangeApi)
        {
            Symbol      = symbol;
            Limit       = limit;
            ExchangeApi = exchangeApi;

            subscribeTrades       = new SubscribeTrades(symbol, limit, ExchangeApi);
            subscribeOrderBook    = new SubscribeOrderBook(symbol, limit, ExchangeApi);
            subscribeCandlesticks = new SubscribeCandlesticks(symbol, limit, ExchangeApi, candlestickInterval);
        }
Example #9
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="api">API</param>
        /// <param name="symbol">The symbol to log, i.e. btcusd</param>
        /// <param name="intervalSeconds">Interval in seconds between updates</param>
        /// <param name="path">The path to write the log files to</param>
        /// <param name="compress">Whether to compress the log files using gzip compression</param>
        public ExchangeLogger(IExchangeApi api, string symbol, float intervalSeconds, string path, bool compress = false)
        {
            string compressExtension = (compress ? ".gz" : string.Empty);

            API           = api;
            Symbol        = symbol;
            Interval      = TimeSpan.FromSeconds(intervalSeconds);
            sysTimeWriter = CreateLogWriter(Path.Combine(path, api.Name + "_time.bin" + compressExtension), compress);
            tickerWriter  = CreateLogWriter(Path.Combine(path, api.Name + "_ticker.bin" + compressExtension), compress);
            bookWriter    = CreateLogWriter(Path.Combine(path, api.Name + "_book.bin" + compressExtension), compress);
            tradeWriter   = CreateLogWriter(Path.Combine(path, api.Name + "_trades.bin" + compressExtension), compress);
        }
Example #10
0
 public Scheduler(IExchangeApi exchangeApi, MessageDispatcher messageispatcher,
                  Enumerations.SchedulerType schedulerType, int schedulerValueInSeconds,
                  int candlePeriodInSeconds, Dictionary <Coin, Coin> coins, Logger logger)
 {
     _exchangeApi             = exchangeApi;
     _messageispatcher        = messageispatcher;
     _schedulerValueInSeconds = schedulerValueInSeconds;
     _coins                 = coins;
     _logger                = logger;
     _schedulerType         = schedulerType;
     _candlePeriodInSeconds = candlePeriodInSeconds;
 }
Example #11
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);
        }
        private static void CrawlData(TimeSpan period, int amountOfCandles, IExchangeApi apiManager, string ticker, CancellationToken cancelletionToken)
        {
            while (!cancelletionToken.IsCancellationRequested)
            {
                CrawlForTimeFrame(Timeframe.FiveMinute, ticker, amountOfCandles, apiManager);
                Thread.Sleep(100);

                CrawlForTimeFrame(Timeframe.FiveMinute, ticker, amountOfCandles, apiManager);
                Thread.Sleep(100);

                CrawlForTimeFrame(Timeframe.FiveMinute, ticker, amountOfCandles, apiManager);
                Thread.Sleep(100);

                CrawlForTimeFrame(Timeframe.FiveMinute, ticker, amountOfCandles, apiManager);
                Thread.Sleep(period);

                CrawlForTimeFrame(Timeframe.OneMinute, ticker, amountOfCandles, apiManager);
                Thread.Sleep(period);

                CrawlForTimeFrame(Timeframe.OneMonth, ticker, amountOfCandles, apiManager);
                Thread.Sleep(period);

                CrawlForTimeFrame(Timeframe.SevenDay, ticker, amountOfCandles, apiManager);
                Thread.Sleep(period);

                CrawlForTimeFrame(Timeframe.OneDay, ticker, amountOfCandles, apiManager);
                Thread.Sleep(period);

                CrawlForTimeFrame(Timeframe.TwelveHour, ticker, amountOfCandles, apiManager);
                Thread.Sleep(period);

                CrawlForTimeFrame(Timeframe.SixHour, ticker, amountOfCandles, apiManager);
                Thread.Sleep(period);

                CrawlForTimeFrame(Timeframe.OneHour, ticker, amountOfCandles, apiManager);
                Thread.Sleep(period);

                CrawlForTimeFrame(Timeframe.ThirtyMinute, ticker, amountOfCandles, apiManager);
                Thread.Sleep(period);

                CrawlForTimeFrame(Timeframe.FiveteenMinute, ticker, amountOfCandles, apiManager);
                Thread.Sleep(period);
            }
        }
Example #13
0
        public async Task <ExchangeOrderResult> Sell(Bot bot, decimal price)
        {
            _exchangeApi = GetExchange(bot);

            if (bot.CurrentPosition == null || bot.CurrentPosition.Status != Enumerations.PositionStatusEnum.Bought)
            {
                throw new Exception("No open current position on bot");
            }

            decimal quantity = (decimal)Math.Round(bot.CurrentPosition.Quantity, bot.Coin.OrderRoundingExponent, MidpointRounding.AwayFromZero);

            switch (bot.OrderType)
            {
            case Enumerations.OrderTypeEnum.Market:
                return(Sell(bot.BaseCoin, bot.Coin, quantity, null, Enumerations.OrderTypeEnum.Market));

            case Enumerations.OrderTypeEnum.Limit:

                // get the best bid
                ExchangeOrderBook orderBook = null;

                if (_exchangeApi.Simulated)
                {
                    orderBook = SimulateExchangeOrderBook(price);
                }
                else
                {
                    orderBook = _exchangeApi.GetOrderBook(bot.BaseCoin, bot.Coin, 1);
                }

                if (orderBook != null)
                {
                    ExchangeOrderPrice bestBid = orderBook.Bids.First();

                    return(Sell(bot.BaseCoin, bot.Coin, quantity, bestBid.Price, Enumerations.OrderTypeEnum.Market));
                }
                break;

            case Enumerations.OrderTypeEnum.Stop:     // to do
                throw new NotImplementedException();
            }
            return(null);
        }
Example #14
0
        public async Task <ExchangeOrderResult> Buy(Bot bot, decimal price)
        {
            _exchangeApi = GetExchange(bot);


            switch (bot.OrderType)
            {
            case Enumerations.OrderTypeEnum.Market:
                return(Buy(bot.BaseCoin, bot.Coin, bot.Amount, null, Enumerations.OrderTypeEnum.Market));

            case Enumerations.OrderTypeEnum.Limit:


                // get the best ask
                ExchangeOrderBook orderBook = null;

                if (_exchangeApi.Simulated)
                {
                    orderBook = SimulateExchangeOrderBook(price);
                }
                else
                {
                    orderBook = _exchangeApi.GetOrderBook(bot.BaseCoin, bot.Coin, 1);
                }

                if (orderBook != null)
                {
                    ExchangeOrderPrice bestAsk = orderBook.Asks.First();

                    decimal quantity = Math.Round(bot.Amount / bestAsk.Price, bot.Coin.OrderRoundingExponent);

                    return(Buy(bot.BaseCoin, bot.Coin, quantity, bestAsk.Price, Enumerations.OrderTypeEnum.Market));
                }

                throw new Exception("Couldn't place a buy order");

            case Enumerations.OrderTypeEnum.Stop:     // to do
                throw new NotImplementedException();
            }

            return(null);
        }
Example #15
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);
        }
Example #16
0
        public void GdaxIntegrationSellTest()
        {
            Bot bot = _dbContext
                      .Bots
                      .Include("BaseCoin")
                      .Include("Coin")
                      .Include("CurrentPosition")
                      .Single(x => x.BotId == 1);

            if (bot == null || bot.CurrentPosition == null ||
                bot.CurrentPosition.Status != Enumerations.PositionStatusEnum.Bought)
            {
                throw new Exception("No current open position");
            }

            ExchangeSettings exchangeSettings = _mapper.Map <ApiSetting, ExchangeSettings>(
                _user.ApiSettings.Single(x => x.Exchange.ExchangeId == bot.Exchange.ExchangeId),
                new ExchangeSettings());

            exchangeSettings.Simulate = false;

            _exchangeApi = ExchangeEngine.ExchangeFactory.GetExchangeApi(
                (Enumerations.ExchangesEnum)bot.Exchange.ExchangeId, exchangeSettings);


            Ticker ticker = _exchangeApi.GetTicker(bot.BaseCoin, bot.Coin);


            bot.Amount = 10M; // €2

            OrderManager orderManager = new OrderManager(bot, new Trader(_logger), _dbContext, _logger, _mapper, _messagingApp);

            orderManager.Sell(new Candle()
            {
                ClosePrice = ticker.Ask, Timestamp = DateTime.Now
            });
        }
Example #17
0
        public PayInternalClient(PayInternalServiceClientSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            if (string.IsNullOrEmpty(settings.ServiceUrl))
            {
                throw new Exception("Service URL required");
            }

            _httpClient = new HttpClient
            {
                BaseAddress           = new Uri(settings.ServiceUrl),
                DefaultRequestHeaders =
                {
                    {
                        "User-Agent",
                        $"{PlatformServices.Default.Application.ApplicationName}/{PlatformServices.Default.Application.ApplicationVersion}"
                    }
                }
            };

            _payInternalApi          = RestService.For <IPayInternalApi>(_httpClient);
            _merchantsApi            = RestService.For <IMerchantsApi>(_httpClient);
            _ordersApi               = RestService.For <IOrdersApi>(_httpClient);
            _paymentRequestsApi      = RestService.For <IPaymentRequestsApi>(_httpClient);
            _assetsApi               = RestService.For <IAssetsApi>(_httpClient);
            _markupsApi              = RestService.For <IMarkupsApi>(_httpClient);
            _supervisorMembershipApi = RestService.For <ISupervisorMembershipApi>(_httpClient);
            _filesApi           = RestService.For <IFilesApi>(_httpClient);
            _merchantWalletsApi = RestService.For <IMerchantWalletsApi>(_httpClient);
            _exchangeApi        = RestService.For <IExchangeApi>(_httpClient);
            _cashoutApi         = RestService.For <ICashoutApi>(_httpClient);
            _runner             = new ApiRunner();
        }
Example #18
0
 public BitfinexDataCrawler(IExchangeApi apiManager)
 {
     _apiManager = apiManager;
 }
 public CurrencyConverterTests()
 {
     _fakeApi = new ExchangeApiFake();
     _service = new ExchangeService(_fakeApi);
 }
Example #20
0
 public SubscriptionBase(IExchangeApi exchangeApi)
 {
     ExchangeApi             = exchangeApi;
     subscribers             = new ConcurrentDictionary <string, StrategyNotification <T> >();
     cancellationTokenSource = new CancellationTokenSource();
 }
Example #21
0
 public NotificationManager(IExchangeApi api, ITradingStrategy strategy, Action <string> log)
 {
     _api      = api;
     _strategy = strategy;
     _log      = log;
 }
Example #22
0
 public SubscriptionContainer(IExchangeApi api)
 {
     Api    = api;
     Subs   = new HashSet <Subscription>();
     Active = new Dictionary <int, Subscription>();
 }
 public SymbolInformationService(IExchangeApi api, ICandleProvider candleProvider)
 {
     this.api            = api;
     this.candleProvider = candleProvider;
 }
Example #24
0
 public SubscribeTrades(string symbol, int limit, IExchangeApi exchangeApi)
     : base(symbol, limit, exchangeApi)
 {
 }
Example #25
0
        public async Task BackTestAllBots()
        {
            // get user
            User user = _dbContext
                        .Users
                        .Include(x => x.ApiSettings.Select(y => y.Exchange))
                        .Include(x => x.MessagingApps)
                        .Include(x => x.MessagingApps.Select(y => y.MessagingAppSettings))
                        .Single(x => x.UserId == 1);

            // get watches, get coins, get exchange

            List <Bot> bots =
                _dbContext
                .Bots
                .Include("User")
                .Include("User.ApiSettings")
                .Include("User.ApiSettings.Exchange")
                .Include("User.MessagingApps")
                .Include("User.MessagingApps.MessagingAppSettings")
                .Include("Exchange")
                .Include("Coin")
                .Include("BaseCoin")
                .Include("Positions")
                .Include("Indicators")
                .Include("Indicators.RuleSets")
                .Include("Indicators.RuleSets.Rules")
                .AsNoTracking()
                .Where(x => x.User.UserId == user.UserId)
                .Where(x => x.Active)
                .ToList();


            // get the messaging app if any
            if (user.MessagingApps.Any(x => x.Active))
            {
                var app = user.MessagingApps.First(x => x.Active);

                _messagingApp = MessagingAppFactory.GetMessagingApp(app, _logger, _dbContext);
            }

            int oneMinute     = 60;
            int fifteenMinute = oneMinute * 15;
            int thirtyMinute  = oneMinute * 30;
            int sixtyMinute   = oneMinute * 60;



            foreach (Bot bot in bots)
            {
                IExchangeApi exchangeApi = ExchangeEngine.ExchangeFactory.GetExchangeApi(
                    (Enumerations.ExchangesEnum)bot.Exchange.ExchangeId,
                    _mapper.Map <ApiSetting, ExchangeSettings>(
                        user.ApiSettings.Single(x => x.Exchange.ExchangeId == bot.Exchange.ExchangeId),
                        new ExchangeSettings()));


                /*
                 *  Note from GDAX...
                 *
                 *  The maximum number of data points for a single request is 200 candles.
                 *  If your selection of start/end time and granularity will result in more than 200 data points, your request will be rejected.
                 *  If you wish to retrieve fine granularity data over a larger time range, you will need to make multiple requests with new start/end ranges.
                 *
                 */

                int requiredWeeks = 1;

                List <Candle> candles = new List <Candle>();



                var requiredHours = 36;

                for (int k = requiredHours; k > 0; k--)
                {
                    var fromDate = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(60 * k));
                    fromDate = new DateTime(fromDate.Year, fromDate.Month, fromDate.Day, fromDate.Hour, 0, 0); // the start of the hour
                    var toDate = fromDate.AddHours(1);
                    toDate = new DateTime(toDate.Year, toDate.Month, toDate.Day, toDate.Hour, 0, 0);

                    int candleSize = 60 * 5; // 60 second x ?

                    try
                    {
                        candles.AddRange(exchangeApi.GetCandles(bot.BaseCoin, bot.Coin, candleSize, fromDate, toDate));
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e);
                    }



                    if (k % 2 == 0) // only three requests allowed per second on GDAX
                    {
                        Thread.Sleep(1000);
                    }
                }



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



                TradeBot tradeBot = new TradeBot(bot, _logger, _dbContext, _mapper, _IndicatorFactoryWrapper, _messagingApp);

                _messageDispatcher.AddMessageHandler(tradeBot);


                foreach (Candle candle in candles)
                {
                    _messageDispatcher.Dispatch(new CandleMessage
                    {
                        Candles = new List <Candle>()
                        {
                            candle
                        },
                        BaseCoin = bot.BaseCoin,
                        Coin     = bot.Coin
                    });
                }

                // close last order in case its open
                if (bot.CurrentPosition?.Status == Enumerations.PositionStatusEnum.Bought)
                {
                    Position position =
                        _dbContext.Positions.Single(x => x.PositionId == bot.CurrentPosition.PositionId);
                    position.Status = Enumerations.PositionStatusEnum.Sold;
                    _dbContext.SaveChanges();
                }


                tradeBot.OnStop();
                tradeBot = null;
            }
        }
Example #26
0
 public SubscribeOrderBook(string symbol, int limit, IExchangeApi exchangeApi)
     : base(symbol, limit, exchangeApi)
 {
 }
Example #27
0
 public KucoinOrderBookHelper(IExchangeApi kucoinExchangeApi)
 {
     this.kucoinExchangeApi = kucoinExchangeApi;
 }
Example #28
0
 public SubscribeAccountInfo(IExchangeApi exchangeApi)
     : base(exchangeApi)
 {
     User = new User();
 }
Example #29
0
 public ExchangeService(IExchangeApi exchangeApi)
 {
     this.exchangeApi = exchangeApi;
 }
Example #30
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="api">Exchange API</param>
 /// <param name="symbol">The symbol to trade by default, can be null</param>
 public ExchangeInfo(IExchangeApi api, Coin baseCoin, Coin coin)
 {
     API       = api;
     Symbols   = api.GetSymbols().ToArray();
     TradeInfo = new ExchangeTradeInfo(this, baseCoin, coin);
 }