Beispiel #1
0
 public static string Get(string uri)
 {
     try {
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
         request.Proxy = null;
         request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
         using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
             using (Stream stream = response.GetResponseStream())
                 using (StreamReader reader = new StreamReader(stream)) {
                     return(reader.ReadToEnd());
                 }
     } catch (Exception) {
         Log.Error($"Error happened during GET {uri}");
         return("");
     }
 }
Beispiel #2
0
        private void Process(object o)
        {
            HttpListenerContext context = o as HttpListenerContext;

            if (context == null)
            {
                logger.Warn("Process was called with something other than HttpListenerContext.");
                return;
            }
            string    Endpoint  = context.Request.Url.AbsolutePath;
            Stopwatch sw        = new Stopwatch();
            int       requestid = ReqId++;

            try
            {
                logger.Info($"[Request {requestid}] Executing {context.Request.Url}");
                sw.Start();
                if (!containerStorage.TryGetValue(Endpoint, out var c_m))
                {
                    Respond(
                        context,
                        new JObject
                    {
                        ["success"] = false,
                        ["error"]   = "Unrecognized endpoint"
                    });
                    return;
                }
                var container = c_m.Item1;
                var method    = c_m.Item2;
                if (method.ReturnType == typeof(JObject))
                {
                    var PathParams =
                        method
                        .GetParameters()
                        .Where(param =>
                               param.GetCustomAttributes(typeof(PathParam), false).Length == 1 ||
                               param.ParameterType == typeof(HttpListenerContext)
                               );
                    string queryString     = context.Request.Url.Query;
                    var    queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
                    var    ParsedParams    = PathParams.Select(param => {
                        if (param.ParameterType == typeof(HttpListenerContext))
                        {
                            // not really cool I know, but nothing I can do about it now.
                            return(context);
                        }
                        string path = ((PathParam)param.GetCustomAttributes(typeof(PathParam), false)[0]).path ?? param.Name;
                        string val  = queryDictionary[path];
                        if (val == null)
                        {
                            string[] data = context.Request.Headers.GetValues(path) ?? new string[0];
                            if (data.Length == 0)
                            {
                                if (param.HasDefaultValue)
                                {
                                    return(param.DefaultValue);
                                }
                                throw new ArgumentException($"Required parameter {path} is not present.");
                            }
                            val = data[0];
                        }
                        return(ParseParam(val, param.ParameterType));
                    }).ToArray();
                    Respond(context, method, container, ParsedParams);
                    return;
                }
            }
            catch (ArgumentException aex)
            {
                try
                {
                    Respond(context, new JObject
                    {
                        ["success"] = false,
                        ["error"]   = aex.Message
                    });
                }
                catch (Exception ex2)
                {
                    logger.Error($"[Reqeust {requestid}] Could not respond. {ex2}");
                }
            }
            catch (Exception ex)
            {
                logger.Error($"[Request {requestid}] Error occured during {context.Request.Url}. {ex}");
                try
                {
                    Respond(context, unknownError);
                }
                catch (Exception ex2)
                {
                    logger.Error($"[Reqeust {requestid}] Could not respond. {ex2}");
                }
            }
            finally
            {
                sw.Stop();
                logger.Info($"[Request {requestid}] took {sw.ElapsedMilliseconds}ms");
            }
        }
Beispiel #3
0
        void RefreshConfig()
        {
            JObject data = JObject.Parse(Utility.Request.Get(Consts.Endpoints.BotConfig));

            if (!data.TryGetValue(botName, out JToken Jtoken))
            {
                Log.Error("Gist config contains no bot definition.");
            }
            else
            {
                JObject token = Jtoken as JObject;
                if (token.ContainsKey("obsolete_bot") && token["obsolete_bot"].Type == JTokenType.Boolean && (bool)token["obsolete_bot"])
                {
                    if (obsolete_bot != (bool)token["obsolete_bot"])
                    {
                        obsolete_bot = (bool)token["obsolete_bot"];
                        if (obsolete_bot)
                        {
                            Log.Info("Bot became obsolete.");
                        }
                        else
                        {
                            Log.Warn("Bot became non-obsolete");
                        }
                    }
                }
                if (token["stopsell"].Type != JTokenType.Integer)
                {
                    Log.Error("Have no idea when to stop selling");
                }
                else
                {
                    if (stopsell != (int)token["stopsell"])
                    {
                        stopsell = (int)token["stopsell"];
                    }
                }
                if (token["stopbuy"].Type != JTokenType.Boolean)
                {
                    Log.Error("Have no idea when to stop buying");
                }
                else
                {
                    if (stopbuy != (bool)token["stopbuy"])
                    {
                        stopbuy = (bool)token["stopbuy"];
                    }
                }

                if (token["sell_only"].Type != JTokenType.Boolean)
                {
                    Log.Error($"Sell only is not a boolean for {botName}");
                }
                else
                {
                    if (sellOnly != (bool)token["sell_only"])
                    {
                        Log.Info("Sellonly was changed from {0} to {1}", sellOnly, (bool)token["sell_only"]);
                        sellOnly = (bool)token["sell_only"];
                    }
                }

                if (token["want_to_buy"].Type != JTokenType.Float)
                {
                    Log.Error($"Want to buy is not a float for {botName}");
                }
                else
                {
                    if (WANT_TO_BUY != (double)token["want_to_buy"])
                    {
                        Log.Info("Want to buy was changed from {0} to {1}", WANT_TO_BUY, (double)token["want_to_buy"]);
                        WANT_TO_BUY = (double)token["want_to_buy"];
                    }
                }

                if (token["max_from_median"].Type != JTokenType.Float)
                {
                    Log.Error($"Max from median is not a float for {botName}");
                }
                else
                {
                    if (MAXFROMMEDIAN != (double)token["max_from_median"])
                    {
                        Log.Info("Max from median was changed from {0} to {1}", WANT_TO_BUY, (double)token["max_from_median"]);
                        MAXFROMMEDIAN = (double)token["max_from_median"];
                    }
                }

                if (token["unstickered_order"].Type != JTokenType.Float)
                {
                    Log.Error($"Unstickered order is not a float for {botName}");
                }
                else
                {
                    if (UNSTICKERED_ORDER != (double)token["unstickered_order"])
                    {
                        Log.Info("Unsctickered order was changed from {0} to {1}", UNSTICKERED_ORDER, (double)token["unstickered_order"]);
                        UNSTICKERED_ORDER = (double)token["unstickered_order"];
                    }
                }
                if (token["experiments"] != null)
                {
                    if (token["experiments"]["new_buy_formula"] is JToken new_buy_formula && new_buy_formula != null)
                    {
                        try {
                            DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                            DateTime start      = DateTime.MinValue;
                            if (new_buy_formula["start"] != null)
                            {
                                start = dtDateTime.AddSeconds((double)new_buy_formula["start"]).ToLocalTime();
                            }
                            DateTime end = dtDateTime.AddSeconds((double)new_buy_formula["end"]).ToLocalTime();
                            if (DateTime.Now < end)
                            {
                                double        want_to_buy = (double)new_buy_formula["want_to_buy"];
                                NewBuyFormula temp        = new NewBuyFormula(start, end, want_to_buy);
                                if (newBuyFormula != temp)
                                {
                                    newBuyFormula = temp;
                                    Log.Info("New newBuyFormula applied:");
                                    Log.Info(new_buy_formula.ToString(Formatting.None));
                                }
                            }
                        } catch {
                            Log.Error("Incorrect experiment");
                        }
                    }
                    if (token["experiments"]["sell_multiplier"] is JToken sell_multiplier && sell_multiplier != null)
                    {
                        try {
                            DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                            DateTime start      = DateTime.MinValue;
                            if (sell_multiplier["start"] != null)
                            {
                                start = dtDateTime.AddSeconds((double)sell_multiplier["start"]).ToLocalTime();
                            }
                            DateTime end = dtDateTime.AddSeconds((double)sell_multiplier["end"]).ToLocalTime();
                            if (DateTime.Now < end)
                            {
                                double         sellmultiplier = (double)sell_multiplier["multiplier"];
                                SellMultiplier temp           = new SellMultiplier(start, end, sellmultiplier);
                                if (sellMultiplier != temp)
                                {
                                    sellMultiplier = temp;
                                    Log.Info("New sellmultiplier applied:");
                                    Log.Info(sell_multiplier.ToString(Formatting.None));
                                }
                            }
                        } catch {
                            Log.Error("Incorrect experiment");
                        }
                    }
                }
            }
        }