public override void OnTick(TickData td) { // ------------------------------------------------------------------- // 测试未成交的挂单 m_iTickCount++; PrintLine("TickCoount = " + m_iTickCount); // 买入测试头寸 if (m_iTickCount == 20) { double dOpenPrice = td.AskPrice1; int lots = 1; PrintLine("开仓"); OpenOrder(dOpenPrice, lots, 0, INSTRUMENT.PriceTick, EnumDirectionType.Buy); } // 平仓 if (m_iTickCount == 40) { double dClosePrice = 4007; PrintLine("平仓"); CloseLongPosition(dClosePrice, 1, 0, INSTRUMENT.PriceTick); } // 检查是否有超时未成交的挂单(平仓单) CheckAllOrder_Timeout(); // ------------------------------------------------------------------- }
public Policy(SecurityInfo si, Parameter rpp, PolicyProperties pp) { this.isSim = pp.IsSim; this.SecInfo = si; this.stockAccount = pp.Account; this.parameter = rpp; this.policyName = string.Format("{0}%{1}%{2}%{3}", PName, si.Code, parameter.Bz1, parameter.Bz2); this.startDate = rpp.StartDate; this.endDate = rpp.EndDate; this.inteval = rpp.Inteval; this.isReal = rpp.IsReal; this.policyguid = Guid.NewGuid(); initialDataReceiver(); InitialDataProcessor(); currentDay = DateTime.MinValue.Date; openPoints = new List <OpenPoint>(); IsSimulateFinished = false; //isOpened = false; if (rpp.save) { SaveParameter(rpp); } currentTick = new TickData(); lockObject = new object(); this.isLiveDataProcessor = true; MomList = new List <double>(); MomAbsList = new List <double>(); DieBars = new List <DieBar>(); tps = new List <TradePoints>(); lock_tps = new object(); eosusdtsi = GlobalValue.GetFutureByCodeAndMarket(parameter.Bz1, si.Market); eosbtcsi = GlobalValue.GetFutureByCodeAndMarket(parameter.Bz2, si.Market); }
public IKLineData GetKLineDataByTick(string code, DataReaderFactory dataReaderFactory, KLinePeriod period, IList <int> dates) { IKLineData lastKLineData = null; float lastPrice = -1; List <IKLineData> klineDataList = new List <IKLineData>(); for (int i = 0; i < dates.Count; i++) { int openDate = dates[i]; TickData tickdata = dataReaderFactory.TickDataReader.GetTickData(code, openDate); List <double[]> openTimes = dataProvider.GetOpenTime(code, openDate); KLineData klineData; if (tickdata != null) { klineData = DataTransfer_Tick2KLine.Transfer(tickdata, period, openTimes, lastPrice); klineDataList.Add(klineData); lastPrice = klineData.arr_end[klineData.Length - 1]; } else { klineData = GetEmptyDayKLineData(code, openDate, openTimes, dataReaderFactory.OpenDateReader, lastKLineData); klineDataList.Add(klineData); } lastKLineData = klineData; } if (klineDataList.Count == 0) { return(null); } IKLineData data = KLineData.Merge(klineDataList); return(data); }
public string Proceed() { string path = dataUpdateHelper.GetPath_KLineData(codeInfo.Code, date, klinePeriod); //if (!(codeInfo.Code.EndsWith("0000") || codeInfo.Code.EndsWith("MI"))) //if (!overwrite && File.Exists(path)) // return codeInfo.Code + "-" + date + "的K线数据已存在"; TickData tickData = (TickData)dataUpdateHelper.GetUpdatedTickData(codeInfo.Code, date); if (tickData == null) { tickData = (TickData)dataUpdateHelper.GetNewTickData(codeInfo.ServerCode, date); } //tick数据没有,则不生成对应K线数据 if (tickData == null) { string msg = codeInfo.Code + "-" + date + "的tick数据不存在"; LogHelper.Warn(GetType(), msg); return(msg); } IList <double[]> tradingPeriod = dataUpdateHelper.GetTradingTime(codeInfo.Code, date).TradingPeriods; //List<double[]> klineTimes = TradingTimeUtils.GetKLineTimeList_Full(tradingPeriod, KLinePeriod.KLinePeriod_1Minute); //timeListGetter.GetKLineTimeList(code, date, klinePeriod); this.klineData = DataTransfer_Tick2KLine.Transfer(tickData, tradingPeriod, KLinePeriod.KLinePeriod_1Minute, lastEndPrice, lastEndHold); CsvUtils_KLineData.Save(path, klineData); return("更新" + codeInfo.Code + "-" + date + "的" + klinePeriod + "K线完成"); }
public Policy(SecurityInfo si, Parameter rpp, PolicyProperties pp) { this.isSim = pp.IsSim; this.SecInfo = si; this.stockAccount = pp.Account; this.parameter = rpp; string name = PName; this.policyName = name; this.startDate = rpp.StartDate; this.endDate = rpp.EndDate; this.inteval = rpp.Inteval; this.isReal = rpp.IsReal; this.policyguid = Guid.NewGuid(); initialDataReceiver(); InitialDataProcessor(); currentDay = DateTime.Now; openPoints = new List <OpenPoint>(); IsSimulateFinished = false; if (rpp.save) { SaveParameter(rpp); } currentTick = new TickData(); this.isLiveDataProcessor = true; tps = new ConcurrentDictionary <Guid, PTradePoints>(); if (!parameter.DebugModel) { InitArgs(); } }
public Policy(SecurityInfo si, Parameter rpp, PolicyProperties pp) { this.isSim = pp.IsSim; this.SecInfo = si; this.stockAccount = pp.Account; this.parameter = rpp; this.policyName = PName + "-" + parameter.BarInteval + "-" + parameter.BarCount + "-" + parameter.TimeCycle.ToString() + "-" + parameter.ZhiYingBeiShu.ToString(); this.startDate = rpp.StartDate; this.endDate = rpp.EndDate; this.inteval = rpp.Inteval; this.isReal = rpp.IsReal; this.policyguid = Guid.NewGuid(); initialDataReceiver(); InitialDataProcessor(); currentDay = DateTime.Now; openPoints = new List <OpenPoint>(); IsSimulateFinished = false; //isOpened = false; if (rpp.save) { SaveParameter(rpp); } currentTick = new TickData(); this.isLiveDataProcessor = true; tps = new ConcurrentDictionary <Guid, PTradePoints>(); }
/// <summary> /// Tick method called on new tick of a TickerService /// </summary> /// <param name="exchange">Exchange that provided this tick</param> /// <param name="tickData">Information regarding tick</param> public void OnTick(Exchange exchange, TickData tickData) { Preconditions.CheckNotNull(exchange); Preconditions.CheckNotNull(tickData); Task.Run(() => ProcessTick(exchange, tickData)); }
private void Open(double price, double qty, OpenType ot, SecurityInfo si, TickData td, string tr) { PolicyResultEventArgs arg = new PolicyResultEventArgs(); arg.PolicyName1 = this.policyName; arg.SecInfo = si; arg.IsReal = currentTick.IsReal; OpenPoint op = new OpenPoint(); op.SecInfo = si; op.OpenTime = td.Time; op.OpenPrice = price; op.OpenType = ot; op.OpenQty = qty; op.DealQty = 0; op.Openop = true; op.FirstTradePriceType = parameter.EnterOrderPriceType; op.CancelLimitTime = parameter.EnterOrderWaitSecond; op.ReEnterPecentage = parameter.ReEnterPercent; TradePoints tp = new TradePoints(op, 0); tp.Fee = parameter.Fee; tp.TpRemark = tr; /////////////add////////////////////// tp.IsReal = arg.IsReal; this.tps.TryAdd(tp.TradeGuid, tp); arg.PairePoint = tp; arg.PolicyObject = this; arg.Tickdata = td; RaiseResult(arg); }
/// <summary> /// 预处理: /// 1.处理掉一些肯定不正确的数据,如提前3分钟开盘,然后到开盘都没有数据了。 /// /// 三种调整算法: /// 1.开始时间和结束时间都向前或向后移了基本相同的时间,整体迁移。 /// 2.开始时间或者结束时间出现大量重复,分两种情况:1.如果另一头出现了时间偏差,那么整体迁移;2.如果没有,则稀释 /// </summary> /// <param name="data"></param> /// <param name="openTime"></param> public void Adjust(TickData data, List <double[]> openTime) { //小于500条数据就不调整了 if (data.Length < 500) { return; } //2013年以后数据就不调整了 if (data.TradingDay > 20120000) { return; } //郑州20140827开始1分钟4个tick List <TickInfo_Period> periods = TickDataAnalysis.Analysis(data, openTime); if (periods[0].StartIndex == -1) { Adjust_Special(data, periods); return; } for (int i = 0; i < periods.Count; i++) { TickInfo_Period period = periods[i]; Adjust(data, period); } }
/// <summary> /// 调整规则: /// 1.如果该开始和结束 /// /// 逻辑: /// 1.是否有repeat,如果没有repeat直接移动时间 /// 2. /// </summary> /// <param name="data"></param> /// <param name="period"></param> private void Adjust(TickData data, TickInfo_Period period) { TickPeriodAdjustInfo adjustInfo = period.adjustInfo; if (!adjustInfo.StartRepeat && !adjustInfo.EndRepeat) { Adjust_NoRepeat(data, period, adjustInfo); Console.WriteLine("NoRepeat"); } else if (adjustInfo.StartRepeat && adjustInfo.EndRepeat) { Adjust_AllRepeat(data, period, adjustInfo); Console.WriteLine("AllRepeat"); } //有时间偏移,首先根据偏移位置移正,再处理repeat else if (adjustInfo.HasTimeOffset()) { Adjust_HasTimeOffsetAndRepeat(data, period, adjustInfo); Console.WriteLine("TimeOffset"); } //起始位置repeat,末尾offset,且正好合拍 else if (adjustInfo.HasRepeatOffset()) { Adjust_HasRepeatOffset(data, period, adjustInfo); } //该数据段没有偏移,只有repeat else { Adjust_NoOffsetOnlyRepeat(data, period, adjustInfo); } }
private void AdjustTime(TickData data, int startIndex, int endIndex, int offSecond) { for (int i = startIndex; i <= endIndex; i++) { data.arr_time[i] = TimeUtils.AddSeconds(data.arr_time[i], offSecond); } }
public Policy(SecurityInfo si, Parameter rpp, PolicyProperties pp) { this.isSim = pp.IsSim; this.SecInfo = si; this.stockAccount = pp.Account; this.parameter = rpp; this.policyName = PName; this.startDate = rpp.StartDate; this.endDate = rpp.EndDate; this.inteval = rpp.Inteval; this.isReal = rpp.IsReal; this.policyguid = Guid.NewGuid(); initialDataReceiver(); InitialDataProcessor(); currentDay = DateTime.Now; openPoints = new List <OpenPoint>(); IsSimulateFinished = false; //isOpened = false; if (rpp.save) { SaveParameter(rpp); } currentTick = new TickData(); this.isLiveDataProcessor = true; tps = new ConcurrentDictionary <Guid, TradePoints>(); SecondSi = GlobalValue.GetFutureByCodeAndMarket(parameter.SecondCode, parameter.SecondMarket); SecondTick = new TickData(); }
private void frm_TickReview_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Right) { if (doubleClicked && dataget) { if (e.KeyCode == Keys.Left) { if (lastindex >= 2) { lastindex--; chart_tick.ChartAreas[0].CursorX.Position = lastindex; } } else if (e.KeyCode == Keys.Right) { if (lastindex < this.chart_tick.Series["PointSerial"].Points.Count) { lastindex++; } chart_tick.ChartAreas[0].CursorX.Position = lastindex; } DataPoint dp = this.chart_tick.Series["PointSerial"].Points[lastindex - 1]; TimeSpan ts = TimeSpan.Parse(dp.AxisLabel); TickData td = th.ticks[ts]; this.uc_stockdetail.Update(td); this.lb_select.Text = string.Format("价格:{0},时间:{1},量:{2}", td.Last.ToString("0.00"), ts.ToString(), td.Volume); } } }
public void TestTickDataStore_Append() { TickData data = (TickData)MockDataLoader.GetTickData("m1005", 20100108); String path = TestCaseManager.GetTestCasePath(GetType(), "output_"); TickData d1 = data.SubData(0, 100); TickData d2 = data.SubData(101, data.Length - 1); TickDataStore_File_Single store = new TickDataStore_File_Single(path); store.Save(d1); TickDataStore_File_Single store2 = new TickDataStore_File_Single(path); store2.Append(d2); TickDataStore_File_Single store3 = new TickDataStore_File_Single(path); TickData data2 = store3.Load(); for (int i = 0; i < data.Length; i++) { data.BarPos = i; data2.BarPos = i; Assert.AreEqual(data.ToString(), data2.ToString()); } File.Delete(path); }
private async Task ProcessTick(Exchange exchange, TickData tickData) { try { // Update instruments var instrument = await _instrumentManager.Update(tickData); foreach (var botStrategy in _botStrategies) { // Verify if bot strategy was created for this exchange if (botStrategy.Exchange != exchange) { continue; } // Verify currency pair used by this bot strategy if (!botStrategy.CurrencyPair.Equals(tickData.CurrencyPair)) { continue; } // Send tick and other relevant information to strategy var marketApi = _marketApis.First(m => m.Exchange == botStrategy.Exchange); botStrategy.HandleTick(tickData, instrument, marketApi); } } catch (Exception e) { Logger.Error("Uncaught exception during tick processing.", e); } }
public void Run() { var timer = new Timer(1000); var current = 10.2; const int deltaChange = 50; const int maxRange = 400; var time = DateTime.Now; timer.Elapsed += (s, a) => { _lastTick = TickData.RandomATicks2(current, deltaChange, maxRange, 60, 30, time); var msg = BuildTransferMessage(_lastTick); SendToAll(msg); var msg2 = BuildTransferMessage(new ChatMessage { From = "System", To = "AllClients", Content = "Welcome", Time = DateTime.Now }); SendToAll(msg2); current = Math.Max(Math.Min(TickData.Random.NextDouble() > 0.5 ? -TickData.Random.NextDouble() * deltaChange + current : TickData.Random.NextDouble() * deltaChange + current, maxRange), 0); time = time.AddSeconds(20); }; timer.Start(); }
void LateUpdate() { if (_tickDataPool.Count == 0) { enabled = false; Debug.LogError("TimeAnalyzerEnd has worked for " + Time.frameCount + " frames. NOW STOP."); return; } int fps = (int)(1f / Time.deltaTime); // 超过 30 的,都按31处理。 if (fps > 30) { fps = 31; } float delta = Time.realtimeSinceStartup - TimeAnalyzerStart.Instance.LateUpdateTime; delta *= 1000; _currentTickData.LateUpdateCost = delta; _currentTickData.Fps = fps; _currentTickData.FrameCount = Time.frameCount; _currentTickData.TimeSinceLevelStartUp = Time.timeSinceLevelLoad; if (Time.deltaTime > 0) { TimeAnalyzerData.Instance.Save(fps, _currentTickData); } // 给下一帧准备 data。 _currentTickData = _tickDataPool.Dequeue(); }
public void LiveDataUpdate(TickData tickdata) { if (LiveData_Arrival != null) { LiveData_Arrival(this, LiveDataEventArgs.ConvertFromTickData(tickdata)); } }
public override Style SelectStyle(object item, DependencyObject container, ViewDefinitionBase activeViewDefinition) { TickData tickData = item as TickData; TimeRulerItem timeRulerItem = container as TimeRulerItem; if (tickData != null && timeRulerItem != null) { if (tickData.Type == TickType.Major) { if (tickData.Offset == TimeSpan.FromTicks(0)) { return(this.CustomMajorHorizontalTimeRulerItemStyle); } } } TimeRulerLine timeRulerLine = container as TimeRulerLine; if (timeRulerLine != null) { if (tickData.Offset == TimeSpan.FromTicks(0)) { return(this.CustomTimeRulerLineStyle); } } return(base.SelectStyle(item, container, activeViewDefinition)); }
public override void QueryQuote5(JObject jomsg) { #region 全量 TickData t = new TickData(); JObject jtick_depth = jomsg; string[] s = jtick_depth["ch"].ToString().Split(new char[] { '.' }); SecurityInfo si = DicSi[s[1]]; t.SecInfo = si; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); t.Time = startTime.AddMilliseconds(System.Convert.ToDouble(jtick_depth["ts"].ToString())); t.Name = si.Name; t.Code = si.Code; t.IsReal = true; t.Bid = System.Convert.ToDouble(jtick_depth["tick"]["bids"][0][0].ToString()); t.Ask = System.Convert.ToDouble(jtick_depth["tick"]["asks"][0][0].ToString()); double last = CurrentTicker.getCurrentTickerPrice(market + s[1]); t.Last = last == 0 ? (t.Bid + t.Ask) / 2 : last; for (int i = 0; i < 10; i++) { t.Bids[i] = System.Convert.ToDouble(jtick_depth["tick"]["bids"][i][0].ToString()); t.Bidsizes[i] = System.Convert.ToDouble(jtick_depth["tick"]["bids"][i][1].ToString()); t.Asks[i] = System.Convert.ToDouble(jtick_depth["tick"]["asks"][i][0].ToString()); t.Asksizes[i] = System.Convert.ToDouble(jtick_depth["tick"]["asks"][i][1].ToString()); } RaiseQueryData(t); if (si.Code == this._querySi.Code && si.Market == market) { RaiseTradeQueryData(t); } #endregion }
void api_tickdataArrived(TickData data, string instrument) { if (pairData.ContainsKey(instrument) == false) { pairData.Add(instrument, new TradingAPIPairData()); } int pos = api.getMarketPosition(instrument); if (pos != 0) { if (pos < 0 && pairData[instrument].lastShortPosition == null) { pairData[instrument].lastShortPosition = new TradePosition(0, data.bid, TradePosition.PositionType.shortPosition, instrument); } if (pos > 0 && pairData[instrument].lastLongPosition == null) { pairData[instrument].lastLongPosition = new TradePosition(0, data.ask, TradePosition.PositionType.longPosition, instrument); } } else // 0 = flat { pairData[instrument].lastShortPosition = null; pairData[instrument].lastLongPosition = null; } pairData[instrument].lastTickData = data; }
/// <summary> /// 行情返回回调 /// </summary> /// <param name="pDepthMarketData"></param> public void HandleOnRtnDepthMarketData(ThostFtdcDepthMarketDataField pDepthMarketData) { var tick = new TickData(); tick.gatewayName = this.Gateway.gatewayName; tick.symbol = pDepthMarketData.InstrumentID; tick.vtSymbol = pDepthMarketData.InstrumentID; tick.exchange = ""; tick.lastPrice = pDepthMarketData.LastPrice; tick.volume = pDepthMarketData.Volume; tick.openInterest = (int)pDepthMarketData.OpenInterest; tick.time = pDepthMarketData.UpdateTime; tick.openPrice = pDepthMarketData.OpenPrice; tick.highPrice = pDepthMarketData.HighestPrice; tick.lowPrice = pDepthMarketData.LowestPrice; tick.preClosePrice = pDepthMarketData.PreClosePrice; tick.upperLimit = pDepthMarketData.UpperLimitPrice; tick.lowerLimit = pDepthMarketData.LowerLimitPrice; tick.bidPrice1 = pDepthMarketData.BidPrice1; tick.bidVolume1 = pDepthMarketData.BidVolume1; tick.bidPrice2 = pDepthMarketData.BidPrice2; tick.bidVolume2 = pDepthMarketData.BidVolume2; tick.bidPrice3 = pDepthMarketData.BidPrice3; tick.bidVolume3 = pDepthMarketData.BidVolume3; tick.bidPrice4 = pDepthMarketData.BidPrice4; tick.bidVolume4 = pDepthMarketData.BidVolume4; tick.bidPrice5 = pDepthMarketData.BidPrice5; tick.bidVolume5 = pDepthMarketData.BidVolume5; ///行情推送 this.Gateway.MainController.MainEvent._OnTick.Invoke(tick); }
//鼠标放在chart中,会出现一个十字线 private void chart_Tick_MouseMove(object sender, MouseEventArgs e) { if (doubleClicked && dataget) { this.SuspendLayout(); int CursorX = e.X; //自定义 int CursorY = e.Y; //显示X轴的线 chart_tick.ChartAreas[0].CursorX.SetCursorPixelPosition(new PointF(CursorX, CursorY), true); //与Y轴的间隔 chart_tick.ChartAreas[0].CursorY.Interval = 0.01; //显示Y轴的线 chart_tick.ChartAreas[0].CursorY.SetCursorPixelPosition(new PointF(CursorX, CursorY), true); //获取X轴光标的位置 int index = System.Convert.ToInt32(chart_tick.ChartAreas[0].CursorX.Position); lastindex = index; DataPoint dp = this.chart_tick.Series["PointSerial"].Points[index - 1]; TimeSpan ts = TimeSpan.Parse(dp.AxisLabel); TickData td = th.ticks[ts]; //chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel(index, index, ts.ToString(), 0, LabelMarkStyle.Box)); this.uc_stockdetail.Update(td); this.lb_select.Text = string.Format("价格:{0},时间:{1},量:{2}", td.Last.ToString("0.00"), ts.ToString(), td.Volume); this.ResumeLayout(); } }
private static void setEndAdjustInfo(TickInfo_Period period, TickData data, int countEverySecond) { TickPeriodAdjustInfo adjustInfo = period.adjustInfo; int endIndex = period.EndIndex; int endRepeatIndex = FindEndTimeIndex(period, data); if (endRepeatIndex > 0) { int endRepeatTimes = FindEndRepeatTimes(endRepeatIndex, data); if (endRepeatTimes > countEverySecond) { adjustInfo.EndRepeatIndex = endRepeatIndex; adjustInfo.EndRepeatTimes = endRepeatTimes; adjustInfo.EndRepeat = true; } } double time = Math.Round(period.EndTime + data.TradingDay, 6); TimeSpan span = TimeUtils.Substract(data.arr_time[endIndex], time); int timeDif = span.Minutes * 60 + span.Seconds; //收盘晚收超过1分钟,认为该收盘时间可能有误 if (timeDif > 60) { adjustInfo.EndErrorData = true; } adjustInfo.EndOffset = timeDif; }
public void TestTickDataStore_Append(string uri) { string code = "m1005"; int day = 20100108; IDataStore dataStore = DataStoreFactory.CreateDataStore(uri); ITickDataStore tickDataStore = dataStore.CreateTickDataStore(); try { TickData data = (TickData)MockDataLoader.GetTickData(code, day); TickData d1 = data.SubData(0, 100); TickData d2 = data.SubData(101, data.Length - 1); tickDataStore.Save(code, day, d1); tickDataStore.Append(code, day, d2); TickData data2 = tickDataStore.Load(code, day); AssertUtils.AssertEqual_TickData(data, data2); } finally { tickDataStore.Delete(code, day); } }
private static void setAdjustInfo(List <TickInfo_Period> periods, TickData data, int countEverySecond) { for (int i = 0; i < periods.Count; i++) { setAdjustInfo(periods[i], data, countEverySecond); } }
private static void setStartAdjustInfo(TickInfo_Period period, TickData data, int countEverySecond) { TickPeriodAdjustInfo adjustInfo = period.adjustInfo; int startIndex = period.StartIndex; if (period.StartTime == 0.09 || period.StartTime == 0.21) { startIndex++; adjustInfo.IsOpen = true; } int startRepeatIndex = FindStartTimeIndex(period, data, startIndex); if (startRepeatIndex >= 0) { int startRepeatTimes = FindStartRepeatTimes(startRepeatIndex, data); if (startRepeatTimes > countEverySecond) { adjustInfo.StartRepeatIndex = startRepeatIndex; adjustInfo.StartRepeatTimes = startRepeatTimes; adjustInfo.StartRepeat = true; } } double time = Math.Round(period.StartTime + data.TradingDay, 6); TimeSpan span = TimeUtils.Substract(data.arr_time[startIndex], time); int timeDif = span.Minutes * 60 + span.Seconds; //开盘提前超过1分钟,认为该开盘时间可能有误 if (timeDif < -60) { adjustInfo.StartErrorData = true; } adjustInfo.StartOffset = timeDif; }
public Deal CalcDeal(Stock stock, TickData tickData) { Deal deal = new Deal(stock, Deal.ENone); if (mEStrategy == EMacd) { maBreak.CalcDeal(stock, tickData, deal); } else if (mEStrategy == EGrid) { grid.CalcDeal(stock, tickData, deal); } if (deal.eType == Deal.EBuy) { if (deal.buy_price <= 0 || deal.buy_shares <= 0) { Utility.Assert("Wrong Deal! deal.buy_price <= 0 || deal.buy_shares <= 0"); } } else if (deal.eType == Deal.ESell) { if (deal.sell_price <= 0 || deal.sell_shares <= 0) { Utility.Assert("Wrong Deal! deal.sell_price <= 0 || deal.sell_shares <= 0"); } if (deal.sell_shares > stock.position.shares_available) { Utility.Assert("Wrong Deal! deal.sell_shares > stock.position.shares_available"); } } return(deal); }
//定义一个带有参数的方法 public void DataArrival(TickData tickdata) { if (Data_Arrival != null) { Data_Arrival(this, tickdata); } }
public static List <TickInfo_Period> Analysis(TickData data, List <double[]> openTime, int countEverySecond) { List <TickInfo_Period> periods = GetPeriods(data, openTime); setAdjustInfo(periods, data, countEverySecond); return(periods); }
private void InsertTick(OleDbConnection dbConnection, OleDbTransaction transaction, TickData tick, string symbolId) { //DateTime long ticksPerSecond = 10000000; long ticks = tick.time.Ticks % ticksPerSecond; double seconds = ticks / (double)ticksPerSecond; string insertCommand = "INSERT INTO TickData ([SymbolId], [Time], [Seconds], [TickType], [Value], [Size]) VALUES (" + "'" + symbolId + "', " + "#" + tick.time.ToString() + "#, " + seconds.ToString() + ", " + ((int)tick.tickType).ToString() + ", " + tick.price.ToString() + ", " + tick.size.ToString() + ")"; OleDbCommand command = new OleDbCommand(insertCommand, dbConnection, transaction); command.ExecuteNonQuery(); }
public void SaveTick(Symbol symbol, TickData tick) { OleDbConnection dbConnection = new OleDbConnection(connectionString); dbConnection.Open(); InsertTick(dbConnection, null, tick, symbol.ToUniqueId()); if (dbConnection.State == ConnectionState.Open) { dbConnection.Close(); } }
public List<TickData> LoadTicks(Symbol symbol, DateTime startDate, DateTime endDate) { List<TickData> ret = new List<TickData>(); OleDbConnection dbConnection = new OleDbConnection(connectionString); dbConnection.Open(); string query = "SELECT * FROM TickData WHERE SymbolId = '" + symbol.ToUniqueId() + "' "; if (startDate != DateTime.MinValue) { query += "AND Time >= #" + startDate.ToShortDateString() + " " + startDate.ToShortTimeString() + "# "; } if (endDate != DateTime.MaxValue) { query += "AND Time <= #" + endDate.ToShortDateString() + " " + endDate.ToShortTimeString() + "# "; } query += "ORDER BY Time ASC, Seconds ASC"; OleDbCommand command = new OleDbCommand(query, dbConnection); OleDbDataReader reader = command.ExecuteReader(); while (reader.Read()) { TickData tick = new TickData(); tick.time = Convert.ToDateTime(reader["Time"]); tick.time = tick.time.AddSeconds(Convert.ToDouble(reader["Seconds"])); tick.tickType = (TickType)Convert.ToInt32(reader["TickType"]); tick.price = Convert.ToDouble(reader["Price"]); tick.size = Convert.ToUInt64(reader["Size"]); if (tick.time >= startDate) { ret.Add(tick); } } if (dbConnection.State == ConnectionState.Open) { dbConnection.Close(); } return ret; }
public void CEL_InstrumentSubscribed(string symbol1, ICQGInstrument instrument) { var sdata = new SymbolData(); try { var symbol = symbol1; var symbolLen = symbol.Length; sdata = new SymbolData("DM_" + symbol.Substring(5, symbolLen - 5).ToUpper()) { Instrument = instrument, Depth = GetDepthForSymbol(instrument.FullName) }; sdata.SymbolName = symbol; if (_addSybolsList.Count == 0) return; sdata.MsgObject = _addSybolsList[symbol]; var tdata = new TickData("TS_" + symbol.Substring(5, symbol.Length - 5).ToUpper(), symbol); DatabaseManager.DoSqlLive(QueryBuilder.createTable_tick(tdata.TableName)); DatabaseManager.DoSqlLive(QueryBuilder.createTable_dom(sdata.TableName)); if (_isMoreInfo) { sdata.MsgObject.Text = @"Subscribed. Waiting for data..."; sdata.MsgObject.ForeColor = Color.Green; } else { sdata.MsgObject.Text = @"Subscribed"; sdata.MsgObject.ForeColor = Color.Green; } instrument.DataSubscriptionLevel = eDataSubscriptionLevel.dsQuotesAndDOM; sdata.GroupId = 0; Console.WriteLine(@"dom:" + sdata.GroupId); if (!_symbolsTable.ContainsKey(instrument.FullName)) _symbolsTable.Add(instrument.FullName, sdata); tdata.GroupID = 0; if (!_tickTable.ContainsKey(instrument.FullName)) _tickTable.Add(instrument.FullName, tdata); if (!_subscribedSymbols.Exists(oo => oo == symbol1)) _subscribedSymbols.Add(symbol1); } catch (Exception ex) { Console.WriteLine(ex.Message); if (sdata.MsgObject != null) { sdata.MsgObject.ForeColor = Color.OrangeRed; sdata.MsgObject.Text = ex.Message; } } }
void iqFeed_IQUpdateMessage(object sender, IQSummaryEventArgs e) { if (!connected) { return; } TickData tick = new TickData(); List<TickData> ticks = new List<TickData>(); if (e.SummaryMessage.Level1.LastTradeTime == DateTime.MinValue) { Console.WriteLine("UpdateMessage DateTime.MinValue encountered for tickType " + e.SummaryMessage.Level1.UpdateType.ToString()); } switch (e.SummaryMessage.Level1.UpdateType) { case UpdateType.AskUpdate: tick.tickType = TickType.Ask; tick.size = (ulong)e.SummaryMessage.Level1.AskSize; tick.price = e.SummaryMessage.Level1.Ask; tick.time = e.SummaryMessage.Level1.LastTradeTime; ticks.Add(tick); break; case UpdateType.BidUpdate: tick.tickType = TickType.Bid; tick.size = (ulong)e.SummaryMessage.Level1.BidSize; tick.price = e.SummaryMessage.Level1.Bid; tick.time = e.SummaryMessage.Level1.LastTradeTime; ticks.Add(tick); // I never get an "AskUpdate" it appears, so I'm going to update // the bid and ask here TickData askTick = new TickData(); askTick.tickType = TickType.Ask; askTick.size = (ulong)e.SummaryMessage.Level1.AskSize; askTick.price = e.SummaryMessage.Level1.Ask; askTick.time = e.SummaryMessage.Level1.LastTradeTime; ticks.Add(askTick); break; case UpdateType.TradeUpdate: tick.tickType = TickType.Trade; tick.size = e.SummaryMessage.Level1.LastSize; tick.price = e.SummaryMessage.Level1.LastPrice; tick.time = e.SummaryMessage.Level1.LastTradeTime; ticks.Add(tick); break; default: break; } if (ticks.Count > 0) { Symbol symbol = symbolMapping[e.SummaryMessage.Level1.SymbolString]; ProcessTicks(symbol, ticks); } }
void oecClient_OnPriceChanged(OEC.API.Contract Contract, OEC.API.Price Price) { Symbol symbol = GetSymbolFromContract(Contract); if (symbol != null) { Trace.WriteLine(Contract.ToString() + " Price (" + symbol.ToString() + ")"); SymbolPrice symbolPrice = null; if (!_symbolPrices.TryGetValue(symbol, out symbolPrice)) { symbolPrice = new SymbolPrice(); symbolPrice.symbol = symbol; symbolPrice.TotalVol = Price.TotalVol; _symbolPrices[symbol] = symbolPrice; } TickData data; if (symbolPrice.AskPrice != Price.AskPrice || symbolPrice.AskSize != Price.AskVol) { symbolPrice.AskPrice = Price.AskPrice; symbolPrice.AskSize = Price.AskVol; data = new TickData(); data.time = Price.LastDateTime; data.tickType = TickType.Ask; data.price = Price.AskPrice; data.size = (UInt64)Price.AskVol; if (tickListener != null) { tickListener(symbol, data); } } if (symbolPrice.BidPrice != Price.BidPrice || symbolPrice.BidSize != Price.BidVol) { symbolPrice.BidPrice = Price.BidPrice; symbolPrice.BidSize = Price.BidVol; data = new TickData(); data.time = Price.LastDateTime; data.tickType = TickType.Bid; data.price = Price.BidPrice; data.size = (UInt64)Price.BidVol; if (tickListener != null) { tickListener(symbol, data); } } if (symbolPrice.TotalVol != Price.TotalVol || symbolPrice.LastPrice != Price.LastPrice) { data = new TickData(); data.time = Price.LastDateTime; data.tickType = TickType.Trade; data.price = Price.LastPrice; if (symbolPrice.TotalVol > Price.TotalVol) { data.size = 0; } else { data.size = (UInt64)(Price.TotalVol - symbolPrice.TotalVol); } symbolPrice.LastPrice = Price.LastPrice; symbolPrice.TotalVol = Price.TotalVol; if (tickListener != null) { tickListener(symbol, data); } } //data = new TickData(); //data.time = DateTime.Now; //data.tickType = TickType.LastSize; //data.value = Price.LastVol; //if (tickListener != null) //{ // tickListener(symbol, data); //} if (symbolPrice.LowPrice != Price.LowPrice) { symbolPrice.LowPrice = Price.LowPrice; data = new TickData(); data.time = Price.LastDateTime; data.tickType = TickType.LowPrice; data.price = Price.LowPrice; if (tickListener != null) { tickListener(symbol, data); } } if (symbolPrice.HighPrice != Price.HighPrice) { symbolPrice.HighPrice = Price.HighPrice; data = new TickData(); data.time = Price.LastDateTime; data.tickType = TickType.HighPrice; data.price = Price.HighPrice; if (tickListener != null) { tickListener(symbol, data); } } //data = new TickData(); //data.time = DateTime.Now; //data.tickType = TickType.OpenPrice; //data.value = Price.OpenPrice; //if (tickListener != null) //{ // tickListener(symbol, data); //} //data = new TickData(); //data.time = DateTime.Now; //data.tickType = TickType.AskSize; //data.value = Price.AskVol; //if (tickListener != null) //{ // tickListener(symbol, data); //} //data = new TickData(); //data.time = DateTime.Now; //data.tickType = TickType.BidSize; //data.value = Price.BidVol; //if (tickListener != null) //{ // tickListener(symbol, data); //} //data = new TickData(); //data.time = DateTime.Now; //data.tickType = TickType.Change; //data.value = Price.Change; //if (tickListener != null) //{ // tickListener(symbol, data); //} } else { //Trace.WriteLine(Contract.ToString() + " Price (unwatched)"); } }
private void CEL_InstrumentDOMChanged(CQGInstrument instrument, CQGDOMQuotes prevAsks, CQGDOMQuotes prevBids) { if (!_symbolsTable.Keys.Contains(instrument.FullName)) return; lock (_waitingLocker) { SymbolData symbolData = _symbolsTable[instrument.FullName]; if (symbolData.IsCanceled) { RemoveSymbol(instrument.FullName); return; } if (!(_cel.IsValid(instrument.DOMBids) && _cel.IsValid(instrument.DOMAsks))) return; if (!symbolData.FirstTride) { const double epsilon = 0.0000001; if ((Math.Abs(instrument.Trade.Price - symbolData.PrevTradePrice) > epsilon) || (Math.Abs(instrument.Trade.Volume - symbolData.PrevTradeVol) > epsilon)) { symbolData.IsNewTrade = true; if (_isMoreInfo) { if (symbolData.MsgObject.Parent.Parent != null) symbolData.MsgObject.Parent.Parent.BeginInvoke( new Action( () => symbolData.MsgObject.Text = @"DOMBids depth: " + instrument.DOMBids.Count + @" DOMAsks depth: " + instrument.DOMAsks.Count)); } } else { symbolData.IsNewTrade = false; } symbolData.PrevTradePrice = instrument.Trade.Price; symbolData.PrevTradeVol = instrument.Trade.Volume; symbolData.PrevTradeTime = instrument.Timestamp; } else { symbolData.PrevTradePrice = instrument.Trade.Price; symbolData.PrevTradeVol = instrument.Trade.Volume; symbolData.PrevTradeTime = instrument.Timestamp; } symbolData.FirstTride = false; double askPrice; double bidPrice; int askVol; int bidVol; var serverTimestamp = new DateTime(instrument.ServerTimestamp.Year, instrument.ServerTimestamp.Month, instrument.ServerTimestamp.Day, instrument.ServerTimestamp.Hour, instrument.ServerTimestamp.Minute, instrument.ServerTimestamp.Second, instrument.ServerTimestamp.Millisecond); var query = QueryBuilder.InsertData_dom(symbolData.TableName, instrument, Convert.ToInt32(symbolData.Depth), ++symbolData.GroupId, symbolData.IsNewTrade, _userName, out askPrice, out askVol, out bidPrice, out bidVol, serverTimestamp); if (instrument.ServerTimestamp < DateTime.Now.AddDays(-1)) return; var tickDomData = new TickData { AskPrice = askPrice, AskVolume = askVol, BidPrice = bidPrice, BidVolume = bidVol, SymbolName = symbolData.SymbolName, Timestamp = serverTimestamp, GroupID = symbolData.GroupId }; if (_onSymbolsList.Contains(instrument.FullName)) { DatabaseManager.AddToBuffer(query, true, tickDomData); if (_allowedSymbols.ContainsKey(_symbolsTable[instrument.FullName].SymbolName) || !DatabaseManager.CurrentDbIsShared) { if (DatabaseManager.CurrentDbIsShared && serverTimestamp < _allowedSymbols[instrument.FullName]) return; DatabaseManager.RunSQLLive(query, "InsertData", instrument.FullName); } } _symbolsTable[instrument.FullName] = symbolData; } }
void client_TickSize(object sender, TickSizeEventArgs e) { Symbol symbol = null; TickData data; GotTickData listener = null; lock (_lockObject) { symbol = idToSymbol(e.TickerId); if (symbol == null) { // Not a watched symbol return; } data = new TickData(); data.time = GetAccountTime("size tick"); data.size = AdjustVolume(symbol, (UInt64)e.Size); if (e.TickType == KRSTickType.BidSize) { // Bid size data.tickType = TickType.Bid; lastBidPrices.TryGetValue(symbol, out data.price); lastBidSizes[symbol] = data.size; } else if (e.TickType == KRSTickType.AskSize) { // Ask size data.tickType = TickType.Ask; lastAskPrices.TryGetValue(symbol, out data.price); lastAskSizes[symbol] = data.size; } else if (e.TickType == KRSTickType.LastSize) { // Last Size return; //data.tickType = TickType.LastSize; } else if (e.TickType == KRSTickType.Volume) { // Volume bool bSend = true; UInt64 lastVolume; TickData tradeTick = new TickData(); if (!lastVolumes.TryGetValue(symbol, out lastVolume)) { bSend = false; } else if ((UInt64)e.Size <= lastVolume) { bSend = false; } else if (!lastPrices.TryGetValue(symbol, out tradeTick.price)) { bSend = false; } //if (lastVolume == -1 || data.value <= lastVolume) //{ // bSend = false; //} if (bSend) { tradeTick.time = data.time; tradeTick.tickType = TickType.Trade; tradeTick.size = AdjustVolume(symbol, (UInt64)e.Size - lastVolume); //lastVolume = e.size * 100; if (tickListener != null) { tickListener(symbol, tradeTick); } } if (e.Size > 0) { lastVolumes[symbol] = (UInt64)e.Size; } data.tickType = TickType.DailyVolume; } else { // Unknown tick type return; } listener = tickListener; } if (listener != null) { listener(symbol, data); } }
static void Cel_InstrumentDOMChanged(CQGInstrument instrument, CQGDOMQuotes prev_asks, CQGDOMQuotes prev_bids) { var symbolData = _symbolsInProgress.Find(oo => oo.Name == instrument.FullName); if (symbolData == null) return; lock (_waitingLocker) { var domData = symbolData.DomData; if (!(Cel.IsValid(instrument.DOMBids) && Cel.IsValid(instrument.DOMAsks))) return; if (!domData.FirstTride) { const double epsilon = 0.0000001; if ((Math.Abs(instrument.Trade.Price - domData.PrevTradePrice) > epsilon) || (Math.Abs(instrument.Trade.Volume - domData.PrevTradeVol) > epsilon)) { domData.IsNewTrade = true; //if (_isMoreInfo) //{ // if (symbolData.MsgObject.Parent.Parent != null) // symbolData.MsgObject.Parent.Parent.BeginInvoke( // new Action( // () => // symbolData.MsgObject.Text = // @"DOMBids depth: " + instrument.DOMBids.Count + @" DOMAsks depth: " + // instrument.DOMAsks.Count)); //} } else { domData.IsNewTrade = false; } domData.PrevTradePrice = instrument.Trade.Price; domData.PrevTradeVol = instrument.Trade.Volume; domData.PrevTradeTime = instrument.Timestamp; } else { domData.PrevTradePrice = instrument.Trade.Price; domData.PrevTradeVol = instrument.Trade.Volume; domData.PrevTradeTime = instrument.Timestamp; } domData.FirstTride = false; double askPrice; double bidPrice; int askVol; int bidVol; var serverTimestamp = new DateTime(instrument.ServerTimestamp.Year, instrument.ServerTimestamp.Month, instrument.ServerTimestamp.Day, instrument.ServerTimestamp.Hour, instrument.ServerTimestamp.Minute, instrument.ServerTimestamp.Second, instrument.ServerTimestamp.Millisecond); var query = QueryBuilder.InsertData_dom(domData.TableName, instrument, Convert.ToInt32(symbolData.Depth), ++domData.GroupId, domData.IsNewTrade, _userName, out askPrice, out askVol, out bidPrice, out bidVol, serverTimestamp); if (instrument.ServerTimestamp < DateTime.Now.AddDays(-1)) return; var tickDomData = new TickData { AskPrice = askPrice, AskVolume = askVol, BidPrice = bidPrice, BidVolume = bidVol, SymbolName = domData.SymbolName, Timestamp = serverTimestamp, GroupID = domData.GroupId }; ClientDatabaseManager.AddToBuffer(query, true, tickDomData); if (!ClientDatabaseManager.CurrentDbIsShared || symbolData.CanInsert) { //if (DatabaseManager.CurrentDbIsShared && serverTimestamp < _allowedSymbols[instrument.FullName])return; ClientDatabaseManager.RunSQLLive(query, "InsertData", instrument.FullName); } symbolData.DomData = domData; } }
void iqFeed_IQSummaryMessage(object sender, IQSummaryEventArgs e) { if (!connected) { return; } TickData bid = new TickData(); TickData ask = new TickData(); List<TickData> ticks = new List<TickData>(); bid.tickType = TickType.Bid; ask.tickType = TickType.Ask; bid.price = e.SummaryMessage.Level1.Bid; ask.price = e.SummaryMessage.Level1.Ask; bid.size = (ulong)e.SummaryMessage.Level1.BidSize; ask.size = (ulong)e.SummaryMessage.Level1.AskSize; if (e.SummaryMessage.Level1.LastTradeTime == DateTime.MinValue) { Console.WriteLine("Summary Message DateTime.MinValue encountered for tickType " + e.SummaryMessage.Level1.UpdateType.ToString()); } if (e.SummaryMessage.Level1.LastTradeTime != DateTime.MinValue) { bid.time = ask.time = e.SummaryMessage.Level1.LastTradeTime; lastGoodTickTime = e.SummaryMessage.Level1.LastTradeTime; } else { bid.time = ask.time = lastGoodTickTime; } TickData totalVolume = new TickData(); totalVolume.size = e.SummaryMessage.Level1.TotalVolume; totalVolume.time = lastGoodTickTime; totalVolume.tickType = TickType.DailyVolume; TickData lastPrice = new TickData(); lastPrice.tickType = TickType.Trade; lastPrice.time = lastGoodTickTime; lastPrice.price = e.SummaryMessage.Level1.LastPrice; TickData prevClose = new TickData(); prevClose.tickType = TickType.PreviousClose; prevClose.time = lastGoodTickTime; prevClose.price = e.SummaryMessage.Level1.LastPrice - e.SummaryMessage.Level1.TodaysChange; TickData open = new TickData(); open.tickType = TickType.OpenPrice; open.time = lastGoodTickTime; open.price = e.SummaryMessage.Level1.Open; TickData high = new TickData(); high.tickType = TickType.HighPrice; high.time = lastGoodTickTime; high.price = e.SummaryMessage.Level1.High; TickData low = new TickData(); low.tickType = TickType.LowPrice; low.price = e.SummaryMessage.Level1.Low; low.time = lastGoodTickTime; ticks.Add(bid); ticks.Add(ask); ticks.Add(totalVolume); ticks.Add(lastPrice); ticks.Add(prevClose); ticks.Add(open); ticks.Add(high); ticks.Add(low); Symbol symbol = symbolMapping[e.SummaryMessage.Level1.SymbolString]; ProcessTicks(symbol, ticks); }
public void SaveTick(Symbol symbol, TickData tick) { SqlConnection dbConnection = null; try { dbConnection = new SqlConnection(ConnectionString); dbConnection.Open(); InsertTick(dbConnection, null, tick, symbol.ToUniqueId()); } finally { if (dbConnection != null) { dbConnection.Close(); } } }
void client_TickPrice(object sender, TickPriceEventArgs e) { Symbol symbol = null; TickData data; GotTickData listener = null; lock (_lockObject) { symbol = idToSymbol(e.TickerId); if (symbol == null) { // Not a watched symbol return; } data = new TickData(); data.time = GetAccountTime("price tick"); data.price = (double)e.Price; if (data.price <= 0 && symbol.AssetClass != AssetClass.Future && symbol.AssetClass != AssetClass.Option && symbol.AssetClass != AssetClass.FuturesOption) { // GBP/USD was getting bid and ask ticks with a price of zero, so ignore these. // 4/20/2010 - A user reported various forex symbols were getting negative prices, so these will also be ignored return; } if (e.TickType == KRSTickType.BidPrice) { // Bid price data.tickType = TickType.Bid; lastBidSizes.TryGetValue(symbol, out data.size); lastBidPrices[symbol] = (double)e.Price; } else if (e.TickType == KRSTickType.AskPrice) { // Ask price data.tickType = TickType.Ask; lastAskSizes.TryGetValue(symbol, out data.size); lastAskPrices[symbol] = (double)e.Price; } else if (e.TickType == KRSTickType.LastPrice) { // Last price; lastPrices[symbol] = (double)e.Price; if (symbol.AssetClass == AssetClass.Index) { // Indexes don't come with volume ticks, so we can // force this tick through instead of trying to match // it up with a volume tick. data.tickType = TickType.Trade; } else { return; } } else if (e.TickType == KRSTickType.HighPrice) { // High price data.tickType = TickType.HighPrice; } else if (e.TickType == KRSTickType.LowPrice) { // Low price data.tickType = TickType.LowPrice; } else if (e.TickType == KRSTickType.ClosePrice) { // Close price data.tickType = TickType.PreviousClose; } else if (e.TickType == Krs.Ats.IBNet.TickType.OpenPrice) { data.tickType = TickType.OpenPrice; } else { // Unknown tick type return; } listener = tickListener; } if (data.tickType != TickType.NotSet && listener != null) { listener(symbol, data); } }
public List<TickData> LoadTicks(Symbol symbol, DateTime startDate, DateTime endDate) { List<TickData> ret = new List<TickData>(); SqlConnection dbConnection = null; try { dbConnection = new SqlConnection(ConnectionString); dbConnection.Open(); string query = "SELECT * FROM TickData WHERE SymbolId = @SymbolId"; // Can't check for DateTime.MinValue because they may ask for DateTime.MinValue + their frequency // in which case, the previous check would fail. See bug ID 1135. if (startDate > new DateTime(1, 1, 1753)) { query += " AND [Time] >= @StartDate "; } if (endDate != DateTime.MaxValue) { query += " AND [Time] <= @EndDate "; } query += " ORDER BY Time ASC, Seconds ASC"; SqlCommand command = new SqlCommand(query, dbConnection); SqlParameter symbolIdParam = new SqlParameter("@SymbolID", SqlDbType.NVarChar, 50); symbolIdParam.Value = symbol.ToUniqueId(); command.Parameters.Add(symbolIdParam); if (startDate.Year > 1) { SqlParameter param = new SqlParameter("@StartDate", SqlDbType.DateTime); param.Value = startDate; command.Parameters.Add(param); } if (endDate != DateTime.MaxValue) { SqlParameter param = new SqlParameter("@EndDate", SqlDbType.DateTime); param.Value = endDate; command.Parameters.Add(param); } SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { TickData tick = new TickData(); tick.time = Convert.ToDateTime(reader["Time"]); tick.time = tick.time.AddSeconds(Convert.ToDouble(reader["Seconds"])); tick.tickType = (TickType)Convert.ToInt32(reader["TickType"]); tick.price = Convert.ToDouble(reader["Price"]); tick.size = Convert.ToUInt64(reader["Size"]); if (tick.time >= startDate) { ret.Add(tick); } } } finally { if (dbConnection != null) { dbConnection.Close(); } } return ret; }
private void InsertTick(SqlConnection dbConnection, SqlTransaction transaction, TickData tick, string symbolId) { // Looks like sometimes we got a MinValue on the date ?? // Not sure if its us or the data provider, but maybe we should // handle it gracefully if it gets to this point. if (tick.time == DateTime.MinValue) { tick.time = DateTime.Now; } long ticksPerSecond = 10000000; long ticks = tick.time.Ticks % ticksPerSecond; double seconds = ticks / (double)ticksPerSecond; string insertCommand = "INSERT INTO TickData ([SymbolId], [Time], [Seconds], [TickType], [Price], [Size]) VALUES (@SymbolID, @Time, @Seconds, @TickType, @Price, @Size)"; SqlCommand command = new SqlCommand(insertCommand, dbConnection, transaction); SqlParameter param = new SqlParameter("@SymbolID", SqlDbType.NVarChar, 50); param.Value = symbolId; command.Parameters.Add(param); param = new SqlParameter("@Time", SqlDbType.DateTime); param.Value = tick.time; command.Parameters.Add(param); param = new SqlParameter("@Seconds", SqlDbType.BigInt); param.Value = seconds; command.Parameters.Add(param); param = new SqlParameter("@TickType", SqlDbType.Int); param.Value = tick.tickType; command.Parameters.Add(param); param = new SqlParameter("@Price", SqlDbType.Float); param.Value = tick.price; command.Parameters.Add(param); param = new SqlParameter("@Size", SqlDbType.BigInt); param.Value = tick.size; command.Parameters.Add(param); command.ExecuteNonQuery(); }