/
YahooGoogelHistorySource.cs
346 lines (250 loc) · 13 KB
/
YahooGoogelHistorySource.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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Ecng.Collections;
using Ecng.Common;
using StockSharp;
using StockSharp.Algo;
using StockSharp.Algo.Candles;
using StockSharp.Algo.History;
using StockSharp.BusinessEntities;
using StockSharp.Hydra;
using StockSharp.Hydra.Core;
using StockSharp.Logging;
namespace StockSharp.Hydra.YahooGoogle
{
class YahooGoogelHistorySource : BaseHistorySource
{
private List<string> _errorSecurititesList = new List<string>();
private DateTime _cachedBeginDate ;
private DateTime _cachedEndDate;
private Security _cachedSecurity;
private TimeSpan _cachedTimeframe;
private List<TimeFrameCandle> _cachedCandleList;
private DateTime _lastUpdate;
public YahooGoogelHistorySource(ISecurityStorage securityStorage) : base(securityStorage)
{
var securities = new List<Security>();
string filepath = Directory.GetCurrentDirectory() + "\\YahooGoogleSourceTickers.txt";
var fileInfo = new FileInfo(filepath);
if (!fileInfo.Exists)
{
File.CreateText(filepath);
}
}
public IEnumerable<Candle> GetCandles(Security security, DateTime beginDate,DateTime endDate,TimeSpan timeframe)
{
if (Math.Abs(timeframe.TotalHours - 24) > 0.000001)
throw new InvalidDataException("unsupported timeframe " + security.Code);
{
if(_cachedCandleList!=null)
if(_cachedCandleList.Count>0)
{
if(_cachedSecurity.Code== security.Code && Math.Abs(_cachedTimeframe.TotalSeconds - timeframe.TotalSeconds) < 0.00001)
if(DateTime.Now -_lastUpdate<TimeSpan.FromMinutes(30))
return _cachedCandleList.Where(c => c.OpenTime >= beginDate && c.OpenTime <= endDate);
}
var candleList = new List<TimeFrameCandle>();
if (_errorSecurititesList.Any(c => c == security.Id)) return candleList;
var web = new WebClient();
string data = "";
try
{
data =
web.DownloadString(string.Format("http://ichart.finance.yahoo.com/table.csv?s={0}&c={1}",
security.Code, 1900));
}
catch
{
}
string[] rows;
if (data == "")
{
try
{
string url = string.Format("http://www.google.com/finance/historical?output=csv&q={0}",
security.Code);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
data = reader.ReadToEnd();
}
catch
{
}
if (data == "")
{
_errorSecurititesList.Add(security.Id);
using (StreamWriter w = File.AppendText(Directory.GetCurrentDirectory() + "\\ErrorTickers.txt"))
{
w.WriteLine(security.Id);
}
return candleList;
}
else
{
data = data.Replace(",", ";");
data = data.Replace(".", ",");
rows = data.Split('\n');
//First row is headers so Ignore it
for (int i = 1; i < rows.Length; i++)
{
if (rows[i].Replace("\n", "").Trim() == "") continue;
string[] cols = rows[i].Split(';');
try
{
var OpenTime = DateTime.Parse(cols[0]);
decimal OpenPrice = -6m, HighPrice = -6m, LowPrice = -6m, ClosePrice = -6m, TotalVolume = -6m;
if (!decimal.TryParse(cols[1], out OpenPrice))
throw new InvalidDataException("Google data error. Symbol: " + security.Id);
if (!decimal.TryParse(cols[2], out HighPrice))
throw new InvalidDataException("Google data error. Symbol: " + security.Id);
if (!decimal.TryParse(cols[3], out LowPrice))
throw new InvalidDataException("Google data error. Symbol: " + security.Id);
if (!decimal.TryParse(cols[4], out ClosePrice))
throw new InvalidDataException("Google data error. Symbol: " + security.Id);
if (!decimal.TryParse(cols[5], out TotalVolume))
throw new InvalidDataException("Google data error. Symbol: " + security.Id);
var candle = new TimeFrameCandle();
candle.OpenPrice = OpenPrice;
candle.HighPrice = HighPrice;
candle.LowPrice = LowPrice;
candle.ClosePrice = ClosePrice;
candle.TimeFrame = timeframe;
candle.OpenTime = OpenTime;
candle.CloseTime = OpenTime + timeframe;
candle.TotalVolume = TotalVolume;
candle.Security = security;
candleList.Add(candle);
}
catch (Exception ex)
{
_errorSecurititesList.Add(security.Id);
using (StreamWriter w = File.AppendText(Directory.GetCurrentDirectory() + "\\ErrorTickers.txt"))
{
w.WriteLine(security.Id);
}
}
}
}
}
data = data.Replace(",", ";");
data = data.Replace(".", ",");
rows = data.Split('\n');
//First row is headers so Ignore it
for (int i = 1; i < rows.Length; i++)
{
if (rows[i].Replace("\n", "").Trim() == "") continue;
string[] cols = rows[i].Split(';');
var candle = new TimeFrameCandle();
string[] parseDate = cols[0].Split("-");
try
{
candle.OpenTime = new DateTime(int.Parse(parseDate[0]), int.Parse(parseDate[1]),
int.Parse(parseDate[2]));
candle.CloseTime = candle.OpenTime + timeframe;
candle.TimeFrame = timeframe;
candle.OpenPrice = decimal.Parse(cols[1]);
candle.HighPrice = decimal.Parse(cols[2]);
candle.LowPrice = decimal.Parse(cols[3]);
candle.ClosePrice = decimal.Parse(cols[4]);
candle.TotalVolume = decimal.Parse(cols[5]);
candle.Security = security;
candleList.Add(candle);
}
catch (Exception ex)
{
_errorSecurititesList.Add(security.Id);
using (StreamWriter w = File.AppendText(Directory.GetCurrentDirectory() + "\\ErrorTickers.txt"))
{
w.WriteLine(security.Id);
}
}
}
_cachedCandleList = candleList.OrderBy
(c => c.OpenTime).ToList();
_cachedBeginDate = _cachedCandleList.First().OpenTime;
_cachedEndDate = _cachedCandleList.Last().OpenTime;
_cachedSecurity = security;
_cachedTimeframe = timeframe;
_lastUpdate = DateTime.Now;
return _cachedCandleList.Where(c => c.OpenTime >= beginDate && c.OpenTime <= endDate);
}
}
public ExchangeBoard GetSmartExchangeBoard()
{
var exchangeBoard = ExchangeBoard.GetOrCreateBoard("SMART", notExistingExchangeBoardCode => new ExchangeBoard
{
Exchange = new Exchange {Name = notExistingExchangeBoardCode + " Exchange", EngName = notExistingExchangeBoardCode + " Exchange", RusName = notExistingExchangeBoardCode + " по-русски" },
Code = notExistingExchangeBoardCode,
IsSupportAtomicReRegister = true,
IsSupportMarketOrders = true,
WorkingTime = ExchangeBoard.Nasdaq.WorkingTime
});
return exchangeBoard;
}
private List<Security> GetSecuritiesFromTxt()
{
var securities = new List<Security>();
string filepath = Directory.GetCurrentDirectory() + "\\YahooGoogleSourceTickers.txt";
var fileInfo = new FileInfo(filepath);
if (!fileInfo.Exists)
{
File.CreateText(filepath);
return securities;
}
StreamReader contractsFile = File.OpenText(filepath);
while (true)
{
string line= contractsFile.ReadLine();
if (line == null) break;
if(line.Length==0) break;
line = line.Trim();
string[] tickers = line.Split(' ');
foreach (var ticker in tickers)
{
var securityId = ticker.Trim();
var splitedId = securityId.Split('@');
var code = splitedId[0];
var exchangeBoardCode = splitedId[1];
var security = SecurityStorage.LoadBy("Id", securityId);
if(security==null)
{
var exchangeBoard = ExchangeBoard.GetOrCreateBoard(exchangeBoardCode, notExistingExchangeBoardCode => new ExchangeBoard
{
Exchange = new Exchange { Name = notExistingExchangeBoardCode + " Exchange", EngName = notExistingExchangeBoardCode + " Exchange", RusName = notExistingExchangeBoardCode + " по-русски"},
Code = notExistingExchangeBoardCode,
IsSupportAtomicReRegister = true,
IsSupportMarketOrders = true,
WorkingTime = ExchangeBoard.Nasdaq.WorkingTime
});
security = EntityFactory.Instance.CreateSecurity(securityId);
security.Id = securityId;
security.Type = SecurityTypes.Stock;
security.Currency = CurrencyTypes.USD;
security.Name = code;
security.ExchangeBoard = exchangeBoard;
security.MinStepPrice = 0.01m;
security.MinStepSize = 0.01m;
security.ShortName = code;
security.Code = code;
security.Class = "YahooGoogleSource";
security.ExtensionInfo = new Dictionary<object, object>();
SecurityStorage.Save(security);
}
securities.Add(security);
}
}
contractsFile.Close();
return securities;
}
public IEnumerable<Security> GetNewSecurities()
{
return GetSecuritiesFromTxt();
}
}
}