using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using StockSharp.Algo;
using StockSharp.Algo.Candles;
using StockSharp.Algo.Storages;
using StockSharp.BusinessEntities;
using StockSharp.Logging;
using Candle = VGn.Robot.Candle;
namespace VGn.Robot
{
/// <summary>
/// Класс предварительной подготовки данных
/// </summary>
public class DataLoader : BaseLogReceiver
{
LogManager logManager;
IMarketDataStorage<Trade> tradesStorage;
Security security;
public DataLoader()
{
logManager = new LogManager();
logManager.Listeners.Add(new FileLogListener(@"c:\candles.log"));
logManager.Sources.Add(this);
var path = Path.GetFullPath(@"c:\Hydra\");
var storageRegistry = new StorageRegistry
{
// изменяем путь, используемый по умолчанию
DefaultDrive = new LocalMarketDataDrive(path)
};
security = GenerateSecurity();
tradesStorage = storageRegistry.GetTradeStorage(security);
}
public CandleSeries CreateTimeSeries(TimeSpan frameSize)
{
var candleFrame = "TimeFrameCandle";
var candleFrameType = Type.GetType(string.Format("StockSharp.Algo.Candles.{0}, StockSharp.Algo", candleFrame), true);
return new CandleSeries(
candleFrameType, security, frameSize) { WorkingTime = ExchangeBoard.Forts.WorkingTime };
}
private static readonly string[] Mounths = { "H", "M", "U", "Z", }; // последовательность важна для правильной генерации имен фьючерсов
public const int FIRST_YEAR = 2009;
//todo: загрузка таблицы дат экспирации из файла
public Dictionary<int, List<int>> FortsExpirationTable =
new Dictionary<int, List<int>>()
{
{9, new List<int> {13,11,14,14}},
{10, new List<int> {12,11,15,15}},
{11, new List<int> {15,15,15,15}},
{12, new List<int> {15,15,17,17}},
{13, new List<int> {15,17,16,16}},
{14, new List<int> {17,16,15,15}},
{15, new List<int> {16,15,15,15}},
};
/// <summary>
/// Создание склеенного фьючерса RI
/// </summary>
/// <returns></returns>
public ContinuousSecurity GenerateSecurity()
{
var prefix = "RI";
var securityName = prefix + "@CONTINIOUS";
var result = new ContinuousSecurity
{
Id = securityName,
Code = securityName,
Name = "ContinuousSecurity for " + securityName,
Board = ExchangeBoard.Forts,
};
for (var year = FIRST_YEAR; year < 2015; year++)
{
for (var i = 0; i < 4; i++)
{
var yearPart = year % 10; // тут получаем последнюю цифру года
var mounth = i * 3 + 3;
var mounthPart = Mounths[i]; // тут выбирается индекс, показывающий месяц
var id = prefix + mounthPart + yearPart + "@FORTS";
var code = prefix + "-" + (yearPart) + "." + (mounth);
var security = new Security
{
Id = id,
Code = code,
Name =
"ContinuousSecurity for " + prefix + " expiration in " + mounth + "." +
year,
Board = ExchangeBoard.Forts,
};
var expiration = new DateTime(year, mounth, FortsExpirationTable[year - 2000][i]);
result.ExpirationJumps.Add(security, expiration);
}
}
return result;
}
/// <summary>
/// Трансформация свечей в короткую форму
/// </summary>
public IEnumerable<Candle> TransformCandles(CandleSeries series, DateTime startTime, DateTime stopTime)
{
var trades = tradesStorage.Load(startTime, stopTime);
var id = 1;
foreach (var candle in trades.ToCandles(series))
{
var mycandle = new Candle
{
Close = candle.ClosePrice,
High = candle.HighPrice,
Id = id++,
Low = candle.LowPrice,
Open = candle.OpenPrice,
Volume = candle.TotalVolume,
Time = candle.CloseTime
};
yield return mycandle;
//CandleList.Add(mycandle);
}
//this.AddInfoLog("Количество свечек {0}", CandleList.Count);
}
/// <summary>
/// Загрузка готовых свечек из файла
/// с целью исключения повторного формирования списка свечей
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static T GetFromFile<T>(string fileName) where T : class
{
if (!File.Exists(fileName))
return null;
//if (File.GetLastWriteTime(fileName).Date.AddDays(1) < DateTime.Now)
//{
// File.Delete(fileName);
// return null;
//}
using (Stream stream = File.Open(fileName, FileMode.Open))
{
var bin = new BinaryFormatter();
var list = (T)bin.Deserialize(stream);
return list;
}
}
/// <summary>
/// Сохранение готовых свечек в файл
/// с целью исключения повторного формирования списка свечей в тот же день
/// </summary>
/// <param name="fileName"></param>
/// <param name="list"></param>
public static void WriteToFile<T>(string fileName, T list)
{
var v = Path.GetPathRoot(fileName);
var c = Directory.Exists(v);
using (Stream stream = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.Read))
{
var bin = new BinaryFormatter();
bin.Serialize(stream, list);
}
}
}
}