Ejemplo n.º 1
0
        public void TEST()
        {
            mainThread = System.Threading.Thread.CurrentThread;

            double balance_BTC = 0;
            double balance_USD = 100;

            double lot = 0.001;



            Hyperparameters order_book;
            var             api = new ExmoApi("k", "s");

            string responce = "";
            string s        = "";

            vis.addParameter("BTC_USD", Color.White, 1000);

            vis.parameters[0].showLastNValues = true;
            vis.enableGrid           = true;
            vis.parameters[0].window = 360;

            //наименьшая цена, по которой можно покупать
            vis.parameters[0].functions.Add(new Function("bid_top", Color.Blue));
            //наивысшая цена, по которой можно продать
            vis.parameters[0].functions.Add(new Function("ask_top", Color.Red));


            expert = new Expert("Expert_Flex", this);

            algorithm = new BidAsk(this, "BidAsk");

            algorithm.Open(@"E:\Anton\Desktop\MAIN\Экспертная система\Экспертная система\Алгоритмы прогнозирования\BidAsk\h.json");

            expert.AddAlgorithm(algorithm);

            int window = int.Parse(algorithm.h.getValueByName("window_size"));

            int step = 60000;

            string[]      input;
            double[]      predictions = null;
            List <string> rawInput    = new List <string>();

            // List<string> spreads = new List<string>();
            rawInput.Add("<DATE_TIME>;<bid_top>;<bid_quantity>;<bid_amount>;<ask_top>;<ask_quantity>;<ask_amount>");
            //ЗАПУСК СКРИПТОВ ПОТОЧНОГО ПРОГНОЗИРОВНИЯ
            Task[] RunTasks = new Task[expert.algorithms.Count];
            foreach (Algorithm algorithm in expert.algorithms)
            {
                RunTasks[expert.algorithms.IndexOf(algorithm)] = Task.Run(() => algorithm.runGetPredictionScript());
            }

            //ОЖИДАНИЕ ЗАВЕРШЕНИЯ ЗАПУСКА
            foreach (var task in RunTasks)
            {
                task.Wait();
            }


            List <double> positions = new List <double>();

            while (true)
            {
                vis.parameters[0].window = 20;
                try
                {
                    responce = api.ApiQuery("order_book", new Dictionary <string, string> {
                        { "pair", "BTC_USD" }
                    });
                    if (responce.Length > 400)
                    {
                        responce = responce.Substring(0, 400);
                    }
                    if (!responce.Contains("maintenance"))
                    {
                        order_book = new Hyperparameters(responce, this);
                        //<bid_top>;<bid_quantity>;<bid_amount>;<ask_top>;<ask_quantity>;<ask_amount>
                        s = DateTime.Now.ToString() + ';'
                            + order_book.nodes[0].getAttributeValue("bid_top") + ';' + order_book.nodes[0].getAttributeValue("bid_quantity") + ';' + order_book.nodes[0].getAttributeValue("bid_amount") + ';'
                            + order_book.nodes[0].getAttributeValue("ask_top") + ';' + order_book.nodes[0].getAttributeValue("ask_quantity") + ';' + order_book.nodes[0].getAttributeValue("ask_amount");

                        s = s.Replace('.', ',');

                        double bid_top = Convert.ToDouble(order_book.nodes[0].getAttributeValue("bid_top").Replace('.', ','));
                        double ask_top = Convert.ToDouble(order_book.nodes[0].getAttributeValue("ask_top").Replace('.', ','));

                        /*
                         * double bid_quantity = Convert.ToDouble(order_book.nodes[0].getAttributeValue("bid_quantity").Replace('.', ','));
                         * double ask_quantity = Convert.ToDouble(order_book.nodes[0].getAttributeValue("ask_quantity").Replace('.', ','));
                         *
                         * double bid_amount = Convert.ToDouble(order_book.nodes[0].getAttributeValue("bid_amount").Replace('.', ','));
                         * double ask_amount = Convert.ToDouble(order_book.nodes[0].getAttributeValue("ask_amount").Replace('.', ','));*/

                        vis.addPoint(bid_top, "bid_top");
                        vis.addPoint(ask_top, "ask_top");

                        vis.refresh();
                        // log(s);
                        //запись входных данных
                        File.AppendAllText("BTC_USD_exmo.txt", s);

                        rawInput.Add(s);
                        // spreads.Add(String.Format("{0:0.#####}", bid_top - ask_top));
                        showInpOutp.fillTextBox1(rawInput);

                        //+1 для заголовка, +1 для нормализации i/(i-1)
                        if (rawInput.Count < window + 2)
                        {
                            File.AppendAllText("BTC_USD_exmo.txt", "\n");
                        }
                        else
                        {
                            input = expert.prepareDataset(rawInput.ToArray(), "<DATE_TIME>", true);

                            //шапка должна оставаться на месте, поэтому 1, а не 0
                            rawInput.RemoveAt(1);

                            showInpOutp.fillTextBox2(input);

                            if (input.Length == window + 1)
                            {
                                predictions = expert.getCommitteePrediction(input);
                            }
                            else
                            {
                                log("input.Length =/= window+1; input.Length = " + input.Length.ToString());
                            }

                            string action = expert.getDecision(predictions);

                            if (action == "error")
                            {
                                log("action = error", Color.Red);
                            }
                            if (action == "buy")
                            {
                                if (balance_USD > ask_top * lot)
                                {
                                    balance_BTC = balance_BTC + lot;
                                    balance_USD = balance_USD - (ask_top * lot);
                                    positions.Add(ask_top);
                                    log("BUY", Color.Blue);
                                    log(ask_top.ToString());
                                    log("   USD:" + balance_USD.ToString());
                                    log("   BTC:" + balance_BTC.ToString());

                                    vis.parameters[0].functions[2].points[vis.parameters[0].functions[1].points.Count - 1].mark = "BUY‾‾‾‾‾‾‾‾";
                                }
                                else
                                {
                                    //      log("Баланс USD: " + balance_USD.ToString() + " Невозможно купить " + (bid_top * lot).ToString() + " BTC");
                                    action += " (fail)";
                                }
                            }

                            for (int i = 0; i < positions.Count; i++)
                            {
                                if (positions[i] < bid_top)
                                {
                                    action = "sell";
                                    positions.RemoveAt(i);
                                    break;
                                }
                            }

                            if (action == "sell")
                            {
                                if (bid_top != 0)
                                {
                                    if (balance_BTC >= lot)
                                    {
                                        balance_BTC = balance_BTC - lot;
                                        balance_USD = balance_USD + (bid_top * lot);
                                        log("SELL", Color.Red);
                                        log(bid_top.ToString());
                                        log("   USD:" + balance_USD.ToString());
                                        log("   BTC:" + balance_BTC.ToString());

                                        vis.parameters[0].functions[1].points[vis.parameters[0].functions[1].points.Count - 1].mark = "SELL‾‾‾‾‾‾‾‾";
                                    }
                                    else
                                    {
                                        //    log("Баланс BTC: " + balance_BTC.ToString() + " Невозможно продать " + (lot).ToString() + " BTC");
                                        action += " (fail)";
                                    }
                                }
                                else
                                {
                                    log("bid_top почему-то равно нулю!", Color.Red);
                                    action += " (fail)";
                                }
                            }
                            log(DateTime.Now.ToString() + " " + action);
                            //запись состояния балансов и последнего действия
                            File.AppendAllText("BTC_USD_exmo.txt", balance_BTC.ToString() + ';' + balance_USD.ToString() + ';' + action + "\n");
                        }
                    }
                    else
                    {
                        log("Технические работы", Color.Red);
                    }
                }
                catch (Exception e)
                {
                    log(e.Message, Color.Red);
                    // log(result);
                }
                Thread.Sleep(step);
            }
        }
Ejemplo n.º 2
0
        internal void script()
        {
            mainThread = System.Threading.Thread.CurrentThread;
            Hyperparameters order_book;

            var api = new ExmoApi("k", "s");

            //  File.AppendAllText("USD_RUB_exmo.txt", "<local_time>;<bid>;<ask>");

            string result = "";

            //  result = api.ApiQuery("order_book", new Dictionary<string, string> { { "pair", "BTC_USD" } });
            //   order_book = new Hyperparameters(result, this);
            //order_book.draw(0, picBox, this, 25, 250);
            string s = "";

            vis.addParameter("BTC_USD", Color.White, 300);

            vis.parameters[0].showLastNValues = true;
            vis.enableGrid           = false;
            vis.parameters[0].window = 200;

            vis.parameters[0].functions.Add(new Function("bid_top", Color.Red));
            vis.parameters[0].functions.Add(new Function("ask_top", Color.Blue));

            //  vis.addParameter("BTC_USD количество", Color.White, 300);
            vis.addParameter("bid_quantity", Color.LightBlue, 300);
            vis.addParameter("ask_quantity", Color.Pink, 300);

            //  vis.addParameter("BTC_USD сумма", Color.White, 300);
            vis.addParameter("bid_amount", Color.Aqua, 300);
            vis.addParameter("ask_amount", Color.Coral, 300);

            int           step   = 60000;
            int           inc    = 0;
            List <string> buffer = new List <string>();

            while (true)
            {
                //       vis.parameters[0].window = 500;

                try
                {
                    result = api.ApiQuery("order_book", new Dictionary <string, string> {
                        { "pair", "BTC_USD" }
                    });
                    if (result.Length > 400)
                    {
                        result = result.Substring(0, 400);
                    }
                    if (!result.Contains("maintenance"))
                    {
                        order_book = new Hyperparameters(result, this);
                        //<bid_top>;<bid_quantity>;<bid_amount>;<ask_top>;<ask_quantity>;<ask_amount>
                        s = DateTime.Now.ToString() + ';'
                            + order_book.nodes[0].getAttributeValue("bid_top") + ';' + order_book.nodes[0].getAttributeValue("bid_quantity") + ';' + order_book.nodes[0].getAttributeValue("bid_amount") + ';'
                            + order_book.nodes[0].getAttributeValue("ask_top") + ';' + order_book.nodes[0].getAttributeValue("ask_quantity") + ';' + order_book.nodes[0].getAttributeValue("ask_amount");

                        double bid_top = Convert.ToDouble(order_book.nodes[0].getAttributeValue("bid_top").Replace('.', ','));
                        double ask_top = Convert.ToDouble(order_book.nodes[0].getAttributeValue("ask_top").Replace('.', ','));

                        double bid_quantity = Convert.ToDouble(order_book.nodes[0].getAttributeValue("bid_quantity").Replace('.', ','));
                        double ask_quantity = Convert.ToDouble(order_book.nodes[0].getAttributeValue("ask_quantity").Replace('.', ','));

                        double bid_amount = Convert.ToDouble(order_book.nodes[0].getAttributeValue("bid_amount").Replace('.', ','));
                        double ask_amount = Convert.ToDouble(order_book.nodes[0].getAttributeValue("ask_amount").Replace('.', ','));


                        buffer.Add(s);


                        vis.addPoint(bid_top, "bid_top");
                        vis.addPoint(ask_top, "ask_top");

                        vis.addPoint(bid_quantity, "bid_quantity");
                        vis.addPoint(ask_quantity, "ask_quantity");

                        vis.addPoint(bid_amount, "bid_amount");
                        vis.addPoint(ask_amount, "ask_amount");
                        vis.refresh();
                        // log(s);
                        inc++;

                        if (inc > 1800 / (step / 1000) & buffer.Count > 0)
                        {
                            File.AppendAllLines("BTC_USD_exmo.txt", buffer.ToArray());
                            buffer.Clear();
                            log(DateTime.Now.TimeOfDay.ToString() + "  Write!");
                            inc = 0;
                        }
                    }
                    else
                    {
                        log("Технические работы");
                    }
                }
                catch (Exception e)
                {
                    log(e.Message);
                    // log(result);
                }
                Thread.Sleep(step);
            }
        }
Ejemplo n.º 3
0
        internal void exmoAsIndicator()
        {
            log("вход в exmoAsIndicator()");
            vis.addParameter("USD_RUB", Color.Lime, 900);
            vis.parameters[0].functions.Add(new Function("AVG1", Color.Green));
            vis.parameters[0].functions.Add(new Function("AVG2", Color.Pink));
            vis.addParameter("Z", Color.Cyan, 200);
            vis.addParameter("OUTPUT", Color.Lime, 200);

            vis.parameters[0].showLastNValues = true;
            vis.enableGrid           = false;
            vis.parameters[0].window = 2000;


            mainThread = System.Threading.Thread.CurrentThread;
            Hyperparameters order_book;

            log("Подключение к ExmoApi...");
            var    api    = new ExmoApi("k", "s");
            string result = "";
            string s      = "";

            double        AVG1    = 0;
            double        AVG2    = 0;
            double        sum     = 0;
            List <double> history = new List <double>();

            string[] dataBase = null;

            DateTime lastTime = new DateTime(1, 1, 1, 0, 0, 0);

            if (tester)
            {
                dataBase = File.ReadAllLines("USD_RUB_exmo.txt");
                DateTime.TryParse(dataBase[1].Split(';')[0], out lastTime);
            }


            Invoke(new Action(() =>
            {
                TrackBar5_Scroll(null, null);
                TrackBar6_Scroll(null, null);
                TrackBar7_Scroll(null, null);
            }));



            log("Попытка запустить сервер...");
            MetaTraderLink mtLink = new MetaTraderLink(this);

            log("Сервер запущен.");
            bool parse;

            if (tester)
            {
                while (mtLink.actualTime == new DateTime(1, 1, 1, 0, 0, 0))
                {
                    log("ожидание подключения metatrader...");
                    Thread.Sleep(1000);
                }
            }


            int screenshotIterationTimer = 3600;
            int inc1 = 0;

            while (true)
            {
                try
                {
                    double bid = 0;
                    if (tester)
                    {
                        for (int i = 1; i < dataBase.Length; i++)
                        {
                            DateTime dt;
                            parse = DateTime.TryParse(dataBase[i].Split(';')[0], out dt);
                            if (parse)
                            {
                                if (mtLink.actualTime == dt)
                                {
                                    bid = Convert.ToDouble(dataBase[i].Split(';')[1].Replace('.', ','));

                                    if (mtLink.actualTime != lastTime.AddSeconds(1))
                                    {
                                        log("Актуальное время не равно предыдущему плюс 1 сек.", Color.Red);
                                        log("> mtLink.actualTime: " + mtLink.actualTime.ToString(), Color.Red);
                                        log("> lastTime: " + lastTime.ToString(), Color.Red);
                                    }
                                    lastTime = mtLink.actualTime;
                                }
                            }
                        }
                        s = mtLink.actualTime.ToString() + ";  " + bid.ToString();
                        log(s);
                    }
                    else
                    {
                        result = api.ApiQuery("order_book", new Dictionary <string, string> {
                            { "pair", "USD_RUB" }
                        });
                        order_book = new Hyperparameters(result, this);

                        s = DateTime.Now.ToString() + ';' + order_book.nodes[0].getAttributeValue("bid_top") + ';' + order_book.nodes[0].getAttributeValue("ask_top");

                        bid = Convert.ToDouble(order_book.nodes[0].getAttributeValue("bid_top").Replace('.', ','));
                        //   double ask = Convert.ToDouble(order_book.nodes[0].getAttributeValue("ask_top").Replace('.', ','));

                        File.AppendAllText("USD_RUB_exmo.txt", s + '\n');
                        log(s);
                    }



                    if (history.Count >= (Nl + Nh))
                    {
                        sum = 0;
                        for (int i = 0; i < Nl; i++)
                        {
                            sum += history[i];
                        }
                        AVG1 = sum / Nl;
                        sum  = 0;
                        for (int i = 0; i < Nh; i++)
                        {
                            sum += history[Nl + i];
                        }
                        AVG2 = sum / Nh;

                        double Zi = AVG2 - AVG1;

                        vis.addPoint(AVG1, "AVG1");
                        vis.addPoint(AVG2, "AVG2");
                        if (Zi >= Z)
                        {
                            vis.parameters[0].functions[0].points[vis.parameters[0].functions[0].points.Count - 1].mark = "buy";
                            vis.addPoint(1, "OUTPUT");
                            // ОТПРАВИТЬ КОМАНДУ НА ПОКУПКУ
                            if (mtLink.handler != null)
                            {
                                mtLink.ACTION = "buy";
                            }
                        }
                        else
                        {
                            vis.addPoint(0, "OUTPUT");
                        }
                        vis.addPoint(Zi, "Z");
                        history.RemoveAt(0);
                    }
                    else
                    {
                        vis.addPoint(0, "OUTPUT");
                        vis.addPoint(0, "Z");
                        vis.addPoint(bid, "AVG1");
                        vis.addPoint(bid, "AVG2");
                    }

                    history.Add(bid);
                    vis.addPoint(bid, "USD_RUB");
                    vis.refresh();


                    if (inc1 == screenshotIterationTimer)
                    {
                        inc1 = 0;
                        Bitmap screenShot = (Bitmap)picBox.Image.Clone();
                        int    h          = screenShot.Height;
                        if (screenShot.Height > 3000)
                        {
                            h = 3000;
                        }
                        for (int i = 0; i < screenShot.Width; i++)
                        {
                            for (int j = 0; j < h; j++)
                            {
                                Color c = screenShot.GetPixel(i, j);
                                if (c == Color.FromArgb(0, 0, 0, 0))
                                {
                                    screenShot.SetPixel(i, j, Color.Black);
                                }
                            }
                        }
                        screenShot.Save(DateTime.Now.ToString().Replace(':', '-') + ".bmp");
                    }
                    inc1++;
                }
                catch (Exception e)
                {
                    log(e.Message, Color.Red);
                }
                Thread.Sleep(1000);
            }
        }