-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStockManager.cs
More file actions
5135 lines (4630 loc) · 243 KB
/
Copy pathStockManager.cs
File metadata and controls
5135 lines (4630 loc) · 243 KB
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 ClosedXML.Excel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace DataAccessLayer
{
public class StockManager
{
static string dbFile = "mfdata.db";
public static string indicators = "quote";
public static string includeTimestamps = "true";
//following link gives a CSV list of all stocks listed on NSE in following format
//SYMBOL,NAME OF COMPANY, SERIES, DATE OF LISTING, PAID UP VALUE, MARKET LOT, ISIN NUMBER, FACE VALUE
//First line is list of fields
static string urlNSEStockMaster = "http://www1.nseindia.com/content/equities/EQUITY_L.csv";
//https://query1.finance.yahoo.com/v7/finance/chart/HDFC.BO?range=2yr&interval=1d&indicators=quote&includeTimestamps=true
//https://query1.finance.yahoo.com/v7/finance/chart/HDFC.BO?range=2yr&interval=1d&indicators=quote&includeTimestamps=true
public static string urlGetStockData = "https://query1.finance.yahoo.com/v8/finance/chart/{0}?range={1}&interval={2}&indicators={3}&includeTimestamps={4}";
//https://query1.finance.yahoo.com/v8/finance/chart/HDFC.BO?range=1d&interval=1d&indicators=quote×tamp=true
public static string urlGlobalQuote = "https://query1.finance.yahoo.com/v8/finance/chart/{0}?range=1d&interval=1d&indicators=quote×tamp=true";
//to get specific historic price
//below is 10-02-2022 to 11-02-2022
//https://finance.yahoo.com/quote/LT.NS/history?period1=1644451200&period2=1644537600&interval=1d&filter=history&frequency=1d&includeAdjustedClose=true
//below is 17-02-2022 to 18-02-2022
//https://finance.yahoo.com/quote/LT.NS/history?period1=1645056000&period2=1645142400&interval=1d&filter=history&frequency=1d&includeAdjustedClose=true
//the following gives json
//https://query1.finance.yahoo.com/v8/finance/chart/LT.NS?period1=1644451200&period2=1644537600&interval=1d&filter=history&frequency=1d&includeAdjustedClose=true
public static string urlGetHistoryQuote = "https://query1.finance.yahoo.com/v8/finance/chart/{0}?period1={1}&period2={2}&interval={3}&filter=history&frequency={4}&includeAdjustedClose={5}";
//https://finance.yahoo.com/lookup/index?s=all
//https://finance.yahoo.com/lookup/all?s=proctor
//https://finance.yahoo.com/lookup/all?s=larsen
public static string urlSearch = "https://finance.yahoo.com/lookup/{0}?s={1}";
#region online menthods
public Root getIndexIntraDayAlternate(string scriptName, string time_interval = "5min", string outputsize = "full")
{
Root myDeserializedClass = null;
try
{
string webservice_url = "";
WebResponse wr;
Stream receiveStream = null;
StreamReader reader = null;
//string convertedScriptName;
string range, interval;
var errors = new List<string>();
if (time_interval == "60min")
{
interval = "60m";
if (outputsize.Equals("compact"))
{
range = "1d";
}
else
{
range = "2y";
}
}
else if (time_interval == "1min")
{
interval = "1m";
if (outputsize.Equals("compact"))
{
range = "1d";
}
else
{
range = "7d";
}
}
else if (time_interval == "15min")
{
interval = "15m";
if (outputsize.Equals("compact"))
{
range = "1d";
}
else
{
range = "60d";
}
}
else if (time_interval == "30min")
{
interval = "30m";
if (outputsize.Equals("compact"))
{
range = "1d";
}
else
{
range = "60d";
}
}
else //if(time_interval == "60min")
{
interval = "5m";
if (outputsize.Equals("compact"))
{
range = "1d";
}
else
{
range = "60d";
}
}
webservice_url = string.Format(urlGetStockData, scriptName, range, interval, indicators, includeTimestamps);
Uri url = new Uri(webservice_url);
var webRequest = WebRequest.Create(url);
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
wr = webRequest.GetResponseAsync().Result;
receiveStream = wr.GetResponseStream();
reader = new StreamReader(receiveStream);
myDeserializedClass = JsonConvert.DeserializeObject<Root>(reader.ReadToEnd(), new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Populate,
Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
//args.ErrorContext.Handled = false;
}
//Converters = { new IsoDateTimeConverter() }
});
//Chart myChart = myDeserializedClass.chart;
//Result myResult = myChart.result[0];
//Meta myMeta = myResult.meta;
//Indicators myIndicators = myResult.indicators;
////this will be typically only 1 row and quote will have list of close, high, low, open, volume
//Quote myQuote = myIndicators.quote[0];
////this will be typically only 1 row and adjClose will have list of adjClose
//Adjclose myAdjClose = null;
//if (bIsDaily)
//{
// myAdjClose = myIndicators.adjclose[0];
//}
reader.Close();
if (receiveStream != null)
receiveStream.Close();
}
catch (Exception ex)
{
myDeserializedClass = null;
Console.WriteLine(ex.Message);
}
return myDeserializedClass;
}
/// <summary>
///
/// </summary>
/// <param name="scriptName"></param>
/// <param name="time_interval"></param>
/// <param name="outputsize"></param>
/// <returns>DataTable with following columns Symbol, Open, High, Low, Price, Volume, latestDay, previousClose, change, changePercent </returns>
public DataTable GetIntraWithPctChange(string scriptName, string time_interval = "5min", string outputsize = "full")
{
DataTable resultDataTable = null;
try
{
string webservice_url = "";
WebResponse wr;
Stream receiveStream = null;
StreamReader reader = null;
string record = "";
//string convertedScriptName;
string range, interval;
if (time_interval == "60min")
{
interval = "60m";
if (outputsize.Equals("compact"))
{
range = "1d";
}
else
{
range = "2y";
}
}
else if (time_interval == "1min")
{
interval = "1m";
if (outputsize.Equals("compact"))
{
range = "1d";
}
else
{
range = "7d";
}
}
else if (time_interval == "15min")
{
interval = "15m";
if (outputsize.Equals("compact"))
{
range = "1d";
}
else
{
range = "60d";
}
}
else if (time_interval == "30min")
{
interval = "30m";
if (outputsize.Equals("compact"))
{
range = "1d";
}
else
{
range = "60d";
}
}
else //if(time_interval == "60min")
{
interval = "5m";
if (outputsize.Equals("compact"))
{
range = "1d";
}
else
{
range = "60d";
}
}
webservice_url = string.Format(urlGetStockData, scriptName, range, interval, indicators, includeTimestamps);
Uri url = new Uri(webservice_url);
var webRequest = WebRequest.Create(url);
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
wr = webRequest.GetResponseAsync().Result;
receiveStream = wr.GetResponseStream();
reader = new StreamReader(receiveStream);
//returnDataTable = getQuoteTableFromJSON(reader.ReadToEnd(), scriptName);
record = reader.ReadToEnd();
reader.Close();
if (receiveStream != null)
receiveStream.Close();
DateTime myDate;
double close;
double high;
double low;
double open;
int volume;
double change;
double changepercent;
double prevclose;
//double adjusetedClose = 0.00;
//string formatedDate;
var errors = new List<string>();
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(record, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Populate,
Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
//args.ErrorContext.Handled = false;
}
//Converters = { new IsoDateTimeConverter() }
});
Chart myChart = myDeserializedClass.chart;
Result myResult = myChart.result[0];
Meta myMeta = myResult.meta;
Indicators myIndicators = myResult.indicators;
//this will be typically only 1 row and quote will have list of close, high, low, open, volume
Quote myQuote = myIndicators.quote[0];
//this will be typically only 1 row and adjClose will have list of adjClose
//Adjclose myAdjClose = null;
//if (bIsDaily)
//{
// myAdjClose = myIndicators.adjclose[0];
//}
if (myResult.timestamp != null)
{
resultDataTable = new DataTable();
resultDataTable.Columns.Add("Symbol", typeof(string));
resultDataTable.Columns.Add("Open", typeof(decimal));
resultDataTable.Columns.Add("High", typeof(decimal));
resultDataTable.Columns.Add("Low", typeof(decimal));
resultDataTable.Columns.Add("Price", typeof(decimal));
resultDataTable.Columns.Add("Volume", typeof(int));
resultDataTable.Columns.Add("LatestDay", typeof(DateTime));
resultDataTable.Columns.Add("previousClose", typeof(decimal));
resultDataTable.Columns.Add("change", typeof(decimal));
resultDataTable.Columns.Add("changePercent", typeof(decimal));
for (int i = 0; i < myResult.timestamp.Count; i++)
{
if ((myQuote.close[i] == null) && (myQuote.high[i] == null) && (myQuote.low[i] == null) && (myQuote.open[i] == null)
&& (myQuote.volume[i] == null))
{
continue;
}
//myDate = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(myResult.timestamp[i]).ToLocalTime();
myDate = convertUnixEpochToLocalDateTime(myResult.timestamp[i], myMeta.timezone);
//myDate = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(myResult.timestamp[i]);
//string formatedDate = myDate.ToString("dd-MM-yyyy");
//formatedDate = myDate.ToString("yyyy-dd-MM");
//myDate = System.Convert.ToDateTime(myResult.timestamp[i]);
//if all are null do not enter this row
if (myQuote.close[i] == null)
{
close = 0.00;
}
else
{
//close = (double)myQuote.close[i];
close = System.Convert.ToDouble(string.Format("{0:0.00}", myQuote.close[i]));
}
if (myQuote.high[i] == null)
{
high = 0.00;
}
else
{
//high = (double)myQuote.high[i];
high = System.Convert.ToDouble(string.Format("{0:0.00}", myQuote.high[i]));
}
if (myQuote.low[i] == null)
{
low = 0.00;
}
else
{
//low = (double)myQuote.low[i];
low = System.Convert.ToDouble(string.Format("{0:0.00}", myQuote.low[i]));
}
if (myQuote.open[i] == null)
{
open = 0.00;
}
else
{
//open = (double)myQuote.open[i];
open = System.Convert.ToDouble(string.Format("{0:0.00}", myQuote.open[i]));
}
if (myQuote.volume[i] == null)
{
volume = 0;
}
else
{
volume = (int)myQuote.volume[i];
}
prevclose = System.Convert.ToDouble(string.Format("{0:0.00}", myMeta.chartPreviousClose));
change = close - prevclose;
changepercent = (change / prevclose) * 100;
change = System.Convert.ToDouble(string.Format("{0:0.00}", change));
changepercent = System.Convert.ToDouble(string.Format("{0:0.00}", changepercent));
resultDataTable.Rows.Add(new object[] {
scriptName,
Math.Round(open, 4),
Math.Round(high, 4),
Math.Round(low, 4),
Math.Round(close, 4),
volume,
myDate,
Math.Round(prevclose, 4),
Math.Round(change, 4),
Math.Round(changepercent, 4)
//adjusetedClose
});
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if (resultDataTable != null)
{
resultDataTable.Clear();
resultDataTable.Dispose();
}
resultDataTable = null;
}
return resultDataTable;
}
/// <summary>
/// Method to fetch stock master data from NSE and then store in SQLite table
/// The url returns comma separated recrods with first record is the field descriptor as shown below
/// SYMBOL,NAME OF COMPANY, SERIES, DATE OF LISTING, PAID UP VALUE, MARKET LOT, ISIN NUMBER, FACE VALUE
///
/// We will read each line, then split the fields and then store each record in DB
/// </summary>
/// <param name="exchangeCode"></param>
/// <returns>true if data is stored else fals</returns>
public int FetchStockMasterFromWebAndInsert(string exchangeCode = "NS")
{
int numOfRowsInserted = 0;
string webservice_url;
Uri url;
WebResponse wr;
Stream receiveStream = null;
StreamReader reader = null;
StringBuilder sourceFile;
string[] fields;
StringBuilder record = new StringBuilder(string.Empty);
string[] sourceLines;
int recCounter = 0;
SQLiteConnection sqlite_conn = null;
SQLiteCommand sqlite_cmd = null;
string dateToday = DateTime.Today.ToString("yyyy-MM-dd");
try
{
if (exchangeCode.Equals("NS"))
{
webservice_url = urlNSEStockMaster;
url = new Uri(webservice_url);
var webRequest = WebRequest.Create(url);
webRequest.Method = WebRequestMethods.File.DownloadFile;
//webRequest.ContentType = "application/json";
wr = webRequest.GetResponseAsync().Result;
receiveStream = wr.GetResponseStream();
reader = new StreamReader(receiveStream);
}
else if (exchangeCode.Equals("BO"))
{
//read stock master from BSE
//i do not have the url to download that
}
if (reader != null)
{
//read first line which is list of fields
reader.ReadLine();
sourceFile = new StringBuilder(reader.ReadToEnd());
if (reader != null)
reader.Close();
if (receiveStream != null)
receiveStream.Close();
sourceLines = sourceFile.ToString().Split('\n');
sourceFile.Clear();
sqlite_conn = CreateConnection();
sqlite_cmd = sqlite_conn.CreateCommand();
var transaction = sqlite_conn.BeginTransaction();
while (recCounter < sourceLines.Length)
{
record.Clear();
record.Append(sourceLines[recCounter++].Trim());
if (record.Length == 0)
{
continue;
}
fields = record.ToString().Split(',');
InsertNewStock(fields[0] + "." + "NS", "NSI", fields[1], "Stocks", System.Convert.ToDateTime(fields[3]).ToString("yyyy-MM-dd"), fields[4],
fields[5], fields[6], fields[7], dateToday, sqlite_cmd: sqlite_cmd);
////sqlite_cmd.CommandText = "REPLACE INTO STOCKMASTER(EXCHANGE, SYMBOL, COMP_NAME, SERIES, DATE_OF_LISTING, PAID_UP_VALUE, " +
//// "MARKET_LOT, ISIN_NUMBER, FACE_VALUE, LASTUPDT) " +
//// "VALUES (@EXCHANGE, @SYMBOL, @COMP_NAME, @SERIES, @DATE_OF_LISTING, @PAID_UP_VALUE, @MARKET_LOT, @ISIN_NUMBER, @FACE_VALUE, @LASTUPDT)";
////Adding IGNORE INTO skips the insert if there are any conflict related to primary key unique or other constraints without raising errors
//sqlite_cmd.CommandText = "INSERT OR IGNORE INTO STOCKMASTER(EXCHANGE, SYMBOL, COMP_NAME, SERIES, DATE_OF_LISTING, PAID_UP_VALUE, " +
// "MARKET_LOT, ISIN_NUMBER, FACE_VALUE, LASTUPDT) " +
// "VALUES (@EXCHANGE, @SYMBOL, @COMP_NAME, @SERIES, @DATE_OF_LISTING, @PAID_UP_VALUE, @MARKET_LOT, @ISIN_NUMBER, @FACE_VALUE, @LASTUPDT)";
////You can use INSERT INTO table(columns) values(..,..) ON CONFLICT DO NOTHING";
//sqlite_cmd.Prepare();
//sqlite_cmd.Parameters.AddWithValue("@EXCHANGE", exchangeCode);
//sqlite_cmd.Parameters.AddWithValue("@SYMBOL", fields[0]);
//sqlite_cmd.Parameters.AddWithValue("@COMP_NAME", fields[1]);
//sqlite_cmd.Parameters.AddWithValue("@SERIES", fields[2]);
//sqlite_cmd.Parameters.AddWithValue("@DATE_OF_LISTING", System.Convert.ToDateTime(fields[3]).ToString("yyyy-MM-dd"));
//sqlite_cmd.Parameters.AddWithValue("@PAID_UP_VALUE", fields[4]);
//sqlite_cmd.Parameters.AddWithValue("@MARKET_LOT", fields[5]);
//sqlite_cmd.Parameters.AddWithValue("@ISIN_NUMBER", fields[6]);
//sqlite_cmd.Parameters.AddWithValue("@FACE_VALUE", fields[7]);
//sqlite_cmd.Parameters.AddWithValue("@LASTUPDT", dateToday);
//try
//{
// numOfRowsInserted += sqlite_cmd.ExecuteNonQuery();
//}
//catch (SQLiteException sqlException)
//{
// Console.WriteLine(sqlException.Message);
// break;
//}
}
transaction.Commit();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (sqlite_cmd != null)
{
sqlite_cmd.Dispose();
}
if (sqlite_conn != null)
{
sqlite_conn.Close();
sqlite_conn.Dispose();
}
}
return numOfRowsInserted;
}
/// <summary>
/// Method to parse the output JSON received by calling yahoo url to get quote using range = 1m and interval = 1m
/// </summary>
/// <param name="record">JSON string</param>
/// <param name="symbol">Symbol for which we fetched the quote</param>
/// <returns>DataTable with following columns Symbol, Open, High, Low, Price, Volume, latestDay, previousClose, change, changePercent </returns>
public DataTable getQuoteTableFromJSON(string record, string symbol)
{
DataTable resultDataTable = null;
if (record.ToUpper().Contains("NOT FOUND"))
{
return null;
}
DateTime myDate;
double close;
double high;
double low;
double open;
int volume;
double change;
double changepercent;
double prevclose;
//double adjusetedClose = 0.00;
//string formatedDate;
var errors = new List<string>();
try
{
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(record, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Populate,
Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
//args.ErrorContext.Handled = false;
}
//Converters = { new IsoDateTimeConverter() }
});
Chart myChart = myDeserializedClass.chart;
Result myResult = myChart.result[0];
Meta myMeta = myResult.meta;
Indicators myIndicators = myResult.indicators;
//this will be typically only 1 row and quote will have list of close, high, low, open, volume
Quote myQuote = myIndicators.quote[0];
//this will be typically only 1 row and adjClose will have list of adjClose
//Adjclose myAdjClose = null;
//if (bIsDaily)
//{
// myAdjClose = myIndicators.adjclose[0];
//}
if (myResult.timestamp != null)
{
resultDataTable = new DataTable();
resultDataTable.Columns.Add("Symbol", typeof(string));
resultDataTable.Columns.Add("Open", typeof(decimal));
resultDataTable.Columns.Add("High", typeof(decimal));
resultDataTable.Columns.Add("Low", typeof(decimal));
resultDataTable.Columns.Add("Price", typeof(decimal));
resultDataTable.Columns.Add("Volume", typeof(int));
resultDataTable.Columns.Add("latestDay", typeof(DateTime));
resultDataTable.Columns.Add("previousClose", typeof(decimal));
resultDataTable.Columns.Add("change", typeof(decimal));
resultDataTable.Columns.Add("changePercent", typeof(decimal));
for (int i = 0; i < myResult.timestamp.Count; i++)
{
if ((myQuote.close[i] == null) && (myQuote.high[i] == null) && (myQuote.low[i] == null) && (myQuote.open[i] == null)
&& (myQuote.volume[i] == null))
{
continue;
}
//myDate = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(myResult.timestamp[i]).ToLocalTime();
myDate = convertUnixEpochToLocalDateTime(myResult.timestamp[i], myMeta.timezone);
//myDate = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(myResult.timestamp[i]);
//string formatedDate = myDate.ToString("dd-MM-yyyy");
//formatedDate = myDate.ToString("yyyy-dd-MM");
//myDate = System.Convert.ToDateTime(myResult.timestamp[i]);
//if all are null do not enter this row
if (myQuote.close[i] == null)
{
close = 0.00;
}
else
{
//close = (double)myQuote.close[i];
close = System.Convert.ToDouble(string.Format("{0:0.00}", myQuote.close[i]));
}
if (myQuote.high[i] == null)
{
high = 0.00;
}
else
{
//high = (double)myQuote.high[i];
high = System.Convert.ToDouble(string.Format("{0:0.00}", myQuote.high[i]));
}
if (myQuote.low[i] == null)
{
low = 0.00;
}
else
{
//low = (double)myQuote.low[i];
low = System.Convert.ToDouble(string.Format("{0:0.00}", myQuote.low[i]));
}
if (myQuote.open[i] == null)
{
open = 0.00;
}
else
{
//open = (double)myQuote.open[i];
open = System.Convert.ToDouble(string.Format("{0:0.00}", myQuote.open[i]));
}
if (myQuote.volume[i] == null)
{
volume = 0;
}
else
{
volume = (int)myQuote.volume[i];
}
prevclose = System.Convert.ToDouble(string.Format("{0:0.00}", myMeta.chartPreviousClose));
change = close - prevclose;
changepercent = (change / prevclose) * 100;
change = System.Convert.ToDouble(string.Format("{0:0.00}", change));
changepercent = System.Convert.ToDouble(string.Format("{0:0.00}", changepercent));
resultDataTable.Rows.Add(new object[] {
symbol,
Math.Round(open, 4),
Math.Round(high, 4),
Math.Round(low, 4),
Math.Round(close, 4),
volume,
myDate,
Math.Round(prevclose, 4),
Math.Round(change, 4),
Math.Round(changepercent, 4)
//adjusetedClose
});
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if (resultDataTable != null)
{
resultDataTable.Clear();
resultDataTable.Dispose();
}
resultDataTable = null;
}
return resultDataTable;
}
public bool InsertStockFromJSON(string record, string symbol, SQLiteCommand sqlite_cmd = null)
{
bool bReturn = true;
if (record.ToUpper().Contains("NOT FOUND"))
{
return false;
}
var errors = new List<string>();
try
{
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(record, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Populate,
Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
//args.ErrorContext.Handled = false;
}
//Converters = { new IsoDateTimeConverter() }
});
Chart myChart = myDeserializedClass.chart;
Result myResult = myChart.result[0];
Meta myMeta = myResult.meta;
if (myMeta != null)
{
bReturn = InsertNewStock(myMeta.symbol, myMeta.exchangeName, myMeta.symbol, myMeta.instrumentType, sqlite_cmd: sqlite_cmd);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
bReturn = false;
}
return bReturn;
}
/// <summary>
/// Method to fetch quote for given symbol + exchange combinations using range = 1m inerval = 1m parameters
/// It will call yahoo quote url and get JSON as output
/// It will parse the JSON and put the data in DataTable
/// </summary>
/// <param name="symbol">Symbol for which to get quote</param>
/// <param name="exchange">Exchange to which this symbol belongs - BSE or NSE</param>
/// <returns></returns>
public DataTable GetQuote(string symbol)
{
DataTable resultDataTable = null;
try
{
string webservice_url = "";
WebResponse wr;
Stream receiveStream = null;
StreamReader reader = null;
//DataRow r;
//https://query1.finance.yahoo.com/v7/finance/chart/HDFC.BO?range=1m&interval=1m&indicators=quote×tamp=true
webservice_url = string.Format(StockManager.urlGlobalQuote, symbol);
Uri url = new Uri(webservice_url);
var webRequest = WebRequest.Create(url);
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
wr = webRequest.GetResponseAsync().Result;
receiveStream = wr.GetResponseStream();
reader = new StreamReader(receiveStream);
resultDataTable = getQuoteTableFromJSON(reader.ReadToEnd(), symbol);
reader.Close();
if (receiveStream != null)
receiveStream.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if (resultDataTable != null)
{
resultDataTable.Clear();
resultDataTable.Dispose();
}
resultDataTable = null;
}
return resultDataTable;
}
//https://query1.finance.yahoo.com/v8/finance/chart/LT.NS?period1=1644451200&period2=1644537600&interval=1d&filter=history&frequency=1d&includeAdjustedClose=true
//public static string urlGetHistoryQuote = "https://query1.finance.yahoo.com/v8/finance/chart/{0}?period1={1}&period2={2}&interval={3}&filter=history&frequency={4}&includeAdjustedClose={5}";
public DataTable GetHistoryQuote(string symbol, string periodDt1, string periodDt2, string interval = "1d", string frequency = "1d", string adjclose = "true")
{
DataTable resultDataTable = null;
try
{
string webservice_url = "";
WebResponse wr;
Stream receiveStream = null;
StreamReader reader = null;
//DataRow r;
//https://query1.finance.yahoo.com/v8/finance/chart/LT.NS?period1=1644451200&period2=1644537600&interval=1d&filter=history&frequency=1d&includeAdjustedClose=true
//public static string urlGetHistoryQuote = "https://query1.finance.yahoo.com/v8/finance/chart/{0}?period1={1}&period2={2}&interval={3}&filter=history&frequency={4}&includeAdjustedClose={5}";
//we need to convert the date first
string period1 = convertDateTimeToUnixEpoch(System.Convert.ToDateTime(periodDt1)).ToString();
string period2 = convertDateTimeToUnixEpoch(System.Convert.ToDateTime(periodDt2)).ToString();
webservice_url = string.Format(StockManager.urlGetHistoryQuote, symbol, period1, period2, interval, frequency, adjclose);
Uri url = new Uri(webservice_url);
var webRequest = WebRequest.Create(url);
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
wr = webRequest.GetResponseAsync().Result;
receiveStream = wr.GetResponseStream();
reader = new StreamReader(receiveStream);
resultDataTable = getQuoteTableFromJSON(reader.ReadToEnd(), symbol);
reader.Close();
if (receiveStream != null)
receiveStream.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if (resultDataTable != null)
{
resultDataTable.Clear();
resultDataTable.Dispose();
}
resultDataTable = null;
}
return resultDataTable;
}
/// <summary>
/// Method will use https://finance.yahoo.com/lookup/all?s=larsen to search input search string
/// The output returned is an XML from which we are interested in
/// <span>All (11)</span> if the search returns valid symbol list it will have number > 0 in () else it will have (0)
/// <section>
/// <ul>
/// <li>
/// <a>
/// <span> All (11)</span>
/// </a>
/// </li>
/// </ul>
/// </section>
/// THe data is in
/// <div>
/// <div>
/// <div>
/// <table>
/// <tbody>
/// <tr>
/// <td class="data-col0 Ta(start) Pstart(6px) Pend(15px)">
/// symbol = <a href = "/quote/LT.NS?p=LT.NS" title="LARSEN & TOUBRO" data-symbol="LT.NS" class="Fw(b)">LT.NS</a>
/// </td>
/// comp_name = <td class="data-col1 Ta(start) Pstart(10px) Miw(80px)">LARSEN & TOUBRO</td>
/// last_price = <td class="data-col2 Ta(end) Pstart(20px) Pend(15px)">1,925.30</td>
/// <td class="data-col3 Ta(start) Pstart(20px) Miw(60px)">
/// Industry/Category = <a href = "https://finance.yahoo.com/sector/industrials" title="Industrials" data-symbol="LT.NS" class="Fw(b)">Industrials</a>
/// </td>
/// Type = <td class="data-col4 Ta(start) Pstart(20px) Miw(30px)">Stocks</td>
/// Exchange = <td class="data-col5 Ta(start) Pstart(20px) Pend(6px) W(30px)">NSI</td>
/// </tr>
/// </tbody>
/// </table>
/// </div>
/// </div>
/// </div><tbody> </tbody>
/// </summary>
/// <param name="searchStr"></param>
/// <param name="qualifier">Send specific qualifier to extract specific type of entity. Valid ones are - all, index</param>
/// <param name="sqlite_cmd"></param>
/// <returns></returns>
public bool SearchOnlineInsertInDB(string searchStr, string qualifier = "all", SQLiteCommand sqlite_cmd = null)
{
bool breturn = false;
string responseStr = null, dataStr = null;
//WebClient webClient = null;
WebResponse wr;
Stream receiveStream = null;
StreamReader reader = null;
int startIndex = 0;
int endIndex = 0;
XmlDocument xmlResult = null;
string compname, exchange, symbol, type, lasttradeprice, category;
try
{
string webservice_url = "";
//https://finance.yahoo.com/lookup/all?s=larsen
webservice_url = string.Format(StockManager.urlSearch, qualifier, searchStr);
//webClient = new System.Net.WebClient();
//byte[] response = webClient.DownloadData(webservice_url);
//responseXML = new StringBuilder( System.Text.UTF8Encoding.UTF8.GetString(response));
//webClient.Dispose();
//webClient = null;
Uri url = new Uri(webservice_url);
var webRequest = WebRequest.Create(url);
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
wr = webRequest.GetResponseAsync().Result;
receiveStream = wr.GetResponseStream();
reader = new StreamReader(receiveStream);
responseStr = reader.ReadToEnd();
reader.Close();
if (receiveStream != null)
receiveStream.Close();
if (responseStr.Contains("<span>All (0)</span>") == false)
{
startIndex = responseStr.IndexOf("<tbody>");
endIndex = responseStr.IndexOf("</tbody>") + 7;
if (startIndex > 0 && endIndex > 0)
{
dataStr = responseStr.Substring(startIndex, endIndex - startIndex + 1);
xmlResult = new XmlDocument();
xmlResult.LoadXml(dataStr);
for (int i = 0; i < xmlResult["tbody"].ChildNodes.Count; i++)
{
//get the data that we are interested in
//compname = xmlResult["tbody"].ChildNodes[i].ChildNodes[0].ChildNodes[0].Attributes["title"].Value; //= "LARSEN AND TOUBRO"
symbol = xmlResult["tbody"].ChildNodes[i].ChildNodes[0].ChildNodes[0].Attributes["data-symbol"].Value.ToUpper(); // = "LTI.NS"
compname = xmlResult["tbody"].ChildNodes[i].ChildNodes[1].ChildNodes[0].Value.ToUpper(); //= "LARSEN AND TOUBRO"
lasttradeprice = xmlResult["tbody"].ChildNodes[i].ChildNodes[2].ChildNodes[0].Value; // = "6034.15"
category = xmlResult["tbody"].ChildNodes[i].ChildNodes[3].ChildNodes[0].Value; // = "Technology"
type = xmlResult["tbody"].ChildNodes[i].ChildNodes[4].ChildNodes[0].Value; // = "Stocks"
exchange = xmlResult["tbody"].ChildNodes[i].ChildNodes[5].ChildNodes[0].Value; // = "NSI"
InsertNewStock(symbol, exchange, compname, type, lastupdt: DateTime.Today.ToString("yyyy-MM-dd"));
}
breturn = true;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
breturn = false;
}
return breturn;
}
/// <summary>
/// Finds current quote from yahoo finance for the given symbol