forked from QuantConnect/Lean
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApi.cs
1996 lines (1726 loc) · 79.7 KB
/
Api.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using RestSharp.Extensions;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Optimizer.Objectives;
using QuantConnect.Optimizer.Parameters;
using QuantConnect.Orders;
using QuantConnect.Statistics;
using QuantConnect.Util;
using QuantConnect.Notifications;
using Python.Runtime;
using System.Threading;
using System.Net.Http.Headers;
using System.Collections.Concurrent;
using System.Text;
using Newtonsoft.Json.Serialization;
namespace QuantConnect.Api
{
/// <summary>
/// QuantConnect.com Interaction Via API.
/// </summary>
public class Api : IApi, IDownloadProvider
{
private readonly BlockingCollection<Lazy<HttpClient>> _clientPool;
private string _dataFolder;
/// <summary>
/// Serializer settings to use
/// </summary>
protected JsonSerializerSettings SerializerSettings { get; set; } = new()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
ProcessDictionaryKeys = false,
OverrideSpecifiedNames = true
}
}
};
/// <summary>
/// Returns the underlying API connection
/// </summary>
protected ApiConnection ApiConnection { get; private set; }
/// <summary>
/// Creates a new instance of <see cref="Api"/>
/// </summary>
public Api()
{
_clientPool = new BlockingCollection<Lazy<HttpClient>>(new ConcurrentQueue<Lazy<HttpClient>>(), 5);
for (int i = 0; i < _clientPool.BoundedCapacity; i++)
{
_clientPool.Add(new Lazy<HttpClient>());
}
}
/// <summary>
/// Initialize the API with the given variables
/// </summary>
public virtual void Initialize(int userId, string token, string dataFolder)
{
ApiConnection = new ApiConnection(userId, token);
_dataFolder = dataFolder?.Replace("\\", "/", StringComparison.InvariantCulture);
//Allow proper decoding of orders from the API.
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Converters = { new OrderJsonConverter() }
};
}
/// <summary>
/// Check if Api is successfully connected with correct credentials
/// </summary>
public bool Connected => ApiConnection.Connected;
/// <summary>
/// Create a project with the specified name and language via QuantConnect.com API
/// </summary>
/// <param name="name">Project name</param>
/// <param name="language">Programming language to use</param>
/// <param name="organizationId">Optional param for specifying organization to create project under.
/// If none provided web defaults to preferred.</param>
/// <returns>Project object from the API.</returns>
public ProjectResponse CreateProject(string name, Language language, string organizationId = null)
{
var request = new RestRequest("projects/create", Method.POST)
{
RequestFormat = DataFormat.Json
};
// Only include organization Id if its not null or empty
string jsonParams;
if (string.IsNullOrEmpty(organizationId))
{
jsonParams = JsonConvert.SerializeObject(new
{
name,
language
});
}
else
{
jsonParams = JsonConvert.SerializeObject(new
{
name,
language,
organizationId
});
}
request.AddParameter("application/json", jsonParams, ParameterType.RequestBody);
ApiConnection.TryRequest(request, out ProjectResponse result);
return result;
}
/// <summary>
/// Get details about a single project
/// </summary>
/// <param name="projectId">Id of the project</param>
/// <returns><see cref="ProjectResponse"/> that contains information regarding the project</returns>
public ProjectResponse ReadProject(int projectId)
{
var request = new RestRequest("projects/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out ProjectResponse result);
return result;
}
/// <summary>
/// List details of all projects
/// </summary>
/// <returns><see cref="ProjectResponse"/> that contains information regarding the project</returns>
public ProjectResponse ListProjects()
{
var request = new RestRequest("projects/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
ApiConnection.TryRequest(request, out ProjectResponse result);
return result;
}
/// <summary>
/// Add a file to a project
/// </summary>
/// <param name="projectId">The project to which the file should be added</param>
/// <param name="name">The name of the new file</param>
/// <param name="content">The content of the new file</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes information about the newly created file</returns>
public RestResponse AddProjectFile(int projectId, string name, string content)
{
var request = new RestRequest("files/create", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
name,
content
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Update the name of a file
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="oldFileName">The current name of the file</param>
/// <param name="newFileName">The new name for the file</param>
/// <returns><see cref="RestResponse"/> indicating success</returns>
public RestResponse UpdateProjectFileName(int projectId, string oldFileName, string newFileName)
{
var request = new RestRequest("files/update", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
name = oldFileName,
newName = newFileName
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Update the contents of a file
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="fileName">The name of the file that should be updated</param>
/// <param name="newFileContents">The new contents of the file</param>
/// <returns><see cref="RestResponse"/> indicating success</returns>
public RestResponse UpdateProjectFileContent(int projectId, string fileName, string newFileContents)
{
var request = new RestRequest("files/update", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
name = fileName,
content = newFileContents
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Read all files in a project
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes the information about all files in the project</returns>
public ProjectFilesResponse ReadProjectFiles(int projectId)
{
var request = new RestRequest("files/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out ProjectFilesResponse result);
return result;
}
/// <summary>
/// Read all nodes in a project.
/// </summary>
/// <param name="projectId">Project id to which the nodes refer</param>
/// <returns><see cref="ProjectNodesResponse"/> that includes the information about all nodes in the project</returns>
public ProjectNodesResponse ReadProjectNodes(int projectId)
{
var request = new RestRequest("projects/nodes/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out ProjectNodesResponse result);
return result;
}
/// <summary>
/// Update the active state of some nodes to true.
/// If you don't provide any nodes, all the nodes become inactive and AutoSelectNode is true.
/// </summary>
/// <param name="projectId">Project id to which the nodes refer</param>
/// <param name="nodes">List of node ids to update</param>
/// <returns><see cref="ProjectNodesResponse"/> that includes the information about all nodes in the project</returns>
public ProjectNodesResponse UpdateProjectNodes(int projectId, string[] nodes)
{
var request = new RestRequest("projects/nodes/update", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
nodes
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out ProjectNodesResponse result);
return result;
}
/// <summary>
/// Read a file in a project
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="fileName">The name of the file</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes the file information</returns>
public ProjectFilesResponse ReadProjectFile(int projectId, string fileName)
{
var request = new RestRequest("files/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
name = fileName
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out ProjectFilesResponse result);
return result;
}
/// <summary>
/// Gets a list of LEAN versions with their corresponding basic descriptions
/// </summary>
public VersionsResponse ReadLeanVersions()
{
var request = new RestRequest("lean/versions/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
ApiConnection.TryRequest(request, out VersionsResponse result);
return result;
}
/// <summary>
/// Delete a file in a project
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="name">The name of the file that should be deleted</param>
/// <returns><see cref="RestResponse"/> that includes the information about all files in the project</returns>
public RestResponse DeleteProjectFile(int projectId, string name)
{
var request = new RestRequest("files/delete", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
name,
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Delete a project
/// </summary>
/// <param name="projectId">Project id we own and wish to delete</param>
/// <returns>RestResponse indicating success</returns>
public RestResponse DeleteProject(int projectId)
{
var request = new RestRequest("projects/delete", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Create a new compile job request for this project id.
/// </summary>
/// <param name="projectId">Project id we wish to compile.</param>
/// <returns>Compile object result</returns>
public Compile CreateCompile(int projectId)
{
var request = new RestRequest("compile/create", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out Compile result);
return result;
}
/// <summary>
/// Read a compile packet job result.
/// </summary>
/// <param name="projectId">Project id we sent for compile</param>
/// <param name="compileId">Compile id return from the creation request</param>
/// <returns><see cref="Compile"/></returns>
public Compile ReadCompile(int projectId, string compileId)
{
var request = new RestRequest("compile/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
compileId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out Compile result);
return result;
}
/// <summary>
/// Sends a notification
/// </summary>
/// <param name="notification">The notification to send</param>
/// <param name="projectId">The project id</param>
/// <returns><see cref="RestResponse"/> containing success response and errors</returns>
public virtual RestResponse SendNotification(Notification notification, int projectId)
{
throw new NotImplementedException($"{nameof(Api)} does not support sending notifications");
}
/// <summary>
/// Create a new backtest request and get the id.
/// </summary>
/// <param name="projectId">Id for the project to backtest</param>
/// <param name="compileId">Compile id for the project</param>
/// <param name="backtestName">Name for the new backtest</param>
/// <returns><see cref="Backtest"/>t</returns>
public Backtest CreateBacktest(int projectId, string compileId, string backtestName)
{
var request = new RestRequest("backtests/create", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
compileId,
backtestName
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out BacktestResponseWrapper result);
// Use API Response values for Backtest Values
result.Backtest.Success = result.Success;
result.Backtest.Errors = result.Errors;
// Return only the backtest object
return result.Backtest;
}
/// <summary>
/// Read out a backtest in the project id specified.
/// </summary>
/// <param name="projectId">Project id to read</param>
/// <param name="backtestId">Specific backtest id to read</param>
/// <param name="getCharts">True will return backtest charts</param>
/// <returns><see cref="Backtest"/></returns>
public Backtest ReadBacktest(int projectId, string backtestId, bool getCharts = true)
{
var request = new RestRequest("backtests/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
backtestId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out BacktestResponseWrapper result);
if (!result.Success)
{
// place an empty place holder so we can return any errors back to the user and not just null
result.Backtest = new Backtest { BacktestId = backtestId };
}
// Go fetch the charts if the backtest is completed and success
else if (getCharts && result.Backtest.Completed)
{
// For storing our collected charts
var updatedCharts = new Dictionary<string, Chart>();
// Create backtest requests for each chart that is empty
foreach (var chart in result.Backtest.Charts)
{
if (!chart.Value.Series.IsNullOrEmpty())
{
continue;
}
var chartRequest = new RestRequest("backtests/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
chartRequest.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
backtestId,
chart = chart.Key
}), ParameterType.RequestBody);
// Add this chart to our updated collection
if (ApiConnection.TryRequest(chartRequest, out BacktestResponseWrapper chartResponse) && chartResponse.Success)
{
updatedCharts.Add(chart.Key, chartResponse.Backtest.Charts[chart.Key]);
}
}
// Update our result
foreach(var updatedChart in updatedCharts)
{
result.Backtest.Charts[updatedChart.Key] = updatedChart.Value;
}
}
// Use API Response values for Backtest Values
result.Backtest.Success = result.Success;
result.Backtest.Errors = result.Errors;
// Return only the backtest object
return result.Backtest;
}
/// <summary>
/// Returns the orders of the specified backtest and project id.
/// </summary>
/// <param name="projectId">Id of the project from which to read the orders</param>
/// <param name="backtestId">Id of the backtest from which to read the orders</param>
/// <param name="start">Starting index of the orders to be fetched. Required if end > 100</param>
/// <param name="end">Last index of the orders to be fetched. Note that end - start must be less than 100</param>
/// <remarks>Will throw an <see cref="WebException"/> if there are any API errors</remarks>
/// <returns>The list of <see cref="Order"/></returns>
public List<ApiOrderResponse> ReadBacktestOrders(int projectId, string backtestId, int start = 0, int end = 100)
{
var request = new RestRequest("backtests/orders/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
start,
end,
projectId,
backtestId
}), ParameterType.RequestBody);
return MakeRequestOrThrow<OrdersResponseWrapper>(request, nameof(ReadBacktestOrders)).Orders;
}
/// <summary>
/// Returns a requested chart object from a backtest
/// </summary>
/// <param name="projectId">Project ID of the request</param>
/// <param name="name">The requested chart name</param>
/// <param name="start">The Utc start seconds timestamp of the request</param>
/// <param name="end">The Utc end seconds timestamp of the request</param>
/// <param name="count">The number of data points to request</param>
/// <param name="backtestId">Associated Backtest ID for this chart request</param>
/// <returns>The chart</returns>
public ReadChartResponse ReadBacktestChart(int projectId, string name, int start, int end, uint count, string backtestId)
{
var request = new RestRequest("backtests/chart/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
name,
start,
end,
count,
backtestId,
}), ParameterType.RequestBody);
ReadChartResponse result;
ApiConnection.TryRequest(request, out result);
var finish = DateTime.UtcNow.AddMinutes(1);
while (DateTime.UtcNow < finish && result.Chart == null)
{
Thread.Sleep(5000);
ApiConnection.TryRequest(request, out result);
}
return result;
}
/// <summary>
/// Update a backtest name
/// </summary>
/// <param name="projectId">Project for the backtest we want to update</param>
/// <param name="backtestId">Backtest id we want to update</param>
/// <param name="name">Name we'd like to assign to the backtest</param>
/// <param name="note">Note attached to the backtest</param>
/// <returns><see cref="RestResponse"/></returns>
public RestResponse UpdateBacktest(int projectId, string backtestId, string name = "", string note = "")
{
var request = new RestRequest("backtests/update", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
backtestId,
name,
note
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// List all the backtest summaries for a project
/// </summary>
/// <param name="projectId">Project id we'd like to get a list of backtest for</param>
/// <param name="includeStatistics">True for include statistics in the response, false otherwise</param>
/// <returns><see cref="BacktestList"/></returns>
public BacktestSummaryList ListBacktests(int projectId, bool includeStatistics = true)
{
var request = new RestRequest("backtests/list", Method.POST)
{
RequestFormat = DataFormat.Json
};
var obj = new Dictionary<string, object>()
{
{ "projectId", projectId },
{ "includeStatistics", includeStatistics }
};
request.AddParameter("application/json", JsonConvert.SerializeObject(obj), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out BacktestSummaryList result);
return result;
}
/// <summary>
/// Delete a backtest from the specified project and backtestId.
/// </summary>
/// <param name="projectId">Project for the backtest we want to delete</param>
/// <param name="backtestId">Backtest id we want to delete</param>
/// <returns><see cref="RestResponse"/></returns>
public RestResponse DeleteBacktest(int projectId, string backtestId)
{
var request = new RestRequest("backtests/delete", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
backtestId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Updates the tags collection for a backtest
/// </summary>
/// <param name="projectId">Project for the backtest we want to update</param>
/// <param name="backtestId">Backtest id we want to update</param>
/// <param name="tags">The new backtest tags</param>
/// <returns><see cref="RestResponse"/></returns>
public RestResponse UpdateBacktestTags(int projectId, string backtestId, IReadOnlyCollection<string> tags)
{
var request = new RestRequest("backtests/tags/update", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
backtestId,
tags
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out RestResponse result);
return result;
}
/// <summary>
/// Read out the insights of a backtest
/// </summary>
/// <param name="projectId">Id of the project from which to read the backtest</param>
/// <param name="backtestId">Backtest id from which we want to get the insights</param>
/// <param name="start">Starting index of the insights to be fetched</param>
/// <param name="end">Last index of the insights to be fetched. Note that end - start must be less than 100</param>
/// <returns><see cref="InsightResponse"/></returns>
/// <exception cref="ArgumentException"></exception>
public InsightResponse ReadBacktestInsights(int projectId, string backtestId, int start = 0, int end = 0)
{
var request = new RestRequest("backtests/insights/read", Method.POST)
{
RequestFormat = DataFormat.Json,
};
var diff = end - start;
if (diff > 100)
{
throw new ArgumentException($"The difference between the start and end index of the insights must be smaller than 100, but it was {diff}.");
}
else if (end == 0)
{
end = start + 100;
}
JObject obj = new()
{
{ "projectId", projectId },
{ "backtestId", backtestId },
{ "start", start },
{ "end", end },
};
request.AddParameter("application/json", JsonConvert.SerializeObject(obj), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out InsightResponse result);
return result;
}
/// <summary>
/// Create a live algorithm.
/// </summary>
/// <param name="projectId">Id of the project on QuantConnect</param>
/// <param name="compileId">Id of the compilation on QuantConnect</param>
/// <param name="nodeId">Id of the node that will run the algorithm</param>
/// <param name="brokerageSettings">Dictionary with brokerage specific settings. Each brokerage requires certain specific credentials
/// in order to process the given orders. Each key in this dictionary represents a required field/credential
/// to provide to the brokerage API and its value represents the value of that field. For example: "brokerageSettings: {
/// "id": "Binance", "binance-api-secret": "123ABC", "binance-api-key": "ABC123"}. It is worth saying,
/// that this dictionary must always contain an entry whose key is "id" and its value is the name of the brokerage
/// (see <see cref="Brokerages.BrokerageName"/>)</param>
/// <param name="versionId">The version of the Lean used to run the algorithm.
/// -1 is master, however, sometimes this can create problems with live deployments.
/// If you experience problems using, try specifying the version of Lean you would like to use.</param>
/// <param name="dataProviders">Dictionary with data providers credentials. Each data provider requires certain credentials
/// in order to retrieve data from their API. Each key in this dictionary describes a data provider name
/// and its corresponding value is another dictionary with the required key-value pairs of credential
/// names and values. For example: "dataProviders: { "InteractiveBrokersBrokerage" : { "id": 12345, "environment" : "paper",
/// "username": "testUsername", "password": "testPassword"}}"</param>
/// <returns>Information regarding the new algorithm <see cref="CreateLiveAlgorithmResponse"/></returns>
public CreateLiveAlgorithmResponse CreateLiveAlgorithm(int projectId,
string compileId,
string nodeId,
Dictionary<string, object> brokerageSettings,
string versionId = "-1",
Dictionary<string, object> dataProviders = null)
{
var request = new RestRequest("live/create", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(
new LiveAlgorithmApiSettingsWrapper
(projectId,
compileId,
nodeId,
brokerageSettings,
versionId,
dataProviders
)
), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out CreateLiveAlgorithmResponse result);
return result;
}
/// <summary>
/// Create a live algorithm.
/// </summary>
/// <param name="projectId">Id of the project on QuantConnect</param>
/// <param name="compileId">Id of the compilation on QuantConnect</param>
/// <param name="nodeId">Id of the node that will run the algorithm</param>
/// <param name="brokerageSettings">Python Dictionary with brokerage specific settings. Each brokerage requires certain specific credentials
/// in order to process the given orders. Each key in this dictionary represents a required field/credential
/// to provide to the brokerage API and its value represents the value of that field. For example: "brokerageSettings: {
/// "id": "Binance", "binance-api-secret": "123ABC", "binance-api-key": "ABC123"}. It is worth saying,
/// that this dictionary must always contain an entry whose key is "id" and its value is the name of the brokerage
/// (see <see cref="Brokerages.BrokerageName"/>)</param>
/// <param name="versionId">The version of the Lean used to run the algorithm.
/// -1 is master, however, sometimes this can create problems with live deployments.
/// If you experience problems using, try specifying the version of Lean you would like to use.</param>
/// <param name="dataProviders">Python Dictionary with data providers credentials. Each data provider requires certain credentials
/// in order to retrieve data from their API. Each key in this dictionary describes a data provider name
/// and its corresponding value is another dictionary with the required key-value pairs of credential
/// names and values. For example: "dataProviders: { "InteractiveBrokersBrokerage" : { "id": 12345, "environment" : "paper",
/// "username": "testUsername", "password": "testPassword"}}"</param>
/// <returns>Information regarding the new algorithm <see cref="CreateLiveAlgorithmResponse"/></returns>
public CreateLiveAlgorithmResponse CreateLiveAlgorithm(int projectId, string compileId, string nodeId, PyObject brokerageSettings, string versionId = "-1", PyObject dataProviders = null)
{
return CreateLiveAlgorithm(projectId, compileId, nodeId, ConvertToDictionary(brokerageSettings), versionId, dataProviders != null ? ConvertToDictionary(dataProviders) : null);
}
/// <summary>
/// Converts a given Python dictionary into a C# <see cref="Dictionary{string, object}"/>
/// </summary>
/// <param name="brokerageSettings">Python dictionary to be converted</param>
private static Dictionary<string, object> ConvertToDictionary(PyObject brokerageSettings)
{
using (Py.GIL())
{
var stringBrokerageSettings = brokerageSettings.ToString();
return JsonConvert.DeserializeObject<Dictionary<string, object>>(stringBrokerageSettings);
}
}
/// <summary>
/// Get a list of live running algorithms for user
/// </summary>
/// <param name="status">Filter the statuses of the algorithms returned from the api</param>
/// <param name="startTime">Earliest launched time of the algorithms returned by the Api</param>
/// <param name="endTime">Latest launched time of the algorithms returned by the Api</param>
/// <returns><see cref="LiveList"/></returns>
public LiveList ListLiveAlgorithms(AlgorithmStatus? status = null,
DateTime? startTime = null,
DateTime? endTime = null)
{
// Only the following statuses are supported by the Api
if (status.HasValue &&
status != AlgorithmStatus.Running &&
status != AlgorithmStatus.RuntimeError &&
status != AlgorithmStatus.Stopped &&
status != AlgorithmStatus.Liquidated)
{
throw new ArgumentException(
"The Api only supports Algorithm Statuses of Running, Stopped, RuntimeError and Liquidated");
}
var request = new RestRequest("live/list", Method.POST)
{
RequestFormat = DataFormat.Json
};
var epochStartTime = startTime == null ? 0 : Time.DateTimeToUnixTimeStamp(startTime.Value);
var epochEndTime = endTime == null ? Time.DateTimeToUnixTimeStamp(DateTime.UtcNow) : Time.DateTimeToUnixTimeStamp(endTime.Value);
JObject obj = new JObject
{
{ "start", epochStartTime },
{ "end", epochEndTime }
};
if (status.HasValue)
{
obj.Add("status", status.ToString());
}
request.AddParameter("application/json", JsonConvert.SerializeObject(obj), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out LiveList result);
return result;
}
/// <summary>
/// Read out a live algorithm in the project id specified.
/// </summary>
/// <param name="projectId">Project id to read</param>
/// <param name="deployId">Specific instance id to read</param>
/// <returns><see cref="LiveAlgorithmResults"/></returns>
public LiveAlgorithmResults ReadLiveAlgorithm(int projectId, string deployId)
{
var request = new RestRequest("live/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId,
deployId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out LiveAlgorithmResults result);
return result;
}
/// <summary>
/// Read out the portfolio state of a live algorithm
/// </summary>
/// <param name="projectId">Id of the project from which to read the live algorithm</param>
/// <returns><see cref="PortfolioResponse"/></returns>
public PortfolioResponse ReadLivePortfolio(int projectId)
{
var request = new RestRequest("live/portfolio/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
projectId
}), ParameterType.RequestBody);
ApiConnection.TryRequest(request, out PortfolioResponse result);
return result;
}
/// <summary>
/// Returns the orders of the specified project id live algorithm.
/// </summary>
/// <param name="projectId">Id of the project from which to read the live orders</param>
/// <param name="start">Starting index of the orders to be fetched. Required if end > 100</param>
/// <param name="end">Last index of the orders to be fetched. Note that end - start must be less than 100</param>
/// <remarks>Will throw an <see cref="WebException"/> if there are any API errors</remarks>
/// <returns>The list of <see cref="Order"/></returns>
public List<ApiOrderResponse> ReadLiveOrders(int projectId, int start = 0, int end = 100)
{
var request = new RestRequest("live/orders/read", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddParameter("application/json", JsonConvert.SerializeObject(new
{
start,
end,
projectId
}), ParameterType.RequestBody);
return MakeRequestOrThrow<OrdersResponseWrapper>(request, nameof(ReadLiveOrders)).Orders;
}
/// <summary>
/// Liquidate a live algorithm from the specified project and deployId.