-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathKite.cs
1375 lines (1155 loc) · 59.3 KB
/
Kite.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Reflection;
using System.Net.Http;
using System.Text;
using System.Net.Mime;
using System.Net;
namespace KiteConnect
{
/// <summary>
/// The API client class. In production, you may initialize a single instance of this class per `APIKey`.
/// </summary>
public class Kite
{
// Default root API endpoint. It's possible to
// override this by passing the `Root` parameter during initialisation.
private string _root = "https://api.kite.trade";
private string _login = "https://kite.zerodha.com/connect/login";
private string _apiKey;
private string _accessToken;
private bool _enableLogging;
private int _timeout;
private Action _sessionHook;
private HttpClient httpClient;
private readonly Dictionary<string, string> _routes = new Dictionary<string, string>
{
["parameters"] = "/parameters",
["api.token"] = "/session/token",
["api.refresh"] = "/session/refresh_token",
["instrument.margins"] = "/margins/{segment}",
["order.margins"] = "/margins/orders",
["basket.margins"] = "/margins/basket",
["order.contractnote"] = "/charges/orders",
["user.profile"] = "/user/profile",
["user.margins"] = "/user/margins",
["user.segment_margins"] = "/user/margins/{segment}",
["orders"] = "/orders",
["trades"] = "/trades",
["orders.history"] = "/orders/{order_id}",
["orders.place"] = "/orders/{variety}",
["orders.modify"] = "/orders/{variety}/{order_id}",
["orders.cancel"] = "/orders/{variety}/{order_id}",
["orders.trades"] = "/orders/{order_id}/trades",
["gtt"] = "/gtt/triggers",
["gtt.place"] = "/gtt/triggers",
["gtt.info"] = "/gtt/triggers/{id}",
["gtt.modify"] = "/gtt/triggers/{id}",
["gtt.delete"] = "/gtt/triggers/{id}",
["portfolio.positions"] = "/portfolio/positions",
["portfolio.holdings"] = "/portfolio/holdings",
["portfolio.positions.modify"] = "/portfolio/positions",
["portfolio.auction.instruments"] = "/portfolio/holdings/auctions",
["market.instruments.all"] = "/instruments",
["market.instruments"] = "/instruments/{exchange}",
["market.quote"] = "/quote",
["market.ohlc"] = "/quote/ohlc",
["market.ltp"] = "/quote/ltp",
["market.historical"] = "/instruments/historical/{instrument_token}/{interval}",
["market.trigger_range"] = "/instruments/trigger_range/{transaction_type}",
["mutualfunds.orders"] = "/mf/orders",
["mutualfunds.order"] = "/mf/orders/{order_id}",
["mutualfunds.orders.place"] = "/mf/orders",
["mutualfunds.cancel_order"] = "/mf/orders/{order_id}",
["mutualfunds.sips"] = "/mf/sips",
["mutualfunds.sips.place"] = "/mf/sips",
["mutualfunds.cancel_sips"] = "/mf/sips/{sip_id}",
["mutualfunds.sips.modify"] = "/mf/sips/{sip_id}",
["mutualfunds.sip"] = "/mf/sips/{sip_id}",
["mutualfunds.instruments"] = "/mf/instruments",
["mutualfunds.holdings"] = "/mf/holdings"
};
/// <summary>
/// Initialize a new Kite Connect client instance.
/// </summary>
/// <param name="APIKey">API Key issued to you</param>
/// <param name="AccessToken">The token obtained after the login flow in exchange for the `RequestToken` .
/// Pre-login, this will default to None,but once you have obtained it, you should persist it in a database or session to pass
/// to the Kite Connect class initialisation for subsequent requests.</param>
/// <param name="Root">API end point root. Unless you explicitly want to send API requests to a non-default endpoint, this can be ignored.</param>
/// <param name="Debug">If set to True, will serialise and print requests and responses to stdout.</param>
/// <param name="Timeout">Time in milliseconds for which the API client will wait for a request to complete before it fails</param>
/// <param name="Proxy">To set proxy for http request. Should be an object of WebProxy.</param>
/// <param name="Pool">Number of connections to server. Client will reuse the connections if they are alive.</param>
public Kite(string APIKey, string AccessToken = null, string Root = null, bool Debug = false, int Timeout = 7000, IWebProxy Proxy = null, int Pool = 2)
{
_accessToken = AccessToken;
_apiKey = APIKey;
if (!String.IsNullOrEmpty(Root)) this._root = Root;
_enableLogging = Debug;
_timeout = Timeout;
HttpClientHandler httpClientHandler = new HttpClientHandler()
{
Proxy = Proxy,
};
httpClient = new(httpClientHandler)
{
BaseAddress = new Uri(_root),
Timeout = TimeSpan.FromMilliseconds(Timeout),
};
ServicePointManager.DefaultConnectionLimit = Pool;
}
/// <summary>
/// Enabling logging prints HTTP request and response summaries to console
/// </summary>
/// <param name="enableLogging">Set to true to enable logging</param>
public void EnableLogging(bool enableLogging)
{
_enableLogging = enableLogging;
}
/// <summary>
/// Set a callback hook for session (`TokenException` -- timeout, expiry etc.) errors.
/// An `AccessToken` (login session) can become invalid for a number of
/// reasons, but it doesn't make sense for the client to
/// try and catch it during every API call.
/// A callback method that handles session errors
/// can be set here and when the client encounters
/// a token error at any point, it'll be called.
/// This callback, for instance, can log the user out of the UI,
/// clear session cookies, or initiate a fresh login.
/// </summary>
/// <param name="Method">Action to be invoked when session becomes invalid.</param>
public void SetSessionExpiryHook(Action Method)
{
_sessionHook = Method;
}
/// <summary>
/// Set the `AccessToken` received after a successful authentication.
/// </summary>
/// <param name="AccessToken">Access token for the session.</param>
public void SetAccessToken(string AccessToken)
{
this._accessToken = AccessToken;
}
/// <summary>
/// Get the remote login url to which a user should be redirected to initiate the login flow.
/// </summary>
/// <returns>Login url to authenticate the user.</returns>
public string GetLoginURL()
{
return String.Format("{0}?api_key={1}&v=3", _login, _apiKey);
}
/// <summary>
/// Do the token exchange with the `RequestToken` obtained after the login flow,
/// and retrieve the `AccessToken` required for all subsequent requests.The
/// response contains not just the `AccessToken`, but metadata for
/// the user who has authenticated.
/// </summary>
/// <param name="RequestToken">Token obtained from the GET paramers after a successful login redirect.</param>
/// <param name="AppSecret">API secret issued with the API key.</param>
/// <returns>User structure with tokens and profile data</returns>
public User GenerateSession(string RequestToken, string AppSecret)
{
string checksum = Utils.SHA256Hash(_apiKey + RequestToken + AppSecret);
var param = new Dictionary<string, dynamic>
{
{"api_key", _apiKey},
{"request_token", RequestToken},
{"checksum", checksum}
};
var userData = Post("api.token", param);
return new User(userData);
}
/// <summary>
/// Kill the session by invalidating the access token
/// </summary>
/// <param name="AccessToken">Access token to invalidate. Default is the active access token.</param>
/// <returns>Json response in the form of nested string dictionary.</returns>
public Dictionary<string, dynamic> InvalidateAccessToken(string AccessToken = null)
{
var param = new Dictionary<string, dynamic>();
Utils.AddIfNotNull(param, "api_key", _apiKey);
Utils.AddIfNotNull(param, "access_token", AccessToken);
return Delete("api.token", param);
}
/// <summary>
/// Invalidates RefreshToken
/// </summary>
/// <param name="RefreshToken">RefreshToken to invalidate</param>
/// <returns>Json response in the form of nested string dictionary.</returns>
public Dictionary<string, dynamic> InvalidateRefreshToken(string RefreshToken)
{
var param = new Dictionary<string, dynamic>();
Utils.AddIfNotNull(param, "api_key", _apiKey);
Utils.AddIfNotNull(param, "refresh_token", RefreshToken);
return Delete("api.token", param);
}
/// <summary>
/// Renew AccessToken using RefreshToken
/// </summary>
/// <param name="RefreshToken">RefreshToken to renew the AccessToken.</param>
/// <param name="AppSecret">API secret issued with the API key.</param>
/// <returns>TokenRenewResponse that contains new AccessToken and RefreshToken.</returns>
public TokenSet RenewAccessToken(string RefreshToken, string AppSecret)
{
var param = new Dictionary<string, dynamic>();
string checksum = Utils.SHA256Hash(_apiKey + RefreshToken + AppSecret);
Utils.AddIfNotNull(param, "api_key", _apiKey);
Utils.AddIfNotNull(param, "refresh_token", RefreshToken);
Utils.AddIfNotNull(param, "checksum", checksum);
return new TokenSet(Post("api.refresh", param));
}
/// <summary>
/// Gets currently logged in user details
/// </summary>
/// <returns>User profile</returns>
public Profile GetProfile()
{
var profileData = Get("user.profile");
return new Profile(profileData);
}
/// <summary>
/// A virtual contract provides detailed charges order-wise for brokerage, STT, stamp duty, exchange transaction charges, SEBI turnover charge, and GST.
/// </summary>
/// <param name="ContractNoteParams">List of all order params to get contract notes for</param>
/// <returns>List of contract notes for the params</returns>
public List<ContractNote> GetVirtualContractNote(List<ContractNoteParams> ContractNoteParams)
{
var paramList = new List<Dictionary<string, dynamic>>();
foreach (var item in ContractNoteParams)
{
var param = new Dictionary<string, dynamic>();
param["order_id"] = item.OrderID;
param["exchange"] = item.Exchange;
param["tradingsymbol"] = item.TradingSymbol;
param["transaction_type"] = item.TransactionType;
param["quantity"] = item.Quantity;
param["average_price"] = item.AveragePrice;
param["product"] = item.Product;
param["order_type"] = item.OrderType;
param["variety"] = item.Variety;
paramList.Add(param);
}
var contractNoteData = Post("order.contractnote", paramList, json: true);
List<ContractNote> contractNotes = new List<ContractNote>();
foreach (Dictionary<string, dynamic> item in contractNoteData["data"])
contractNotes.Add(new ContractNote(item));
return contractNotes;
}
/// <summary>
/// Margin data for a specific order
/// </summary>
/// <param name="OrderMarginParams">List of all order params to get margins for</param>
/// <param name="Mode">Mode of the returned response content. Eg: Constants.MARGIN_MODE_COMPACT</param>
/// <returns>List of margins of order</returns>
public List<OrderMargin> GetOrderMargins(List<OrderMarginParams> OrderMarginParams, string Mode = null)
{
var paramList = new List<Dictionary<string, dynamic>>();
foreach (var item in OrderMarginParams)
{
var param = new Dictionary<string, dynamic>();
param["exchange"] = item.Exchange;
param["tradingsymbol"] = item.TradingSymbol;
param["transaction_type"] = item.TransactionType;
param["quantity"] = item.Quantity;
param["price"] = item.Price;
param["product"] = item.Product;
param["order_type"] = item.OrderType;
param["trigger_price"] = item.TriggerPrice;
param["variety"] = item.Variety;
paramList.Add(param);
}
var queryParams = new Dictionary<string, dynamic>();
if (Mode != null)
{
queryParams["mode"] = Mode;
}
var orderMarginsData = Post("order.margins", paramList, QueryParams: queryParams, json: true);
List<OrderMargin> orderMargins = new List<OrderMargin>();
foreach (Dictionary<string, dynamic> item in orderMarginsData["data"])
orderMargins.Add(new OrderMargin(item));
return orderMargins;
}
/// <summary>
/// Margin data for a basket orders
/// </summary>
/// <param name="OrderMarginParams">List of all order params to get margins for</param>
/// <param name="ConsiderPositions">Consider users positions while calculating margins</param>
/// <param name="Mode">Mode of the returned response content. Eg: Constants.MARGIN_MODE_COMPACT</param>
/// <returns>List of margins of order</returns>
public BasketMargin GetBasketMargins(List<OrderMarginParams> OrderMarginParams, bool ConsiderPositions = true, string Mode = null)
{
var paramList = new List<Dictionary<string, dynamic>>();
foreach (var item in OrderMarginParams)
{
var param = new Dictionary<string, dynamic>();
param["exchange"] = item.Exchange;
param["tradingsymbol"] = item.TradingSymbol;
param["transaction_type"] = item.TransactionType;
param["quantity"] = item.Quantity;
param["price"] = item.Price;
param["product"] = item.Product;
param["order_type"] = item.OrderType;
param["trigger_price"] = item.TriggerPrice;
param["variety"] = item.Variety;
paramList.Add(param);
}
var queryParams = new Dictionary<string, dynamic>();
queryParams["consider_positions"] = ConsiderPositions ? "true" : "false";
if (Mode != null)
{
queryParams["mode"] = Mode;
}
var basketMarginsData = Post("basket.margins", paramList, QueryParams: queryParams, json: true);
return new BasketMargin(basketMarginsData["data"]);
}
/// <summary>
/// Get account balance and cash margin details for all segments.
/// </summary>
/// <returns>User margin response with both equity and commodity margins.</returns>
public UserMarginsResponse GetMargins()
{
var marginsData = Get("user.margins");
return new UserMarginsResponse(marginsData["data"]);
}
/// <summary>
/// Get account balance and cash margin details for a particular segment.
/// </summary>
/// <param name="Segment">Trading segment (eg: equity or commodity)</param>
/// <returns>Margins for specified segment.</returns>
public UserMargin GetMargins(string Segment)
{
var userMarginData = Get("user.segment_margins", new Dictionary<string, dynamic> { { "segment", Segment } });
return new UserMargin(userMarginData["data"]);
}
/// <summary>
/// Place an order
/// </summary>
/// <param name="Exchange">Name of the exchange</param>
/// <param name="TradingSymbol">Tradingsymbol of the instrument</param>
/// <param name="TransactionType">BUY or SELL</param>
/// <param name="Quantity">Quantity to transact</param>
/// <param name="Price">For LIMIT orders</param>
/// <param name="Product">Margin product applied to the order (margin is blocked based on this)</param>
/// <param name="OrderType">Order type (MARKET, LIMIT etc.)</param>
/// <param name="Validity">Order validity (DAY, IOC and TTL)</param>
/// <param name="DisclosedQuantity">Quantity to disclose publicly (for equity trades)</param>
/// <param name="TriggerPrice">For SL, SL-M etc.</param>
/// <param name="SquareOffValue">Price difference at which the order should be squared off and profit booked (eg: Order price is 100. Profit target is 102. So squareoff = 2)</param>
/// <param name="StoplossValue">Stoploss difference at which the order should be squared off (eg: Order price is 100. Stoploss target is 98. So stoploss = 2)</param>
/// <param name="TrailingStoploss">Incremental value by which stoploss price changes when market moves in your favor by the same incremental value from the entry price (optional)</param>
/// <param name="Variety">You can place orders of varieties; regular orders, after market orders, cover orders, iceberg orders etc. </param>
/// <param name="Tag">An optional tag to apply to an order to identify it (alphanumeric, max 20 chars)</param>
/// <param name="ValidityTTL">Order life span in minutes for TTL validity orders</param>
/// <param name="IcebergLegs">Total number of legs for iceberg order type (number of legs per Iceberg should be between 2 and 10)</param>
/// <param name="IcebergQuantity">Split quantity for each iceberg leg order (Quantity/IcebergLegs)</param>
/// <returns>Json response in the form of nested string dictionary.</returns>
public Dictionary<string, dynamic> PlaceOrder(
string Exchange,
string TradingSymbol,
string TransactionType,
int Quantity,
decimal? Price = null,
string Product = null,
string OrderType = null,
string Validity = null,
int? DisclosedQuantity = null,
decimal? TriggerPrice = null,
decimal? SquareOffValue = null,
decimal? StoplossValue = null,
decimal? TrailingStoploss = null,
string Variety = Constants.VARIETY_REGULAR,
string Tag = "",
int? ValidityTTL = null,
int? IcebergLegs = null,
int? IcebergQuantity = null,
string AuctionNumber = null
)
{
var param = new Dictionary<string, dynamic>();
Utils.AddIfNotNull(param, "exchange", Exchange);
Utils.AddIfNotNull(param, "tradingsymbol", TradingSymbol);
Utils.AddIfNotNull(param, "transaction_type", TransactionType);
Utils.AddIfNotNull(param, "quantity", Quantity.ToString());
Utils.AddIfNotNull(param, "price", Price.ToString());
Utils.AddIfNotNull(param, "product", Product);
Utils.AddIfNotNull(param, "order_type", OrderType);
Utils.AddIfNotNull(param, "validity", Validity);
Utils.AddIfNotNull(param, "disclosed_quantity", DisclosedQuantity.ToString());
Utils.AddIfNotNull(param, "trigger_price", TriggerPrice.ToString());
Utils.AddIfNotNull(param, "squareoff", SquareOffValue.ToString());
Utils.AddIfNotNull(param, "stoploss", StoplossValue.ToString());
Utils.AddIfNotNull(param, "trailing_stoploss", TrailingStoploss.ToString());
Utils.AddIfNotNull(param, "variety", Variety);
Utils.AddIfNotNull(param, "tag", Tag);
Utils.AddIfNotNull(param, "validity_ttl", ValidityTTL.ToString());
Utils.AddIfNotNull(param, "iceberg_legs", IcebergLegs.ToString());
Utils.AddIfNotNull(param, "iceberg_quantity", IcebergQuantity.ToString());
Utils.AddIfNotNull(param, "auction_number", AuctionNumber);
return Post("orders.place", param);
}
/// <summary>
/// Modify an open order.
/// </summary>
/// <param name="OrderId">Id of the order to be modified</param>
/// <param name="ParentOrderId">Id of the parent order (obtained from the /orders call) as BO is a multi-legged order</param>
/// <param name="Exchange">Name of the exchange</param>
/// <param name="TradingSymbol">Tradingsymbol of the instrument</param>
/// <param name="TransactionType">BUY or SELL</param>
/// <param name="Quantity">Quantity to transact</param>
/// <param name="Price">For LIMIT orders</param>
/// <param name="Product">Margin product applied to the order (margin is blocked based on this)</param>
/// <param name="OrderType">Order type (MARKET, LIMIT etc.)</param>
/// <param name="Validity">Order validity</param>
/// <param name="DisclosedQuantity">Quantity to disclose publicly (for equity trades)</param>
/// <param name="TriggerPrice">For SL, SL-M etc.</param>
/// <param name="Variety">You can place orders of varieties; regular orders, after market orders, cover orders etc. </param>
/// <returns>Json response in the form of nested string dictionary.</returns>
public Dictionary<string, dynamic> ModifyOrder(
string OrderId,
string ParentOrderId = null,
string Exchange = null,
string TradingSymbol = null,
string TransactionType = null,
string Quantity = null,
decimal? Price = null,
string Product = null,
string OrderType = null,
string Validity = Constants.VALIDITY_DAY,
int? DisclosedQuantity = null,
decimal? TriggerPrice = null,
string Variety = Constants.VARIETY_REGULAR)
{
var param = new Dictionary<string, dynamic>();
string VarietyString = Variety;
string ProductString = Product;
if ((ProductString == "bo" || ProductString == "co") && VarietyString != ProductString)
throw new Exception(String.Format("Invalid variety. It should be: {0}", ProductString));
Utils.AddIfNotNull(param, "order_id", OrderId);
Utils.AddIfNotNull(param, "parent_order_id", ParentOrderId);
Utils.AddIfNotNull(param, "trigger_price", TriggerPrice.ToString());
Utils.AddIfNotNull(param, "variety", Variety);
if (VarietyString == "bo" && ProductString == "bo")
{
Utils.AddIfNotNull(param, "quantity", Quantity);
Utils.AddIfNotNull(param, "price", Price.ToString());
Utils.AddIfNotNull(param, "disclosed_quantity", DisclosedQuantity.ToString());
}
else if (VarietyString != "co" && ProductString != "co")
{
Utils.AddIfNotNull(param, "exchange", Exchange);
Utils.AddIfNotNull(param, "tradingsymbol", TradingSymbol);
Utils.AddIfNotNull(param, "transaction_type", TransactionType);
Utils.AddIfNotNull(param, "quantity", Quantity);
Utils.AddIfNotNull(param, "price", Price.ToString());
Utils.AddIfNotNull(param, "product", Product);
Utils.AddIfNotNull(param, "order_type", OrderType);
Utils.AddIfNotNull(param, "validity", Validity);
Utils.AddIfNotNull(param, "disclosed_quantity", DisclosedQuantity.ToString());
}
return Put("orders.modify", param);
}
/// <summary>
/// Cancel an order
/// </summary>
/// <param name="OrderId">Id of the order to be cancelled</param>
/// <param name="Variety">You can place orders of varieties; regular orders, after market orders, cover orders etc. </param>
/// <param name="ParentOrderId">Id of the parent order (obtained from the /orders call) as BO is a multi-legged order</param>
/// <returns>Json response in the form of nested string dictionary.</returns>
public Dictionary<string, dynamic> CancelOrder(string OrderId, string Variety = Constants.VARIETY_REGULAR, string ParentOrderId = null)
{
var param = new Dictionary<string, dynamic>();
Utils.AddIfNotNull(param, "order_id", OrderId);
Utils.AddIfNotNull(param, "parent_order_id", ParentOrderId);
Utils.AddIfNotNull(param, "variety", Variety);
return Delete("orders.cancel", param);
}
/// <summary>
/// Gets the collection of orders from the orderbook.
/// </summary>
/// <returns>List of orders.</returns>
public List<Order> GetOrders()
{
var ordersData = Get("orders");
List<Order> orders = new List<Order>();
foreach (Dictionary<string, dynamic> item in ordersData["data"])
orders.Add(new Order(item));
return orders;
}
/// <summary>
/// Gets information about given OrderId.
/// </summary>
/// <param name="OrderId">Unique order id</param>
/// <returns>List of order objects.</returns>
public List<Order> GetOrderHistory(string OrderId)
{
var param = new Dictionary<string, dynamic>();
param.Add("order_id", OrderId);
var orderData = Get("orders.history", param);
List<Order> orderhistory = new List<Order>();
foreach (Dictionary<string, dynamic> item in orderData["data"])
orderhistory.Add(new Order(item));
return orderhistory;
}
/// <summary>
/// Retreive the list of trades executed (all or ones under a particular order).
/// An order can be executed in tranches based on market conditions.
/// These trades are individually recorded under an order.
/// </summary>
/// <param name="OrderId">is the ID of the order (optional) whose trades are to be retrieved. If no `OrderId` is specified, all trades for the day are returned.</param>
/// <returns>List of trades of given order.</returns>
public List<Trade> GetOrderTrades(string OrderId = null)
{
Dictionary<string, dynamic> tradesdata;
if (!String.IsNullOrEmpty(OrderId))
{
var param = new Dictionary<string, dynamic>();
param.Add("order_id", OrderId);
tradesdata = Get("orders.trades", param);
}
else
tradesdata = Get("trades");
List<Trade> trades = new List<Trade>();
foreach (Dictionary<string, dynamic> item in tradesdata["data"])
trades.Add(new Trade(item));
return trades;
}
/// <summary>
/// Retrieve the list of positions.
/// </summary>
/// <returns>Day and net positions.</returns>
public PositionResponse GetPositions()
{
var positionsdata = Get("portfolio.positions");
return new PositionResponse(positionsdata["data"]);
}
/// <summary>
/// Retrieve the list of equity holdings.
/// </summary>
/// <returns>List of holdings.</returns>
public List<Holding> GetHoldings()
{
var holdingsData = Get("portfolio.holdings");
List<Holding> holdings = new List<Holding>();
foreach (Dictionary<string, dynamic> item in holdingsData["data"])
holdings.Add(new Holding(item));
return holdings;
}
/// <summary>
/// Retrieve the list of auction instruments.
/// </summary>
/// <returns>List of auction instruments.</returns>
public List<AuctionInstrument> GetAuctionInstruments()
{
var instrumentsData = Get("portfolio.auction.instruments");
List<AuctionInstrument> instruments = new List<AuctionInstrument>();
foreach (Dictionary<string, dynamic> item in instrumentsData["data"])
instruments.Add(new AuctionInstrument(item));
return instruments;
}
/// <summary>
/// Modify an open position's product type.
/// </summary>
/// <param name="Exchange">Name of the exchange</param>
/// <param name="TradingSymbol">Tradingsymbol of the instrument</param>
/// <param name="TransactionType">BUY or SELL</param>
/// <param name="PositionType">overnight or day</param>
/// <param name="Quantity">Quantity to convert</param>
/// <param name="OldProduct">Existing margin product of the position</param>
/// <param name="NewProduct">Margin product to convert to</param>
/// <returns>Json response in the form of nested string dictionary.</returns>
public Dictionary<string, dynamic> ConvertPosition(
string Exchange,
string TradingSymbol,
string TransactionType,
string PositionType,
int? Quantity,
string OldProduct,
string NewProduct)
{
var param = new Dictionary<string, dynamic>();
Utils.AddIfNotNull(param, "exchange", Exchange);
Utils.AddIfNotNull(param, "tradingsymbol", TradingSymbol);
Utils.AddIfNotNull(param, "transaction_type", TransactionType);
Utils.AddIfNotNull(param, "position_type", PositionType);
Utils.AddIfNotNull(param, "quantity", Quantity.ToString());
Utils.AddIfNotNull(param, "old_product", OldProduct);
Utils.AddIfNotNull(param, "new_product", NewProduct);
return Put("portfolio.positions.modify", param);
}
/// <summary>
/// Retrieve the list of market instruments available to trade.
/// Note that the results could be large, several hundred KBs in size,
/// with tens of thousands of entries in the list.
/// </summary>
/// <param name="Exchange">Name of the exchange</param>
/// <returns>List of instruments.</returns>
public List<Instrument> GetInstruments(string Exchange = null)
{
var param = new Dictionary<string, dynamic>();
List<Dictionary<string, dynamic>> instrumentsData;
if (String.IsNullOrEmpty(Exchange))
instrumentsData = Get("market.instruments.all", param);
else
{
param.Add("exchange", Exchange);
instrumentsData = Get("market.instruments", param);
}
List<Instrument> instruments = new List<Instrument>();
foreach (Dictionary<string, dynamic> item in instrumentsData)
instruments.Add(new Instrument(item));
return instruments;
}
/// <summary>
/// Retrieve quote and market depth of upto 200 instruments
/// </summary>
/// <param name="InstrumentId">Indentification of instrument in the form of EXCHANGE:TRADINGSYMBOL (eg: NSE:INFY) or InstrumentToken (eg: 408065)</param>
/// <returns>Dictionary of all Quote objects with keys as in InstrumentId</returns>
public Dictionary<string, Quote> GetQuote(string[] InstrumentId)
{
var param = new Dictionary<string, dynamic>();
param.Add("i", InstrumentId);
Dictionary<string, dynamic> quoteData = Get("market.quote", param)["data"];
Dictionary<string, Quote> quotes = new Dictionary<string, Quote>();
foreach (string item in quoteData.Keys)
quotes.Add(item, new Quote(quoteData[item]));
return quotes;
}
/// <summary>
/// Retrieve LTP and OHLC of upto 200 instruments
/// </summary>
/// <param name="InstrumentId">Indentification of instrument in the form of EXCHANGE:TRADINGSYMBOL (eg: NSE:INFY) or InstrumentToken (eg: 408065)</param>
/// <returns>Dictionary of all OHLC objects with keys as in InstrumentId</returns>
public Dictionary<string, OHLC> GetOHLC(string[] InstrumentId)
{
var param = new Dictionary<string, dynamic>();
param.Add("i", InstrumentId);
Dictionary<string, dynamic> ohlcData = Get("market.ohlc", param)["data"];
Dictionary<string, OHLC> ohlcs = new Dictionary<string, OHLC>();
foreach (string item in ohlcData.Keys)
ohlcs.Add(item, new OHLC(ohlcData[item]));
return ohlcs;
}
/// <summary>
/// Retrieve LTP of upto 200 instruments
/// </summary>
/// <param name="InstrumentId">Indentification of instrument in the form of EXCHANGE:TRADINGSYMBOL (eg: NSE:INFY) or InstrumentToken (eg: 408065)</param>
/// <returns>Dictionary with InstrumentId as key and LTP as value.</returns>
public Dictionary<string, LTP> GetLTP(string[] InstrumentId)
{
var param = new Dictionary<string, dynamic>();
param.Add("i", InstrumentId);
Dictionary<string, dynamic> ltpData = Get("market.ltp", param)["data"];
Dictionary<string, LTP> ltps = new Dictionary<string, LTP>();
foreach (string item in ltpData.Keys)
ltps.Add(item, new LTP(ltpData[item]));
return ltps;
}
/// <summary>
/// Retrieve historical data (candles) for an instrument.
/// </summary>
/// <param name="InstrumentToken">Identifier for the instrument whose historical records you want to fetch. This is obtained with the instrument list API.</param>
/// <param name="FromDate">Date in format yyyy-MM-dd for fetching candles between two days. Date in format yyyy-MM-dd hh:mm:ss for fetching candles between two timestamps.</param>
/// <param name="ToDate">Date in format yyyy-MM-dd for fetching candles between two days. Date in format yyyy-MM-dd hh:mm:ss for fetching candles between two timestamps.</param>
/// <param name="Interval">The candle record interval. Possible values are: minute, day, 3minute, 5minute, 10minute, 15minute, 30minute, 60minute</param>
/// <param name="Continuous">Pass true to get continous data of expired instruments.</param>
/// <param name="OI">Pass true to get open interest data.</param>
/// <returns>List of Historical objects.</returns>
public List<Historical> GetHistoricalData(
string InstrumentToken,
DateTime FromDate,
DateTime ToDate,
string Interval,
bool Continuous = false,
bool OI = false)
{
var param = new Dictionary<string, dynamic>();
param.Add("instrument_token", InstrumentToken);
param.Add("from", FromDate.ToString("yyyy-MM-dd HH:mm:ss"));
param.Add("to", ToDate.ToString("yyyy-MM-dd HH:mm:ss"));
param.Add("interval", Interval);
param.Add("continuous", Continuous ? "1" : "0");
param.Add("oi", OI ? "1" : "0");
var historicalData = Get("market.historical", param);
List<Historical> historicals = new List<Historical>();
foreach (ArrayList item in historicalData["data"]["candles"])
historicals.Add(new Historical(item));
return historicals;
}
/// <summary>
/// Retrieve the buy/sell trigger range for Cover Orders.
/// </summary>
/// <param name="InstrumentId">Indentification of instrument in the form of EXCHANGE:TRADINGSYMBOL (eg: NSE:INFY) or InstrumentToken (eg: 408065)</param>
/// <param name="TrasactionType">BUY or SELL</param>
/// <returns>List of trigger ranges for given instrument ids for given transaction type.</returns>
public Dictionary<string, TrigerRange> GetTriggerRange(string[] InstrumentId, string TrasactionType)
{
var param = new Dictionary<string, dynamic>();
param.Add("i", InstrumentId);
param.Add("transaction_type", TrasactionType.ToLower());
var triggerdata = Get("market.trigger_range", param)["data"];
Dictionary<string, TrigerRange> triggerRanges = new Dictionary<string, TrigerRange>();
foreach (string item in triggerdata.Keys)
triggerRanges.Add(item, new TrigerRange(triggerdata[item]));
return triggerRanges;
}
#region GTT
/// <summary>
/// Retrieve the list of GTTs.
/// </summary>
/// <returns>List of GTTs.</returns>
public List<GTT> GetGTTs()
{
var gttsdata = Get("gtt");
List<GTT> gtts = new List<GTT>();
foreach (Dictionary<string, dynamic> item in gttsdata["data"])
gtts.Add(new GTT(item));
return gtts;
}
/// <summary>
/// Retrieve a single GTT
/// </summary>
/// <param name="GTTId">Id of the GTT</param>
/// <returns>GTT info</returns>
public GTT GetGTT(int GTTId)
{
var param = new Dictionary<string, dynamic>();
param.Add("id", GTTId.ToString());
var gttdata = Get("gtt.info", param);
return new GTT(gttdata["data"]);
}
/// <summary>
/// Place a GTT order
/// </summary>
/// <param name="gttParams">Contains the parameters for the GTT order</param>
/// <returns>Json response in the form of nested string dictionary.</returns>
public Dictionary<string, dynamic> PlaceGTT(GTTParams gttParams)
{
var condition = new Dictionary<string, dynamic>();
condition.Add("exchange", gttParams.Exchange);
condition.Add("tradingsymbol", gttParams.TradingSymbol);
condition.Add("trigger_values", gttParams.TriggerPrices);
condition.Add("last_price", gttParams.LastPrice);
condition.Add("instrument_token", gttParams.InstrumentToken);
var ordersParam = new List<Dictionary<string, dynamic>>();
foreach (var o in gttParams.Orders)
{
var order = new Dictionary<string, dynamic>();
order["exchange"] = gttParams.Exchange;
order["tradingsymbol"] = gttParams.TradingSymbol;
order["transaction_type"] = o.TransactionType;
order["quantity"] = o.Quantity;
order["price"] = o.Price;
order["order_type"] = o.OrderType;
order["product"] = o.Product;
ordersParam.Add(order);
}
var parms = new Dictionary<string, dynamic>();
parms.Add("condition", Utils.JsonSerialize(condition));
parms.Add("orders", Utils.JsonSerialize(ordersParam));
parms.Add("type", gttParams.TriggerType);
return Post("gtt.place", parms);
}
/// <summary>
/// Modify a GTT order
/// </summary>
/// <param name="GTTId">Id of the GTT to be modified</param>
/// <param name="gttParams">Contains the parameters for the GTT order</param>
/// <returns>Json response in the form of nested string dictionary.</returns>
public Dictionary<string, dynamic> ModifyGTT(int GTTId, GTTParams gttParams)
{
var condition = new Dictionary<string, dynamic>();
condition.Add("exchange", gttParams.Exchange);
condition.Add("tradingsymbol", gttParams.TradingSymbol);
condition.Add("trigger_values", gttParams.TriggerPrices);
condition.Add("last_price", gttParams.LastPrice);
condition.Add("instrument_token", gttParams.InstrumentToken);
var ordersParam = new List<Dictionary<string, dynamic>>();
foreach (var o in gttParams.Orders)
{
var order = new Dictionary<string, dynamic>();
order["exchange"] = gttParams.Exchange;
order["tradingsymbol"] = gttParams.TradingSymbol;
order["transaction_type"] = o.TransactionType;
order["quantity"] = o.Quantity;
order["price"] = o.Price;
order["order_type"] = o.OrderType;
order["product"] = o.Product;
ordersParam.Add(order);
}
var parms = new Dictionary<string, dynamic>();
parms.Add("condition", Utils.JsonSerialize(condition));
parms.Add("orders", Utils.JsonSerialize(ordersParam));
parms.Add("type", gttParams.TriggerType);
parms.Add("id", GTTId.ToString());
return Put("gtt.modify", parms);
}
/// <summary>
/// Cancel a GTT order
/// </summary>
/// <param name="GTTId">Id of the GTT to be modified</param>
/// <returns>Json response in the form of nested string dictionary.</returns>
public Dictionary<string, dynamic> CancelGTT(int GTTId)
{
var parms = new Dictionary<string, dynamic>();
parms.Add("id", GTTId.ToString());
return Delete("gtt.delete", parms);
}
#endregion GTT
#region MF Calls
/// <summary>
/// Gets the Mutual funds Instruments.
/// </summary>
/// <returns>The Mutual funds Instruments.</returns>
public List<MFInstrument> GetMFInstruments()
{
var param = new Dictionary<string, dynamic>();
List<Dictionary<string, dynamic>> instrumentsData;
instrumentsData = Get("mutualfunds.instruments", param);
List<MFInstrument> instruments = new List<MFInstrument>();
foreach (Dictionary<string, dynamic> item in instrumentsData)
instruments.Add(new MFInstrument(item));
return instruments;
}
/// <summary>
/// Gets all Mutual funds orders.
/// </summary>
/// <returns>The Mutual funds orders.</returns>
public List<MFOrder> GetMFOrders()
{
var param = new Dictionary<string, dynamic>();
Dictionary<string, dynamic> ordersData;
ordersData = Get("mutualfunds.orders", param);
List<MFOrder> orderlist = new List<MFOrder>();
foreach (Dictionary<string, dynamic> item in ordersData["data"])
orderlist.Add(new MFOrder(item));
return orderlist;
}
/// <summary>
/// Gets the Mutual funds order by OrderId.
/// </summary>
/// <returns>The Mutual funds order.</returns>
/// <param name="OrderId">Order id.</param>
public MFOrder GetMFOrders(String OrderId)
{
var param = new Dictionary<string, dynamic>();
param.Add("order_id", OrderId);
Dictionary<string, dynamic> orderData;
orderData = Get("mutualfunds.order", param);