Пример #1
0
    public static ReturnDataArray getDataArray(string coin, string timeGraph, string limit = "1000")
    {
        System.Threading.Thread.Sleep(6000);
        ReturnDataArray returnDataArray = new ReturnDataArray();
        String          jsonAsString    = Http.get("https://api.binance.com/api/v1/klines?symbol=" + coin + "&interval=" + timeGraph + "&limit=" + limit);

        Newtonsoft.Json.Linq.JContainer json = (Newtonsoft.Json.Linq.JContainer)JsonConvert.DeserializeObject(jsonAsString);

        returnDataArray.arrayPriceClose  = new double[json.Count];
        returnDataArray.arrayPriceHigh   = new double[json.Count];
        returnDataArray.arrayPriceLow    = new double[json.Count];
        returnDataArray.arrayPriceOpen   = new double[json.Count];
        returnDataArray.arrayVolume      = new double[json.Count];
        returnDataArray.arrayDate        = new double[json.Count];
        returnDataArray.arrayQuoteVolume = new double[json.Count];
        int i = 0;

        foreach (JContainer element in json.Children())
        {
            returnDataArray.arrayPriceClose[i]  = double.Parse(element[4].ToString());
            returnDataArray.arrayPriceHigh[i]   = double.Parse(element[2].ToString());
            returnDataArray.arrayPriceLow[i]    = double.Parse(element[3].ToString());
            returnDataArray.arrayPriceOpen[i]   = double.Parse(element[1].ToString());
            returnDataArray.arrayVolume[i]      = double.Parse(element[5].ToString());
            returnDataArray.arrayQuoteVolume[i] = double.Parse(element[7].ToString());
            returnDataArray.arrayDate[i]        = double.Parse(element[6].ToString());
            i++;
        }

        return(returnDataArray);
    }
Пример #2
0
    public static ReturnDataArray getDataArrayCW(string coin, string timeGraph)
    {
        ReturnDataArray returnDataArray = new ReturnDataArray();
        String          jsonAsStringRSI = Http.get("https://api.cryptowat.ch/markets/binance/" + coin + "/ohlc?periods=" + (int.Parse(timeGraph.Replace("m", "")) * 60) + "&after=1514764800", false);

        Newtonsoft.Json.Linq.JContainer jsonRSI = (Newtonsoft.Json.Linq.JContainer)JsonConvert.DeserializeObject(jsonAsStringRSI);

        string auxarray = "300";

        if (timeGraph == "5m")
        {
            auxarray = "300";
        }
        if (timeGraph == "15m")
        {
            auxarray = "900";
        }

        int count = 0;

        foreach (JContainer element in jsonRSI["result"][auxarray])
        {
            count++;
        }

        returnDataArray.arrayPriceClose  = new double[count];
        returnDataArray.arrayPriceHigh   = new double[count];
        returnDataArray.arrayPriceLow    = new double[count];
        returnDataArray.arrayPriceOpen   = new double[count];
        returnDataArray.arrayVolume      = new double[count];
        returnDataArray.arrayDate        = new double[count];
        returnDataArray.arrayQuoteVolume = new double[count];
        int i = 0;

        foreach (JContainer element in jsonRSI["result"][auxarray])
        {
            returnDataArray.arrayPriceClose[i] = double.Parse(element[4].ToString().Replace(".", ","));
            returnDataArray.arrayPriceHigh[i]  = double.Parse(element[2].ToString().Replace(".", ","));
            returnDataArray.arrayPriceLow[i]   = double.Parse(element[3].ToString().Replace(".", ","));
            returnDataArray.arrayPriceOpen[i]  = double.Parse(element[1].ToString().Replace(".", ","));
            returnDataArray.arrayVolume[i]     = double.Parse(element[5].ToString().Replace(".", ","));
            //returnDataArray.arrayQuoteVolume[i] = double.Parse(element[7].ToString().Replace(".", ","));
            returnDataArray.arrayDate[i] = double.Parse(element[0].ToString().Replace(".", ","));
            i++;
        }

        return(returnDataArray);
    }
Пример #3
0
    void generateIA(string pair = "BTCUSDT", string interval = "1d", int totalEntry = 5, int totalExit = 1, int totalEpochs = 99999, int round = 5)
    {
        try
        {
            string          separator       = ".";
            ReturnDataArray returnDataArray = getDataArray(pair, interval, "1000");



            List <double[]> exitList  = new List <double[]>();
            List <double[]> entryList = new List <double[]>();

            for (int z = 0; z < returnDataArray.arrayPriceClose.Length; z++)
            {
                try
                {
                    List <double> lineEntry = new List <double>();
                    List <double> lineExit  = new List <double>();
                    for (int i = 0; i < totalEntry; i++)
                    {
                        lineEntry.Add(double.Parse("0" + separator + Math.Round(returnDataArray.arrayPriceClose[z + i])));
                    }
                    lineExit.Add(double.Parse("0" + separator + Math.Round(returnDataArray.arrayPriceClose[z + totalEntry])));

                    exitList.Add(lineExit.ToArray());

                    entryList.Add(lineEntry.ToArray());
                    z += totalEntry - 1;
                }
                catch { }
            }

            double[][] entry = entryList.ToArray();

            double[][] exits = exitList.ToArray();

            Perceptron perceptron = new Perceptron(totalEntry, totalExit);

            for (int i = 0; i < totalEpochs; i++)
            {
                for (int k = 0; k < entry.Length; k++)
                {
                    perceptron.Train(entry[k], exits[k]);
                }
            }


            List <double> lastsPrices = new List <double>();
            returnDataArray = getDataArray(pair, interval, totalEntry.ToString());
            for (int i = 0; i < returnDataArray.arrayPriceClose.Length; i++)
            {
                lastsPrices.Add(double.Parse("0" + separator + Math.Round(returnDataArray.arrayPriceClose[i])));
            }
            double[][] newEntry =
            {
                lastsPrices.ToArray()
            };

            String result = perceptron.Compute(newEntry[0])[0].ToString();
            result = result.Replace("0,", "").Replace("0.", "").Substring(0, round);

            string vies = "BAIXA";
            if (double.Parse(result) > Math.Round(returnDataArray.arrayPriceClose[returnDataArray.arrayPriceClose.Length - 1]))
            {
                vies = "ALTA";
            }

            lblResultado.Text = "O resultado para o próximo intervalo é de: $ " + result + "<br/>";



            lblResultado.Text += "Como o BITCOIN hoje está custando $" + (returnDataArray.arrayPriceClose[returnDataArray.arrayPriceClose.Length - 1]) + " e a previsão para o BITCOIN amanhã é de " + vies;
        }
        catch (Exception ex)
        {
            lblResultado.Text = "ERROR " + ex.Message + ex.StackTrace;
        }
    }
Пример #4
0
    public void run(String coin, DateTime begin, DateTime final, decimal totalBtc = 2, double profit = 0.4, double stop = 0.6, double investPerOperation = 0.05, string ___timegraph = "5m")
    {
        try
        {
            //log("Profit(0.3): ");
            //profit = double.Parse(Console.ReadLine());
            profit = _profit;
            //log("Sstop(0.3): ");
            stop = _stop;// double.Parse(Console.ReadLine());
            //log("Time Frame(5m): ");

            FileStream   ostrm;
            StreamWriter writer;
            TextWriter   oldOut = Console.Out;
            try
            {
                ostrm  = new FileStream("./time_" + timegraph + "_log_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt", FileMode.OpenOrCreate, FileAccess.Write);
                writer = new StreamWriter(ostrm);
            }
            catch (Exception e)
            {
                Console.WriteLine("Cannot open Redirect.txt for writing");
                Console.WriteLine(e.Message);
                return;
            }
            //Console.SetOut(writer);


            String     _coins     = "";
            String     jsonTicker = Http.get("https://api.binance.com/api/v1/ticker/24hr", false);
            JContainer jContainer = (JContainer)JsonConvert.DeserializeObject(jsonTicker, (typeof(JContainer)));
            foreach (var item in jContainer)
            {
                if (item["symbol"].ToString().Substring(item["symbol"].ToString().Length - pair.Length, pair.Length).Trim().ToUpper() == pair)
                {
                    decimal volume      = decimal.Parse(item["quoteVolume"].ToString().Replace(".", ","));
                    decimal priceChange = decimal.Parse(item["priceChange"].ToString().Replace(".", ","));
                    if (volume >= _volume)
                    {
                        //if (item["symbol"].ToString().IndexOf("BCH") < 0)
                        if (item["symbol"].ToString().IndexOf("BNB") < 0)
                        {
                            //if (item["symbol"].ToString().IndexOf("VET") < 0)
                            // if (item["symbol"].ToString().IndexOf("USD") < 0)
                            if (decimal.Parse(item["lastPrice"].ToString().Replace(".", ",")) > 0.00000200m)
                            {
                                if (decimal.Parse(item["bidPrice"].ToString().Replace(".", ",")) > 0)
                                {
                                    //if (( decimal.Parse(item["priceChangePercent"].ToString().Replace(".", ","))) > -10 && (decimal.Parse(item["priceChangePercent"].ToString().Replace(".", ","))) < 10)
                                    _coins += item["symbol"].ToString() + ";";
                                }
                            }
                        }
                    }
                }
            }
            _coins = _coins.Substring(0, _coins.Length - 1);


            //_coins = "BTCUSDT;XRPUSDT;ETHUSDT;TRXUSDT;EOSUSDT;BNBUSDT;ADAUSDT;LTCUSDT;ETCUSDT;IOTAUSDT;NEOUSDT;ONTUSDT;QTUMUSDT;XLMUSDT;VETUSDT";
            //_coins = "ETHBTC;ETCBTC;NEOBTC;XRPBTC;XLMBTC;EOSBTC;TUSDBTC;XMRBTC;NANOBTC;IOTABTC";

            ReturnDataArray returnDataArray = null;
            StringBuilder   sb        = new StringBuilder();
            String[]        arrayPair = _coins.Split(';');
            double          gainTotal = 0;
            double          lossTotal = 0;
            int             openTotal = 0;
            double          perc      = 0;
            for (int zx = 0; zx < arrayPair.Length; zx++)
            {
                try
                {
                    //log("Pair(XMRBTC): ");
                    coin = arrayPair[zx];// Console.ReadLine();



                    create();
                    log("Backteste " + coin);

                    if (source == "CW")
                    {
                        returnDataArray = getDataArrayCW(coin, timegraph);
                    }
                    else
                    {
                        returnDataArray = getDataArray(coin, timegraph);
                    }

                    int gain = 0;
                    int loss = 0;

                    for (int i = 0; i < returnDataArray.arrayDate.Length; i++)
                    {
                        if (UnixTimeStampToDateTime(returnDataArray.arrayDate[i]) > DateTime.Parse(_begin) && UnixTimeStampToDateTime(returnDataArray.arrayDate[i]) < DateTime.Parse(_end))
                        {
                            Console.Title = UnixTimeStampToDateTime(returnDataArray.arrayDate[i]).ToString("dd/MM/yyyy HH:mm:ss") + "| GAIN: " + gain + "| LOSS: " + loss + "| Perc " + perc;
                            double stopValue   = 0;
                            double targetValue = 0;
                            double diff        = 0;
                            String ret         = Strategy(returnDataArray.arrayDate, returnDataArray.arrayPriceOpen, returnDataArray.arrayPriceClose, returnDataArray.arrayPriceLow, returnDataArray.arrayPriceHigh, returnDataArray.arrayVolume, i, out stopValue, out targetValue, out diff);


                            for (int x = 0; x < dt.Rows.Count; x++)
                            {
                                if (dt.Rows[x]["Status"].ToString() == "open")
                                {
                                    //if (1 == 1)
                                    {
                                    }
                                    //   else
                                    {
                                        if (returnDataArray.arrayPriceHigh[i] > double.Parse(dt.Rows[x]["Sell"].ToString()))
                                        {
                                            dt.Rows[x]["Status"]    = "gain";
                                            dt.Rows[x]["DateFinal"] = UnixTimeStampToDateTime(returnDataArray.arrayDate[i]);
                                            TimeSpan ts = UnixTimeStampToDateTime(returnDataArray.arrayDate[i]) - DateTime.Parse(dt.Rows[x]["Date"].ToString());
                                            dt.Rows[x]["TotalTime"] = ts.TotalMinutes;
                                            double auxPerc = ((double.Parse(dt.Rows[x]["Sell"].ToString()) * 100) / double.Parse(dt.Rows[x]["Buy"].ToString()) - 100);
                                            //if (auxPerc > profit)
                                            //  auxPerc = profit;

                                            auxPerc = profit - 0.2;

                                            perc += auxPerc;
                                            dt.Rows[x]["Perc"] = auxPerc;
                                            gain++;
                                        }
                                        else if (double.Parse(dt.Rows[x]["Stoploss"].ToString()) >= returnDataArray.arrayPriceLow[i])
                                        {
                                            dt.Rows[x]["Status"]    = "loss";
                                            dt.Rows[x]["DateFinal"] = UnixTimeStampToDateTime(returnDataArray.arrayDate[i]);
                                            TimeSpan ts = UnixTimeStampToDateTime(returnDataArray.arrayDate[i]) - DateTime.Parse(dt.Rows[x]["Date"].ToString());
                                            dt.Rows[x]["TotalTime"] = ts.TotalMinutes;
                                            double auxPerc = ((double.Parse(dt.Rows[x]["Stoploss"].ToString()) * 100) / double.Parse(dt.Rows[x]["Buy"].ToString()) - 100);
                                            // if (auxPerc < -1 * stop)
                                            auxPerc           += -1 * (0.2);
                                            perc              += auxPerc;
                                            dt.Rows[x]["Perc"] = auxPerc;
                                            loss++;
                                        }
                                        else
                                        {
                                            if (ret == "sell")
                                            {
                                                if (returnDataArray.arrayPriceClose[i] > double.Parse(dt.Rows[x]["Buy"].ToString()))
                                                {
                                                    gain++;
                                                    dt.Rows[x]["Status"] = "gain";
                                                }
                                                else
                                                {
                                                    loss++;
                                                    dt.Rows[x]["Status"] = "loss";
                                                }

                                                dt.Rows[x]["DateFinal"] = UnixTimeStampToDateTime(returnDataArray.arrayDate[i]);
                                                TimeSpan ts = UnixTimeStampToDateTime(returnDataArray.arrayDate[i]) - DateTime.Parse(dt.Rows[x]["Date"].ToString());
                                                dt.Rows[x]["TotalTime"] = ts.TotalMinutes;
                                                double auxPerc = ((returnDataArray.arrayPriceClose[i] * 100) / double.Parse(dt.Rows[x]["Buy"].ToString()) - 100) - 0.2;
                                                //if (auxPerc > 5)
                                                //auxPerc = 0;

                                                perc += auxPerc;
                                                dt.Rows[x]["Perc"] = auxPerc;
                                            }
                                        }
                                    }
                                }
                            }


                            if (ret == "buy")
                            {
                                //Console.WriteLine(UnixTimeStampToDateTime(returnDataArray.arrayDate[i]).ToString());
                                //Console.WriteLine((returnDataArray.arrayPriceOpen[i]).ToString());
                                //Console.WriteLine((returnDataArray.arrayPriceClose[i]).ToString());
                                //Console.WriteLine((returnDataArray.arrayPriceHigh[i]).ToString());
                                //Console.WriteLine((returnDataArray.arrayPriceLow[i]).ToString());
                                double sell     = targetValue;// ((returnDataArray.arrayPriceClose[i] * profit) / 100) + returnDataArray.arrayPriceClose[i];
                                double stoploss = returnDataArray.arrayPriceClose[i] - ((returnDataArray.arrayPriceClose[i] * stop) / 100);
                                if (stopValue != 0)
                                {
                                    stoploss = stopValue;
                                }
                                dt.Rows.Add(UnixTimeStampToDateTime(returnDataArray.arrayDate[i]).ToString(), Math.Round(returnDataArray.arrayPriceClose[i], 8), Math.Round((investPerOperation / returnDataArray.arrayPriceClose[i]), 8), Math.Round(sell, 8), 0, "open", Math.Round(stoploss, 8), DateTime.Now.AddDays(-5000), "", diff);
                            }
                        }
                    }



                    sb.AppendLine(coin);
                    sb.AppendLine("GAIN: " + gain + " | " + (gain * profit) + "%");
                    sb.AppendLine("LOSS: " + loss + " | " + (loss * stop) + "%");
                    sb.AppendLine("RESULT FINAL: " + ((gain * profit) - (loss * stop)) + "%");

                    gainTotal += (gain);
                    lossTotal += (loss);

                    for (int x = 0; x < dt.Rows.Count; x++)
                    {
                        if (dt.Rows[x]["Status"].ToString().Trim().ToLower().IndexOf("open") >= 0)
                        {
                            openTotal++;
                            dt.Rows[x]["DateFinal"] = UnixTimeStampToDateTime(returnDataArray.arrayDate[returnDataArray.arrayDate.Length - 1]);
                            TimeSpan ts = UnixTimeStampToDateTime(returnDataArray.arrayDate[returnDataArray.arrayDate.Length - 1]) - DateTime.Parse(dt.Rows[x]["Date"].ToString());
                            dt.Rows[x]["TotalTime"] = ts.TotalMinutes;
                            double auxPerc = ((returnDataArray.arrayPriceClose[returnDataArray.arrayDate.Length - 1] * 100) / double.Parse(dt.Rows[x]["Buy"].ToString()) - 100) - 0.2;
                            //if (auxPerc > 5)
                            //  auxPerc = 0;
                            dt.Rows[x]["Status"] = "force";
                            //perc += auxPerc;
                            dt.Rows[x]["Perc"] = auxPerc;
                        }
                    }

                    ToPrintConsole(dt);

                    sb.AppendLine("===========================");
                    //Console.ReadLine();

                    Console.Title = "GAIN: " + gainTotal + "| LOSS: " + lossTotal + "| Perc " + perc;
                }
                catch
                { }
            }



            log(sb.ToString());
            log(UnixTimeStampToDateTime(returnDataArray.arrayDate[0]).ToString());
            log(UnixTimeStampToDateTime(returnDataArray.arrayDate[returnDataArray.arrayDate.Length - 1]).ToString());
            log("TRADE OPEN: " + openTotal);
            log("TRADE GAIN: " + gainTotal);
            log("TRADE LOSS: " + lossTotal);
            log("RESULT GAIN(GAIN-LOSS): " + (gainTotal - lossTotal) + "");
            log("RESULT GAIN %: " + (gainTotal * 100) / ((gainTotal + lossTotal)) + "%");
            log("PERC PROFIT-LOSS: " + perc + "%");

            //Console.SetOut(oldOut);
            //writer.Close();
            //ostrm.Close();

            log("Press enter to exit...");
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            log("ERROR " + ex.Message + ex.StackTrace);
            Console.ReadLine();
            Environment.Exit(0);
        }
    }
Пример #5
0
    public static ReturnDataArray getDataArray(string coin, string timeGraph)
    {
        int i = 0;

        try
        {
            ReturnDataArray returnDataArray = new ReturnDataArray();



            String jsonAsStringRSI = "";
            if (source == "CACHE")
            {
                DateTime begin = DateTime.Parse("2018-01-01");
                if (!System.IO.File.Exists(Program.location + @"\cache\" + coin + timeGraph + ".txt"))
                {
                    System.IO.StreamWriter w = new System.IO.StreamWriter(Program.location + @"\cache\" + coin + timeGraph + ".txt", true);
                    while (begin != DateTime.Parse("2018-12-29"))
                    {
                        jsonAsStringRSI  = Http.get("https://api.binance.com/api/v1/klines?symbol=" + coin + "&interval=" + timeGraph + "&startTime=" + DatetimeToUnix(DateTime.Parse(begin.ToString("yyyy-MM-dd") + " 00:00:00")) + "&endTime=" + DatetimeToUnix(DateTime.Parse(begin.ToString("yyyy-MM-dd") + " 12:59:59")), false).Replace("[[", "[").Replace("]]", "]") + ",";
                        jsonAsStringRSI += Http.get("https://api.binance.com/api/v1/klines?symbol=" + coin + "&interval=" + timeGraph + "&startTime=" + DatetimeToUnix(DateTime.Parse(begin.ToString("yyyy-MM-dd") + " 13:00:00")) + "&endTime=" + DatetimeToUnix(DateTime.Parse(begin.ToString("yyyy-MM-dd") + " 23:59:59")), false).Replace("[[", "[").Replace("]]", "]") + ",";

                        w.Write(jsonAsStringRSI);

                        begin = begin.AddDays(1);
                        System.Threading.Thread.Sleep(1000);
                    }
                    w.Close();
                    w.Dispose();
                    jsonAsStringRSI = "[" + System.IO.File.ReadAllText(Program.location + @"\cache\" + coin + timeGraph + ".txt") + "]";
                    jsonAsStringRSI = jsonAsStringRSI.Substring(0, jsonAsStringRSI.Length - 1);
                    System.IO.File.Delete(Program.location + @"\cache\" + coin + timeGraph + ".txt");

                    w = new System.IO.StreamWriter(Program.location + @"\cache\" + coin + timeGraph + ".txt", true);
                    w.Write(jsonAsStringRSI);
                    w.Close();
                    w.Dispose();
                }


                jsonAsStringRSI = System.IO.File.ReadAllText(Program.location + @"\cache\" + coin + timeGraph + ".txt");
            }
            else
            {
                jsonAsStringRSI = Http.get("https://api.binance.com/api/v1/klines?symbol=" + coin + "&interval=" + timeGraph + "&limit=1000", true);
            }



            Newtonsoft.Json.Linq.JContainer jsonRSI = (Newtonsoft.Json.Linq.JContainer)JsonConvert.DeserializeObject(jsonAsStringRSI);

            i = 0;
            foreach (JContainer element in jsonRSI.Children())
            {
                i++;
            }

            returnDataArray.arrayPriceClose  = new double[i];
            returnDataArray.arrayPriceHigh   = new double[i];
            returnDataArray.arrayPriceLow    = new double[i];
            returnDataArray.arrayPriceOpen   = new double[i];
            returnDataArray.arrayVolume      = new double[i];
            returnDataArray.arrayDate        = new double[i];
            returnDataArray.arrayQuoteVolume = new double[i];

            i = 0;
            foreach (JContainer element in jsonRSI.Children())
            {
                returnDataArray.arrayPriceClose[i]  = double.Parse(element[4].ToString().Replace(".", ","));
                returnDataArray.arrayPriceHigh[i]   = double.Parse(element[2].ToString().Replace(".", ","));
                returnDataArray.arrayPriceLow[i]    = double.Parse(element[3].ToString().Replace(".", ","));
                returnDataArray.arrayPriceOpen[i]   = double.Parse(element[1].ToString().Replace(".", ","));
                returnDataArray.arrayVolume[i]      = double.Parse(element[5].ToString().Replace(".", ","));
                returnDataArray.arrayQuoteVolume[i] = double.Parse(element[7].ToString().Replace(".", ","));
                returnDataArray.arrayDate[i]        = double.Parse(element[6].ToString().Replace(".", ","));
                i++;
            }

            return(returnDataArray);
        }
        catch (Exception ex)
        {
            return(null);
        }
    }