public void FillWithJsonObject(JContainer dict, Scheme scheme) { Title = (string)dict["title"]; Id = (string)dict["id"]; Color = (Color)ColorConverter.ConvertFromString((string)dict["color"]); Points = (dict["points"]).Select(p => new Point((double)p[0], (double)p[1])).ToArray(); }
private void RemoveParent() { _parent = _parent.Parent; if (_parent != null && _parent.Type == JsonTokenType.Property) _parent = _parent.Parent; }
public static byte[] Serialize(JContainer item) { var stringWriter = new StringWriter(); var writer = new JsonTextWriter(stringWriter); item.WriteTo(writer); return Encoding.UTF8.GetBytes(stringWriter.ToString()); }
private void RemoveParent() { this._parent = this._parent.Parent; if (this._parent == null || this._parent.Type != JTokenType.Property) return; this._parent = this._parent.Parent; }
/// <summary> /// Initializes a new instance of the <see cref="JTokenWriter"/> class writing to the given <see cref="JContainer"/>. /// </summary> /// <param name="container">The container being written to.</param> public JTokenWriter(JContainer container) { ValidationUtils.ArgumentNotNull(container, "container"); _token = container; _parent = container; }
public virtual void FillWithJsonObject(JContainer dict, Scheme scheme) { Title = (string)dict["title"]; Room = scheme.Rooms.Single(r => r.Id.Equals(dict["room"])); QRCode = (string)dict[@"qr_code"]; Image = (string)dict["image"]; Visible = (bool)dict[@"visible"]; }
private void AddParent(JContainer container) { if (this._parent == null) this._token = container; else this._parent.AddAndSkipParentCheck((JToken) container); this._parent = container; }
/** * @param uri * @param method Case-insensitive * @param bodyObject * @param responseObject output, the value would be JObject or JArray */ private bool _SendHttpRequest(string uri, string method, JObject bodyObject, out JContainer responseObject) { responseObject = null; var url = APIEndPoint + BaseURL + @"/" + uri; // Set remote url and http method. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; // Set the content type header and http body. if(bodyObject != null){ var body = JsonConvert.SerializeObject(bodyObject); if (body.Length != 0) { request.ContentType = "application/json"; using (Stream requestStream = request.GetRequestStream()) using (StreamWriter writer = new StreamWriter(requestStream)) { writer.Write(body); } } } // Set the authorization id. string sAuth = "auth_id=" + AuthoId; request.Headers.Add("Authorization", sAuth); string responseData = ""; try { // Send request System.Net.WebResponse response = (HttpWebResponse)request.GetResponse(); responseData = new StreamReader(response.GetResponseStream()).ReadToEnd(); } catch (WebException e) { HttpWebResponse response = (HttpWebResponse)e.Response; if (response != null) { responseData = new StreamReader(response.GetResponseStream()).ReadToEnd(); response.Close(); // Releases the resources of the response. } } catch (Exception) { return false; } if (!string.IsNullOrEmpty(responseData)) { var res = JsonConvert.DeserializeObject(responseData); responseObject = res as JContainer; } return true; }
public void FormatLinks(JContainer container, IEnumerable<Link> links, JsonSerializer serializer) { var jLinks = new JArray(); foreach (var link in links) { jLinks.Add(JObject.FromObject(link, serializer)); } container[_linksPropertyName] = jLinks; }
public static QueryAggregateDigestsRequest FromJObject(JContainer jObject) { var request = JsonConvert.DeserializeObject<QueryAggregateDigestsRequest>(jObject.ToString()); if (request.Constraints == null || request.Buckets == null) { throw new ArgumentNullException(); } return request; }
private void AddParent(JContainer container) { if (_parent == null) _token = container; else _parent.Add(container); _parent = container; }
public void FormatLinks(JContainer container, IEnumerable<Link> links, JsonSerializer serializer) { var jLinks = new JObject(); foreach (var link in links) { jLinks[link.Rel] = JValue.CreateString(link.Href); } container[_linksPropertyName] = jLinks; }
public static void AssertSchemaIsValid(JSchema jSchema, JContainer jContainer) { IList<string> messages; var isValid = jContainer.IsValid(jSchema, out messages); foreach (var message in messages) { Console.WriteLine(message); } Assert.IsTrue(isValid); }
/// <summary> /// Parse the child Actions object that is part of the Tropo Result object. /// </summary> /// <param name="actions">Actions - is either an Object or an Array.</param> /// <returns></returns> public static JContainer parseActions(JContainer actions) { JTokenType type = actions.Type; if (type == JTokenType.Array) { return JArray.Parse(actions.ToString()); } else { return parseObject(actions); } }
private bool ReadInto(JContainer c) { JToken firstChild = c.First; if (firstChild == null) { return SetEnd(c); } else { SetToken(firstChild); _current = firstChild; _parent = c; return true; } }
private JsonToken? GetEndToken(JContainer c) { switch (c.Type) { case JsonTokenType.Object: return JsonToken.EndObject; case JsonTokenType.Array: return JsonToken.EndArray; case JsonTokenType.Constructor: return JsonToken.EndConstructor; case JsonTokenType.Property: return null; default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException("Type", c.Type, "Unexpected JContainer type."); } }
/// <summary> /// Generates a collection of patterns for the specified <see cref="JContainer"/>. /// </summary> public PatternCollection GeneratePatterns(JContainer root, int desiredCount, bool skipValues = true) { var descendants = root.DescendantsAndSelf().ToArray(); descendants.Shuffle(random); if (skipValues) descendants = descendants.Where(x => x is JObject || x is JArray).ToArray(); var patterns = descendants .Select(x => x.Path) .Where(x => !string.IsNullOrWhiteSpace(x)) .Take(desiredCount) .Select(x => (random.NextBool() ? "!" : "") + x) .Select(AddWildcards) .ToArray(); return PatternCollection.Parse(patterns); }
private bool DoesParentHaveSaidKey(JContainer container, string tokenPath) { if (container == null) return false; var result = DoesParentHaveSaidKey(container.Parent, tokenPath); var key = tokenPath.Split('.').LastOrDefault(); foreach (var desc in container.Values()) { var descPath = desc.Path.Split('.'); if (descPath.Length < tokenPath.Split('.').Length && descPath.Last() == key) { result = result || true; break; } } return result; }
private IEnumerable<Source> ReadSources(JContainer json) { var sources = new List<Source>(); var items = json.ToObject<List<JObject>>(); foreach (var item in items) { var source = new Source() { Id = item["id"].Value<int>(), Title = item["title"].ToString(), Spout = item["spout"].ToString(), Params = item["params"].ToObject<Dictionary<string, string>>(), Error = item["error"].ToString(), Favicon = item["icon"].ToString(), Tags = new List<string>(item["tags"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) }; sources.Add(source); } return sources; }
public void FillWithJsonObject(JContainer dict, Scheme scheme) { Rooms = dict["rooms"].Select(r => { Room room = new Room(); room.FillWithJsonObject((JContainer)r, scheme); return room; }).ToArray(); Items = dict["items"].Select(i => { Item item; string locType = (string)i["location_type"]; if (locType.Equals("room")) item = new RoomItem(); else item = new CoordinateItem(); item.FillWithJsonObject((JContainer)i, scheme); return item; }).ToArray(); }
public HttpResponseMessage DynExecute(string sp, JContainer requestBody) { if (requestBody == null) return Execute(sp, null); JObject parameters = requestBody as JObject; if (parameters != null) return Execute(sp, parameters.ToObject<Dictionary<string, object>>()); JArray bulkParameters = requestBody as JArray; if (bulkParameters != null) { List<Dictionary<string, object>> listOfDicts = bulkParameters.ToObject<List<Dictionary<string, object>>>(); if (listOfDicts != null && listOfDicts.Count > 0) return BulkExecute(sp, listOfDicts); else return Request.CreateResponse(HttpStatusCode.NoContent); } return Request.CreateResponse(HttpStatusCode.BadRequest); }
async void Start() { List <KLine> history_data = new List <KLine>(); OKExV5APi api = CommonData.Ins.V5pApi; //AccountAPIKey api = new AccountAPIKey(keys); //web.WebSocketPush += Result; //await web.ConnectAsync(); //await web.LoginAsync(api.V_ApiKey, api.V_SecretKey, api.V_Passphrase); //SpotApi api = new SpotApi("", "", ""); DateTime t_start = DateTime.Now.AddMinutes(-100); DateTime t_end = DateTime.Now; TimeSpan timeSpan = t_end - new DateTime(1970, 1, 1); Console.WriteLine(timeSpan.TotalSeconds); timeSpan = TimeZoneInfo.ConvertTimeToUtc(t_end) - new DateTime(1970, 1, 1); Console.WriteLine(timeSpan.TotalSeconds); //return; int length = 1; while (t_start.AddMinutes(length * 100) < t_end) { JContainer con = await api.getCandlesDataAsyncV5("BTC-USDT", t_start, t_start.AddMinutes(length * 100), length); List <KLine> d = KLine.GetListFormJContainer(con); t_start = t_start.AddMinutes(length * 100); } //SwapApi api = new SwapApi("", "", ""); //DateTime t_start = DateTime.Now.AddMinutes(-5 * 181); //JContainer con = await api.getCandlesDataAsync("BTC-USD-SWAP", t_start, DateTime.Now, 300); //data = KLine.GetListFormJContainer(con); //float f_10 = EMA.GetEMA(10, data); //float f_30 = EMA.GetEMA(30, data); //float f_180 = EMA.GetEMA(180, data); //float f_120 = EMA.GetEMA(120, data); //float f_60 = EMA.GetEMA(60, data); //Console.WriteLine(data.Count); //Console.WriteLine(con.First); //Console.WriteLine("next"); //WriteNext(con.First); //Console.WriteLine("last"); //WriteLast(con); //KLine k = new KLine("111", "1", "2", "3", "4","5"); //Console.WriteLine(JToken.FromObject(k).ToString()); //List<KLine> list = KLine.GetListFormJContainer(con); //foreach (var item in list) //{ // Console.WriteLine(item.closePrice); //} //KLineCache cache = new KLineCache(); //cache.SetData(con); //MA ma = new MA(); //ma.SetCache(cache); //Console.WriteLine(ma.GetMAValue(5) + " " + ma.GetMAValue(10) + " " + ma.GetMAValue(15) + " " + ma.GetMAValue(30)); //Console.WriteLine(con.ToString()); //curentIndex = 0; //KLineCache cache = new KLineCache(); //cache.RefreshData(data); //MATaticsHelper helper = new MATaticsHelper(); //helper.Init(AppSetting.Ins.GetValue("MA_ETH")); //await helper.RunHistory(); //MATaticsHelper2 helper = new MATaticsHelper2(); //helper.Init(AppSetting.Ins.GetValue("MA_BTC")); //await helper.RunHistory(); ////TurtleTaticsHelper helper3 = new TurtleTaticsHelper(); ////helper3.Init(AppSetting.Ins.GetValue("Turtle_ETH")); //EMATaticsHelper helper2 = new EMATaticsHelper(); //helper2.Init(AppSetting.Ins.GetValue("EMA_BTC")); //await helper2.RunHistory(); //EMATaticsHelper2 helper3 = new EMATaticsHelper2(); //helper3.Init(AppSetting.Ins.GetValue("EMA_BTC")); //await helper3.RunHistory(); //await helper3.RunHistory(); //int winCount = 0; //float allMoney = 0; //Dictionary<int, int> lossCountDic = new Dictionary<int, int>(); //Dictionary<int, List<int>> lossWinDic = new Dictionary<int, List<int>>(); //Dictionary<int, int> winDic = new Dictionary<int, int>(); //Dictionary<int, Dictionary<int, float>> all_ResultDic = new Dictionary<int, Dictionary<int, float>>(); //float t = await CommonData.Ins.V_InformationApi.F_GetLongShortRatio("BTC", DateTime.Now, 5); //var result = await CommonData.Ins.V_SpotApi.getInstrumentsAsync(); int runHelper = AppSetting.Ins.GetInt("RunHelper"); string[] coins = AppSetting.Ins.GetValue("Run").Split(';'); Console.WriteLine(AppSetting.Ins.GetValue("Run")); for (int i = 0; i < coins.Length; i++) { string item = coins[i]; if (runHelper == 1) { MATaticsHelper m_helper = new MATaticsHelper(); m_helper.Init(AppSetting.Ins.GetValue(string.Format("MA_{0}", item))); await m_helper.RunHistory(); } else if (runHelper == 2) { MATaticsHelper2 m_helper = new MATaticsHelper2(); m_helper.Init(AppSetting.Ins.GetValue(string.Format("MA_{0}", item))); await m_helper.RunHistory(); } else if (runHelper == 3) { EMATaticsHelper m_helper = new EMATaticsHelper(); m_helper.Init(AppSetting.Ins.GetValue(string.Format("EMA_{0}", item))); await m_helper.RunHistory(); } else if (runHelper == 4) { EMATaticsHelper2 m_helper = new EMATaticsHelper2(); m_helper.Init(AppSetting.Ins.GetValue(string.Format("EMA2_{0}", item))); await m_helper.RunHistory(); } else if (runHelper == 5) { EMAHelper3 m_helper = new EMAHelper3(); m_helper.Init(AppSetting.Ins.GetValue(string.Format("EMA3_{0}", item))); await m_helper.RunHistory(); } else if (runHelper == 6) { FourPriceHelper m_helper = new FourPriceHelper(); m_helper.Init(AppSetting.Ins.GetValue(string.Format("FOUR_{0}", item))); await m_helper.RunHistory(); } else if (runHelper == 7) { TurtleTaticsHelper m_helper = new TurtleTaticsHelper(); m_helper.Init(AppSetting.Ins.GetValue(string.Format("Turtle_{0}", item))); } } void WriteNext(JToken con) { if (con != null) { Console.WriteLine(con); WriteNext(con.Next); } } void WriteLast(JToken con) { if (con != null) { Console.WriteLine(con); WriteNext(con.Last); } } async void Result(string msg) { if (msg.Contains("success")) { List <string> list = new List <string>(); list.Add("swap/account:BTC-USD-SWAP"); await web.Subscribe(list); } Console.WriteLine(msg); } }
public void AddToJsonObjects(string name, JContainer jContainer) { _env = WarewolfDataEvaluationCommon.addToJsonObjects(_env, name, jContainer); }
public RestClient SetBody(JContainer body) { return(SetBody(new JsonStringContent(body.ToString()))); }
private static TreeNode GetJson2NodePri(JContainer json) { TreeNode tn = new TreeNode(); for (int i = 0; i < json.Count; i++) { TreeNode td = new TreeNode(); JObject jo = (JObject)json[i]; JToken jk = jo["List"]; CarItem ci = new CarItem() { UrlI = jo["I"].ToString(), N = jo["N"].ToString(), L = jo["L"] == null ? "" : jo["L"].ToString() }; ci.List = new List <CarItem>(); int index = jk == null ? 0 : jk.Count(); if (index > 0) { ci.List.AddRange(GetJson2ItemPri((JContainer)jk)); td = GetJson2NodePri((JContainer)jk); } td.Name = ci.N; td.Text = ci.DisplayName; td.Tag = ci; if (!string.IsNullOrEmpty(ci.L)) { var treens = tn.Nodes.Find(ci.L, false); if (treens.Length > 0) { //找到根 TreeNode tnd = treens[0]; Font subfont = new Font("微软雅黑", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134))); td.NodeFont = subfont; td.ForeColor = Color.Black; tnd.Nodes.Add(td); } else { //没有找到就创建 TreeNode tnd = new TreeNode(ci.L); tnd.Name = ci.L; Font subfont = new Font("微软雅黑", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134))); td.NodeFont = subfont; td.ForeColor = Color.Black; tnd.Nodes.Add(td); tnd.Expand(); tn.Nodes.Add(tnd); } } else { Font subfont = new Font("微软雅黑", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134))); td.NodeFont = subfont; td.ForeColor = Color.BlueViolet; tn.Nodes.Add(td); } } return(tn); }
void AccessToChannelLevelCallback(string receivedMessage) { try { if (!string.IsNullOrEmpty(receivedMessage) && !string.IsNullOrEmpty(receivedMessage.Trim())) { object[] serializedMessage = JsonConvert.DeserializeObject <object[]>(receivedMessage); JContainer dictionary = serializedMessage[0] as JContainer; string currentChannel = serializedMessage[1].ToString(); if (dictionary != null) { int statusCode = dictionary.Value <int>("status"); string statusMessage = dictionary.Value <string>("message"); if (statusCode == 200 && statusMessage.ToLower() == "success") { var payload = dictionary.Value <JContainer>("payload"); if (payload != null) { string level = payload.Value <string>("level"); var channels = payload.Value <JContainer>("channels"); if (channels != null) { var channelContainer = channels.Value <JContainer>(currentChannel); if (channelContainer != null) { bool read = channelContainer.Value <bool>("r"); bool write = channelContainer.Value <bool>("w"); if (level == "channel") { switch (currentUnitTestCase) { case "ThenChannelLevelWithReadWriteShouldReturnSuccess": case "ThenRevokeAtChannelLevelReturnSuccess": if (read && write) { receivedGrantMessage = true; } break; case "ThenChannelLevelWithReadShouldReturnSuccess": if (read && !write) { receivedGrantMessage = true; } break; case "ThenChannelLevelWithWriteShouldReturnSuccess": if (!read && write) { receivedGrantMessage = true; } break; default: break; } } } } } } } } } catch { } finally { mreGrant.Set(); } }
/// <summary> /// Set a named value on an object and return that object so multiple /// calls can be chained. /// </summary> /// <param name="obj">The object to set the value on.</param> /// <param name="name">The name to set.</param> /// <param name="value">The value to set.</param> /// <returns>The object the value was set on.</returns> public static JContainer Set(this JContainer obj, string name, bool value) { return(obj.Set(name, new JValue(value))); }
/// <summary> /// Call a remote procedure /// </summary> /// <param name="endpoint">The endpoint to which to route the request</param> /// <param name="body">The request body</param> /// <returns>The response</returns> public JContainer Call(string endpoint, JContainer body) { return Call(endpoint, body, 60000); }
void AccessToUserLevelCallback(string receivedMessage) { try { if (!string.IsNullOrEmpty(receivedMessage) && !string.IsNullOrEmpty(receivedMessage.Trim())) { object[] serializedMessage = JsonConvert.DeserializeObject <object[]>(receivedMessage); JContainer dictionary = serializedMessage[0] as JContainer; string currentChannel = serializedMessage[1].ToString(); if (dictionary != null) { int statusCode = dictionary.Value <int>("status"); string statusMessage = dictionary.Value <string>("message"); if (statusCode == 200 && statusMessage.ToLower() == "success") { var payload = dictionary.Value <JContainer>("payload"); if (payload != null) { string level = payload.Value <string>("level"); string channel = payload.Value <string>("channel"); var auths = payload.Value <JContainer>("auths"); if (auths != null && auths.Count > 0) { foreach (JToken auth in auths.Children()) { if (auth is JProperty) { var authProperty = auth as JProperty; if (authProperty != null) { string authKey = authProperty.Name; var authKeyContainer = auths.Value <JContainer>(authKey); if (authKeyContainer != null && authKeyContainer.Count > 0) { bool read = authKeyContainer.Value <bool>("r"); bool write = authKeyContainer.Value <bool>("w"); if (level == "user") { switch (currentUnitTestCase) { case "ThenUserLevelWithReadWriteShouldReturnSuccess": case "ThenRevokeAtUserLevelReturnSuccess": if (read && write) { receivedGrantMessage = true; } break; case "ThenUserLevelWithReadShouldReturnSuccess": if (read && !write) { receivedGrantMessage = true; } break; case "ThenUserLevelWithWriteShouldReturnSuccess": if (!read && write) { receivedGrantMessage = true; } break; default: break; } } } } } } } } } } } } catch { } finally { mreGrant.Set(); } }
private void SaveCustomerBaseInfo() { this.Data = new Dictionary <object, object>(); int code = 0; int customerid = this.GetFormValue("customerid", 0); Micro.AdminConfig.Model.UserInfoModel userinfo = new Micro.AdminConfig.Model.UserInfoModel(); userinfo.UserLoginName = Server.UrlDecode(this.GetFormValue("loginName", "")); userinfo.UserLoginPassword = this.GetFormValue("loginPwd", ""); userinfo.UserNickName = Server.UrlDecode(this.GetFormValue("realName", "")); userinfo.UserIndustryType = this.GetFormValue("industryid", 0); userinfo.UserActivate = this.GetFormValue("activate", 1); userinfo.UserBelongManagerID = Convert.ToInt32(CookieHelper.GetCookieVal(Enum.GetName(typeof(CookieKeyValue), CookieKeyValue.UserID))); userinfo.UserLastLoginIP = "0.0.0.0"; userinfo.UserID = this.GetFormValue("customerid", 0); userinfo.UserRoleID = -2; userinfo.UserCityID = this.GetFormValue("cityid", 0); userinfo.UserIsSmsService = this.GetFormValue("sms", 0); userinfo.UserMoney = this.GetFormValue("money", "0"); userinfo.UserPrice = this.GetFormValue("price", "1"); userinfo.SubDomain = this.GetFormValue("myDomain", ""); string jsoncontent = Server.UrlDecode(this.GetFormValue("jsoncontent", "")); int flag = 0; if (customerid > 0) { flag = ICustomer.Instance.UpdateCustomerInfoV2(userinfo); ICustomerCommonConfig.Intance.AddDefaultConfig(customerid); code = 1; } else { userinfo.UserDeveloperUrl = Server.UrlDecode(this.GetFormValue("developerurl", "")); userinfo.UserDeveloperToken = this.GetFormValue("developertoken", ""); userinfo.UserIsOld = this.GetFormValue("version", 1); flag = ICustomer.Instance.AddCustomerInfoV2(userinfo); if (flag > 0) { ICustomerCommonConfig.Intance.AddDefaultConfig(flag); UserBaseInfoService.Instance.AddDefaultBuddy(userinfo.UserLoginName, EncryptHelper.MD5(userinfo.UserLoginPassword), flag); string strReg = "key=(?<key>.*?)&"; Match m = Regex.Match(userinfo.UserDeveloperUrl, strReg); if (m.Success) { string key = m.Groups["key"].Value; IUserInfo.Instance.SetDeveloperPatternRecord(key, userinfo.UserDeveloperToken, flag); } code = 1; customerid = flag; } } if (code == 1) { if (!jsoncontent.StrIsNull()) { System.Text.StringBuilder strCustomHtml = new System.Text.StringBuilder(); JContainer jc = (JContainer)JsonConvert.DeserializeObject(jsoncontent); JToken token = jc["apps"]; List <UserInfoMicroAppModel> listModel = new List <UserInfoMicroAppModel>(); for (int i = 0; i < token.Count(); i++) { UserInfoMicroAppModel _am = new UserInfoMicroAppModel(); _am.ID = Convert.ToInt32(token[i]["id"].ToString()); _am.AppID = token[i]["appid"].ToString(); _am.AppKey = token[i]["appkey"].ToString(); _am.AppSecret = token[i]["appsecret"].ToString(); _am.AppTitle = token[i]["apptitle"].ToString(); _am.AppType = Convert.ToInt32(token[i]["apptype"].ToString()); _am.AppCustomerID = customerid; listModel.Add(_am); } if (listModel != null && listModel.Count() > 0) { IUserInfo.Instance.SetCustomerPullicAccount(listModel); } } } this.Data["code"] = code; string json = GetJson(this.Data); Response.Write(json); Response.End(); }
public static void captureData() { lock (MainClass.data) { string dataBaseFile = MainClass.location + "bd.xml"; try { System.Data.DataSet ds = null; bool create = false; if (!System.IO.File.Exists(dataBaseFile)) { System.Data.DataTable dt = new System.Data.DataTable("Balances"); dt.Columns.Add("Date"); dt.Columns.Add("Coin"); dt.Columns.Add("Amount"); dt.Rows.Add("", "", ""); System.Data.DataTable dtParameters = new System.Data.DataTable("Parameters"); dtParameters.Columns.Add("Parameter"); dtParameters.Columns.Add("Value"); dtParameters.Rows.Add("", ""); ds = new System.Data.DataSet(); ds.DataSetName = "Database"; ds.Tables.Add(dt); ds.Tables.Add(dtParameters); ds.WriteXml(dataBaseFile); create = true; } ds = new System.Data.DataSet(); ds.ReadXml(dataBaseFile); BitMEX.BitMEXApi bitMEXApi = new BitMEX.BitMEXApi(MainClass.bitmexKey, MainClass.bitmexSecret, MainClass.bitmexDomain); string json = bitMEXApi.GetWallet(); JContainer data = (JContainer)JsonConvert.DeserializeObject(json, (typeof(JContainer))); ClassDB.execS(ClassDB.dbquery.Replace("@balance", data[0]["walletBalance"].ToString().Replace(",", "."))); if (create) { ds.Tables[0].Rows.Clear(); } ds.Tables[0].Rows.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), MainClass.pair, data[0]["walletBalance"].ToString()); ds.Tables[1].Rows.Clear(); ds.Tables[1].Rows.Add("OpenOrders", bitMEXApi.GetOpenOrders(MainClass.pair).Count); ds.Tables[1].Rows.Add("Amount", data[0]["walletBalance"].ToString()); System.IO.File.Delete(dataBaseFile); ds.WriteXml(dataBaseFile); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
private void SaveOptions() { List <ActSurveyOptionsModel> models = new List <ActSurveyOptionsModel>(); int questionID = string.IsNullOrEmpty(GetQueryString("questionID", "")) ? 0 : Convert.ToInt32(GetQueryString("questionID", "")); this.Data = new Dictionary <object, object>(); if (questionID != 0) { string content1 = GetQueryString("content1", ""); int isRight1 = string.IsNullOrEmpty(GetQueryString("isRight1", "")) ? 0 : Convert.ToInt32(GetQueryString("isRight1", "")); string content2 = GetQueryString("content2", ""); int isRight2 = string.IsNullOrEmpty(GetQueryString("isRight2", "")) ? 0 : Convert.ToInt32(GetQueryString("isRight2", "")); ActSurveyOptionsModel model1 = new ActSurveyOptionsModel(); model1.SurveyQuestionID = questionID; model1.SurveyOptionContent = content1; model1.ASO_IsRight = isRight1; ActSurveyOptionsModel model2 = new ActSurveyOptionsModel(); model2.SurveyQuestionID = questionID; model2.SurveyOptionContent = content2; model2.ASO_IsRight = isRight2; models.Add(model1); models.Add(model2); JContainer jc = (JContainer)JsonConvert.DeserializeObject(GetFormValue("options", "")); JToken token = jc["options"]; foreach (JToken tk in token) { if (tk["_destroy"] == null ? true : false) { ActSurveyOptionsModel model = new ActSurveyOptionsModel(); model.SurveyQuestionID = questionID; model.SurveyOptionContent = tk["content"].ToString(); model.ASO_IsRight = tk["isRight"] != null && Convert.ToBoolean(tk["isRight"].ToString()) ? 1 : 0; models.Add(model); } } int type = IActSurvey.Instance.GetQuestionModel(questionID).QuestionNum; int count = models.Count(p => p.ASO_IsRight == 1); if (type == 0 && count > 1) { this.Data["result"] = "保存失败,此题为单选题"; } else { if (IActSurvey.Instance.AddOption(models)) { this.Data["result"] = "保存成功"; } else { this.Data["result"] = "保存失败"; } } } else { this.Data["result"] = "保存失败"; } string json = GetJson(this.Data); Response.Write(json); Response.End(); }
private object DeserializeComplexType(JContainer obj, Type targetType) { return(obj.ToObject(targetType, JsonSerializer.Create(_jsonApiContext.Options.SerializerSettings))); }
/// <summary> /// Set a named value on an object of any type. Unlike the other set /// overloads, this will attempt to convert arbitrary CLR values into /// the correct JSON types. /// </summary> /// <param name="obj">The object to set the value on.</param> /// <param name="name">The name of the value to set.</param> /// <param name="value">The value to set.</param> /// <returns>Whether we were able to set the value.</returns> public static bool TrySet(this JContainer obj, string name, object value) { Debug.Assert(obj != null, "obj should probably not be null!"); Debug.Assert(!string.IsNullOrEmpty(name), "name cannot be null or empty."); if (obj == null) { return(false); } if (value == null) { obj.Set(name, JsonExtensions.Null()); } else { // If the type is nullable, strip off the Nullable<> which will // allow the comparisons below to convert correctly (since // we've already checked the value isn't null) Type memberType = value.GetType(); memberType = Nullable.GetUnderlyingType(memberType) ?? memberType; RuntimeTypeHandle handle = memberType.TypeHandle; // Set the value based on the type for known primitives if (handle.Equals(typeof(bool).TypeHandle)) { obj.Set(name, Convert.ToBoolean(value, CultureInfo.InvariantCulture)); } else if (handle.Equals(typeof(int).TypeHandle) || handle.Equals(typeof(uint).TypeHandle) || handle.Equals(typeof(sbyte).TypeHandle) || handle.Equals(typeof(byte).TypeHandle) || handle.Equals(typeof(short).TypeHandle) || handle.Equals(typeof(ushort).TypeHandle) || handle.Equals(typeof(double).TypeHandle) || handle.Equals(typeof(float).TypeHandle) || handle.Equals(typeof(Decimal).TypeHandle) || handle.Equals(typeof(uint).TypeHandle)) { // Convert all numeric types into doubles obj.Set(name, Convert.ToDouble(value, CultureInfo.InvariantCulture)); } else if (handle.Equals(typeof(long).TypeHandle) || handle.Equals(typeof(ulong).TypeHandle)) { if (!NumericCanRoundtrip(value, memberType)) { throw new ArgumentOutOfRangeException( name, //value, string.Format( Resources.JsonExtensions_TrySetValue_CannotRoundtripNumericValue, value, name, CultureInfo.InvariantCulture)); } obj.Set(name, Convert.ToDouble(value, CultureInfo.InvariantCulture)); } else if (handle.Equals(typeof(char).TypeHandle)) { // Convert characters to strings obj.Set(name, value.ToString()); } else if (handle.Equals(typeof(string).TypeHandle)) { obj.Set(name, value as string); } else if (handle.Equals(typeof(DateTime).TypeHandle)) { // Serialize DateTime as an ISO 8061 date/time obj.Set(name, ((DateTime)value).ToRoundtripDateString()); } else if (handle.Equals(typeof(DateTimeOffset).TypeHandle)) { // Serialize DateTimeOffset as an ISO 8061 date/time obj.Set(name, ((DateTimeOffset)value).DateTime.ToRoundtripDateString()); } else { return(false); } } return(true); }
public void ThenPresenceShouldReturnCustomUUID() { Pubnub pubnub = new Pubnub(Common.PublishKey, Common.SubscribeKey, "", "", false); Common commonHereNow = new Common(); commonHereNow.DeliveryStatus = false; commonHereNow.Response = null; Common commonSubscribe = new Common(); commonSubscribe.DeliveryStatus = false; commonSubscribe.Response = null; pubnub.PubnubUnitTest = commonHereNow.CreateUnitTestInstance("WhenAClientIsPresented", "ThenPresenceShouldReturnCustomUUID"); ; pubnub.SessionUUID = "CustomSessionUUIDTest"; string channel = "hello_world3"; pubnub.Unsubscribe <string> (channel, commonSubscribe.DisplayReturnMessageDummy, commonSubscribe.DisplayReturnMessageDummy, commonSubscribe.DisplayReturnMessage, commonSubscribe.DisplayReturnMessage); commonSubscribe.WaitForResponse(30); pubnub.Subscribe <string> (channel, commonSubscribe.DisplayReturnMessageDummy, commonSubscribe.DisplayReturnMessage, commonSubscribe.DisplayReturnMessage); commonSubscribe.WaitForResponse(30); Thread.Sleep(5000); pubnub.HereNow <string> (channel, commonHereNow.DisplayReturnMessage, commonHereNow.DisplayReturnMessage); commonHereNow.WaitForResponse(30); pubnub.Unsubscribe <string> (channel, commonSubscribe.DisplayReturnMessageDummy, commonSubscribe.DisplayReturnMessageDummy, commonSubscribe.DisplayReturnMessageDummy, commonSubscribe.DisplayReturnMessage); if (commonHereNow.Response != null) { #if (USE_JSONFX || USE_JSONFX_UNITY || USE_JSONFX_UNITY_IOS || USE_MiniJSON) #if (USE_JSONFX) IList <object> fields = new JsonFXDotNet().DeserializeToObject(commonHereNow.Response.ToString()) as IList <object>; #elif (USE_JSONFX_UNITY) IList <object> fields = new JsonFXDotNet().DeserializeToObject(commonHereNow.Response.ToString()) as IList <object>; #elif (USE_JSONFX_UNITY_IOS) IList <object> fields = JsonReader.Deserialize <IList <object> > (commonHereNow.Response.ToString()) as IList <object>; #elif (USE_MiniJSON) IList <object> fields = Json.Deserialize(commonHereNow.Response.ToString()) as IList <object>; #endif if (fields [0] != null) { bool result = false; Dictionary <string, object> message = (Dictionary <string, object>)fields [0]; foreach (KeyValuePair <String, object> entry in message) { Console.WriteLine("value:" + entry.Value + " " + "key:" + entry.Key); Type valueType = entry.Value.GetType(); var expectedType = typeof(string[]); if (valueType.IsArray && expectedType.IsAssignableFrom(valueType)) { List <string> uuids = new List <string> (entry.Value as string[]); if (uuids.Contains(pubnub.SessionUUID)) { result = true; break; } } } Assert.True(result); } else { Assert.Fail("Null response"); } #else object[] serializedMessage = JsonConvert.DeserializeObject <object[]>(commonHereNow.Response.ToString()); JContainer dictionary = serializedMessage[0] as JContainer; var uuid = dictionary["uuids"].ToString(); if (uuid != null) { Assert.True(uuid.Contains(pubnub.SessionUUID)); } else { Assert.Fail("Custom uuid not found."); } #endif } else { Assert.Fail("Null response"); } pubnub.EndPendingRequests(); }
private void ValidateCollectionObject(JContainer obj, CodeBlockAnnotation annotation, Dictionary<string, JsonSchema> otherSchemas, string collectionPropertyName, List<ValidationError> detectedErrors) { // TODO: also validate additional properties on the collection, like nextDataLink var collection = obj[collectionPropertyName]; if (null == collection) { detectedErrors.Add(new ValidationError(ValidationErrorCode.MissingCollectionProperty, null, "Failed to locate collection property '{0}' in response.", collectionPropertyName)); } else { var collectionMembers = obj[collectionPropertyName]; if (!collectionMembers.Any()) { if (!annotation.IsEmpty) { detectedErrors.Add( new ValidationWarning( ValidationErrorCode.CollectionArrayEmpty, null, "Property contained an empty array that was not validated: {0}", collectionPropertyName)); } } else if (annotation.IsEmpty) { detectedErrors.Add( new ValidationWarning( ValidationErrorCode.CollectionArrayNotEmpty, null, "Property contained a non-empty array that was expected to be empty: {0}", collectionPropertyName)); } foreach (var jToken in collectionMembers) { var container = jToken as JContainer; if (null != container) { this.ValidateContainerObject( container, new ValidationOptions { AllowTruncatedResponses = annotation.TruncatedResult }, otherSchemas, detectedErrors); } } } }
void RevokeToSubKeyLevelCallback(string receivedMessage) { try { if (!string.IsNullOrEmpty(receivedMessage) && !string.IsNullOrEmpty(receivedMessage.Trim())) { object[] serializedMessage = JsonConvert.DeserializeObject <object[]>(receivedMessage); JContainer dictionary = serializedMessage[0] as JContainer; if (dictionary != null) { int statusCode = dictionary.Value <int>("status"); string statusMessage = dictionary.Value <string>("message"); if (statusCode == 200 && statusMessage.ToLower() == "success") { var payload = dictionary.Value <JContainer>("payload"); if (payload != null) { bool read = payload.Value <bool>("r"); bool write = payload.Value <bool>("w"); string level = payload.Value <string>("level"); if (level == "subkey") { switch (currentUnitTestCase) { case "ThenRevokeAtSubKeyLevelReturnSuccess": if (!read && !write) { receivedRevokeMessage = true; } break; case "ThenSubKeyLevelWithReadShouldReturnSuccess": //if (read && !write) receivedGrantMessage = true; break; case "ThenSubKeyLevelWithWriteShouldReturnSuccess": //if (!read && write) receivedGrantMessage = true; break; default: break; } } } } //if (dictionary. //if (status == "200") //{ // receivedGrantMessage = true; //} } //var level = dictionary["level"].ToString(); } } catch { } finally { mreGrant.Set(); } }
private async Task LoadDataAsync() { using (var reader = new StreamReader(DataConstants.AssemblyLocation + "/Data/Abilities.json")) { _abilities = new List <Ability>(); var statusEffects = await _statusEffectRepo.GetDataAsync(); var categories = await _categoryRepo.GetDataAsync(); JContainer abilitiesAsList = JsonConvert.DeserializeObject <JContainer>(reader.ReadToEnd()); foreach (var abilityObject in abilitiesAsList) { var ability = abilityObject.ToObject <Ability>(); if (abilityObject["categoryId"] != null) { var categoryId = abilityObject["categoryId"].ToObject <int>(); var foundCategory = categories.FirstOrDefault(c => c.Id == categoryId); if (foundCategory != null) { ability.Category = foundCategory; } } var appliedStatusEffects = new List <StatusEffect>(); List <int> appliedStatusIds = null; if (abilityObject["appliedStatusEffectIds"] != null) { appliedStatusIds = abilityObject["appliedStatusEffectIds"].ToObject <List <int> >(); foreach (var id in appliedStatusIds) { var foundStatus = statusEffects.FirstOrDefault(se => se.Id == id); if (foundStatus != null) { appliedStatusEffects.Add(foundStatus); } } ability.AppliedStatusEffects = appliedStatusEffects; } var selfAppliedStatusEffects = new List <StatusEffect>(); List <int> selfAppliedStatusIds = null; if (abilityObject["selfAppliedStatusEffectIds"] != null) { selfAppliedStatusIds = abilityObject["selfAppliedStatusEffectIds"].ToObject <List <int> >(); foreach (var id in selfAppliedStatusIds) { var foundStatus = statusEffects.FirstOrDefault(se => se.Id == id); if (foundStatus != null) { selfAppliedStatusEffects.Add(foundStatus); } } ability.SelfAppliedStatusEffects = selfAppliedStatusEffects; } if (ability.IsOffensive == null) { ability.IsOffensive = IsAbilityOffensive(ability); } _abilities.Add(ability); } } }
private void BuildIndexMap(LanguageAST.JsonIdentifierExpression var, string exp, List <string> indexMap, JContainer container) { var jsonIdentifierExpression = var; if (jsonIdentifierExpression != null) { var nameExpression = jsonIdentifierExpression as LanguageAST.JsonIdentifierExpression.IndexNestedNameExpression; if (nameExpression != null) { var objectName = nameExpression.Item.ObjectName; JContainer obj; JArray arr = null; if (container == null) { obj = _env.JsonObjects[objectName]; arr = obj as JArray; } else { var props = container.FirstOrDefault(token => token.Type == JTokenType.Property && ((JProperty)token).Name == objectName); if (props != null) { obj = props.First as JContainer; arr = obj as JArray; } else { obj = container; } } if (arr != null) { var indexToInt = AssignEvaluation.indexToInt(LanguageAST.Index.Star, arr).ToList(); foreach (var i in indexToInt) { if (!string.IsNullOrEmpty(exp)) { var indexed = objectName + @"(" + i + @")"; var updatedExp = exp.Replace(objectName + @"(*)", indexed); indexMap.Add(updatedExp); BuildIndexMap(nameExpression.Item.Next, updatedExp, indexMap, arr[i - 1] as JContainer); } } } else { if (!nameExpression.Item.Next.IsTerminal) { BuildIndexMap(nameExpression.Item.Next, exp, indexMap, obj); } } } else { var nestedNameExpression = jsonIdentifierExpression as LanguageAST.JsonIdentifierExpression.NestedNameExpression; if (nestedNameExpression != null) { JContainer obj; var objectName = nestedNameExpression.Item.ObjectName; if (container == null) { obj = _env.JsonObjects[objectName]; } else { var props = container.FirstOrDefault(token => token.Type == JTokenType.Property && ((JProperty)token).Name == objectName); if (props != null) { obj = props.First as JContainer; } else { obj = container; } } BuildIndexMap(nestedNameExpression.Item.Next, exp, indexMap, obj); } } } }
private NewtonsoftJsonAdapter(JContainer owner, string name) { this.owner = owner; itemName = name; }
private void AsyncComplete(IAsyncResult ar) { if (this.IsDisposed) { return; } var caller = ar.AsyncState as AsyncMethodCaller; var value = caller.EndInvoke(ar); var data = value as InvokeResponse; if (!data.IsError) { InvokeMethod(new Action(() => { richTextBox1.Text = string.Format("【InvokeValue】({0} rows) =>\r\n{1}\r\n\r\n【OutParameters】 =>\r\n{2}", data.Count, data.Value, data.OutParameters); richTextBox1.Refresh(); })); //启用线程来处理数据 ThreadPool.QueueUserWorkItem(state => { var invokeData = state as InvokeData; var container = JContainer.Parse(invokeData.Value); //获取DataView数据 var table = GetDataTable(container); if (table == null) { //写Document文档 InvokeMethod(new Action(() => { gridDataQuery.DataSource = null; var html = container.ToString(); webBrowser1.Url = new Uri("about:blank"); webBrowser1.DocumentCompleted += (sender, e) => { if (this.IsDisposed) { return; } webBrowser1.Document.GetElementsByTagName("body")[0].InnerHtml = string.Empty; webBrowser1.Document.Write(html); }; })); } else { InvokeMethod(new Action(() => gridDataQuery.DataSource = table)); } }, data); } else { InvokeMethod(new Action(() => { richTextBox1.Text = string.Format("【Error】 =>\r\n{0}", data.Exception.Message); })); } InvokeMethod(new Action(() => { label5.Text = data.ElapsedMilliseconds + " ms"; label5.Refresh(); button1.Enabled = true; if (txtParameters.Count > 0) { var p = txtParameters.Values.FirstOrDefault(); p.Focus(); } else { button1.Focus(); } })); }
fileData; //Individual file data (SOLO DISPONIBLE EN GITLAB) public SerializedObjectData(string v, JContainer t, JContainer f) { Version = v; treeData = t; fileData = f; }
/// <summary> /// <para>Merge the right token into the left</para> /// <para>Default options are used</para> /// </summary> /// <param name="left">Token to be merged into</param> /// <param name="right">Token to merge, overwriting the left</param> public static void MergeInto( this JContainer left, JToken right) { MergeInto(left, right, new JsonMergeSettings()); }
internal void AddValue(JValue value, JsonToken token) { if (_parent != null) { _parent.Add(value); if (_parent.Type == JTokenType.Property) _parent = _parent.Parent; } else { _value = value ?? JValue.CreateNull(); } }
void UserCallbackForCleanUpAccessAtUserLevel(string receivedMessage) { try { Console.WriteLine(receivedMessage); if (!string.IsNullOrEmpty(receivedMessage) && !string.IsNullOrEmpty(receivedMessage.Trim())) { object[] serializedMessage = JsonConvert.DeserializeObject <object[]> (receivedMessage); JContainer dictionary = serializedMessage [0] as JContainer; if (dictionary != null) { int statusCode = dictionary.Value <int> ("status"); string statusMessage = dictionary.Value <string> ("message"); if (statusCode == 200 && statusMessage.ToLower() == "success") { var payload = dictionary.Value <JContainer> ("payload"); if (payload != null) { bool read = payload.Value <bool> ("r"); bool write = payload.Value <bool> ("w"); var channels = payload.Value <JContainer> ("channels"); if (channels != null && channels.Count > 0) { Console.WriteLine("CleanupGrant / AtUserLevel / UserCallbackForCleanUpAccess - Channel Count = {0}", channels.Count); foreach (JToken channel in channels.Children()) { if (channel is JProperty) { var channelProperty = channel as JProperty; if (channelProperty != null) { string channelName = channelProperty.Name; Console.WriteLine(channelName); var channelContainer = channels.Value <JContainer> (channelName); if (channelContainer != null && channelContainer.Count > 0) { var auths = channelContainer.Value <JContainer> ("auths"); if (auths != null && auths.Count > 0) { foreach (JToken auth in auths.Children()) { if (auth is JProperty) { var authProperty = auth as JProperty; if (authProperty != null) { receivedRevokeMessage = false; string authKey = authProperty.Name; Console.WriteLine("Auth Key = " + authKey); Pubnub pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, PubnubCommon.SecretKey, "", false); pubnub.AuthenticationKey = authKey; Thread.Sleep(1000); pubnub.GrantAccess <string> (channelName, false, false, UserCallbackForRevokeAccess, ErrorCallbackForRevokeAccess); revokeManualEvent.WaitOne(1000); } } } } } } } } } string level = payload.Value <string> ("level"); if (level == "subkey") { receivedAuditMessage = true; } } } } } } catch (Exception ex) { Console.WriteLine("UserCallbackForCleanUpAccessAtUserLevel" + ex.ToString()); } finally { auditManualEvent.Set(); } }
public void RefreshAData(JContainer jcontainer) { List <KLine> list = KLine.GetAListFormJContainer(jcontainer); RefreshData(list); }
public string getBalancesAsync() { try { var client = new RestClient("https://api.binance.com"); String parameters = "timestamp=" + Utils.GenerateTimeStamp(DateTime.Now.ToUniversalTime()).Split(',')[0]; HMACSHA256 encryptor = new HMACSHA256(); encryptor.Key = Encoding.ASCII.GetBytes(Key.secret); String sign = BitConverter.ToString(encryptor.ComputeHash(Encoding.ASCII.GetBytes(parameters))).Replace("-", ""); parameters += "&signature=" + sign; var request = new RestRequest("/api/v3/account?" + parameters, Method.GET); request.AddHeader("X-MBX-APIKEY", Key.key); var response = client.Execute(request); Console.WriteLine(response.Content); String json = response.Content.ToString(); JContainer dt = (JContainer)JsonConvert.DeserializeObject(json, (typeof(JContainer))); int index = 0; decimal totalBTC = 0; String jsonTicker = Http.get("https://api.binance.com/api/v1/ticker/24hr"); JContainer jCointanerTicker = (JContainer)JsonConvert.DeserializeObject(jsonTicker, (typeof(JContainer))); foreach (var item in dt["balances"]) { String coin = item["asset"].ToString(); decimal value = decimal.Parse(item["free"].ToString().Replace(".", ",")) + decimal.Parse(item["locked"].ToString().ToString().Replace(".", ",")); if (value > 0) { if (coin.ToString().ToUpper() == "BTC") { totalBTC += value; //Key.btcInvest = Math.Round((totalBTC / 8), 13); //if(Key.btcInvest > 1) //Key.btcInvest = 0.05m; //ClassDB.execS("update anubis_user set num_btc = '" + Key.btcInvest.ToString().Replace(",", ".") + "' where cod_user = 540 "); } else { decimal priceLast = 0; foreach (var itemTicker in jCointanerTicker) { if (coin + "BTC" == itemTicker["symbol"].ToString()) { priceLast = decimal.Parse(itemTicker["lastPrice"].ToString().ToString().Replace(".", ",")); break; } } totalBTC += value * priceLast; } } index++; } return(response.Content.ToString()); } catch (Exception ex) { return(null); } finally { } }
private bool SetEnd(JContainer c) { JsonToken? endToken = GetEndToken(c); if (endToken != null) { SetToken(endToken.Value); _current = c; _parent = c; return true; } else { return ReadOver(c); } }
/// <summary> /// Call a remote procedure with a specified timeout /// </summary> /// <param name="endpoint">The endpoint to which to route the request</param> /// <param name="body">The request body</param> /// <param name="receiveTimeout">Timeout in ms, after which a null response is returned</param> /// <returns>The response</returns> public JContainer Call(string endpoint, JContainer body, int receiveTimeout) { var message = _messaging.CreateMessage(); message.To = _target; message.ReplyTo = _replyTo; message.Body = Json.Serialize(body); message.Properties.Headers = AmqpRpc.CreateHeaders(endpoint, null); _messaging.Send(message); var reply = _messaging.Receive(receiveTimeout); if (AmqpRpc.GetStatusCode(reply) != 200) { throw new AmqpRpcError(Encoding.UTF8.GetString(reply.Body)); } // TODO handle null reply (timeout) return Json.Deserialize(reply.Body); }
private void SocketClientMessage(object sender, MessageEventArgs args) { try { if (args.Message.MessageText != null) { LastMessage = DateTime.Now; JContainer o = (JContainer)JsonConvert.DeserializeObject(args.Message.MessageText); string op = o["op"].Value <string>(); if (op == "remark") { return; } string channel = o["channel"].Value <string>(); if (op.Equals("private")) { switch (channel) { case TickerChannel: if (GoxTickerHandlers != null) { GoxTickerHandlers(new Ticker(JsonConvert.DeserializeObject <MtGoxTicker>(o["ticker"].ToString()))); } //Mediator.Instance.NotifyColleagues("Ticker", new Ticker(JsonConvert.DeserializeObject<MtGoxTicker>(o["ticker"].ToString()))); break; case TradesChannel: if (GoxTradeHandlers != null) { GoxTradeHandlers(JsonConvert.DeserializeObject <Trade>(o["trade"].ToString())); } //Mediator.Instance.NotifyColleagues("Trade", JsonConvert.DeserializeObject<Trade>(o["trade"].ToString())); break; case DepthChannel: if (GoxDepthHandlers != null) { GoxDepthHandlers(JsonConvert.DeserializeObject <DepthUpdate>(o["depth"].ToString())); } if (GoxDepthStringHandlers != null) { GoxDepthStringHandlers(args.Message.MessageText); } //Mediator.Instance.NotifyColleagues("DepthUpdate", JsonConvert.DeserializeObject<DepthUpdate>(o["depth"].ToString())); break; case LagChannel: if ((long)o["lag"]["age"] == 0 || (o["lag"]["qid"] == null && o["lag"]["stamp"] == null)) { if (GoxLagHandlers != null) { GoxLagHandlers(new LagChannelResponse { age = 0, qid = new Guid(), stamp = DateTime.Now }); } //Mediator.Instance.NotifyColleagues("Lag", new LagChannelResponse { age = 0, qid = new Guid(), stamp = DateTime.Now }); else if (GoxLagHandlers != null) { GoxLagHandlers(JsonConvert.DeserializeObject <LagChannelResponse>(o["lag"].ToString())); } } //Mediator.Instance.NotifyColleagues("Lag", JsonConvert.DeserializeObject<LagChannelResponse>(o["lag"].ToString())); break; default: if (channel == OrderChannel) { if (o["private"].Value <String>().Equals("wallet")) { if (GoxWalletHandlers != null) { GoxWalletHandlers(JsonConvert.DeserializeObject <WalletResponse>(o["wallet"].ToString())); } //Mediator.Instance.NotifyColleagues("Wallet", JsonConvert.DeserializeObject<WalletResponse>(o["wallet"].ToString())); } else if (o["private"].Value <String>().Equals("user_order")) { if (GoxOrderHandlers != null) { GoxOrderHandlers(JsonConvert.DeserializeObject <Order>(o["user_order"].ToString())); } //Mediator.Instance.NotifyColleagues("Order", JsonConvert.DeserializeObject<Order>(o["user_order"].ToString())); } } break; } } else { if (op == "subscribe" && channel != TickerChannel && channel != TradesChannel && channel != DepthChannel && channel != LagChannel) { OrderChannel = channel; } } } } catch (Exception ex) { Logger.Logger.LogException(ex); } }
/// <summary> /// Verify that a Json container (object) is valid according to it's resource name (schema). /// </summary> /// <param name="obj"></param> /// <param name="options"></param> /// <param name="otherSchemas"></param> /// <param name="detectedErrors"></param> private void ValidateContainerObject(JContainer obj, ValidationOptions options, Dictionary<string, JsonSchema> otherSchemas, List<ValidationError> detectedErrors) { var containerProperties = from p in obj select ParseProperty(p, this, detectedErrors); this.ValidateObjectProperties(containerProperties.Where(x => null != x), options, otherSchemas, detectedErrors); }
static private IEnumerable <KeyValuePair <string, TwinValue> > AsEnumerableFlatten(this JContainer container, string prefix = "", bool IgnoreNullValue = true) { foreach (var child in container.Children <JProperty>()) { if (child.Value is JContainer) { var results = AsEnumerableFlatten(child.Value as JContainer, $"{prefix}{child.Name}.", IgnoreNullValue); foreach (var result in results) { yield return(result); } } else if (child.Value is JValue) { var value = child.Value as JValue; if (value.Type != JTokenType.Null) { yield return(new KeyValuePair <string, TwinValue>($"{prefix}{child.Name}", new TwinValue { Value = value, LastUpdated = (child.Value as TwinCollectionValue)?.GetLastUpdated() })); } else { if (!IgnoreNullValue) { yield return(new KeyValuePair <string, TwinValue>($"{prefix}{child.Name}", new TwinValue { Value = JValue.CreateNull(), LastUpdated = (child.Value as TwinCollectionValue)?.GetLastUpdated() })); } } } else { #if DEBUG throw new ApplicationException($"Unexpected TwinCollection item JTokenType: {child.Value.Type} @ {prefix}{child.Name}"); #endif } } }
internal void AddValue(JValue value, JsonToken token) { if (_parent != null) { _parent.Add(value); if (_parent.Type == JTokenType.Property) _parent = _parent.Parent; } else { _value = value ?? new JValue((object)null); } }
private void HandleMessage(string json) { var coll = JsonConvert.DeserializeObject <ReadOnlyCollection <object> >(json); JContainer container = coll[0] as JContainer; Dictionary <string, string> msg = container.ToObject <Dictionary <string, string> >(); Console.WriteLine(); Console.WriteLine("---------------------------"); Console.WriteLine(); Console.WriteLine("Server incoming message: {0}", container); if (!msg.ContainsKey("uuid") || !msg.ContainsKey("username") || !msg.ContainsKey("type")) { Console.WriteLine("Invalid message received"); return; } /** * Local variables for the switch block **/ Dictionary <string, string> response = new Dictionary <string, string>(); GameManager game; Player player; string gameName; string message; bool success; response["type"] = msg["type"]; try { switch (msg["type"]) { case "create-user": bool uuidExists = this.db.uuidExists(msg["uuid"]); bool nameExists = this.db.userExists(msg["username"]); success = (!uuidExists && !nameExists); response["success"] = success.ToString(); if (success) { player = this.db.addUser(msg["username"], msg["uuid"]); if (player != null) { this.players.Add(player.Uuid, player); } } else if (nameExists) { response["message"] = String.Format("Username '{0}' is already taken.", msg["username"]); } else if (uuidExists) { response["message"] = String.Format("You have already created a user for this device"); } response["username"] = msg["username"]; break; case "login": success = this.db.authenticateUser(msg["username"], msg["uuid"]); if (!success) { response["message"] = String.Format("The username '{0}' is not associated with your device.", msg["username"]); } else if (!this.players.ContainsKey(msg["uuid"])) { player = db.loadPlayer(msg["uuid"]); if (player != null) { this.players.Add(player.Uuid, player); } else { success = false; response["message"] = String.Format("An error occurred during login."); } } response["success"] = success.ToString(); response["username"] = msg["username"]; break; case "joinable": // Trying to join game bool publicGame = true; if (msg.ContainsKey("game") && msg["game"].Length > 0) { gameName = msg["game"]; publicGame = false; } else { gameName = GameManager.FindPublicGame(); } message = null; success = true; game = GameManager.GetGame(gameName); if (game != null) { success = game.MemberCount < GameManager.MEMBER_LIMIT; if (!success) { message = String.Format("Game '{0}' is full.", gameName); } else { // Success is true response["channel"] = game.GameChannel; response["message"] = game.MemberCount.ToString(); // If trying to join private game, notify creator to allow access for new person if (!publicGame) { Dictionary <string, string> promptAuth = new Dictionary <string, string>(3); promptAuth["type"] = "authrequest"; promptAuth["requester-name"] = msg["username"]; promptAuth["requester-uuid"] = msg["uuid"]; this.SendMessage(game.CreatorUuid, promptAuth); } } } else { success = false; message = String.Format("Game '{0}' does not exist", gameName); } response["success"] = success.ToString(); if (message != null) { response["message"] = message; } break; case "create": // Creating a new game gameName = msg["game"]; message = null; success = true; game = GameManager.GetGame(gameName); player = this.GetPlayer(msg["uuid"]); if (player == null) { success = false; message = String.Format("{0} is not a logged in user", msg["username"]); } else if (game == null) { success = true; GameManager.CreateGame(gameName, msg["uuid"]); game = GameManager.GetGame(gameName); game.Join(player); response["channel"] = game.GameChannel; } else { success = false; message = String.Format("Game '{0}' exists already", gameName); } response["success"] = success.ToString(); if (message != null) { response["message"] = message; } break; case "stats": player = this.GetPlayer(msg["uuid"]); if (player != null) { response = player.GetStats(); response["success"] = true.ToString(); } else { response["success"] = false.ToString(); } break; } } catch (Exception e) { response["type"] = "exception"; } finally { this.SendMessage(msg["uuid"], response); } }
private void AddParent(JContainer container) { if (_parent == null) _token = container; else _parent.AddAndSkipParentCheck(container); _parent = container; _current = container; }
/// <summary> /// Initializes a new instance of the <see cref="Core.Models.PositionI"/> class. /// </summary> /// <param name="obj">JSON Object.</param> public PositionI(JContainer obj) { X = (int)obj.SelectToken("X"); Y = (int)obj.SelectToken("Y"); }
public static void Main(string[] args) { try { //Config log("BOTMEX - ONOBOT - v" + version + " - Bitmex version"); log("by ONO NAKAMOTO"); log("GITHUB http://github.com/ononakamoto"); log(" ******* DONATE ********* "); log("BTC 36dbH2hr1mphZYrNKzYBHXLK1sgEwEYF2m"); log("Load config..."); String jsonConfig = System.IO.File.ReadAllText(location + "key.txt"); JContainer jCointaner = (JContainer)JsonConvert.DeserializeObject(jsonConfig, (typeof(JContainer))); bitmexKey = jCointaner["key"].ToString(); bitmexSecret = jCointaner["secret"].ToString(); bitmexKeyWeb = jCointaner["webserverKey"].ToString(); bitmexSecretWeb = jCointaner["webserverSecret"].ToString(); bitmexDomain = jCointaner["domain"].ToString(); statusShort = jCointaner["short"].ToString(); statusLong = jCointaner["long"].ToString(); pair = jCointaner["pair"].ToString(); timeGraph = jCointaner["timeGraph"].ToString(); qtdyContacts = int.Parse(jCointaner["contract"].ToString()); interval = int.Parse(jCointaner["interval"].ToString()); intervalOrder = int.Parse(jCointaner["intervalOrder"].ToString()); intervalCapture = int.Parse(jCointaner["webserverIntervalCapture"].ToString()); profit = double.Parse(jCointaner["profit"].ToString()); fee = double.Parse(jCointaner["fee"].ToString()); if (jCointaner["webserver"].ToString() == "enable") { WebServer ws = new WebServer(WebServer.SendResponse, jCointaner["webserverConfig"].ToString()); ws.Run(); System.Threading.Thread tCapture = new Thread(Database.captureDataJob); tCapture.Start(); System.Threading.Thread.Sleep(1000); } bitMEXApi = new BitMEX.BitMEXApi(bitmexKey, bitmexSecret, bitmexDomain); log("wait 1s..."); System.Threading.Thread.Sleep(1000); log("Total open orders: " + bitMEXApi.GetOpenOrders(pair).Count); log(""); log("Wallet: " + bitMEXApi.GetWallet()); lstIndicatorsAll.Add(new IndicatorMFI()); lstIndicatorsAll.Add(new IndicatorBBANDS()); lstIndicatorsAll.Add(new IndicatorCCI()); lstIndicatorsAll.Add(new IndicatorCMO()); lstIndicatorsAll.Add(new IndicatorDI()); lstIndicatorsAll.Add(new IndicatorDM()); lstIndicatorsAll.Add(new IndicatorMA()); lstIndicatorsAll.Add(new IndicatorMACD()); lstIndicatorsAll.Add(new IndicatorMOM()); lstIndicatorsAll.Add(new IndicatorPPO()); lstIndicatorsAll.Add(new IndicatorROC()); lstIndicatorsAll.Add(new IndicatorRSI()); lstIndicatorsAll.Add(new IndicatorSAR()); lstIndicatorsAll.Add(new IndicatorSTOCH()); lstIndicatorsAll.Add(new IndicatorSTOCHRSI()); lstIndicatorsAll.Add(new IndicatorTRIX()); lstIndicatorsAll.Add(new IndicatorULTOSC()); lstIndicatorsAll.Add(new IndicatorWILLR()); foreach (var item in jCointaner["indicatorsEntry"]) { foreach (var item2 in lstIndicatorsAll) { if (item["name"].ToString().Trim().ToUpper() == item2.getName().Trim().ToUpper()) { item2.setPeriod(int.Parse((item["period"].ToString().Trim().ToUpper()))); lstIndicatorsEntry.Add(item2); } } } foreach (var item in jCointaner["indicatorsEntryCross"]) { foreach (var item2 in lstIndicatorsAll) { if (item["name"].ToString().Trim().ToUpper() == item2.getName().Trim().ToUpper()) { item2.setPeriod(int.Parse((item["period"].ToString().Trim().ToUpper()))); lstIndicatorsEntryCross.Add(item2); } } } foreach (var item in jCointaner["indicatorsEntryDecision"]) { foreach (var item2 in lstIndicatorsAll) { if (item["name"].ToString().Trim().ToUpper() == item2.getName().Trim().ToUpper()) { item2.setPeriod(int.Parse((item["period"].ToString().Trim().ToUpper()))); lstIndicatorsEntryDecision.Add(item2); } } } if (jCointaner["webserver"].ToString() == "enable") { System.Diagnostics.Process.Start(jCointaner["webserverConfig"].ToString()); } //LOOP while (true) { //GET CANDLES if (getCandles()) { /////VERIFY OPERATION LONG string operation = "buy"; //VERIFY INDICATORS ENTRY foreach (var item in lstIndicatorsEntry) { Operation operationBuy = item.GetOperation(arrayPriceOpen, arrayPriceClose, arrayPriceLow, arrayPriceHigh, arrayPriceVolume); log("Indicator: " + item.getName()); log("Result1: " + item.getResult()); log("Result2: " + item.getResult2()); log("Operation: " + operationBuy.ToString()); log(""); if (operationBuy != Operation.buy) { operation = "nothing"; break; } } //VERIFY INDICATORS CROSS if (operation == "buy") { //Prepare to long while (true) { log("wait operation long..."); getCandles(); foreach (var item in lstIndicatorsEntryCross) { Operation operationBuy = item.GetOperation(arrayPriceOpen, arrayPriceClose, arrayPriceLow, arrayPriceHigh, arrayPriceVolume); log("Indicator Cross: " + item.getName()); log("Result1: " + item.getResult()); log("Result2: " + item.getResult2()); log("Operation: " + operationBuy.ToString()); log(""); if (item.getTypeIndicator() == TypeIndicator.Cross) { if (operationBuy == Operation.buy) { operation = "long"; break; } } else if (operationBuy != Operation.buy) { operation = "long"; break; } } if (lstIndicatorsEntryCross.Count == 0) { operation = "long"; } if (operation != "buy") { break; } log("wait " + interval + "ms"); Thread.Sleep(interval); } } //VERIFY INDICATORS DECISION if (operation == "long" && lstIndicatorsEntryDecision.Count > 0) { operation = "decision"; foreach (var item in lstIndicatorsEntryDecision) { Operation operationBuy = item.GetOperation(arrayPriceOpen, arrayPriceClose, arrayPriceLow, arrayPriceHigh, arrayPriceVolume); log("Indicator Decision: " + item.getName()); log("Result1: " + item.getResult()); log("Result2: " + item.getResult2()); log("Operation: " + operationBuy.ToString()); log(""); if (getValue("indicatorsEntryDecision", item.getName(), "decision") == "enable" && getValue("indicatorsEntryDecision", item.getName(), "tendency") == "enable") { int decisionPoint = int.Parse(getValue("indicatorsEntryDecision", item.getName(), "decisionPoint")); if (item.getResult() >= decisionPoint && item.getTendency() == Tendency.high) { operation = "long"; break; } } if (getValue("indicatorsEntryDecision", item.getName(), "decision") == "enable") { int decisionPoint = int.Parse(getValue("indicatorsEntryDecision", item.getName(), "decisionPoint")); if (item.getResult() >= decisionPoint) { operation = "long"; break; } } if (getValue("indicatorsEntryDecision", item.getName(), "tendency") == "enable") { if (item.getTendency() == Tendency.high) { operation = "long"; break; } } } } //EXECUTE OPERATION if (operation == "long") { makeOrder("Buy"); } ////////////FINAL VERIFY OPERATION LONG////////////////// ////////////////////////////////////////////////////////////// /////VERIFY OPERATION LONG operation = "sell"; //VERIFY INDICATORS ENTRY foreach (var item in lstIndicatorsEntry) { Operation operationBuy = item.GetOperation(arrayPriceOpen, arrayPriceClose, arrayPriceLow, arrayPriceHigh, arrayPriceVolume); log("Indicator: " + item.getName()); log("Result1: " + item.getResult()); log("Result2: " + item.getResult2()); log("Operation: " + operationBuy.ToString()); log(""); if (operationBuy != Operation.sell) { operation = "nothing"; break; } } //VERIFY INDICATORS CROSS if (operation == "sell") { //Prepare to long while (true) { log("wait operation short..."); getCandles(); foreach (var item in lstIndicatorsEntryCross) { Operation operationBuy = item.GetOperation(arrayPriceOpen, arrayPriceClose, arrayPriceLow, arrayPriceHigh, arrayPriceVolume); log("Indicator Cross: " + item.getName()); log("Result1: " + item.getResult()); log("Result2: " + item.getResult2()); log("Operation: " + operationBuy.ToString()); log(""); if (item.getTypeIndicator() == TypeIndicator.Cross) { if (operationBuy == Operation.sell) { operation = "short"; break; } } else if (operationBuy != Operation.sell) { operation = "short"; break; } } if (lstIndicatorsEntryCross.Count == 0) { operation = "short"; } if (operation != "sell") { break; } log("wait " + interval + "ms"); Thread.Sleep(interval); } } //VERIFY INDICATORS DECISION if (operation == "short" && lstIndicatorsEntryDecision.Count > 0) { operation = "decision"; foreach (var item in lstIndicatorsEntryDecision) { Operation operationBuy = item.GetOperation(arrayPriceOpen, arrayPriceClose, arrayPriceLow, arrayPriceHigh, arrayPriceVolume); log("Indicator Decision: " + item.getName()); log("Result1: " + item.getResult()); log("Result2: " + item.getResult2()); log("Operation: " + operationBuy.ToString()); log(""); if (getValue("indicatorsEntryDecision", item.getName(), "decision") == "enable" && getValue("indicatorsEntryDecision", item.getName(), "tendency") == "enable") { int decisionPoint = int.Parse(getValue("indicatorsEntryDecision", item.getName(), "decisionPoint")); if (item.getResult() <= decisionPoint && item.getTendency() == Tendency.low) { operation = "short"; break; } } if (getValue("indicatorsEntryDecision", item.getName(), "decision") == "enable") { int decisionPoint = int.Parse(getValue("indicatorsEntryDecision", item.getName(), "decisionPoint")); if (item.getResult() <= decisionPoint) { operation = "short"; break; } } if (getValue("indicatorsEntryDecision", item.getName(), "tendency") == "enable") { if (item.getTendency() == Tendency.low) { operation = "short"; break; } } } } //EXECUTE OPERATION if (operation == "short") { makeOrder("Sell"); } ////////////FINAL VERIFY OPERATION LONG////////////////// } log("wait " + interval + "ms"); Thread.Sleep(interval); } } catch (Exception ex) { log("ERROR FATAL::" + ex.Message + ex.StackTrace); } }
public static bool IsNullOrEmpty(this JContainer jC) { return(jC.IsNull() || jC.Count == 0); }
public JObjectValueProvider(JContainer jcontainer) { _jcontainer = jcontainer; }
public void AddToJsonObjects(string exp, JContainer jContainer) { _inner.AddToJsonObjects(exp, jContainer); }