Ejemplo n.º 1
0
        public async Task doWork(object objState)
        {
            logger.Trace("Start getCandles");

            // update the wallet.
            this.myWallet = await getWallet();

            int numTickers = this.Assets.Count();

            for (int i = 0; i < numTickers; i++)
            {
                var ticker = this.Assets[i].Ticker;
                var candle = (await api.GetCandlesAsync(ticker, 900, null, null, 100)).ToArray();
                var ohlc   = candle.Last();
                var asset  = this.Assets[i];
                asset.UpdateOHLC(ohlc.Timestamp, ohlc.OpenPrice, ohlc.HighPrice, ohlc.LowPrice, ohlc.ClosePrice, ohlc.QuoteCurrencyVolume);

                if (asset.percentagePriceChange > 2.5m && !asset.HasTrade && asset.CanBuy)
                {
                    doBuy(asset);
                }
            }

            logger.Trace("End getCandles");
        }
Ejemplo n.º 2
0
        public async Task <List <Candle> > GetTickerHistory(string market, Period period, DateTime startDate, DateTime?endDate = null)
        {
            IEnumerable <MarketCandle> tickers = new List <MarketCandle>();

            int k = 9;

            if (Global.Configuration.ExchangeOptions.FirstOrDefault().IsSimulation)
            {
                k = 9;
            }

            while (tickers.Count() <= 0 && k < 10)
            {
                k++;
                try
                {
                    tickers = await _api.GetCandlesAsync(market, period.ToMinutesEquivalent() * 60, startDate, endDate);
                }
                catch (Exception ex)
                {
                    Global.Logger.Error(ex, $"Error on GetCandlesAsync");

                    await Task.Delay(1000);
                }
            }

            var candles = new List <Candle>();

            foreach (var item in tickers)
            {
                if (item != null)
                {
                    try
                    {
                        var candle = new Candle();

                        candle.Close     = item.ClosePrice;
                        candle.High      = item.HighPrice;
                        candle.Low       = item.LowPrice;
                        candle.Open      = item.OpenPrice;
                        candle.Timestamp = item.Timestamp;
                        candle.Volume    = (decimal)item.ConvertedVolume;

                        candles.Add(candle);
                    }
                    catch (Exception ex)
                    {
                        Global.Logger.Error(ex, $"Error on GetTickerHistory {item} {tickers}");
                    }
                }
                else
                {
                    Global.Logger.Error(new Exception(), $"Error ticker is null {tickers}");
                }
            }

            //candles = await candles.FillCandleGaps(period);

            return(candles.OrderBy(x => x.Timestamp).ToList());
        }
Ejemplo n.º 3
0
        private async Task <List <MarketCandle> > GetTrendCandles(string marketSymbol)
        {
            var candles = (await _api.GetCandlesAsync(marketSymbol, 60 * 60, DateTime.UtcNow.AddHours(-4), null, 4)).Reverse().ToList();

            if (candles.Count() != 4)
            {
                Trace.WriteLine("Couldn't get 4 candles");
                return(candles);
            }
            return(candles);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Performs a scan for all filtered symbols
        /// </summary>
        /// <returns></returns>
        public async Task <Signal> ScanAsync(string symbol)
        {
            try
            {
                // download the new candles
                var candles = (await _api.GetCandlesAsync(symbol, 60 * _minutes, DateTime.Now.AddMinutes(-5 * 50))).Reverse().ToList();
                candles = AddMissingCandles(candles);
                // scan candles for buy/sell signal
                TradeType tradeType = TradeType.Long;
                var       strategy  = new DayTradingStrategy(symbol, _settings);
                if (strategy.IsValidEntry(candles, 0, out tradeType))
                {
                    // ignore signals for shorts when not allowed
                    if (tradeType == TradeType.Short && !_settings.AllowShorts)
                    {
                        return(null);
                    }

                    // got buy/sell signal.. write to console
                    Console.Beep();
                    return(new Signal()
                    {
                        Symbol = symbol,
                        Trade = tradeType.ToString(),
                        Date = $"{candles[0].Timestamp.AddHours(2):dd-MM-yyyy HH:mm}"
                    });
                }
Ejemplo n.º 5
0
        /// <summary>
        /// Downloads 5min. candle sticks data for the symbol from 1/1/2018 until now
        /// </summary>
        /// <returns>list of 5m candle sticks</returns>
        /// <param name="api">exchange api</param>
        /// <param name="symbol">symbol to get the candlesticks from</param>
        private List <MarketCandle> DownloadCandlesFromExchange(ExchangeAPI api, string symbol, DateTime startDate, DateTime endDate)
        {
            // get candle stick data
            Console.WriteLine($"Downloading 5m candlesticks for {symbol} from {api.Name}");
            var allCandles = new List <MarketCandle>();

            while (true)
            {
                try
                {
                    var candles = api.GetCandlesAsync(symbol, 5 * 60, startDate, DateTime.Now, 1000).Result.ToList();
                    if (candles == null)
                    {
                        break;
                    }
                    if (candles.Count == 0)
                    {
                        break;
                    }
                    allCandles.AddRange(candles);
                    startDate = candles.Last().Timestamp;
                    Console.WriteLine($"date:{candles[0].Timestamp} - {startDate}  / total:{allCandles.Count}");
                    if (candles.Count < 1000)
                    {
                        break;
                    }
                    if (startDate > endDate)
                    {
                        break;
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("-");
                }

                //if (allCandles.Count > 4000) break;
            }
            allCandles.Reverse();
            return(allCandles);
        }
Ejemplo n.º 6
0
        public async Task doWork(object objState)
        {
            logger.Trace("Start getCandles");

            // retry 10 times and if still fails, just skip this timestamp.
            for (int retry = 0; retry < 10; retry++)
            {
                try
                {
                    // update the wallet.
                    this.myWallet = await getWallet();

                    logger.Trace($"Wallet: {myWallet[QUOTECURRENCY]}");
                    break;
                }
                catch (Exception ex)
                {
                    logger.Trace($"retry-{retry} wallet. {ex}");

                    if (retry >= 9)
                    {
                        throw new Exception("Give up after 10 tries");
                    }

                    Thread.Sleep(30000);
                }
            }

            int numTickers = this.Assets.Count();

            for (int i = 0; i < numTickers; i++)
            {
                var asset  = this.Assets[i];
                var ticker = asset.Ticker;
                try
                {
                    Console.Write(".");
                    var candles = (await api.GetCandlesAsync(ticker, CANDLEPERIODSECS, null, null, 300)).ToArray();
                    var cc      = candles[candles.Count() - 2];

                    IList <Quote> history = new List <Quote>();
                    foreach (var candle in candles)
                    {
                        history.Add(new Quote
                        {
                            Date   = candle.Timestamp,
                            Open   = candle.OpenPrice,
                            High   = candle.HighPrice,
                            Low    = candle.LowPrice,
                            Close  = candle.ClosePrice,
                            Volume = (decimal)candle.QuoteCurrencyVolume
                        });
                    }

                    // calculate RSI(14)
                    IList <RsiResult>        rsi      = Indicator.GetRsi(history, 14).ToArray();
                    IList <HeikinAshiResult> ha       = Indicator.GetHeikinAshi(history).ToArray();
                    IList <HeikinAshi>       ashiList = new List <HeikinAshi>();
                    foreach (var item in ha)
                    {
                        ashiList.Add(new HeikinAshi(item));
                    }

                    // remember to throw out the last candle because that is the active candle that is not completed yet.
                    var completedRSI  = rsi[rsi.Count - 2];
                    var previousRSI   = rsi[rsi.Count - 3];
                    var completedAshi = ashiList[ashiList.Count - 2];
                    var previousAshi  = ashiList[ashiList.Count - 3];

                    asset.UpdateOHLC(cc.Timestamp, cc.OpenPrice, cc.HighPrice, cc.LowPrice, cc.ClosePrice, cc.QuoteCurrencyVolume);
                    asset.RSI = completedRSI.Rsi.Value;

                    //var isBuy = this.checkRSI30UpCrossing(previousRSI.Rsi, completedRSI.Rsi) && !asset.HasTrade;
                    //var isBuy = completedRSI.Rsi < 20;
                    //var isSellProfit = completedRSI.Rsi > 69;
                    var isBuy        = completedAshi.Signal == HeikinAshi.HeikinAshiSignal.STRONGBUY && previousAshi.Signal != HeikinAshi.HeikinAshiSignal.STRONGBUY;
                    var isSellProfit = completedAshi.Signal == HeikinAshi.HeikinAshiSignal.STRONGSELL || previousAshi.Signal == HeikinAshi.HeikinAshiSignal.SELL;

                    if (isBuy && !asset.HasTrade)
                    {
                        var et = await api.GetTickerAsync(asset.Ticker);

                        asset.UpdatePrices(et.Last, et.Ask, et.Bid);
                        doBuy(asset);
                    }
                    else if (isSellProfit && asset.HasTrade)
                    {
                        var et = await api.GetTickerAsync(asset.Ticker);

                        asset.UpdatePrices(et.Last, et.Ask, et.Bid);
                        doSell(asset);
                    }
                }
                catch (Exception ex)
                {
                    logger.Trace(ex);
                }
            }

            // print out some trade summary
            var tradedAssets = this.Assets.Where(a => a.HasTrade);
            var timeStamps   = this.Assets.Select(a => a.TimeStamp).Distinct();

            logger.Trace(String.Join(",", timeStamps));
            foreach (var tA in tradedAssets)
            {
                logger.Trace($"{tA.Ticker}, BuyPrice: {tA.BuyPrice:0.000}, ClosePrice:{tA.ClosePrice:0.000}");
            }

            logger.Trace("End getCandles");
        }
Ejemplo n.º 7
0
        public async Task <List <MarketCandle> > GetKlines(string symbol, KlineInterval interval)
        {
            List <MarketCandle> candles = (await api.GetCandlesAsync(symbol, (int)interval, null, null, 100)).ToList();

            return(candles);
        }