Пример #1
0
        public override int CheckPattern(Kline kline)
        {
            avgPrice = SaveKlineToPriceQueue(kline);
            var time = kline.CloseTime;

            TickTime = Parser.ConvertTimeMsToDateTime(time);


            //RunRules
            decimal newTrend = 0;

            //1. Check Trend
            if (avgPrice > 0)
            {
                newTrend     = CalculateTrend(avgPrice, lastAvgPrice);
                avgChangePct = SaveAvgPriceChange(avgPriceChange);
            }


            //2. Compare to previous trend
            var buySell = CheckTrendShift(Trend, newTrend, time);

            lastAvgPrice = avgPrice;
            Trend        = newTrend;

            return(buySell);
        }
Пример #2
0
        private void GetHistoryCandle()
        {
            try
            {
                candles.Clear();
                kline = new Kline(SelectedPair, SelectedInterval);
                var klineString = kline.GetHistory();
                var klines      = JConverter.JsonConver <List <object[]> >(klineString);

                foreach (var k in klines)
                {
                    var ohlcPoint = new Charts.Models.Candle(
                        Convert.ToInt64(k[0], new CultureInfo("en-US")),
                        Convert.ToDouble(k[2], new CultureInfo("en-US")),
                        Convert.ToDouble(k[3], new CultureInfo("en-US")),
                        Convert.ToDouble(k[1], new CultureInfo("en-US")),
                        Convert.ToDouble(k[4], new CultureInfo("en-US")));
                    candles.Add(ohlcPoint);
                }
            }
            catch (Exception ex)
            {
                // запись логов в БД
            }
        }
Пример #3
0
        private void MarketHepler_OnMessage(object sender, MarketLibrary.API.WebSocket.FCMessageReceivedEventArgs e)
        {
            #region ticker
            if (e.Message.Contains("ticker"))
            {
                var model = ModelHelper <ticker_ws> .Json2Model(e.Message);

                if (model != null)
                {
                    Ticker ticker = new Ticker(model);
                    if (ticker != null && !string.IsNullOrEmpty(ticker.type))
                    {
                        string sy = ticker.type.Replace("ticker.", "");
                        updateTicker(sy, ticker);
                    }
                }
            }
            #endregion
            #region depth
            else if (e.Message.Contains("depth"))
            {
                var model = ModelHelper <depth_ws> .Json2Model(e.Message);

                if (model != null)
                {
                    Depth depth = new Depth(model);
                    if (depth != null && !string.IsNullOrEmpty(depth.type))
                    {
                        string symbol = depth.type.Replace("depth.L150.", "");
                        symbol = symbol.Replace("depth.full.", "");

                        updateDepth(symbol, depth);
                    }
                }
            }
            #endregion
            #region candle
            else if (e.Message.Contains("candle"))
            {
                //Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} msg: {Utils.Exception2String(e)}  ");
                var model = ModelHelper <candle_ws> .Json2Model(e.Message);

                if (model != null)
                {
                    Kline kline = new Kline(model);
                    if (kline != null && !string.IsNullOrEmpty(kline.type))
                    {
                        string type = kline.type.Replace("candle.", "");

                        updateKline(type, kline);
                    }
                }
            }
            #endregion
            else
            {
                Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} msg: {e.Message}  ");
            }
        }
Пример #4
0
        public List <Kline> GetKline_FC(string symbol, string resolution, int limit)
        {
            string type    = $"{resolution}.{symbol}";
            string JsonStr = getRequest_FC.candles(symbol, resolution, limit);
            var    data    = ModelHelper <API.Rest.FCoin.candle> .Json2Model(JsonStr);

            return(Kline.Klines(data, type));
        }
Пример #5
0
        public override bool CheckRule(Kline kline)
        {
            IsAchieved = false;
            ProcessKline(kline);

            var trend = CalculateTrend();

            if (trend > this.Threshold)
            {
                IsAchieved = true;
            }
            return(IsAchieved);
        }
Пример #6
0
        public ModelView()
        {
            dispatcher   = Dispatcher.CurrentDispatcher;
            GridHeight   = 400;
            GridWidth    = 1150;
            candlestick  = new Candlestick();
            ChartService = new ChartService(candlestick);

            kline   = new Kline("BTCUSDT", "1m");
            candles = new List <Candle>();

            timer          = new Timer(2000);
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }
Пример #7
0
        public bool CheckStopLoss(IPattern p, Kline kline)
        {
            if (!Transactions.ContainsKey(kline.Symbol))
            {
                return(false);
            }

            var t = Transactions[kline.Symbol];

            t.HighPrice = p.HighPrice;

            var sell = t.CheckStopLoss(t, kline.Close);

            return(sell);
        }
Пример #8
0
 private decimal SaveKlineToPriceQueue(Kline kline)
 {
     if (PriceQueue.Count() < this.Retention)
     {
         PriceQueue.Enqueue(kline.Close);
         return(0);
     }
     else
     {
         PriceQueue.Dequeue();
         PriceQueue.Enqueue(kline.Close);
         var avg = PriceQueue.Average();
         return(avg);
     }
 }
Пример #9
0
        private string ConvertKlineToString(Kline kline)
        {
            var msg = "{";

            msg += " \"Symbol\" : \"" + kline.Symbol + "\",";
            msg += " \"Interval\" : \"" + kline.Interval + "\",";
            msg += " \"OpenTime\" : \"" + kline.OpenTime + "\",";
            msg += " \"CloseTime\" : \"" + kline.CloseTime + "\",";
            msg += " \"Open\" : \"" + kline.Open + "\",";
            msg += " \"Close\" : \"" + kline.Close + "\",";
            msg += " \"High\" : \"" + kline.High + "\",";
            msg += " \"Low\" : \"" + kline.Low + "\",";
            msg += " \"Volume\" : \"" + kline.Volume + "\"";
            msg += " }";
            return(msg);
        }
Пример #10
0
 private void SaveKline(Kline kline)
 {
     _logger.Debug("kline received for " + kline.Symbol + "-" + kline.Interval);
     using (var context = new InfraContext())
     {
         try
         {
             context.Klines.Add(kline);
             context.SaveChanges();
         }
         catch (Exception e)
         {
             _logger.Error("Failed to save kline.\n" + e);
         }
     }
 }
Пример #11
0
        public override int CheckPattern(Kline kline)
        {
            var avgPrice = SaveKlineToPriceQueue(kline);
            var time     = kline.CloseTime;

            TickTime = Parser.ConvertTimeMsToDateTime(time);
            //First data - Reset Params
            if (Low == 0 && High == 0 && Spring == 0)
            {
                ResetData(avgPrice);
                LastPrice = avgPrice;
                return(0);
            }

            //RunRules
            //1. Wait for up trend and set low
            if (!Rules["Low"])
            {
                Low = CheckLow(avgPrice, Low);
            }
            //2. Wait for trend shift down and set high
            else if (Rules["Low"] && !Rules["High"])
            {
                High = CheckHigh(avgPrice, High, Spring);
            }
            //3. Wait for spring (Trend shift up), while staying above low
            else if (Rules["High"] && !Rules["Spring"])
            {
                Spring = CheckSpring(avgPrice, Spring);
            }
            //4. Wait to pass high
            else if (Rules["Spring"] && !Rules["Complete"])
            {
                Pivot = CheckComplete(avgPrice, Spring, High, Pivot);
            }

            else if (Rules["Complete"])
            {
                ResetData(Spring);
                return(1);
            }

            _logger.Debug(String.Format("{6} {7}: Low: {0}, High: {1}, Spring: {2}, Last Price: {3}, Highest Price: {4}, time: {5}", Low, High, Spring, LastPrice, HighPrice, TickTime, this.Symbol, this.Interval));
            LastPrice = avgPrice;
            return(0);
        }
Пример #12
0
        public void RunMultiplePatterns(Kline kline)
        {
            var partialKey  = kline.Symbol + "_" + kline.Interval;
            var partialDict = PartialMatch(PatternRepository, partialKey);
            var results     = new Dictionary <string, decimal>();
            var sell        = false;

            if (partialDict.Count() > 0)
            {
                _logger.Debug(string.Format("Checking Patterns for {0} {1}", kline.Symbol, kline.Interval));
                foreach (var p in partialDict)
                {
                    var buy = p.CheckPattern(kline);
                    p.SetHighPrice(kline.High);

                    if (buy == 1)
                    {
                        p.Engine.BuyPair(kline, p, p.Name);
                    }

                    else if (buy == -1)
                    {
                        sell = true;
                    }

                    else if (p.Engine.Transactions.Count > 0)
                    {
                        sell = p.Engine.CheckStopLoss(p, kline);
                    }

                    if (sell)
                    {
                        decimal profit;
                        p.Engine.Sell(kline, out profit);
                        if (profit > decimal.MinValue)
                        {
                            p.Engine.TradeResults.Add(profit);
                        }
                    }
                }
            }
        }
        public void LoadChart(string pair)
        {
            this.pair = pair;
            var formatPrecision = PrecisionFormatting();

            FormatterY = value => Math.Round(value, quotePrecision).ToString(formatPrecision); // настроить величину оеругления в зависимоти от спецификации инструмента
            isClose    = false;

            if (kline != null)
            {
                kline.MessageEvent      -= Kline_MessageEvent;
                kline.ConnectStateEvent -= Kline_ConnectStateEvent;
                kline.ConnectEvent      -= Kline_ConnectEvent;
                kline = null;
            }
            kline = new Kline(pair, selectedInterval);
            kline.MessageEvent      += Kline_MessageEvent;
            kline.ConnectStateEvent += Kline_ConnectStateEvent;
            kline.ConnectEvent      += Kline_ConnectEvent;
            kline.SocketOpen();
        }
Пример #14
0
 public void BuyPair(Kline kline, IPattern p, string name)/*Dictionary<string, PatternConfig> patternsConfig*/
 {
     if (Transactions.ContainsKey(kline.Symbol))
     {
         _logger.Info("Not Buying since we already baught it");
     }
     else
     {
         var time = Parser.ConvertTimeMsToDateTime(kline.CloseTime);
         var t    = new Transaction(kline.Symbol, kline.Close);
         t.StopLossConfig = GenerateStopLossObject(p);
         t.CalculateStopLoss(kline.Close);
         Transactions.Add(t.Symbol, t);
         var msg = String.Format("Trade: Buying {0} at {1}. Pattern: {2} Interval - {3}", t.Symbol, t.BuyPrice, p.Name, p.Interval);
         _logger.Email(string.Format("{0} Detected! Buy {1}", p.Name, t.Symbol), msg);
         if (FirstTransactionTime == DateTime.MinValue)
         {
             FirstTransactionTime = time;
         }
     }
 }
Пример #15
0
        public override int CheckPattern(Kline kline)
        {
            var buy = true;

            foreach (var rule in Rules)
            {
                rule.CheckRule(kline);
                if (!rule.IsAchieved)
                {
                    buy = false;
                }
            }

            if (buy)
            {
                return(1);
            }
            else
            {
                return(0);
            }
        }
Пример #16
0
        public void Sell(Kline kline, out decimal profit)
        {
            profit = decimal.MinValue;
            var symbol = kline.Symbol;
            var price  = kline.Close;
            var time   = Parser.ConvertTimeMsToDateTime(kline.CloseTime);

            if (Transactions.Count > 0 && Transactions.ContainsKey(symbol))
            {
                var t = Transactions[symbol];
                profit = ((price / t.BuyPrice) - 1);
                var profitText = (profit * 100).ToString();
                if (profitText.Length > 5)
                {
                    profitText = profit.ToString().Substring(0, 5);
                }
                var msg = string.Format("Trade: SELLING {0}!!! Buy Price: {1}, Sell Price: {2}, Profit: {3}%", t.Symbol, t.BuyPrice, price.ToString(), profitText);
                _logger.Email(string.Format("SELL notice! selling {0} at {1}% from buy price", t.Symbol, profitText), msg);
                Transactions.Remove(symbol);
                UpdateStats(profit, time);
            }
        }
Пример #17
0
        public override int CheckPattern(Kline kline)
        {
            avgPrice = SaveKlineToPriceQueue(kline);
            var time = kline.CloseTime;

            TickTime = Parser.ConvertTimeMsToDateTime(time);


            //RunRules
            var buySell = 0;

            //1. Check Trend
            if (avgPrice > 0)
            {
                buySell = CalculateIncline(avgPrice, lastAvgPrice, kline.Close);
            }


            SetHighPrice(kline.Close);
            lastAvgPrice     = avgPrice;
            LastTrendIncline = TrendIncline;

            return(buySell);
        }
Пример #18
0
        public void ProcessKline(Kline kline)
        {
            if (Repository.Klines.Count() > 0)
            {
                LastPrice  = Repository.Klines.Peek().Close;
                LastVolume = Repository.Klines.Peek().Volume;
            }


            if (Repository.Klines.Count() >= Retention)
            {
                Repository.Klines.Dequeue();
                Repository.Klines.Enqueue(kline);
            }
            else
            {
                Repository.Klines.Enqueue(kline);
            }

            LastAvgPrice  = AvgPrice;
            LastAvgVolume = AvgVolume;
            AvgPrice      = CheckAvgPrice();
            AvgVolume     = CheckAvgVolume();
        }
Пример #19
0
 private void updateKline(string type, Kline kline)
 {
     try
     {
         List <Kline> list  = Klinedic[type];
         int          count = list.Count;
         var          k     = list.FirstOrDefault(a => a.id == kline.id);
         if (k != null)
         {
             list.Remove(k);
         }
         list.Add(kline);
         //list = list.OrderBy(a => a.id).ToList();
         list = list.OrderBy(a => a.id).ToList();
         if (count > 60)
         {
             list.RemoveRange(0, count - 60);
         }
     }
     catch (Exception e)
     {
         throw (e);
     }
 }
Пример #20
0
 public abstract bool CheckRule(Kline kline);
Пример #21
0
        //public abstract bool CheckPattern(decimal avgPrice, long time);

        public abstract int CheckPattern(Kline kline);
Пример #22
0
        public override int CheckPattern(Kline kline)
        {
            var price    = kline.Close;
            var volume   = kline.Volume;
            var time     = long.Parse(kline.CloseTime.ToString());
            var TickTime = Parser.ConvertTimeMsToDateTime(time);
            var result   = false;

            if (LastPrice == 0 || PriceQueue.Count < Retention)
            {
                LastPrice = kline.Close;
                LastOpen  = kline.Open;
                PriceQueue.Enqueue(price);
                VolumeQueue.Enqueue(volume);
                return(0);
            }

            var avgPrice = PriceQueue.Average();
            var sd       = CalculateSd(VolumeQueue);

            var priceToBeat = LastPrice + (LastPrice * Threshold);

            if (PriceQueue.Count >= Retention)
            {
                PriceQueue.Dequeue();
                PriceQueue.Enqueue(price);
                VolumeQueue.Dequeue();
                VolumeQueue.Enqueue(volume);

                if (kline.Open > avgPrice && kline.Open > LastOpen && price > priceToBeat)
                {
                    Streak += 1;
                    var msg = String.Format("Streak Forming {5} {6}! Average Price: {0}, Current Price: {1}, Last Price: {2} Streak: {3}, Time: {4}", avgPrice, price, LastPrice, Streak, TickTime, this.Symbol, this.Interval);
                    _logger.Debug(msg);
                }
                else
                {
                    Streak = 0;
                    var msg = String.Format("Streak Ended {5} {6}! Average Price: {0}, Current Price: {1}, Last Price: {2} Streak: {3}, Time: {4}", avgPrice, price, LastPrice, Streak, TickTime, this.Symbol, this.Interval);
                    _logger.Debug(msg);
                }
            }

            if (Streak == 3 && volume > 2 * sd)
            {
                result = true;
                var msg = String.Format("Streak Achieved {5} {6}! Average Price: {0}, Current Price: {1}, Last Price: {2} Streak: {3}, Time: {4}", avgPrice, price, LastPrice, Streak, TickTime, this.Symbol, this.Interval);
                _logger.Info(msg);
            }

            LastPrice = kline.Close;
            LastOpen  = kline.Open;
            if (result)
            {
                return(1);
            }
            else
            {
                return(0);
            }
        }