Lean  $LEAN_TAG$
ChartPointJsonConverter.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 Newtonsoft.Json;
18 using Newtonsoft.Json.Linq;
19 
20 namespace QuantConnect.Util
21 {
22  /// <summary>
23  /// Json Converter for ChartPoint which handles special reading
24  /// </summary>
25  public class ChartPointJsonConverter : JsonConverter
26  {
27  /// <summary>
28  /// Determine if this Converter can convert this type
29  /// </summary>
30  /// <param name="objectType">Type that we would like to convert</param>
31  /// <returns>True if <see cref="Series"/></returns>
32  public override bool CanConvert(Type objectType)
33  {
34  return objectType == typeof(ChartPoint);
35  }
36 
37  /// <summary>
38  /// Reads series from Json
39  /// </summary>
40  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
41  {
42  if (reader.TokenType == JsonToken.StartObject)
43  {
44  var jObject = JObject.Load(reader);
45  var x = jObject["x"];
46 
47  if (!jObject.ContainsKey("y"))
48  {
49  return new ChartPoint(x.Value<long>(), 0);
50  }
51 
52  var y = jObject["y"];
53  if (y != null && (y.Type == JTokenType.Float || y.Type == JTokenType.Integer))
54  {
55  return new ChartPoint(x.Value<long>(), y.Value<decimal>());
56  }
57 
58  if (y.Type == JTokenType.Null)
59  {
60  return new ChartPoint(x.Value<long>(), null);
61  }
62 
63  return null;
64  }
65 
66  var jArray = JArray.Load(reader);
67  return new ChartPoint(jArray[0].Value<long>(), jArray[1].Value<decimal?>());
68  }
69 
70  /// <summary>
71  /// Write point to Json
72  /// </summary>
73  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
74  {
75  var chartPoint = (ChartPoint)value;
76  writer.WriteStartArray();
77  writer.WriteValue(chartPoint.X);
78  writer.WriteValue(chartPoint.Y);
79  writer.WriteEndArray();
80  }
81  }
82 }