public void Throws()
        {
            var        time         = DateTimeOffset.FromUnixTimeMilliseconds(DateTime.UtcNow.ToTimestamp()).UtcDateTime;
            const long firstTradeId = 1234567890;
            const long lastTradeId  = 1234567899;
            const bool isFinal      = true;

            var symbol = Symbol.BTC_USDT;
            const CandlestickInterval interval = CandlestickInterval.Hour;
            var           openTime             = DateTimeOffset.FromUnixTimeMilliseconds(DateTime.UtcNow.ToTimestamp()).UtcDateTime;
            const decimal open                     = 4950;
            const decimal high                     = 5100;
            const decimal low                      = 4900;
            const decimal close                    = 5050;
            const decimal volume                   = 1000;
            var           closeTime                = openTime.AddHours(1);
            const long    quoteAssetVolume         = 5000000;
            const int     numberOfTrades           = 555555;
            const decimal takerBuyBaseAssetVolume  = 4444;
            const decimal takerBuyQuoteAssetVolume = 333;

            var candlestick = new Candlestick(symbol, interval, openTime, open, high, low, close, volume, closeTime, quoteAssetVolume, numberOfTrades, takerBuyBaseAssetVolume, takerBuyQuoteAssetVolume);

            Assert.Throws <ArgumentNullException>("candlestick", () => new CandlestickEventArgs(time, null, firstTradeId, lastTradeId, isFinal));
            Assert.Throws <ArgumentException>("firstTradeId", () => new CandlestickEventArgs(time, candlestick, -2, lastTradeId, isFinal));
            Assert.Throws <ArgumentException>("lastTradeId", () => new CandlestickEventArgs(time, candlestick, firstTradeId, -2, isFinal));
            Assert.Throws <ArgumentException>("lastTradeId", () => new CandlestickEventArgs(time, candlestick, firstTradeId, firstTradeId - 1, isFinal));
        }
Exemplo n.º 2
0
        public override void Calculate(int index)
        {
            //Print("LastCandlestick: {0} at index: {1}", this.GetMarketSeries(index), index);
            cs1 = this.GetMarketSeries(index);
            cs2 = this.GetMarketSeries(index - 1);
            cs3 = this.GetMarketSeries(index - 2);
            // Calculate value at specified index
            // Result[index] = ...

            if (
                cs2.Height.IsPositive() && cs3.Height.IsPositive() &&
                cs2.Height / cs3.Height >= TriggerHeightRatio &&
                cs2.High < cs3.High && cs2.Low < cs3.Low &&
                cs2.CloseToLowHeight / cs3.CloseToLowHeight >= TriggerHLRatio
                )
            {
                BuySignal[index - 1] = cs2.RealBodyLow;
                SellSignal[index]    = this.ShiftPrice(cs1.Open, TargetPoints);
            }


            if (
                cs2.Height.IsPositive() && cs3.Height.IsPositive() &&
                cs2.Height / cs3.Height >= TriggerHeightRatio &&
                cs2.High > cs3.High && cs2.Low > cs3.Low &&
                cs2.HighToCloseHeight / cs3.HighToCloseHeight >= TriggerHLRatio
                )
            {
                SellSignal[index - 1] = cs2.RealBodyHigh;
                BuySignal[index]      = this.ShiftPrice(cs1.Open, -TargetPoints);
            }
        }
Exemplo n.º 3
0
        public void AddCandleStick(Candlestick futureCandleStick)
        {
            var list = new List <Candlestick>();

            list.Add(futureCandleStick);
            list.AddRange(_candleSticks.Take(100));
            _candleSticks = list;
            rsi.AddCandleStick(futureCandleStick);
            var     sRsiList   = new List <decimal>();
            var     rsiLenList = rsi.rsi.Take(_shochRsiLength).ToList();
            var     maxRsi     = rsiLenList.Max();
            var     minRsi     = rsiLenList.Min();
            decimal shochrsi;

            if (maxRsi - minRsi != 0)
            {
                shochrsi = (rsi.Value - minRsi) / (maxRsi - minRsi);
            }
            else
            {
                shochrsi = 0;
            }

            sRsiList.Add(shochrsi);
            sRsiList.AddRange(stochRsi.Take(100));
            stochRsi = sRsiList;
            CalculateKandD();
        }
Exemplo n.º 4
0
 internal static void Display(Candlestick candlestick)
 {
     lock (ConsoleSync)
     {
         Console.WriteLine($"  {candlestick.Symbol} - O: {candlestick.Open:0.00000000}  H: {candlestick.High:0.00000000}  L: {candlestick.Low:0.00000000}  C: {candlestick.Close:0.00000000}  V: {candlestick.Volume:0.00}  [{candlestick.OpenTime.ToTimestamp()}]");
     }
 }
Exemplo n.º 5
0
        public void AddCandleStick(Candlestick candleStick)
        {
            var diff = _closePrices.First() - candleStick.Close;

            var            list    = new List <decimal>();
            List <decimal> avgGain = new List <decimal>();
            List <decimal> avgLoss = new List <decimal>();
            List <decimal> rsiList = new List <decimal>();

            list.Add(candleStick.Close);
            list.AddRange(_closePrices.Take(100));
            _closePrices = list;

            var t1 = (_avgGain.First() * (_length - 1) + (diff > 0 ? diff : 0)) / _length;
            var t2 = (_avgLoss.First() * (_length - 1) + (diff < 0 ? -diff : 0)) / _length;

            avgGain.Add(t1);
            avgLoss.Add(t2);
            rsiList.Add(GetRsi(avgGain.First(), avgLoss.First()));

            avgGain.AddRange(_avgGain.Take(100));
            avgLoss.AddRange(_avgLoss.Take(100));

            rsiList.AddRange(rsi.Take(100));
            rsi      = rsiList;
            _avgGain = avgGain;
            _avgLoss = avgLoss;
        }
 public Trend getTrend(Candlestick candlestick)
 {
     double midPoint = calculateMidPoint(candlestick);
     if (candlestick.Quote > midPoint) return Trend.Bullish;
     if (candlestick.Quote < midPoint) return Trend.Bearish;
     return Trend.UnTrended;
 }
Exemplo n.º 7
0
        public void Throws()
        {
            var        timestamp    = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            const long firstTradeId = 1234567890;
            const long lastTradeId  = 1234567899;
            const bool isFinal      = true;

            var symbol = Symbol.BTC_USDT;
            const CandlestickInterval interval = CandlestickInterval.Hour;
            const long    openTime             = 1234567890;
            const decimal open                     = 4950;
            const decimal high                     = 5100;
            const decimal low                      = 4900;
            const decimal close                    = 5050;
            const decimal volume                   = 1000;
            const long    closeTime                = 2345678901;
            const long    quoteAssetVolume         = 5000000;
            const int     numberOfTrades           = 555555;
            const decimal takerBuyBaseAssetVolume  = 4444;
            const decimal takerBuyQuoteAssetVolume = 333;

            var candlestick = new Candlestick(symbol, interval, openTime, open, high, low, close, volume, closeTime, quoteAssetVolume, numberOfTrades, takerBuyBaseAssetVolume, takerBuyQuoteAssetVolume);

            using (var cts = new CancellationTokenSource())
            {
                Assert.Throws <ArgumentException>("timestamp", () => new CandlestickEventArgs(-1, cts.Token, candlestick, firstTradeId, lastTradeId, isFinal));
                Assert.Throws <ArgumentException>("timestamp", () => new CandlestickEventArgs(0, cts.Token, null, firstTradeId, lastTradeId, isFinal));
                Assert.Throws <ArgumentNullException>("candlestick", () => new CandlestickEventArgs(timestamp, cts.Token, null, firstTradeId, lastTradeId, isFinal));
                Assert.Throws <ArgumentException>("firstTradeId", () => new CandlestickEventArgs(timestamp, cts.Token, candlestick, -2, lastTradeId, isFinal));
                Assert.Throws <ArgumentException>("lastTradeId", () => new CandlestickEventArgs(timestamp, cts.Token, candlestick, firstTradeId, -2, isFinal));
                Assert.Throws <ArgumentException>("lastTradeId", () => new CandlestickEventArgs(timestamp, cts.Token, candlestick, firstTradeId, firstTradeId - 1, isFinal));
            }
        }
Exemplo n.º 8
0
        public void Equality()
        {
            var symbol = Symbol.BTC_USDT;
            const CandlestickInterval interval = CandlestickInterval.Hour;
            var           openTime             = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            const decimal open                     = 4950;
            const decimal high                     = 5100;
            const decimal low                      = 4900;
            const decimal close                    = 5050;
            const decimal volume                   = 1000;
            var           closeTime                = DateTimeOffset.FromUnixTimeMilliseconds(openTime).AddHours(1).ToUnixTimeMilliseconds();
            const long    quoteAssetVolume         = 5000000;
            const int     numberOfTrades           = 555555;
            const decimal takerBuyBaseAssetVolume  = 4444;
            const decimal takerBuyQuoteAssetVolume = 333;

            var candlestick = new Candlestick(symbol, interval, openTime, open, high, low, close, volume, closeTime, quoteAssetVolume, numberOfTrades, takerBuyBaseAssetVolume, takerBuyQuoteAssetVolume);

            var serializer = new CandlestickSerializer();

            var json = serializer.Serialize(candlestick);

            var other = serializer.Deserialize(json);

            Assert.True(candlestick.Equals(other));
        }
Exemplo n.º 9
0
        public void Properties()
        {
            var symbol = Symbol.BTC_USDT;
            const CandlestickInterval interval = CandlestickInterval.Hour;
            var           openTime             = DateTimeOffset.FromUnixTimeMilliseconds(DateTime.UtcNow.ToTimestamp()).UtcDateTime;
            const decimal open                     = 4950;
            const decimal high                     = 5100;
            const decimal low                      = 4900;
            const decimal close                    = 5050;
            const decimal volume                   = 1000;
            var           closeTime                = openTime.AddHours(1);
            const long    quoteAssetVolume         = 5000000;
            const int     numberOfTrades           = 555555;
            const decimal takerBuyBaseAssetVolume  = 4444;
            const decimal takerBuyQuoteAssetVolume = 333;

            var candlestick = new Candlestick(symbol, interval, openTime, open, high, low, close, volume, closeTime, quoteAssetVolume, numberOfTrades, takerBuyBaseAssetVolume, takerBuyQuoteAssetVolume);

            Assert.Equal(symbol, candlestick.Symbol);
            Assert.Equal(interval, candlestick.Interval);
            Assert.Equal(openTime, candlestick.OpenTime);
            Assert.Equal(open, candlestick.Open);
            Assert.Equal(high, candlestick.High);
            Assert.Equal(low, candlestick.Low);
            Assert.Equal(close, candlestick.Close);
            Assert.Equal(volume, candlestick.Volume);
            Assert.Equal(closeTime, candlestick.CloseTime);
            Assert.Equal(quoteAssetVolume, candlestick.QuoteAssetVolume);
            Assert.Equal(numberOfTrades, candlestick.NumberOfTrades);
            Assert.Equal(takerBuyBaseAssetVolume, candlestick.TakerBuyBaseAssetVolume);
            Assert.Equal(takerBuyQuoteAssetVolume, candlestick.TakerBuyQuoteAssetVolume);
        }
Exemplo n.º 10
0
        private static void Display(Candlestick candlestick)
        {
            lock (_sync)
            {
                _candlesticks[candlestick.Symbol] = candlestick;

                if (_displayTask.IsCompleted)
                {
                    // Delay to allow multiple data updates between display updates.
                    _displayTask = Task.Delay(100)
                                   .ContinueWith(_ =>
                    {
                        Candlestick[] latestCandlesticks;
                        lock (_sync)
                        {
                            latestCandlesticks = _candlesticks.Values.ToArray();
                        }

                        Console.SetCursorPosition(0, 0);

                        foreach (var c in latestCandlesticks)
                        {
                            Console.WriteLine($" {c.Symbol} - O: {c.Open:0.00000000} | H: {c.High:0.00000000} | L: {c.Low:0.00000000} | C: {c.Close:0.00000000} | V: {c.Volume:0.00} - [{c.OpenTime.ToTimestamp()}]".PadRight(119));
                            Console.WriteLine();
                        }

                        Console.WriteLine(message);
                    });
                }
            }
        }
Exemplo n.º 11
0
        private PatternViewModel CreatePVM(Ticker ticker, List <Candlestick> listOfCandlesticks)
        {
            PatternViewModel pvm = new PatternViewModel();


            var CandlesticksForValidTickers = listOfCandlesticks.FindAll(x => x.Symbol == ticker.Symbol);

            if (CandlesticksForValidTickers.Count > 0)
            {
                pvm.Symbol      = ticker.Symbol;
                pvm.Price       = ticker.Price.ToString();
                pvm.AskPrice    = ticker.AskPrice.ToString();
                pvm.PatternType = "BULLFLAG";
                for (int i = 0; i < CandlesticksForValidTickers.Count; i++)
                {
                    Candlestick candlestick = CandlesticksForValidTickers[i];
                    pvm.Interval = candlestick.Interval;
                    pvm.OpenTimes.Add(Convert.ToDouble(candlestick.OpenTime));
                    pvm.Opens.Add(candlestick.Open);
                    pvm.Highs.Add(candlestick.High);
                    pvm.Lows.Add(candlestick.Low);
                    pvm.Closes.Add(candlestick.Close);
                    pvm.Volumes.Add(candlestick.Volume);
                    pvm.CloseTimes.Add(Convert.ToDouble(candlestick.CloseTime));
                    pvm.QuoteAssetVolumes.Add(candlestick.QuoteAssetVolume);
                    pvm.NumberOfTrades.Add(Convert.ToInt32(candlestick.NumberOfTrades));
                    pvm.TakerBuyBaseAssetVolume.Add(candlestick.TakerBuyBaseAssetVolume);
                    pvm.TakerBuyQuoteAssetVolume.Add(candlestick.TakerBuyQuoteAssetVolume);
                }
                return(pvm);
            }
            return(null);
        }
Exemplo n.º 12
0
 internal static void Display(Candlestick candlestick)
 {
     lock (ConsoleSync)
     {
         Console.WriteLine($"  {candlestick.Symbol} - O: {candlestick.Open:0.00000000} | H: {candlestick.High:0.00000000} | L: {candlestick.Low:0.00000000} | C: {candlestick.Close:0.00000000} | V: {candlestick.Volume:0.00} - [{candlestick.OpenTime}]");
     }
 }
Exemplo n.º 13
0
        private List <Candlestick> GetCandlesticks(string ticker, string interval, string limit)
        {
            HttpClientHandler handler = new HttpClientHandler();

            handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
            List <Candlestick> listOfCandlesticks = new List <Candlestick>();
            HttpClient         client             = new HttpClient(handler);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization");
            string query  = "/api/v1/klines?symbol=" + ticker + "&interval=" + interval + "&limit=" + limit;
            var    result = client.GetAsync(new Uri(burl + query)).Result;

            if (result.IsSuccessStatusCode)
            {
                string myContent        = result.Content.ReadAsStringAsync().Result;
                var    candlestickRange = JsonConvert.DeserializeObject <List <List <string> > >(myContent);

                foreach (var candlestick in candlestickRange)
                {
                    Candlestick cvm = new Candlestick(ticker, candlestick);
                    listOfCandlesticks.Add(cvm);
                }
                return(listOfCandlesticks);
                //WriteToTextFile(listOfCandlesticks);
                //return View(listOfCandlesticks);
            }
            return(null);
        }
Exemplo n.º 14
0
    //**************************************************************************************

    /// <summary>
    /// Load candlesticks from DB.
    /// </summary>
    public static List <Candlestick> LoadFromDB(string iTableName)
    {
        var results = new List <Candlestick>();

        using (var connection = new SqlConnection(Program.SQLConnectionName))
        {
            connection.Open();

            var sql = "Select * from " + iTableName;

            var command = new SqlCommand(sql, connection);
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    var startTime   = Utils.DateTimeToUnix(reader.GetDateTime(0));
                    var endTime     = Utils.DateTimeToUnix(reader.GetDateTime(1));
                    var openPrice   = (float)reader.GetDouble(2);
                    var closePrice  = (float)reader.GetDouble(3);
                    var highPrice   = (float)reader.GetDouble(4);
                    var lowPrice    = (float)reader.GetDouble(5);
                    var medianPrice = (float)reader.GetDouble(6);

                    var c = new Candlestick(startTime, endTime, openPrice, closePrice, highPrice, lowPrice, medianPrice);
                    results.Add(c);
                }
            }
        }

        return(results);
    }
Exemplo n.º 15
0
        protected override void OnBar()
        {
            // Put your core logic here

            cs2 = this.GetMarketSeries(1);
            cs3 = this.GetMarketSeries(2);

            Print("{0}", cs2.OpenTime.ToLocalTime().ToString("dd MMM yy HH:mm"));

            if (
                cs2.Height.IsPositive() && cs3.Height.IsPositive() &&
                cs2.Height / cs3.Height >= TriggerHeightRatio &&
                cs2.High < cs3.High && cs2.Low < cs3.Low &&
                cs2.CloseToLowHeight / cs3.CloseToLowHeight >= TriggerHLRatio
                )
            {
                //BUY
                ExecuteMarketOrder(TradeType.Buy, Symbol.Name, Volume, string.Empty, StopLossPips > 0 ? new Nullable <double>(StopLossPips) : null, TakeProfitPips > 0 ? new Nullable <double>(TakeProfitPips) : null);
            }

            if (
                cs2.Height.IsPositive() && cs3.Height.IsPositive() &&
                cs2.Height / cs3.Height >= TriggerHeightRatio &&
                cs2.High > cs3.High && cs2.Low > cs3.Low &&
                cs2.HighToCloseHeight / cs3.HighToCloseHeight >= TriggerHLRatio
                )
            {
                //SELL
                ExecuteMarketOrder(TradeType.Sell, Symbol.Name, Volume, string.Empty, StopLossPips > 0 ? new Nullable <double>(StopLossPips) : null, TakeProfitPips > 0 ? new Nullable <double>(TakeProfitPips) : null);
            }
        }
Exemplo n.º 16
0
        public void Insert(Candlestick candlestick, string exchange = "Binance")
        {
            var openTime   = new DateTime(candlestick.OpenTime.Year, candlestick.OpenTime.Month, candlestick.OpenTime.Day, candlestick.OpenTime.Hour, candlestick.OpenTime.Minute, 0);
            var closeTime  = new DateTime(candlestick.CloseTime.Year, candlestick.CloseTime.Month, candlestick.CloseTime.Day, candlestick.CloseTime.Hour, candlestick.CloseTime.Minute, 0);
            var sql        = @"INSERT INTO public.klines(""openTime"", open, high, low, close, ""closeTime"", ""quoteAssetVolume"", ""numberOfTrades"", ""baseVolume"", ""quoteVolume"", symbol, exchange)
                VALUES(@openTime, @open, @high, @low, @close, @closeTime, @quoteAssetVolume, @numberOfTrades, @baseVolume, @quoteVolume, @symbol, @exchange); ";
            var parameters = new
            {
                openTime,
                open   = candlestick.Open,
                high   = candlestick.High,
                low    = candlestick.Low,
                close  = candlestick.Close,
                volume = candlestick.Volume,
                closeTime,
                quoteAssetVolume = candlestick.QuoteAssetVolume,
                numberOfTrades   = candlestick.NumberOfTrades,
                baseVolume       = candlestick.TakerBuyBaseAssetVolume,
                quoteVolume      = candlestick.TakerBuyQuoteAssetVolume,
                symbol           = candlestick.Symbol,
                exchange
            };

            using (IDbConnection connection = Connection)
            {
                connection.Execute(sql, parameters);
            }
        }
Exemplo n.º 17
0
        public void Add(Candlestick futureCandleStick)
        {
            //kdb c = new kdb("localhost", 5000);
            List <Candlestick> list = new List <Candlestick>();

            list.Add(futureCandleStick);
            list.AddRange(_candleSticks);
            _candleSticks = list;
            foreach (KeyValuePair <int, Sma> keyValuePair in Sma)
            {
                keyValuePair.Value.AddCandleStick(futureCandleStick);
                //c.k($"insert[`MA](`{pair};\"Z\"$ \"{futureCandleStick.OpenDateTime:yyyy-MM-ddTHH:mm:ss:fffff}\"; `SMA; {keyValuePair.Key.ToString()}; \"f\"${keyValuePair.Value.Value})");
            }
            foreach (KeyValuePair <int, Ema> keyValuePair in Ema)
            {
                keyValuePair.Value.AddCandleStick(futureCandleStick);
                // c.k($"insert[`MA](`{pair};\"Z\"$ \"{futureCandleStick.OpenDateTime:yyyy-MM-ddTHH:mm:ss:fffff}\"; `EMA;{keyValuePair.Key.ToString()}; \"f\"${keyValuePair.Value.Value})");
            }
            foreach (KeyValuePair <int, Gsma> keyValuePair in Gsma)
            {
                keyValuePair.Value.AddCandleStick(futureCandleStick);
                //c.k($"insert[`MA](`{pair};\"Z\"$ \"{futureCandleStick.OpenDateTime:yyyy-MM-ddTHH:mm:ss:fffff}\"; `GSMA; {keyValuePair.Key.ToString()}; \"f\"${keyValuePair.Value.Value*10000000000})");
            }
            stochRsi.AddCandleStick(futureCandleStick);
            //c.k($"insert[`Oscillator](`{pair};\"Z\"$ \"{futureCandleStick.OpenDateTime:yyyy-MM-ddTHH:mm:ss:fffff}\"; `SRSI; \"f\"${ stochRsi.KValue};\"f\"${stochRsi.DValue})");
            rsi.AddCandleStick(futureCandleStick);
            //c.k($"insert[`Oscillator](`{pair};\"Z\"$ \"{futureCandleStick.OpenDateTime:yyyy-MM-ddTHH:mm:ss:fffff}\"; `RSI; \"f\"${ rsi.Value};0.0)");
            macd.AddCandleStick(futureCandleStick);
            //c.k($"insert[`Oscillator](`{pair};\"Z\"$ \"{futureCandleStick.OpenDateTime:yyyy-MM-ddTHH:mm:ss:fffff}\"; `MACD; \"f\"${ macd.MacdLine.First()*100000000};\"f\"${macd.SignalLine.First()*100000000})");
        }
Exemplo n.º 18
0
        public void Properties()
        {
            var        timestamp    = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            const long firstTradeId = 1234567890;
            const long lastTradeId  = 1234567899;
            const bool isFinal      = true;

            var symbol = Symbol.BTC_USDT;
            const CandlestickInterval interval = CandlestickInterval.Hour;
            const long    openTime             = 1234567890;
            const decimal open                     = 4950;
            const decimal high                     = 5100;
            const decimal low                      = 4900;
            const decimal close                    = 5050;
            const decimal volume                   = 1000;
            const long    closeTime                = 2345678901;
            const long    quoteAssetVolume         = 5000000;
            const int     numberOfTrades           = 555555;
            const decimal takerBuyBaseAssetVolume  = 4444;
            const decimal takerBuyQuoteAssetVolume = 333;

            var candlestick = new Candlestick(symbol, interval, openTime, open, high, low, close, volume, closeTime, quoteAssetVolume, numberOfTrades, takerBuyBaseAssetVolume, takerBuyQuoteAssetVolume);

            using (var cts = new CancellationTokenSource())
            {
                var args = new CandlestickEventArgs(timestamp, cts.Token, candlestick, firstTradeId, lastTradeId, isFinal);

                Assert.Equal(timestamp, args.Timestamp);
                Assert.Equal(candlestick, args.Candlestick);
                Assert.Equal(firstTradeId, args.FirstTradeId);
                Assert.Equal(lastTradeId, args.LastTradeId);
                Assert.Equal(isFinal, args.IsFinal);
            }
        }
        static LineProtocolPoint Convert(this Candlestick source)
        {
            if (source == null)
            {
                return(null);
            }

            var fields = new Dictionary <string, object>
            {
                { "high", source.High },
                { "low", source.Low },
                { "open", source.Open },
                { "close", source.Close },
                { "lowerWick", source.LowerWick },
                { "upperWick", source.UpperWick },
            };


            // No Measurements to be inserted:
            if (fields.Count == 0)
            {
                return(null);
            }

            var tags = new Dictionary <string, string>
            {
                { "body_type", source.BodyType.ToString() },
                //                   {"quality_code", source.QualityCode.ToString(CultureInfo.InvariantCulture)}
            };

            return(new LineProtocolPoint("candles", new ReadOnlyDictionary <string, object>(fields), tags,
                                         DateTime.SpecifyKind(source.CloseTime, DateTimeKind.Utc)));
        }
Exemplo n.º 20
0
        public void AddCandleStick(Candlestick candleStick)
        {
            List <Candlestick> candlesticklist = new List <Candlestick>();

            candlesticklist.Add(candleStick);
            candlesticklist.AddRange(_candleSticks.Take(100));
            _candleSticks = candlesticklist;
            Fast.AddCandleStick(candleStick);
            Slow.AddCandleStick(candleStick);
            var            diff = Fast.Value - Slow.Value;
            List <decimal> list = new List <decimal>();

            list.Add(diff);
            list.AddRange(MacdLine.Take(100));
            MacdLine = list;
            MacdLineEma.AddCandleStick(new Candlestick()
            {
                Close = diff
            });

            list = new List <decimal>();
            list.Add(diff - MacdLineEma.Value);
            list.AddRange(Histogram.Take(100));
            Histogram = list;
        }
Exemplo n.º 21
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JArray objects = JArray.Load(reader);
            var    candles = new List <Candlestick>();

            foreach (var obj in objects)
            {
                var candle = new Candlestick();
                candle.OpenTime = (long)obj[0];

                candle.Open = (decimal)obj[1];

                candle.High = (decimal)obj[2];

                candle.Low = (decimal)obj[3];

                candle.Close = (decimal)obj[4];

                candle.Volume = (decimal)obj[5];

                candle.CloseTime = (long)obj[6];

                candle.QuoteAssetVolume = (decimal)obj[7];

                candle.NumberOfTrades = (long)obj[8];

                candle.TakerBuyBaseAssetVolume = (decimal)obj[9];

                candle.TakerBuyQuoteAssetVolume = (decimal)obj[10];

                candles.Add(candle);
            }
            return(candles);
        }
Exemplo n.º 22
0
        private void CalculateCurrentEma(Candlestick futureCandleStick)
        {
            var list = new List <decimal>();

            list.Add((futureCandleStick.Close - Value) * Multiplier + Value);
            list.AddRange(ema.Take(100));
            ema = list;
        }
Exemplo n.º 23
0
        public void AddCandleStick(Candlestick futureCandleStick)
        {
            var list = new List <decimal>();

            list.Add(futureCandleStick.Close);
            list.AddRange(_closePrices.Take(100));
            _closePrices = list;
            CalculateCurrentEma(futureCandleStick);
        }
Exemplo n.º 24
0
 public CandlestickPlus(Candlestick candlestick)
 {
     time     = candlestick.time;
     bid      = candlestick.bid;
     ask      = candlestick.ask;
     mid      = candlestick.mid;
     volume   = candlestick.volume;
     complete = candlestick.complete;
 }
Exemplo n.º 25
0
 // LONGエントリー予約
 public void reserveLongOrder(Candlestick _reserved_candle, int _fib_idx, double _fib_origin_high)
 {
     entry_state     = OrderState.RESERVED;
     state           = PositionState.LONG;
     reserved_price  = _reserved_candle.last;
     reserved_candle = _reserved_candle;
     entry_fib_idx   = _fib_idx;
     fib_origin_high = _fib_origin_high;
     return;
 }
Exemplo n.º 26
0
        public void AddCandleStick(Candlestick futureCandleStick)
        {
            var list = new List <decimal>();

            list.Add(futureCandleStick.Close);
            list.AddRange(_closePrices.Take(100));
            _closePrices = list;
            //_candleSticks = list.OrderByDescending(x=>x.CloseDateTime);
            CalculateCurrentSma();
        }
Exemplo n.º 27
0
 // SHORTエントリー予約
 public void reserveShortOrder(Candlestick _reserved_candle, int _fib_idx, double _fib_origin_low)
 {
     entry_state     = OrderState.RESERVED;
     state           = PositionState.SHORT;
     reserved_price  = _reserved_candle.last;
     reserved_candle = _reserved_candle;
     entry_fib_idx   = _fib_idx;
     fib_origin_low  = _fib_origin_low;
     return;
 }
Exemplo n.º 28
0
    //**************************************************************************************

    /// <summary>
    /// Creates and returns a new candlestick list that is the copy of provided list with range [iStartIndex; iEndIndex].
    /// </summary>
    public static List <Candlestick> CreateCopy(List <Candlestick> iCandlesticks, int iStartIndex, int iEndIndex)
    {
        if (iCandlesticks is null)
        {
            throw new ArgumentNullException(nameof(iCandlesticks));
        }

        Candlestick[] results = new Candlestick[iEndIndex - iStartIndex + 1];
        iCandlesticks.CopyTo(iStartIndex, results, 0, results.Length);
        return(new List <Candlestick>(results));
    }
Exemplo n.º 29
0
    //**************************************************************************************

    /// <summary>
    /// Creates and returns array containing average prices starting with iIndex-iPeriods up to iIndex.
    /// </summary>
    public static float[] CreatePriceArray(List <Candlestick> iCandlestickData, int iPeriods, int iIndex)
    {
        Candlestick[] rawData = new Candlestick[iPeriods];
        iCandlestickData.CopyTo(iIndex - iPeriods + 1, rawData, 0, iPeriods);

        if (rawData[rawData.Length - 1] != iCandlestickData[iIndex])
        {
            throw new SystemException("Last element mismatch.");
        }

        return(rawData.Select(x => x.ClosePrice).ToArray());
    }
Exemplo n.º 30
0
    //**************************************************************************************

    /// <summary>
    /// Retrieves candlesticks from a server.
    /// </summary>
    public static List <Candlestick> RetrieveCandlesticks(Candlestick.Period iCandlestickPeriod)
    {
        HttpWebRequest request;

        switch (iCandlestickPeriod)
        {
        case Candlestick.Period.D1:
            request = (HttpWebRequest)WebRequest.Create("https://www.alphavantage.co/query?function=FX_DAILY&from_symbol=EUR&to_symbol=USD&apikey=" + kAlphaVantageAPIKey + "&datatype=csv&outputsize=full");
            break;

        case Candlestick.Period.m1:
            request = (HttpWebRequest)WebRequest.Create("https://www.alphavantage.co/query?function=FX_INTRADAY&from_symbol=EUR&to_symbol=USD&interval=1min&apikey=" + kAlphaVantageAPIKey + "&datatype=csv&outputsize=full");
            break;

        case Candlestick.Period.m5:
            request = (HttpWebRequest)WebRequest.Create("https://www.alphavantage.co/query?function=FX_INTRADAY&from_symbol=EUR&to_symbol=USD&interval=5min&apikey=" + kAlphaVantageAPIKey + "&datatype=csv&outputsize=full");
            break;

        case Candlestick.Period.m15:
            request = (HttpWebRequest)WebRequest.Create("https://www.alphavantage.co/query?function=FX_INTRADAY&from_symbol=EUR&to_symbol=USD&interval=15min&apikey=" + kAlphaVantageAPIKey + "&datatype=csv&outputsize=full");
            break;

        case Candlestick.Period.m30:
            request = (HttpWebRequest)WebRequest.Create("https://www.alphavantage.co/query?function=FX_INTRADAY&from_symbol=EUR&to_symbol=USD&interval=30min&apikey=" + kAlphaVantageAPIKey + "&datatype=csv&outputsize=full");
            break;

        default:
            throw new ArgumentException("Unsuported candlestick period", "iCandlestickPeriod");
        }

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode != HttpStatusCode.OK)
        {
            throw new Exception("Could not load candlesticks.");
        }

        using (Stream stream = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(stream))
            {
                List <Candlestick> results = Candlestick.LoadCSV(reader, iCandlestickPeriod, 0);
                results.Reverse();

                // Remove not full periods.
                if (Utils.UnixToDateTime(results[results.Count - 1].EndTime) > DateTime.UtcNow)
                {
                    results.RemoveAt(results.Count - 1);
                }

                return(results);
            }
    }
Exemplo n.º 31
0
        internal bool IsTimeToSell(Candlestick LastClosed)
        {
            bool bRet = (!bsBot.EnableBB || (bsBot.EnableBB && LastClosed.High > bb.Top.Last(1))) &&
                        (!bsBot.EnableRSI || (bsBot.EnableRSI && rsi.Result.Last(1) > bsBot.RSIUpperLevel)) &&
                        (!bsBot.EnableADX || (bsBot.EnableADX && adx.ADX.Last(1) < bsBot.DMSLevel)) &&
                        (bsBot.Aggressive || (!bsBot.Aggressive && Positions.Count() == 0));

            if (bRet)
            {
                bsBot.Print("LastClosed.High: {0} > BB Top: {1}, RSI: {2} > RSIUpperLevel: {3}", LastClosed.High, bb.Top.Last(1), rsi.Result.Last(1), bsBot.RSIUpperLevel);
            }
            return(bRet);
        }
 public double calculateMidPoint(Candlestick candlestick)
 {
     return (candlestick.HighPrice + candlestick.LowPrice) / 2;
 }