Lean  $LEAN_TAG$
ReadOrdersResponseJsonConverter.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2024 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 using System.Collections.Generic;
21 
22 namespace QuantConnect.Orders
23 {
24  /// <summary>
25  /// Api orders read response json converter
26  /// </summary>
27  public class ReadOrdersResponseJsonConverter : JsonConverter
28  {
29  /// <summary>
30  /// Determines if can convert the given open type
31  /// </summary>
32  public override bool CanConvert(Type objectType)
33  {
34  return objectType == typeof(ApiOrderResponse);
35  }
36 
37  /// <summary>
38  /// Serialize the given api order response
39  /// </summary>
40  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
41  {
42  var orderResponse = (ApiOrderResponse)value;
43  var jObject = JObject.FromObject(orderResponse.Order);
44  jObject["symbol"] = JToken.FromObject(orderResponse.Symbol);
45  jObject["events"] = JToken.FromObject(orderResponse.Events);
46  jObject.WriteTo(writer);
47  }
48 
49  /// <summary>
50  /// Deserialize the given api order response
51  /// </summary>
52  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
53  {
54  var jObject = JObject.Load(reader);
55 
56  serializer.Converters.Add(new OrderJsonConverter());
57  var order = jObject.ToObject<Order>(serializer);
58 
59  var events = jObject["Events"] ?? jObject["events"];
60  List<SerializedOrderEvent> deserializedEvents = null;
61  if (events != null)
62  {
63  deserializedEvents = events.ToObject<List<SerializedOrderEvent>>();
64  }
65 
66  var symbol = jObject["Symbol"] ?? jObject["symbol"];
67  Symbol deserializedSymbol = null;
68  if (symbol != null)
69  {
70  deserializedSymbol = symbol.ToObject<Symbol>();
71  }
72 
73  return new ApiOrderResponse(order, deserializedEvents ?? new(), deserializedSymbol);
74  }
75  }
76 }