public ActionResult <string> All()
        {
            var RequestData = CryptoGlobals.GetRequestData(Request);

            if (RequestData.ContainsKey("action"))
            {
                var action = RequestData["action"];

                if (action == "login")
                {
                    var user = RequestData["username"];
                    var pass = RequestData["password"];

                    var tempUI = Globals.LoginUser(user, pass);

                    if (tempUI == null)
                    {
                        return("error");
                    }
                    else
                    {
                        return(JsonConvert.SerializeObject(tempUI));
                    }
                }
                else if (action == "signup")
                {
                    var user = RequestData["username"];
                    var pass = RequestData["password"];

                    if (Globals.SignupUser(user, pass))
                    {
                        // all good
                        return("success");
                    }
                    else
                    {
                        return("error");
                    }
                }

                // we need token
                if (!RequestData.ContainsKey("token"))
                {
                    return("invalid token");
                }

                var token = RequestData["token"];

                var ui = Globals.GetUserFromToken(token);

                if (ui == null)
                {
                    return("invalid token");
                }
            }

            return("");
        }
Exemple #2
0
        public static void Main(string[] args)
        {
            //var c = new Context(new List<CandleInfo>());
            //var w = CryptoGlobals.RunScript("Console.WriteLine(2.ToString());", ref c);


            CryptoGlobals.InitGlobals();


            var balances = CryptoGlobals.adminBinanceClient.GetAccountInfo();

            DBHelper.CreateTables();
            CryptoGlobals.FillMarketsInDB();

            var test = CryptoGlobals.adminBinanceClient.Get24HPricesList();

            CreateWebHostBuilder(args).Build().Run();
        }
        public string Backtest(string source, string market, KlineInterval kline, DateTime start, DateTime end, StrategyOptions actStrat)
        {
            //var source = "";
            //var market = "BTCTUSDT";
            //var kline = Binance.Net.Objects.KlineInterval.FifteenMinutes;
            //var start = new DateTime(2019, 11, 1);
            //var end = new DateTime(2019, 12, 30);
            //var actStrat = new StrategyOptions();

            // get all candles
            CandleHelper.RetrieveCandles(market, kline, start, end);


            DateTime          small      = DateTime.MinValue;
            DateTime          big        = DateTime.MinValue;
            List <CandleInfo> allCandles = null;


            if (!CandleHelper.CandlesAvailable(market, kline, start, end, out small, out big, out allCandles))
            {
                return("no candles available");
            }



            var temp = new Context(allCandles);


            temp.ActiveStrategyOptions = Globals.ActiveStrategyOptions;
            if (!CryptoGlobals.RunScript(source, ref temp))
            {
                return("error in script: " + temp.SCRIPT_ERROR);
            }



            var c = new Context(allCandles);

            c.ActiveStrategyOptions = actStrat;

            var startingBalance = c.ActiveStrategyOptions.BacktestStartingBalance;

            var originalBalance = startingBalance;

            var l = new List <CandleInfo>();

            dynamic script = CSScript.RoslynEvaluator.LoadCode(source);

            foreach (var item in allCandles)
            {
                l.Add(item);

                if (l.Count < 20)
                {
                    continue;
                }

                c.RawCandles = l;

                try
                {
                    script.OnData(c);
                }catch (Exception ex)
                {
                    return("error: " + ex.Message);
                }
            }


            foreach (var item in c.GetOpenOrders())
            {
                c.CloseOrder(item);
            }



            var orders = c.GetAllOrders();

            var candlesAndOrders = new SortedDictionary <DateTime, List <OrderInfo> >();

            foreach (var item in orders)
            {
                var buyDate  = item.BuyCandle.OpenTime;
                var sellDate = item.SellCandle.OpenTime;

                if (!candlesAndOrders.ContainsKey(buyDate))
                {
                    candlesAndOrders[buyDate] = new List <OrderInfo>();
                }

                if (!candlesAndOrders.ContainsKey(sellDate))
                {
                    candlesAndOrders[sellDate] = new List <OrderInfo>();
                }


                candlesAndOrders[buyDate].Add(item);
                candlesAndOrders[sellDate].Add(item);
            }

            candlesAndOrders.OrderBy(x => x.Key);



            var originalEquity = originalBalance;


            double finalEquity = 0f;

            var equityOrders = new Dictionary <string, OrderInfo>();

            List <OrderResultInfo> finalOrders = new List <OrderResultInfo>();

            double totalProfits = 0f;


            var tempCount       = 0;
            var alreadyAddedIds = new List <string>();

            foreach (var cao in candlesAndOrders)
            {
                var currDate  = cao.Key;
                var orderList = cao.Value;
                foreach (var item in orderList)
                {
                    tempCount++;

                    var isSell = false;
                    if (alreadyAddedIds.Contains(item.Id))
                    {
                        isSell = true;
                    }
                    else
                    {
                        alreadyAddedIds.Add(item.Id);
                    }

                    var ord = item;

                    var      id = ord.Id;
                    string   type;
                    DateTime time;
                    double   orderPrice = 0.0f;;
                    double   size       = ord.BuyAmountInUSD;
                    double   profitLoss = 0f;
                    double   balance    = 0f;



                    if (isSell == false) // buy
                    {
                        originalBalance -= ord.BuyAmountInUSD;

                        originalBalance = Math.Round(originalBalance, 2);

                        time       = ord.BuyCandle.OpenTime;
                        type       = "Buy";
                        orderPrice = Math.Round(ord.BuyPrice, 2);

                        equityOrders[ord.Id] = ord;
                    }
                    else // sell
                    {
                        var tUsd = ord.TotalUSD();
                        tUsd = Math.Round(tUsd, 2);

                        originalBalance += tUsd;

                        originalBalance = Math.Round(originalBalance, 2);

                        time = ord.SellCandle.OpenTime;
                        type = "Sell";
                        var tmpPL = Math.Round(tUsd - ord.BuyAmountInUSD, 2);
                        profitLoss = tmpPL;
                        balance    = originalBalance;
                        balance    = Math.Round(balance, 2);


                        totalProfits += tmpPL;

                        orderPrice = Math.Round(ord.GetSellPrice(), 2);

                        equityOrders.Remove(ord.Id);
                    }


                    size = Math.Round(size, 8);


                    var finalBalance = balance;// (isSell) ? "$ " + balance.ToString() : "";

                    finalEquity = 0f;


                    CandleInfo tempCandle = (isSell) ? orderList[0].SellCandle : orderList[0].BuyCandle;

                    double ttttemp = 0f;
                    foreach (var eOrd in equityOrders.Values)
                    {
                        finalEquity += tempCandle.MidPrice * ord.CoinAmount;
                        ttttemp     += ord.BuyAmountInUSD;
                    }

                    ttttemp = Math.Round(ttttemp, 3);

                    finalEquity = Math.Round(finalEquity, 3);

                    var ori = new OrderResultInfo()
                    {
                        Id = id.ToString(), Time = time, Type = type, OrderPrice = orderPrice, OrderAmountUSD = size, ProfitLoss = profitLoss, FinalBalance = finalBalance, FinalEquity = finalEquity
                    };
                    finalOrders.Add(ori);
                }
            }

            var finalPL = Math.Round(originalBalance - startingBalance, 2);

            finalOrders.Add(new OrderResultInfo()
            {
                Id = "", Time = DateTime.MinValue, Type = "blank", OrderPrice = 0f, OrderAmountUSD = 0f, ProfitLoss = 0f, FinalBalance = 0f
            });
            finalOrders.Add(new OrderResultInfo()
            {
                Id = "", Time = DateTime.MinValue, Type = "blank2", OrderPrice = 0f, OrderAmountUSD = 0f, ProfitLoss = finalPL, FinalBalance = originalBalance
            });

            var final = JsonConvert.SerializeObject(finalOrders);

            return(final);
        }
        public ActionResult <string> All()
        {
            var RequestData = CryptoGlobals.GetRequestData(Request);

            if (RequestData.ContainsKey("action") && RequestData.ContainsKey("source") && RequestData.ContainsKey("options") && RequestData.ContainsKey("token"))
            {
                var action   = RequestData["action"];
                var token    = RequestData["token"];
                var source   = RequestData["source"];
                var market   = RequestData["market"];
                var startS   = RequestData["start"];
                var endS     = RequestData["end"];
                var interval = RequestData["interval"];
                var options  = RequestData["options"];

                var ui = Globals.GetUserFromToken(token);

                if (ui == null)
                {
                    return("invalid token");
                }

                if (action == "backtest")
                {
                    var tOptions = JsonConvert.DeserializeObject <StrategyOptions>(options);

                    if (tOptions == null)
                    {
                        return("invalid strategy options");
                    }

                    var cInterval = CryptoGlobals.GetKlineFromString(interval);

                    DateTime start = DateTime.MinValue;
                    DateTime end   = DateTime.MaxValue;

                    DateTime dt1, dt2;
                    if (DateTime.TryParseExact(startS,
                                               "yyyy-MM-dd",
                                               CultureInfo.InvariantCulture,
                                               DateTimeStyles.None,
                                               out dt1))
                    {
                        start = dt1;
                    }
                    else
                    {
                        return("Invalid start date");
                    }


                    if (DateTime.TryParseExact(endS,
                                               "yyyy-MM-dd",
                                               CultureInfo.InvariantCulture,
                                               DateTimeStyles.None,
                                               out dt2))
                    {
                        end = dt2;
                    }
                    else
                    {
                        return("Invalid end date");
                    }


                    var res = Backtest(source, market, cInterval, start, end, tOptions);

                    return(res);
                }
            }

            return("");
        }
Exemple #5
0
        public ActionResult <string> All()
        {
            var RequestData = CryptoGlobals.GetRequestData(Request);

            if (!RequestData.ContainsKey("token") || !RequestData.ContainsKey("action"))
            {
                return("Token and/or action missing!");
            }

            var token  = RequestData["token"].Trim();
            var action = RequestData["action"].Trim();



            UserInfo currUser = Globals.GetUserFromToken(token);

            if (currUser == null)
            {
                return("invalid token");
            }



            if (action == "get")
            {
                var sql = "SELECT * FROM Strategies WHERE UserId='" + currUser.Id + "'";

                var rows = DBHelper.GetDataTable(sql);

                var l = new List <StrategyInfo>();


                foreach (DataRow row in rows.Rows)
                {
                    var s = new StrategyInfo(row);

                    l.Add(s);
                }

                var res = JsonConvert.SerializeObject(l);

                return(res);
            }
            else if (action == "new")
            {
                var script = @"using System.Linq;
using CryptoCore.Scripting;
using CryptoCore.Classes;


public class MyStrategy
{
    // how much to buy in USD
    float BUY_AMOUNT = 100f;
    
    // this event runs every time we have a new Candle (of the interval we have selected)
    public void OnData(Context context)
    {
        

    }   

}";
                var si     = Globals.AddNewStrategyToDB(new StrategyInfo()
                {
                    Name = "Strategy - New", UserId = currUser.Id, Script = script
                });
                return(JsonConvert.SerializeObject(si));
            }
            else if (action == "update")
            {
                if (!RequestData.ContainsKey("strategy"))
                {
                    return("Invalid strategy");
                }

                StrategyInfo si = JsonConvert.DeserializeObject <StrategyInfo>(RequestData["strategy"]);

                if (si == null)
                {
                    return("Invalid strategy 2");
                }


                Globals.UpdateStrategy(si);

                return(JsonConvert.SerializeObject(si));
            }
            else if (action == "delete")
            {
                if (!RequestData.ContainsKey("strategy"))
                {
                    return("Invalid strategy");
                }

                StrategyInfo si = JsonConvert.DeserializeObject <StrategyInfo>(RequestData["strategy"]);

                SQLiteCommand com = new SQLiteCommand();

                com.CommandText = "DELETE FROM Strategies WHERE Id=@Id";

                com.Parameters.AddWithValue("@Id", si.Id);

                DBHelper.ExecuteSqlCommand(com);

                return("ok");
            }
            else if (action == "rename")
            {
                if (!RequestData.ContainsKey("strategy"))
                {
                    return("Invalid strategy");
                }

                StrategyInfo si = JsonConvert.DeserializeObject <StrategyInfo>(RequestData["strategy"]);

                SQLiteCommand com = new SQLiteCommand();

                com.CommandText = "UPDATE Strategies SET Name=@Name WHERE Id=@Id";

                com.Parameters.AddWithValue("@Name", si.Name);
                com.Parameters.AddWithValue("@Id", si.Id);

                DBHelper.ExecuteSqlCommand(com);

                return("ok");
            }

            return("Error 33");
        }
Exemple #6
0
        public ActionResult <string> Get(string Symbol)
        {
            var RequestData = new Dictionary <string, string>();

            RequestData = CryptoGlobals.GetRequestData(Request);

            Symbol = Symbol.Replace("-", "");

            var interval = KlineInterval.FifteenMinutes;
            var start    = new DateTime(2019, 7, 1);
            var end      = DateTime.Now;
            var symbol   = Symbol.ToUpper();

            var liteJson = false;
            var justOK   = false;
            var jsonP    = "";



            if (RequestData.ContainsKey("interval"))
            {
                var tempInterval = RequestData["interval"].ToString();

                interval = CryptoGlobals.GetKlineFromString(tempInterval);
            }
            else
            {
                return("interval missing");
            }

            Response.Headers.Add("Access-Control-Allow-Origin", "*");

            if (RequestData.ContainsKey("jsonp"))
            {
                jsonP = RequestData["jsonp"];
            }

            if (RequestData.ContainsKey("justok"))
            {
                justOK = true;
            }

            if (RequestData.ContainsKey("lite") && RequestData["lite"] == "true")
            {
                liteJson = true;
            }

            if (RequestData.ContainsKey("start") && RequestData.ContainsKey("end"))
            {
                var startS = RequestData["start"].ToString();
                var endS   = RequestData["end"].ToString();

                DateTime dt1;
                if (DateTime.TryParseExact(startS,
                                           "yyyy-MM-dd",
                                           CultureInfo.InvariantCulture,
                                           DateTimeStyles.None,
                                           out dt1))
                {
                    start = dt1;
                }
                else
                {
                    return("Invalid start date");
                }

                DateTime dt2;
                if (DateTime.TryParseExact(endS,
                                           "yyyy-MM-dd",
                                           CultureInfo.InvariantCulture,
                                           DateTimeStyles.None,
                                           out dt2))
                {
                    end = dt2.AddDays(1); // because we are NOT getting time. So we want to get UNTIL the next day
                    if (end > DateTime.Now)
                    {
                        end = DateTime.Now;
                    }
                }
                else
                {
                    return("Invalid end date");
                }
            }
            else
            {
                return(JsonConvert.SerializeObject(new KeyValuePair <string, string>("Error", "You have to use start & date query")));
            }


            if (!CandleHelper.Jobs.ContainsKey(symbol) || (CandleHelper.Jobs.ContainsKey(symbol) && CandleHelper.Jobs[symbol].Done))
            {
                if (CandleHelper.Jobs.ContainsKey(symbol))
                {
                    CandleHelper.Jobs.Remove(symbol);
                }



                DateTime          small      = DateTime.MinValue;
                DateTime          big        = DateTime.MinValue;
                List <CandleInfo> allCandles = null;

                if (CandleHelper.CandlesAvailable(symbol, interval, start, end, out small, out big, out allCandles))
                {
                    var finalS = "";

                    if (justOK)
                    {
                        finalS = "ok";
                    }
                    else
                    {
                        if (liteJson)
                        {
                            var temp = new List <CandleInfo>();
                            foreach (var item in allCandles)
                            {
                                temp.Add(item); // timestamp, o,h,l,c
                                                // highchart requires timestamp*1000 or else dates are invalid
                            }

                            finalS = JsonConvert.SerializeObject(temp);
                        }
                        else
                        {
                            finalS = JsonConvert.SerializeObject(allCandles);
                        }
                    }



                    //Response.ContentType = "application/javascript";
                    if (jsonP != "")
                    {
                        return(jsonP + "(" + finalS + ")");
                    }
                    return(finalS);


                    // let's retrieve em all??
                    return("Small: " + small.ToString() + Environment.NewLine + "Big: " + big.ToString());
                }
                else
                {
                    if (big == DateTime.MinValue)
                    {
                        big = start;
                    }
                    else
                    {
                        big = big.MinusKlineInterval(interval).MinusKlineInterval(interval);
                    }
                    CandleHelper.Jobs[symbol] = new CandleJob(symbol, start, end, interval); // we just started the job
                    CandleHelper.Jobs[symbol].StartWork();

                    return("working");
                }
            }
            else
            {
                return("working");
            }
        }
        public ActionResult <string> All()
        {
            var RequestData = CryptoGlobals.GetRequestData(Request);
            var jsonP       = "";

            if (RequestData.ContainsKey("jsonp"))
            {
                jsonP = RequestData["jsonp"];
            }

            if (RequestData.ContainsKey("market"))
            {
                var Symbol = RequestData["market"].Replace("-", "");
                var sql    = "SELECT * FROM Markets WHERE Symbol='" + Symbol.ToUpper() + "'";

                var rows = DBHelper.GetDataTable(sql);


                if (rows.Rows.Count != 1)
                {
                    return("{}");
                }
                else
                {
                    var res = JsonConvert.SerializeObject(rows.Rows[0].Table);
                    //res = res.Substring(1, res.Length - 2); // we do not want the [] in the beginning and end
                    return(res);
                }
            }
            else
            {
                if (RequestData.ContainsKey("refresh"))
                {
                    CryptoGlobals.FillMarketsInDB(true);
                }


                var rows = DBHelper.dtMarkets.Rows;

                var markets = new List <MarketInfo>();

                foreach (DataRow row in rows)
                {
                    markets.Add(new MarketInfo(row));
                }

                var res = JsonConvert.SerializeObject(markets);

                //Response.ContentType = "application/javascript";


                Response.Headers.Add("Access-Control-Allow-Origin", "*");
                Response.Headers.Add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");

                if (jsonP != "")
                {
                    return(jsonP + "(" + res + ")");
                }
                return(res);
            }
        }