PageRenderTime 40ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/JAhlen/StockInsightGraphical/MainWnd.cs

#
C# | 316 lines | 293 code | 12 blank | 11 comment | 0 complexity | 78a896c5e25df2502a84b31cc7554889 MD5 | raw file
Possible License(s): Apache-2.0
  1. // StockInsight
  2. // - Microsoft StreamInsight application examples
  3. // (C) Johan Ĺhlén, 2010. Released under Apache License 2.0 (http://www.apache.org/licenses/)
  4. using System;
  5. using System.Collections.Generic;
  6. using System.ComponentModel;
  7. using System.Data;
  8. using System.Drawing;
  9. using System.Linq;
  10. using System.Text;
  11. using System.IO;
  12. using System.Windows.Forms;
  13. using System.ServiceModel;
  14. using System.ServiceModel.Channels;
  15. using Microsoft.ComplexEventProcessing;
  16. using Microsoft.ComplexEventProcessing.Linq;
  17. using AdvantIQ.StockInsight.InputAdapters;
  18. using AdvantIQ.StockInsight.OutputAdapters;
  19. namespace AdvantIQ.StockInsight
  20. {
  21. public partial class MainWnd : Form
  22. {
  23. /// <summary>
  24. /// SET THIS TO THE NAME OF YOUR STREAMINSIGHT INSTANCE, OR BLANK TO AUTODETECT
  25. /// </summary>
  26. private const string InstanceName = "Default";
  27. public List<Source> Sources;
  28. public Dictionary<string, QueryTemplate> Queries;
  29. private Microsoft.ComplexEventProcessing.Application application;
  30. public MainWnd()
  31. {
  32. InitializeComponent();
  33. var instanceName = !string.IsNullOrEmpty(InstanceName) ? InstanceName : StreamInsightSetupInfo.EnumerateInstances()[0];
  34. Server server;
  35. try
  36. {
  37. server = Server.Create(instanceName);
  38. }
  39. catch
  40. {
  41. Console.WriteLine("Could not create StreamInsight instance. Please open MainWnd.cs and check InstanceName.");
  42. return;
  43. }
  44. application = server.CreateApplication("StockInsightGraphical");
  45. InputAdapter inputAdapter = application.CreateInputAdapter<StockQuoteInputFactory>("StockQuoteInput", "Description...");
  46. OutputAdapter outputAdapter = application.CreateOutputAdapter<StockSignalOutputFactory>("StockSignalOutput", "Description...");
  47. // Initialize drop down lists and properties for queries and sources
  48. InitQueries();
  49. InitSources();
  50. stockGraph1.EnableWCF();
  51. }
  52. /// <summary>
  53. /// Inits the user selection of source
  54. /// </summary>
  55. private void InitSources()
  56. {
  57. Sources = new List<Source>();
  58. // Determine path for historical data
  59. var dataPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\HistoricalData\\";
  60. Sources.Add(new Source
  61. {
  62. Name = "NASDAQ Composite",
  63. Config = new StockQuoteInputConfig
  64. {
  65. Filename = dataPath + "nasdaq_2009.csv",
  66. ID = "NASDAQ-USD",
  67. ColumnNames = new string[] { "Adj Close" }
  68. },
  69. MinValue = 1200,
  70. MaxValue = 3000,
  71. GridValueSize = 200
  72. });
  73. Sources.Add(new Source
  74. {
  75. Name = "Nokia",
  76. Config = new StockQuoteInputConfig
  77. {
  78. Filename = dataPath + "nokia_2009.csv",
  79. ID = "NOKIA-USD",
  80. ColumnNames = new string[] { "Adj Close" }
  81. },
  82. MinValue = 6,
  83. MaxValue = 20,
  84. GridValueSize = 2
  85. });
  86. Sources.Add(new Source
  87. {
  88. Name = "Ericsson",
  89. Config = new StockQuoteInputConfig
  90. {
  91. Filename = dataPath + "eric_b_usd_2009.csv",
  92. ID = "ERIC-USD",
  93. ColumnNames = new string[] { "Adj Close" }
  94. },
  95. MinValue = 6,
  96. MaxValue = 14,
  97. GridValueSize = 1
  98. });
  99. SourceDpl.Items.Clear();
  100. foreach (var source in Sources)
  101. SourceDpl.Items.Add(source.Name);
  102. //SourceDpl.Items.Add("Browse...");
  103. SourceDpl.SelectedIndex = 0;
  104. }
  105. /// <summary>
  106. /// Inits the user selection of query
  107. /// </summary>
  108. private void InitQueries()
  109. {
  110. Queries = new Dictionary<string, QueryTemplate>();
  111. Queries.Add("Bollinger Bands", AddBollingerBandsQuery());
  112. Queries.Add("Follow the Trend", AddFollowTheTrendQuery());
  113. Queries.Add("Sell on Fridays", AddSellOnFridaysQuery());
  114. QueryDpl.Items.Clear();
  115. foreach (var query in Queries.Keys)
  116. QueryDpl.Items.Add(query);
  117. QueryDpl.SelectedIndex = 0;
  118. }
  119. /// <summary>
  120. /// Example query
  121. /// </summary>
  122. /// <param name="input"></param>
  123. /// <returns></returns>
  124. private QueryTemplate AddFollowTheTrendQuery()
  125. {
  126. CepStream<StockQuote> input = CepStream<StockQuote>.Create("input");
  127. var avg = (from w in input.AlterEventDuration(e => TimeSpan.FromDays(1)).HoppingWindow(TimeSpan.FromDays(5), TimeSpan.FromDays(1), HoppingWindowOutputPolicy.ClipToWindowEnd)
  128. select new
  129. {
  130. Value = w.Avg(e => e.Value),
  131. }).AlterEventLifetime(e => e.StartTime.AddDays(4), e => TimeSpan.FromTicks(1));;
  132. var query = from e1 in input
  133. from e2 in avg
  134. select new StockSignal
  135. {
  136. StockID = e1.StockID,
  137. Value = e1.Value,
  138. BuySignal = e1.Value > e2.Value,
  139. TimeStamp = e1.TimeStamp
  140. };
  141. return application.CreateQueryTemplate<StockSignal>("FollowTheTrend", "...", query);
  142. }
  143. /// <summary>
  144. /// Example query
  145. /// </summary>
  146. /// <param name="input"></param>
  147. /// <returns></returns>
  148. private QueryTemplate AddSellOnFridaysQuery()
  149. {
  150. CepStream<StockQuote> input = CepStream<StockQuote>.Create("input");
  151. var query = from e in input
  152. select new StockSignal
  153. {
  154. StockID = e.StockID,
  155. Value = e.Value,
  156. BuySignal = ((e.TimeStamp - new DateTime(2010,05,14,0,0,0,0,DateTimeKind.Utc)).Days % 7 != 0), // The 14th of May 2010 is a Friday
  157. TimeStamp = e.TimeStamp
  158. };
  159. return application.CreateQueryTemplate<StockSignal>("SellOnFridays", "...", query);
  160. }
  161. /// <summary>
  162. /// Example query
  163. /// </summary>
  164. /// <param name="input"></param>
  165. /// <returns></returns>
  166. private QueryTemplate AddBollingerBandsQuery()
  167. {
  168. CepStream<StockQuote> input = CepStream<StockQuote>.Create("input");
  169. var bb = (from w in input.AlterEventDuration(e => TimeSpan.FromDays(1)).HoppingWindow(TimeSpan.FromDays(20), TimeSpan.FromDays(1), HoppingWindowOutputPolicy.ClipToWindowEnd)
  170. select w.BollingerBands()).AlterEventLifetime(e => e.StartTime.AddDays(19), e => TimeSpan.FromTicks(1));
  171. var query = from e1 in input
  172. from e2 in bb
  173. select new StockSignal
  174. {
  175. StockID = e1.StockID,
  176. Value = e1.Value,
  177. BuySignal = e2.BandWidth * 100 > 5,
  178. TimeStamp = e1.TimeStamp
  179. };
  180. return application.CreateQueryTemplate<StockSignal>("BollingerBands", "...", query);
  181. }
  182. /// <summary>
  183. /// Event handler for Run button
  184. /// </summary>
  185. /// <param name="sender"></param>
  186. /// <param name="eventArgs"></param>
  187. private void RunBtn_Click(object sender, EventArgs eventArgs)
  188. {
  189. // Get selected source and query
  190. Source source;
  191. if (SourceDpl.SelectedItem.ToString() == "Browse...")
  192. {
  193. source = BrowseAndReadSource();
  194. }
  195. else
  196. {
  197. source = Sources.Single(s => s.Name == SourceDpl.SelectedItem.ToString());
  198. }
  199. var queryTemplate = Queries[QueryDpl.SelectedItem.ToString()];
  200. // Initialize display properties
  201. stockGraph1.StartDate = new DateTime(2009, 01, 01);
  202. stockGraph1.EndDate = new DateTime(2009, 12, 31);
  203. stockGraph1.GridDateSize = 30;
  204. stockGraph1.ValueLabelFormat = "f0";
  205. stockGraph1.DateLabelFormat = "dd MMM";
  206. stockGraph1.MaxValue = source.MaxValue;
  207. stockGraph1.MinValue = source.MinValue;
  208. stockGraph1.GridValueSize = source.GridValueSize;
  209. // Clear previous stock signals
  210. stockGraph1.Clear();
  211. // Instantiate query
  212. var queryBinder = new QueryBinder(queryTemplate);
  213. queryBinder.BindProducer<StockQuote>("input", application.InputAdapters["StockQuoteInput"], source.Config, EventShape.Point);
  214. queryBinder.AddConsumer<StockQuote>("output", application.OutputAdapters["StockSignalOutput"], new StockSignalOutputConfig(), EventShape.Point, StreamEventOrder.ChainOrdered);
  215. var query = application.CreateQuery(queryTemplate.ShortName + " " + Guid.NewGuid().ToString(), "Description...", queryBinder);
  216. backgroundWorker1.RunWorkerAsync(query);
  217. }
  218. private Source BrowseAndReadSource()
  219. {
  220. var dlg = new OpenFileDialog();
  221. if (dlg.ShowDialog() != DialogResult.OK)
  222. return null;
  223. return new Source
  224. {
  225. Name = Path.GetFileNameWithoutExtension(dlg.FileName),
  226. Config = new StockQuoteInputConfig { Filename = dlg.FileName,
  227. ID = Path.GetFileNameWithoutExtension(dlg.FileName),
  228. ColumnNames = new string[] { "Adj Close" }
  229. },
  230. MinValue = 0,
  231. MaxValue = 3000,
  232. GridValueSize = 300
  233. };
  234. }
  235. /// <summary>
  236. /// Event handler
  237. /// </summary>
  238. /// <param name="sender"></param>
  239. /// <param name="e"></param>
  240. private void MainWnd_Load(object sender, EventArgs e)
  241. {
  242. }
  243. /// <summary>
  244. /// Event handler
  245. /// </summary>
  246. /// <param name="sender"></param>
  247. /// <param name="e"></param>
  248. private void MainWnd_SizeChanged(object sender, EventArgs e)
  249. {
  250. this.Invalidate();
  251. }
  252. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  253. {
  254. var query = e.Argument as Query;
  255. query.Start();
  256. DiagnosticView dv;
  257. do
  258. {
  259. System.Threading.Thread.Sleep(100);
  260. dv = application.Server.GetDiagnosticView(query.Name);
  261. } while (dv[DiagnosticViewProperty.QueryState] as string == "Running");
  262. query.Stop();
  263. query.Delete();
  264. ChannelFactory<IStockGraphCtl> stockGraphCtlFactory =
  265. new ChannelFactory<IStockGraphCtl>(new NetNamedPipeBinding(),
  266. new EndpointAddress("net.pipe://localhost/StockGraphCtl"));
  267. var stockGraphCtl = stockGraphCtlFactory.CreateChannel();
  268. stockGraphCtl.Display();
  269. }
  270. }
  271. }