コード例 #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);
            }
        }