Lean  $LEAN_TAG$
NullResultValueTypeJsonConverter.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System;
17 using System.Collections.Generic;
18 using System.Linq;
19 using Newtonsoft.Json;
20 using Newtonsoft.Json.Linq;
21 
22 namespace QuantConnect.Report
23 {
24  /// <summary>
25  /// Removes null values in the <see cref="Result"/> object's x,y values so that
26  /// deserialization can occur without exceptions.
27  /// </summary>
28  /// <typeparam name="T">Result type to deserialize into</typeparam>
29  public class NullResultValueTypeJsonConverter<T> : JsonConverter
30  where T : Result
31  {
32  private JsonSerializerSettings _settings;
33 
34  /// <summary>
35  /// Initialize a new instance of <see cref="NullResultValueTypeJsonConverter{T}"/>
36  /// </summary>
38  {
39  _settings = new JsonSerializerSettings
40  {
41  Converters = new List<JsonConverter> { new OrderTypeNormalizingJsonConverter() },
42  FloatParseHandling = FloatParseHandling.Decimal
43  };
44  }
45 
46  /// <summary>
47  /// Determine if this converter can convert a given type
48  /// </summary>
49  /// <param name="objectType">Object type to convert</param>
50  /// <returns>Always true</returns>
51  public override bool CanConvert(Type objectType)
52  {
53  return objectType.IsAssignableTo(typeof(T));
54  }
55 
56  /// <summary>
57  /// Read Json for conversion
58  /// </summary>
59  /// <returns>Resulting object</returns>
60  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
61  {
62  var token = JToken.ReadFrom(reader);
63  if (token.Type == JTokenType.Null)
64  {
65  return null;
66  }
67 
68  foreach (JProperty property in GetProperty(token, "Charts").Children())
69  {
70  foreach (JProperty seriesProperty in GetProperty(property.Value, "Series"))
71  {
72  var newValues = new List<JToken>();
73  foreach (var entry in GetProperty(seriesProperty.Value, "Values"))
74  {
75  if (entry is JObject jobj &&
76  (jobj["x"] == null || jobj["x"].Value<long?>() == null ||
77  jobj["y"] == null || jobj["y"].Value<decimal?>() == null))
78  {
79  // null chart point
80  continue;
81  }
82 
83  if (entry is JArray jArray && jArray.Any(jToken => jToken.Type == JTokenType.Null))
84  {
85  // null candlestick
86  continue;
87  }
88 
89  newValues.Add(entry);
90  }
91 
92  var chart = GetProperty(token, "Charts")[property.Name];
93  var series = GetProperty(chart, "Series")[seriesProperty.Name];
94  if (series["Values"] != null)
95  {
96  series["Values"] = JArray.FromObject(newValues);
97  }
98  else if (series["values"] != null)
99  {
100  series["values"] = JArray.FromObject(newValues);
101  }
102  }
103  }
104 
105  // Deserialize with OrderJsonConverter, otherwise it will fail. We convert the token back
106  // to its JSON representation and use the `JsonConvert.DeserializeObject<T>(...)` method instead
107  // of using `token.ToObject<T>()` since it can be provided a JsonConverter in its arguments.
108  return JsonConvert.DeserializeObject<T>(token.ToString(), _settings);
109  }
110 
111  /// <summary>
112  /// Write Json; Not implemented
113  /// </summary>
114  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
115  {
116  throw new NotImplementedException();
117  }
118 
119  private static JToken GetProperty(JToken jToken, string name)
120  {
121  return jToken[name] ?? jToken[name.ToLower()];
122  }
123  }
124 }