예제 #1
0
        static void wc_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
            string          res = string.Empty;
            BarListDownload bld = (BarListDownload)e.UserState;

            if (!bld.isValid)
            {
                return;
            }
            if (e.Cancelled || (e.Error != null))
            {
                if (bld.AppendAMEXonFail)
                {
                    DayFromGoogleAsync(bld.Symbol + AMEX, bld.DoResults, false);
                    return;
                }
                bld.DoResults(new BarListImpl(BarInterval.Day, bld.Symbol));
                return;
            }
            res = e.Result;
            BarListImpl bl = new BarListImpl(BarInterval.Day, bld.Symbol);

            string[] line = res.Split(Environment.NewLine.ToCharArray());
            for (int i = line.Length - 1; i > 0; i--)
            {
                if (line[i] != "")
                {
                    addbar(bl, BarImpl.FromCSV(line[i]), 0);
                }
            }
            bld.DoResults(bl);
        }
예제 #2
0
        private static BarList DayFromURL(string url, string Symbol, bool appendAMEXonfail)
        {
            BarListImpl bl = new BarListImpl(BarInterval.Day, Symbol);

            if (Symbol == "")
            {
                return(bl);
            }
            System.Net.WebClient wc = new System.Net.WebClient();
            string res = "";

            try
            {
                res = wc.DownloadString(url + Symbol);
            }
            catch (Exception)
            {
                if (appendAMEXonfail)
                {
                    return(DayFromURL(url, Symbol + AMEX, false));
                }
                return(bl);
            }
            string[] line = res.Split(Environment.NewLine.ToCharArray());
            for (int i = line.Length - 1; i > 0; i--)
            {
                if (line[i] != "")
                {
                    addbar(bl, BarImpl.FromCSV(line[i]), 0);
                }
            }
            return(bl);
        }
예제 #3
0
 public Bar GetBar(int index, string symbol)
 {
     Bar b = new BarImpl();
     if ((index < 0) || (index >= _Count)) return b;
     b = new BarImpl(opens[index], highs[index], lows[index], closes[index], vols[index], dates[index], times[index], symbol);
     if (index == Last()) b.isNew = _isRecentNew;
     return b;
 }
예제 #4
0
파일: TikUtil.cs 프로젝트: nacht/tradelink
        /// <summary>
        /// create ticks from bars on default interval
        /// </summary>
        /// <param name="bl"></param>
        /// <returns></returns>
        public static Tick[] Barlist2Tick(BarList bl)
        {
            List <Tick> k = new List <Tick>(bl.Count * 4);

            foreach (Bar b in bl)
            {
                k.AddRange(BarImpl.ToTick(b));
            }
            return(k.ToArray());
        }
예제 #5
0
 public BarImpl(BarImpl b)
 {
     v = b.Volume;
     h = b.lHigh;
     l = b.lLow;
     o = b.lOpen;
     c = b.lClose;
     DAYEND = b.DAYEND;
     bartime = b.bartime;
     bardate = b.bardate;
 }
예제 #6
0
 public BarImpl(BarImpl b)
 {
     v       = b.Volume;
     h       = b.High;
     l       = b.Low;
     o       = b.Open;
     c       = b.Close;
     DAYEND  = b.DAYEND;
     bartime = b.bartime;
     bardate = b.bardate;
 }
예제 #7
0
 public BarImpl(BarImpl b)
 {
     v       = b.Volume;
     h       = b.lHigh;
     l       = b.lLow;
     o       = b.lOpen;
     c       = b.lClose;
     DAYEND  = b.DAYEND;
     _time   = b._time;
     bardate = b.bardate;
 }
예제 #8
0
        public virtual bool SendMessage(MessageTypes type, long source, long dest, long msgid, string request, string response)
        {
            if (_tl == null)
            {
                return(false);
            }
            if (!_tl.RequestFeatureList.Contains(type))
            {
                SendDebug(type.ToString() + " not supported by " + _tl.Name);
                return(false);
            }
            try
            {
                // prepare message
                switch (type)
                {
                case MessageTypes.DOMREQUEST:
                    request = request.Replace(Book.EMPTYREQUESTOR, _tl.Name);
                    break;

                case MessageTypes.BARREQUEST:
                {
                    BarRequest br = BarImpl.ParseBarRequest(request);
                    br.Client = _tl.Name;
                    request   = BarImpl.BuildBarRequest(br);
                }
                break;

                case MessageTypes.FEATUREREQUEST:
                    request = _tl.Name;
                    break;

                case MessageTypes.IMBALANCEREQUEST:
                    request = _tl.Name;
                    break;
                }
                // send it
                long   result = _tl.TLSend(type, request);
                string res    = result.ToString();
                // pass along result
                if ((SendMessageResponse != null) && (result != 0))
                {
                    SendMessageResponse(type, source, dest, msgid, request, ref res);
                }
                return(true);
            }
            catch (Exception ex)
            {
                debug("Error on: " + type.ToString() + source + dest + msgid + request + response);
                debug(ex.Message + ex.StackTrace);
            }
            return(false);
        }
예제 #9
0
 public Bar GetBar(int index, string symbol)
 {
     Bar b = new BarImpl();
     if (index >= _Count) return b;
     else if (index < 0)
     {
         index = _Count - 1 + index;
         if (index < 0) return b;
     }
     b = new BarImpl(opens[index], highs[index], lows[index], closes[index], vols[index], dates[index], times[index], symbol,intervaltype,intervallength);
     if (index == Last()) b.isNew = _isRecentNew;
     return b;
 }
예제 #10
0
    public static Bar parseline(string line, string sym)
    {
        string[] values = line.Split(',');
 
        Bar bar = new BarImpl(sym);
 
        DateTime date;
        if(DateTime.TryParse(line[DATE], out date))
        {
            bar.Date = date;
        }
 
        decimal priceOpen;
        if(decimal.TryParse(line[OPEN], out priceOpen))
        {
            bar.Open = priceOpen;
        }
 
        decimal priceHigh;
        if(decimal.TryParse(line[HIGH], out priceHigh))
        {
            bar.High = priceHigh;
        }
 
        decimal priceLow;
        if(decimal.TryParse(line[LOW], out priceLow))
        {
            bar.Low = priceLow;
        }
 
        decimal priceClose;
        if(decimal.TryParse(line[CLOSE], out priceClose))
        {
            bar.Close = priceClose;
        }
 
        int volume;
        if(decimal.TryParse(line[VOLUME], out volume))
        {
            bar.Volume = volume;
        }
 
        int openInterest;
        if(decimal.TryParse(line[OPENINTEREST], out volume))
        {
            bar.OpenInterest = openInterest;
        }
 
        return bar;
    }
예제 #11
0
 public BarImpl(BarImpl b)
 {
     _id     = b.id;
     units   = b.units;
     _ci     = b.CustomInterval;
     v       = b.Volume;
     h       = b.lHigh;
     l       = b.lLow;
     o       = b.lOpen;
     c       = b.lClose;
     DAYEND  = b.DAYEND;
     _time   = b._time;
     bardate = b.bardate;
 }
예제 #12
0
 public BarImpl(BarImpl b)
 {
     _id = b.id;
     units = b.units;
     _ci = b.CustomInterval;
     v = b.Volume;
     h = b.lHigh;
     l = b.lLow;
     o = b.lOpen;
     c = b.lClose;
     DAYEND = b.DAYEND;
     _time = b._time;
     bardate = b.bardate;
 }
예제 #13
0
        /// <summary>
        /// Create a barlist from a succession of bar records provided as comma-delimited OHLC+volume data.
        /// </summary>
        /// <param name="symbol">The symbol.</param>
        /// <param name="file">The file containing the CSV records.</param>
        /// <returns></returns>
        public static BarListImpl FromCSV(string symbol, string file)
        {
            BarListImpl b = new BarListImpl(BarInterval.Day, symbol);

            string[] line = file.Split(Environment.NewLine.ToCharArray());
            for (int i = line.Length - 1; i > 0; i--)
            {
                if (line[i] != string.Empty)
                {
                    addbar(b, BarImpl.FromCSV(line[i]), 0);
                }
            }
            return(b);
        }
예제 #14
0
            void bl_GotNewBar(string symbol, int interval)
            {
                Bar b = bl[-1];

                Tick[] ks = BarImpl.ToTick(b);
                foreach (Tick t in ks)
                {
                    if (_saveticks)
                    {
                        ticks.Add(t);
                    }
                    datetimes.Add(t.datetime);
                    index.Add(idx);
                }
            }
예제 #15
0
        public Bar GetBar(int index, string symbol)
        {
            Bar b = new BarImpl();

            if ((index < 0) || (index >= _Count))
            {
                return(b);
            }
            b = new BarImpl(opens[index], highs[index], lows[index], closes[index], vols[index], dates[index], times[index], symbol);
            if (index == Last())
            {
                b.isNew = _isRecentNew;
            }
            return(b);
        }
예제 #16
0
        public void BarTime()
        {
            Bar b = new BarImpl(1, 1, 1, 1, 1, 20100302, 93533, "IBM", (int)BarInterval.FiveMin);
            Assert.AreEqual(93500, b.Bartime);
            Assert.AreEqual(93533, b.time);
            Console.WriteLine(b.Bartime + " " + b.time);

            b = new BarImpl(1, 1, 1, 1, 1, 20100302, 93533, "IBM", (int)BarInterval.Hour);
            Assert.AreEqual(90000, b.Bartime);
            Assert.AreEqual(93533, b.time);
            Console.WriteLine(b.Bartime + " " + b.time);

            b = new BarImpl(1, 1, 1, 1, 1, 20100302, 95504, "IBM", (int)BarInterval.FiveMin);
            Assert.AreEqual(95500, b.Bartime);
            Assert.AreEqual(95504, b.time);
            Console.WriteLine(b.Bartime + " " + b.time);
        }
예제 #17
0
        public void Construction()
        {
            BarImpl b = new BarImpl();
            Assert.That(!b.isValid);
            Assert.That(!b.isNew);
            b.newTick(ticklist[0]);
            Assert.That(b.isValid);
            Assert.That(b.isNew);
            b.newTick(ticklist[1]);
            Assert.That(b.isValid);
            Assert.That(!b.isNew);
            Assert.That(b.Volume == 200);
            b.newTick(TickImpl.NewQuote(sym,d,t,0,10m,11m,1,1,x,x));
            Assert.That(b.TradeCount == 2);


        }
예제 #18
0
        /// <summary>
        /// send a message to providers
        /// </summary>
        /// <param name="type"></param>
        /// <param name="source"></param>
        /// <param name="dest"></param>
        /// <param name="msgid"></param>
        /// <param name="message"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public long TLSend(MessageTypes type, long source, long dest, long msgid, string message, ref string result)
        {
            v(type.ToString() + " sending to all providers: " + message);
            for (int i = 0; i < _pcon.Count; i++)
            {
                if (_pcon[i].RequestFeatureList.Contains(type))
                {
                    bool showret = false;
                    // prepare message
                    switch (type)
                    {
                    case MessageTypes.DOMREQUEST:
                        message = message.Replace(Book.EMPTYREQUESTOR, _pcon[i].Name);
                        showret = true;
                        break;

                    case MessageTypes.BARREQUEST:
                    {
                        BarRequest br = BarImpl.ParseBarRequest(message);
                        br.Client = _pcon[i].Name;
                        message   = BarImpl.BuildBarRequest(br);
                        showret   = true;
                    }
                    break;

                    case MessageTypes.FEATUREREQUEST:
                        message = _pcon[i].Name;
                        showret = true;
                        break;
                    }
                    long res = _pcon[i].TLSend(type, message);
                    result = res.ToString();
                    if (gotUnknownMessage != null)
                    {
                        gotUnknownMessage(type, source, dest, msgid, message, ref result);
                    }

                    return(res);
                }
                else if (VerboseDebugging)
                {
                    v(_pcon[i].BrokerName + " " + _pcon[i].Name + " does not support feature " + type + ", dropping message.");
                }
            }
            return(0);
        }
예제 #19
0
        /// <summary>
        /// gets specific date range of bars from google
        /// </summary>
        /// <param name="symbol"></param>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        /// <returns></returns>
        public static BarList DayFromGoogle(string symbol, int startdate, int enddate)
        {
            const string AMEX = ":AMEX";

            if ((symbol == null) || (symbol == string.Empty))
            {
                return(new
                       BarListImpl());
            }
            string      url = @"http://finance.google.com/finance/historical?
histperiod=daily&startdate=" + startdate + "&enddate=" + enddate + "&output=csv&q=" + symbol;
            BarListImpl bl  = new BarListImpl(BarInterval.Day, symbol);

            System.Net.WebClient wc = new System.Net.WebClient();
            string res = "";

            try
            {
                res = wc.DownloadString(url);
            }
            catch (Exception)
            {
                if (!symbol.Contains(AMEX))
                {
                    DayFromGoogle(symbol + AMEX, startdate, enddate);
                }
                return(bl);
            }
            string[] line = res.Split(Environment.NewLine.ToCharArray());
            for (int i = line.Length - 1; i > 0; i--)
            {
                if (line[i] == "")
                {
                    continue;
                }
                Bar b = BarImpl.FromCSV(line[i]);
                foreach (Tick k in BarImpl.ToTick(b))
                {
                    bl.newTick(k);
                }
            }
            return(bl);
        }
예제 #20
0
        public void BarIntervals()
        {


            BarImpl b = new BarImpl(BarInterval.FiveMin);
            int accepts = 0;
            foreach (TickImpl k in ticklist)
                if (b.newTick(k)) accepts++;
            Assert.AreEqual(5, accepts);

            b = new BarImpl(BarInterval.FifteenMin);
            accepts = 0;
            foreach (TickImpl k in ticklist)
                if (b.newTick(k)) accepts++;
            Assert.AreEqual(9, accepts);

            b = new BarImpl(BarInterval.Minute);
            accepts = 0;
            for (int i = 7; i<ticklist.Length; i++)
                if (b.newTick(ticklist[i])) accepts++;
            Assert.AreEqual(2,accepts);

        }
예제 #21
0
        public Bar GetBar(int index, string symbol)
        {
            Bar b = new BarImpl();

            if (index >= _Count)
            {
                return(b);
            }
            else if (index < 0)
            {
                index = _Count - 1 + index;
                if (index < 0)
                {
                    return(b);
                }
            }
            b = new BarImpl(opens[index], highs[index], lows[index], closes[index], vols[index], dates[index], times[index], symbol, intervallength);
            if (index == Last())
            {
                b.isNew = _isRecentNew;
            }
            return(b);
        }
예제 #22
0
        public void SerializeDeseralize_Custom()
        {
            
            Bar b = new BarImpl(1, 1, 1, 1, 1, 20100302, 93533, "IBM", (int)BarInterval.CustomVol,10000, OrderImpl.Unique);
            g.d(b.Interval + b.CustomInterval.ToString());
            Assert.IsTrue(b.isCustom, "org not custom");
            string msg = BarImpl.Serialize(b);
            Bar cb = BarImpl.Deserialize(msg);

            Assert.AreEqual(b.Symbol, cb.Symbol);
            Assert.AreEqual(b.time, cb.time);
            Assert.AreEqual(b.Interval, cb.Interval);
            Assert.AreEqual(b.High, cb.High);
            Assert.AreEqual(b.Low, cb.Low);
            Assert.AreEqual(b.Open, cb.Open);
            Assert.AreEqual(b.Close, cb.Close);
            Assert.AreEqual(b.Volume, cb.Volume);
            Assert.AreEqual(b.Bardate, cb.Bardate);

            Assert.IsTrue(cb.isCustom, "copy not custom");
            Assert.AreEqual(b.CustomInterval, cb.CustomInterval,"cust int mismatch");
            Assert.AreNotEqual(b.id, 0, "id was zero");
            Assert.AreEqual(b.id, cb.id);
            

        }
예제 #23
0
        public void SerializeDeseralize()
        {
            Bar b = new BarImpl(1, 1, 1, 1, 1, 20100302, 93533, "IBM", (int)BarInterval.FiveMin);
            string msg = BarImpl.Serialize(b);
            Bar cb = BarImpl.Deserialize(msg);

            Assert.AreEqual(b.Symbol, cb.Symbol);
            Assert.AreEqual(b.time, cb.time);
            Assert.AreEqual(b.Interval, cb.Interval);
            Assert.AreEqual(b.High, cb.High);
            Assert.AreEqual(b.Low, cb.Low);
            Assert.AreEqual(b.Open, cb.Open);
            Assert.AreEqual(b.Close, cb.Close);
            Assert.AreEqual(b.Volume, cb.Volume);
            Assert.AreEqual(b.Bardate, cb.Bardate);

        }
예제 #24
0
 void OnReceiveHist(IAsyncResult result)
 {
     try
     {
         int bytesReceived = m_hist.EndReceive(result);
         string recvdata = Encoding.ASCII.GetString(m_buffhist, 0, bytesReceived);
         string rawData = _histbuff ==string.Empty ? recvdata : _histbuff+recvdata;
         string[] bars = rawData.Split(Environment.NewLine.ToCharArray());
         foreach (string bar in bars)
         {
             string[] r = bar.Split(',');
             // this should get hit on ENDMSG
             if (r.Length < 8) 
                 continue;
             // get request id
             long rid = 0;
             if (!long.TryParse(r[0], out rid))
                 continue;
             BarRequest br;
             if (!reqid2req.TryGetValue(rid, out br))
                 continue;
             bool errorfree = true;
             Bar b = new BarImpl();
             try
             {
                 DateTime dt = DateTime.Parse(r[1]);
                 decimal h = Convert.ToDecimal(r[2]);
                 decimal l = Convert.ToDecimal(r[3]);
                 decimal o = Convert.ToDecimal(r[4]);
                 decimal c = Convert.ToDecimal(r[5]);
                 long v = Convert.ToInt64(r[7]);
                 // build bar
                 b = new BarImpl(o, h, l, c, v, Util.ToTLDate(dt), Util.ToTLTime(dt), br.Symbol, br.Interval);
             }
             catch { errorfree = false; }
             // send it
             if (errorfree)
                 tl.TLSend(BarImpl.Serialize(b), MessageTypes.BARRESPONSE, br.Client);
         }
         string lastrecord = bars[bars.Length-1];
         if (lastrecord.Contains(HISTEND))
             _histbuff = string.Empty;
         else
             _histbuff = lastrecord;
         // wait for more historical data
         WaitForData(HISTSOCKET);
     }
     catch (Exception ex)
     {
         debug(ex.Message + ex.StackTrace);
     }
 }
예제 #25
0
 private void m_Session_OnHistMessage(object sender, BWHistResponse histMsg)
 {
     if (histMsg.Error.Length > 0)
     {
         debug("ERROR: " + histMsg.Error);
     }
     else
     {
         v(histMsg.Symbol + " received bar history data containing " + histMsg.bars.Length + " bars.");
         if (histMsg.bars != null && histMsg.bars.Length > 0)
         {
             string sym = histMsg.Symbol;
                                 
             foreach (BWBar bar in histMsg.bars)
             {
                 int tlDate = TradeLink.Common.Util.ToTLDate(bar.time);
                 int tlTime = TradeLink.Common.Util.ToTLTime(bar.time);
                 Bar tlBar = new BarImpl((decimal)bar.open, (decimal)bar.high, (decimal)bar.low, (decimal)bar.close, (int)bar.volume, tlDate, tlTime,sym,(int)histMsg.Interval);
                 for (int i = 0; i < tl.NumClients; i++)
                     tl.TLSend(BarImpl.Serialize(tlBar), MessageTypes.BARRESPONSE, i.ToString());
                 
                
             }
         }
         //else if (histMsg.ticks != null && histMsg.ticks.Length > 0)
         //{
         //    foreach (BWTickData tick in histMsg.ticks)
         //    {
         //        Tick tlTick = new TickImpl(tick.symbol);
         //        tlTick.ask = (decimal)tick.askprice;
         //        tlTick.AskSize = (int)tick.asksize;
         //        tlTick.bid = (decimal)tick.bidprice;
         //        tlTick.BidSize = (int)tick.bidsize;
         //        tlTick.trade = (decimal)tick.price;
         //        tlTick.size = (int)tick.size;
         //    }
         //}
     }
 }
예제 #26
0
        Bar GetBar(List<string> r)
        {
            if (type != ConvertMapType.Bar)
                return new BarImpl();

            Bar b = new BarImpl(get(gi(r,O)), get(gi(r,H)), get(gi(r,L)), get(gi(r,C)), getl(gi(r,V)), 
                getd(gi(r,DATE)), gett(gi(r,TIME)), gi(r,SYM), geti(gi(r,BI)));
            
            return b;
        }
 private void m_Session_OnHistMessage(object sender, CBWMsgHistResponse histMsg)
 {
     if (histMsg.Error.Value.Length > 0)
     {
         debug("ERROR: " + histMsg.Error);
     }
     else
     {
         v(String.Format("{0} received bar history data containing {1} bars.", histMsg.Symbol.Value, histMsg.Bars.Length ));
         if (histMsg.Bars != null && histMsg.Bars.Length > 0)
         {
             string sym = histMsg.Symbol;
             foreach (CBWMsgHistResponse.BarData bar in histMsg.Bars)
             {
                 int tlDate = TradeLink.Common.Util.ToTLDate(bar.Time);
                 int tlTime = TradeLink.Common.Util.ToTLTime(bar.Time);
                 Bar tlBar = new BarImpl((decimal)bar.Open, (decimal)bar.High, (decimal)bar.Low, (decimal)bar.Close, (int)bar.Volume, tlDate, tlTime, sym, Convert.ToInt32(histMsg.Interval));
                 for (int i = 0; i < tl.NumClients; i++)
                     tl.TLSend(BarImpl.Serialize(tlBar), MessageTypes.BARRESPONSE, i.ToString());
             }
         }
     }
 }
예제 #28
0
		  //pmh MbtHist events ####################################################################################
		  public void m_HistMgr_OnDataEvent(int lRequestId, object pHist, enumHistEventType evt)
		  {
			  debug(String.Format("m_HistMgr_OnDataEvent lRequestId: {0}, evt: {1}", lRequestId, evt));
			  Bar b;
			  int date, time; 
			  long vol;
			  decimal open, high, low, close;
			  string symbol;

			  // Notice we are using lRequestId in the original SendRequest()s to indicate whether we're
			  // dealing with a Day, Min or Tick bar object. Process accordingly.
			  BarRequest br;
			  int MbtCustInt;

//pmh ?!?			  debug("Unknown barrequest handle: ");

			  if (!_barhandle2barrequest.TryGetValue(lRequestId, out br))
			  {
				  debug("Unknown barrequest handle, lRequestId: " + lRequestId);
				  return;
			  }

			  int lRequestType = lRequestId % 10;

			  switch (lRequestType)
			  {
				  case 1:
					  //pmh ?!? - debug("number of client");
					  MbtHistDayBar barDay = pHist as MbtHistDayBar;
					  debug("Day bar, " + barDay.Count + " recs");
					  barDay.Last();
					  while (!barDay.Bof)
					  {
						  debug("number of client"); //pmh ?!?
						  symbol = barDay.Symbol; //pmh - 10/4/12 - was absent, but not sure if needed
						  open = Convert.ToDecimal(barDay.Open, System.Globalization.CultureInfo.InvariantCulture);
						  high = Convert.ToDecimal(barDay.High, System.Globalization.CultureInfo.InvariantCulture);
						  low = Convert.ToDecimal(barDay.Low, System.Globalization.CultureInfo.InvariantCulture);
						  close = Convert.ToDecimal(barDay.Close, System.Globalization.CultureInfo.InvariantCulture);
						  vol = Convert.ToInt64(barDay.TotalVolume, System.Globalization.CultureInfo.InvariantCulture);
						  date = Util.ToTLDate(barDay.CloseDate);
						  time = 0;
						  MbtCustInt = MbtDayInt2CustInt((int)br.Interval / 100);
						  b = new BarImpl(open, high, low, close, vol, date, time, barDay.Symbol, MbtCustInt);
						  debug("number of client" + tl.NumClients);
						  debug("bar" + BarImpl.Serialize(b));
						  tl.TLSend(BarImpl.Serialize(b), MessageTypes.BARRESPONSE, br.Client);
						  barDay.Previous();
					  }
					  //use this message to inform that the data for requestID is completed
					  tl.TLSend(Convert.ToString(lRequestId), MessageTypes.CUSTOM40, br.Client);
					  break;

				  case 2:
					  MbtHistMinBar barMin = pHist as MbtHistMinBar;
					  debug("Min bar, " + barMin.Count + " recs");
					  barMin.Last();
					  while (!barMin.Bof)
					  {
						  symbol = barMin.Symbol; //pmh - 10/4/12 - was absent, but not sure if needed
						  open = Convert.ToDecimal(barMin.Open, System.Globalization.CultureInfo.InvariantCulture);
						  high = Convert.ToDecimal(barMin.High, System.Globalization.CultureInfo.InvariantCulture);
						  low = Convert.ToDecimal(barMin.Low, System.Globalization.CultureInfo.InvariantCulture);
						  close = Convert.ToDecimal(barMin.Close, System.Globalization.CultureInfo.InvariantCulture);
						  vol = Convert.ToInt64(barMin.TotalVolume, System.Globalization.CultureInfo.InvariantCulture);
						  date = Util.ToTLDate(barMin.LocalDateTime);
						  time = Util.ToTLTime(barMin.LocalDateTime);
						  MbtCustInt = MbtMinInt2CustInt((int)br.Interval / 100);
						  b = new BarImpl(open, high, low, close, vol, date, time, barMin.Symbol, MbtCustInt);
						  tl.TLSend(BarImpl.Serialize(b), MessageTypes.BARRESPONSE, br.Client);
						  barMin.Previous();
					  }
					  //use this message to inform that the data for requestID is completed
					  tl.TLSend(Convert.ToString(lRequestId), MessageTypes.CUSTOM40, br.Client);
					  break;

				  case 3:
					  /* pmh
					   * 0 = All ticks
					   * 1 = Trade ticks
					   * 2 = Bid/Ask ticks
					   * 3 = Bid ticks
					   * 4 = Ask ticks
					   */
					  MbtHistTick barTick = pHist as MbtHistTick;
					  debug("Tick bar, " + barTick.Count + " recs (showing only 1 - Trade ticks)");
					  TickImpl k = new TickImpl(barTick.Symbol);
					  //MBT default tick data is trade data
					  int lTickFilter = 1;
					  barTick.First();
					  switch (lTickFilter)
					  {
						  case 1:
							  while (!barTick.Bof)
							  {
								  k.symbol = barTick.Symbol; //pmh - 10/4/12 - was absent, but not sure if needed
								  k.trade = Convert.ToDecimal(barTick.Price);
								  k.ex = barTick.Exchange;
								  k.size = barTick.Volume;
								  k.date = Util.ToTLDate(barTick.LocalDateTime);
								  k.time = Util.ToTLTime(barTick.LocalDateTime);
								  SendNewTick(k);
								  barTick.Previous();
							  };
							  break;
					  }
					  break;

				  case 4: //pmh - 9/15/12 - PV bars
					  MbtHistPVBar barPV = pHist as MbtHistPVBar;
					  debug("PV bar, " + barPV.Count + " recs");
					  barPV.Last();
					  while (!barPV.Bof)
					  {
						  open = high = low = 0;
						  symbol = barPV.Symbol; //pmh - 10/4/12 - was absent, but not sure if needed
						  close = Convert.ToDecimal(barPV.Price, System.Globalization.CultureInfo.InvariantCulture);
						  vol = Convert.ToInt64(barPV.Volume, System.Globalization.CultureInfo.InvariantCulture);
						  date = Util.ToTLDate(barPV.LocalDateTime);
						  time = Util.ToTLTime(barPV.LocalDateTime);
						  MbtCustInt = MbtMinInt2CustInt((int)br.Interval / 100);
						  b = new BarImpl(open, high, low, close, vol, date, time, barPV.Symbol, MbtCustInt);
						  tl.TLSend(BarImpl.Serialize(b), MessageTypes.BARRESPONSE, br.Client);
						  barPV.Previous();
					  }
					  //use this message to inform that the data for requestID is completed
					  tl.TLSend(Convert.ToString(lRequestId), MessageTypes.CUSTOM40, br.Client);
					  break;
			  }

			  if (_barrequests.hasItems)
			  {
				  // BarRequest br1= new BarRequest();
				  try
				  {
					  br = _barrequests.Read();
					  submitBarRequest(br);
				  }
				  catch (Exception ex)
				  {
					  debug("error on historical bar request: " + br.ToString());
					  debug(ex.Message + ex.StackTrace);
				  }
			  }
			  else waitforhistorical2complete = false;
		  }
예제 #29
0
        public void InsertBar_MultipleInsert()
        {
            string sym = "FTI";
            int d = 20070926;
            var bint = BarInterval.FiveMin;
            var bsize = (int)bint;
            BarList org = new BarListImpl(bint, sym);
            Assert.IsTrue(org.isValid, "your original barlist is not valid 1");
            int orgcount = org.Count;
            Assert.AreEqual(0, orgcount);

            int h = 7;
            int m = 55;
            for (int i = 0; i < 10; i++)
            {
                int t = h*10000+m*100;
                Bar insert = new BarImpl(30, 30, 30, 30, 10000, d, t, sym, bsize);
                Assert.IsTrue(insert.isValid, "your bar to insert is not valid #" + i);
                int insertpos = BarListImpl.GetBarIndexPreceeding(org, insert.Bardate, insert.Bartime);
                Assert.AreEqual(i - 1, insertpos, "insertion position#" + i);
                BarList inserted = BarListImpl.InsertBar(org, insert, insertpos);
                Assert.IsTrue(g.ta(i + 1 == inserted.Count, BarListImpl.Bars2String(org)+Environment.NewLine+ BarListImpl.Bars2String(inserted)), "element count after insertion #" + i + " pos: " + insertpos);
                m += 5;
                if (m >= 60)
                {
                    h += m / 60;
                    m = m % 60;
                }
                org = inserted;
            }
            Assert.AreEqual(orgcount+10, org.Count, "total element count after insertion");
        }
예제 #30
0
 public void InsertBar_HistoricalPlusNewBarsPresent()
 {
     string sym = "FTI";
     int d = 20070926;
     // historical bar filename
     string filename = sym + d + TikConst.DOT_EXT;
     // case 3 - middle insertion aka (some historical and some new bars already present)
     var org = BarListImpl.FromTIK(filename);
     Assert.IsTrue(org.isValid, "your original bar is not valid 3");
     var orgcount = org.Count;
     Assert.Greater(orgcount,0);
     // create bar to insert
     var insert = new BarImpl(30, 30, 30, 30, 10000, d, 75500, sym, (int)BarInterval.FiveMin);
     Assert.IsTrue(insert.isValid, "your bar to insert is not valid 3");
     int insertpos = BarListImpl.GetBarIndexPreceeding(org,insert.Bardate);
     var inserted = BarListImpl.InsertBar(org, insert, insertpos);
     Assert.AreEqual(inserted.Count,orgcount+1);
     var actualinsert = inserted[insertpos];
     Assert.IsTrue(actualinsert.isValid);
     Assert.AreEqual(insert.Close,actualinsert.Close);
     Assert.AreEqual(insert.Open,actualinsert.Open);
     Assert.AreEqual(insert.High,actualinsert.High);
     Assert.AreEqual(insert.Low,actualinsert.Low);
     Assert.AreEqual(insert.Symbol,actualinsert.Symbol);
 }
예제 #31
0
        /// <summary>
        /// build bar request for certain # of bars back from present
        /// </summary>
        /// <param name="sym"></param>
        /// <param name="barsback"></param>
        /// <param name="interval"></param>
        /// <returns></returns>
        public static string BuildBarRequestBarsBack(string sym, int barsback, int interval)
        {
            DateTime n = DateTime.Now;

            return(BarImpl.BuildBarRequest(new BarRequest(sym, interval, Util.ToTLDate(BarImpl.DateFromBarsBack(barsback, interval, n)), Util.ToTLTime(BarImpl.DateFromBarsBack(barsback, interval, n)), Util.ToTLDate(n), Util.ToTLTime(n), string.Empty)));
        }
예제 #32
0
        public virtual bool GotMessage(MessageTypes type, long source, long dest, long msgid, string request, ref string response)
        {
            long lv = 0;

            switch (type)
            {
            case MessageTypes.BARRESPONSE:
            {
                try
                {
                    // get bar
                    Bar b = BarImpl.Deserialize(response);
                    // quit if bar is invalid
                    if (!b.isValid)
                    {
                        debug(b.Symbol + " ignoring invalid bar message: " + response);
                        return(true);
                    }
                    else
                    {
                        v(b.Symbol + " got bar: " + b.ToString());
                    }
                    // notify bar was received
                    if (GotNewBar != null)
                    {
                        GotNewBar(b.Symbol, b.Interval);
                    }
                    // update blt if desired
                    if (BLT != null)
                    {
                        // get bar list
                        BarList bl = BLT[b.Symbol, b.Interval];
                        // convert to ticks
                        var barticks = BarImpl.ToTick(b);
                        // insert
                        for (int i = 0; i < barticks.Length; i++)
                        {
                            bl.newTick(barticks[i]);
                        }
                        // put it back
                        BLT[b.Symbol] = bl;
                    }
                }
                catch (Exception ex)
                {
                    debug("error receiving bardata: " + response + " err: " + ex.Message + ex.StackTrace);
                    return(false);
                }
                return(true);
            }

            case MessageTypes.CLOSEPRICE:
            {
                if ((GotClosePrice != null) && long.TryParse(response, out lv))
                {
                    GotClosePrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.OPENPRICE:
            {
                if ((GotOpenPrice != null) && long.TryParse(response, out lv))
                {
                    GotOpenPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.DAYHIGH:
            {
                if ((GotHighPrice != null) && long.TryParse(response, out lv))
                {
                    GotHighPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.DAYLOW:
            {
                if ((GotLowPrice != null) && long.TryParse(response, out lv))
                {
                    GotLowPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.NYSEDAYHIGH:
            {
                if ((GotNyseHighPrice != null) && long.TryParse(response, out lv))
                {
                    GotNyseHighPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.NYSEDAYLOW:
            {
                if ((GotNyseLowPrice != null) && long.TryParse(response, out lv))
                {
                    GotNyseLowPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.INTRADAYHIGH:
            {
                if ((GotIntraHighPrice != null) && long.TryParse(response, out lv))
                {
                    GotIntraHighPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.INTRADAYLOW:
            {
                if ((GotIntraLowPrice != null) && long.TryParse(response, out lv))
                {
                    GotIntraLowPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.BROKERNAME:
            {
                if (GotProvider != null)
                {
                    try
                    {
                        Providers p = (Providers)Enum.Parse(typeof(Providers), response);
                        GotProvider(p);
                    }
                    catch (Exception ex)
                    {
                        debug("Unknown provider: " + response);
                        debug(ex.Message + ex.StackTrace);
                        return(false);
                    }
                }
                return(true);
            }

            case MessageTypes.FEATURERESPONSE:
            {
                if (GotFeatures != null)
                {
                    string[]            r = response.Split(',');
                    List <MessageTypes> f = new List <MessageTypes>();
                    foreach (string rs in r)
                    {
                        try
                        {
                            MessageTypes mt = (MessageTypes)Enum.Parse(typeof(MessageTypes), rs);
                            f.Add(mt);
                        }
                        catch { continue; }
                    }
                    if (f.Count > 0)
                    {
                        GotFeatures(f.ToArray());
                    }
                }
                return(true);
            }

            default:
                v("ignoring message: " + type + " " + request + " " + response);
                return(true);
            }
        }
예제 #33
0
        public void InsertBar_NoexistingBars()
        {
            string sym = "FTI";
            int d = 20070926;
            // historical bar filename
            string filename = sym+d+TikConst.DOT_EXT;
            
            // test for the parameter's prescence
            Assert.IsNotEmpty(filename,"forgot to assign insert bar filename");

            // unit test case 1 no existing bars aka (empty or brand-new insertion)
            BarList org = new BarListImpl(BarInterval.FiveMin,sym);
            Assert.IsTrue(org.isValid, "your original barlist is not valid 1");
            int orgcount = org.Count;
            Assert.AreEqual(0,orgcount);
            // make up a bar here  (eg at 755 in FTI there are no ticks so this should add a new bar in most scenarios)
            Bar insert = new BarImpl(30,30,30,30,10000,d,75500,sym,(int)BarInterval.FiveMin);
            Assert.IsTrue(insert.isValid,"your bar to insert is not valid 1");
            BarList inserted = BarListImpl.InsertBar(org,insert,org.Count);
            Assert.AreEqual(inserted.Count,orgcount+1);
            Bar actualinsert = inserted.RecentBar;
            Assert.IsTrue(actualinsert.isValid);
            Assert.AreEqual(insert.Close,actualinsert.Close);
            Assert.AreEqual(insert.Open,actualinsert.Open);
            Assert.AreEqual(insert.High,actualinsert.High);
            Assert.AreEqual(insert.Low,actualinsert.Low);
            Assert.AreEqual(insert.Symbol,actualinsert.Symbol);
        }
예제 #34
0
        public static BarList DayFromEuronext(string isin, DateTime?startDate, DateTime?endDate)
        {
            string market;
            string urlTemplate =
                @"http://www.euronext.com/tools/datacentre/dataCentreDownloadExcell.jcsv?cha=2593&lan=EN&fileFormat=txt&separator=.&dateFormat=dd/MM/yy" +
                "&isinCode=[symbol]&selectedMep=[market]&indexCompo=&opening=on&high=on&low=on&closing=on&volume=on&dateFrom=[startDay]/[startMonth]/[startYear]&" +
                "dateTo=[endDay]/[endMonth]/[endYear]&typeDownload=2";

            if (!endDate.HasValue)
            {
                endDate = DateTime.Now;
            }
            if (!startDate.HasValue)
            {
                startDate = DateTime.Now.AddYears(-5);
            }
            if (isin == null || !Regex.IsMatch(isin, "[A-Za-z0-9]{12}"))
            {
                throw new ArgumentException("Invalid ISIN: " + isin);
            }

            /* ugly hack to get the market number from the isin (not always valid..) */
            CompareInfo myComp = CultureInfo.InvariantCulture.CompareInfo;

            if (myComp.IsPrefix(isin, "BE"))
            {
                market = "3";
            }
            else if (myComp.IsPrefix(isin, "FR"))
            {
                market = "1";
            }
            else if (myComp.IsPrefix(isin, "NL"))
            {
                market = "2";
            }
            else if (myComp.IsPrefix(isin, "PT"))
            {
                market = "5";
            }
            else
            {
                market = "1";
            }

            string startMonth = startDate.Value.Month.ToString();
            string startDay   = startDate.Value.Day.ToString();
            string startYear  = startDate.Value.Year.ToString();

            string endMonth = endDate.Value.Month.ToString();
            string endDay   = endDate.Value.Day.ToString();
            string endYear  = endDate.Value.Year.ToString();

            urlTemplate = urlTemplate.Replace("[symbol]", isin);
            urlTemplate = urlTemplate.Replace("[market]", market);
            urlTemplate = urlTemplate.Replace("[startMonth]", startMonth);
            urlTemplate = urlTemplate.Replace("[startDay]", startDay);
            urlTemplate = urlTemplate.Replace("[startYear]", startYear);

            urlTemplate = urlTemplate.Replace("[endMonth]", endMonth);
            urlTemplate = urlTemplate.Replace("[endDay]", endDay);
            urlTemplate = urlTemplate.Replace("[endYear]", endYear);

            BarListImpl bl = new BarListImpl(BarInterval.Day, isin);

            System.Net.WebClient wc = new System.Net.WebClient();
            StreamReader         res;

            try
            {
                res = new StreamReader(wc.OpenRead(urlTemplate));
                int    skipCount = 0;
                string tmp       = null;
                do
                {
                    tmp = res.ReadLine();
                    if (skipCount++ < 7)
                    {
                        continue;
                    }
                    tmp = tmp.Replace(";", ",");
                    Bar b = BarImpl.FromCSV(tmp, isin, (int)BarInterval.Day);
                    foreach (Tick k in BarImpl.ToTick(b))
                    {
                        bl.newTick(k);
                    }
                } while (tmp != null);
            }
            catch (Exception)
            {
                return(bl);
            }

            return(bl);
        }
예제 #35
0
        public virtual bool GotMessage(MessageTypes type, long source, long dest, long msgid, string request, ref string response)
        {
            long lv = 0;

            switch (type)
            {
            case MessageTypes.CLOSEPRICE:
            {
                if ((GotClosePrice != null) && long.TryParse(response, out lv))
                {
                    GotClosePrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.OPENPRICE:
            {
                if ((GotOpenPrice != null) && long.TryParse(response, out lv))
                {
                    GotOpenPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.DAYHIGH:
            {
                if ((GotHighPrice != null) && long.TryParse(response, out lv))
                {
                    GotHighPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.DAYLOW:
            {
                if ((GotLowPrice != null) && long.TryParse(response, out lv))
                {
                    GotLowPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.NYSEDAYHIGH:
            {
                if ((GotNyseHighPrice != null) && long.TryParse(response, out lv))
                {
                    GotNyseHighPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.NYSEDAYLOW:
            {
                if ((GotNyseLowPrice != null) && long.TryParse(response, out lv))
                {
                    GotNyseLowPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.INTRADAYHIGH:
            {
                if ((GotIntraHighPrice != null) && long.TryParse(response, out lv))
                {
                    GotIntraHighPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.INTRADAYLOW:
            {
                if ((GotIntraLowPrice != null) && long.TryParse(response, out lv))
                {
                    GotIntraLowPrice(request, WMUtil.unpack(lv));
                }
                return(true);
            }

            case MessageTypes.BROKERNAME:
            {
                if (GotProvider != null)
                {
                    try
                    {
                        Providers p = (Providers)Enum.Parse(typeof(Providers), response);
                        GotProvider(p);
                    }
                    catch (Exception ex)
                    {
                        debug("Unknown provider: " + response);
                        debug(ex.Message + ex.StackTrace);
                        return(false);
                    }
                }
                return(true);
            }

            case MessageTypes.FEATURERESPONSE:
            {
                if (GotFeatures != null)
                {
                    string[]            r = response.Split(',');
                    List <MessageTypes> f = new List <MessageTypes>();
                    foreach (string rs in r)
                    {
                        try
                        {
                            MessageTypes mt = (MessageTypes)Enum.Parse(typeof(MessageTypes), rs);
                            f.Add(mt);
                        }
                        catch { continue; }
                    }
                    if (f.Count > 0)
                    {
                        GotFeatures(f.ToArray());
                    }
                }
                return(true);
            }

            case MessageTypes.BARRESPONSE:
            {
                try
                {
                    // get bar
                    Bar b = BarImpl.Deserialize(response);
                    // quit if bar is invalid
                    if (!b.isValid)
                    {
                        return(true);
                    }
                    // notify bar was received
                    if (GotNewBar != null)
                    {
                        GotNewBar(b.Symbol, b.Interval);
                    }
                    // update blt if desired
                    if (BLT != null)
                    {
                        // get bar list
                        BarList bl = BLT[b.Symbol, b.Interval];
                        //cjyu
                        //return if bar already exists
                        //if (BarListImpl.BarExists(bl, b))
                        //  return true;

                        // get nearest intrday bar
                        int preceed = BarListImpl.GetBarIndexPreceeding(bl, b.Bardate, b.Bartime);
                        // increment by one to get new position
                        int newpos = preceed + 1;
                        // insert bar
                        BLT[b.Symbol] = BarListImpl.InsertBar(bl, b, newpos);
                    }
                }
                catch (Exception ex)
                {
                    debug("error receiving bardata: " + response + " err: " + ex.Message + ex.StackTrace);
                    return(false);
                }
                return(true);
            }
            break;
            }
            return(false);
        }
예제 #36
0
        void OnReceiveHist(IAsyncResult result)
        {
            try
            {
                int bytesReceived = m_hist.EndReceive(result);
                var records = getrecords(m_buffhist, bytesReceived);

                // mark record processing status
                var lastrecordprocessed = false;
                var lastrecordidx = records.Length - 1;

                // process records
                for (int i = 0; i<records.Length; i++)
                {
                    // get record
                    var rec = records[i];
                    // mark it's status
                    lastrecordprocessed = false;
                    // skip empty data
                    if (string.IsNullOrWhiteSpace(rec))
                        continue;
                    // look for misc responses
                    if (checkhistproto && rec.Contains(expecthistproto))
                    {
                        checkhistproto = false;
                        rec = rec.Replace(expecthistproto, string.Empty);
                        records[i] = rec;
                        lastrecordprocessed = i == lastrecordidx;
                        v("hist protocol ack:" + expecthistproto);
                    }
                    string[] r = rec.Split(',');
                    // test for request id and response type
                    BarRequest br = new BarRequest();
                    var prev = (i == 0) ? string.Empty : records[i - 1];
                    if (isrecorddone(rec, r, prev, out br))
                    {
                        v("hist processed: " + rec);
                        lastrecordprocessed = i == lastrecordidx;
                        continue;
                    }
                    else if (i==lastrecordidx)
                    {
                        lastrecordprocessed = false;
                    }

                    Bar b = new BarImpl();

                    try
                    {
                        if (br.isValid)
                        {
                            if (br.BarInterval == BarInterval.Day)
                            {
                                DateTime dt = DateTime.MinValue;
                                if (!DateTime.TryParse(r[1], System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out dt))
                                {
                                    v("hist can't parse date: " + r[1] + " data: " + rec);
                                    continue;
                                }
                                decimal o, h, l, c;
                                long vol;
                                if (!decimal.TryParse(r[2], System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out h))
                                {
                                    v("hist can't parse high: " + r[2] + " data: " + rec);
                                    continue;
                                }
                                else if (!decimal.TryParse(r[3], System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out l))
                                {
                                    v("hist can't parse low: " + r[3] + " data: " + rec);
                                    continue;
                                }
                                else if (!decimal.TryParse(r[4], System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out o))
                                {
                                    v("hist can't parse open: " + r[4] + " data: " + rec);
                                    continue;
                                }
                                else if (!decimal.TryParse(r[5], System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out c))
                                {
                                    v("hist can't parse close: " + r[5] + " data: " + rec);
                                    continue;
                                }
                                else if (!long.TryParse(r[6], System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out vol))
                                {
                                    v("hist can't parse vol: " + r[6] + " data: " + rec);
                                    continue;
                                }
                                // mark iqfeed processing status
                                lastrecordprocessed = i == lastrecordidx;
                                // build bar
                                b = new BarImpl(o, h, l, c, vol, Util.ToTLDate(dt), Util.ToTLTime(dt), br.symbol, br.Interval,br.CustomInterval,br.ID);
                                if (VerboseDebugging)
                                    debug("hist got bar: " + b);
                            }
                            else
                            {
                                DateTime dt = DateTime.MinValue;
                                if (!DateTime.TryParse(r[1], System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out dt))
                                {
                                    v("hist can't parse date: " + r[1] + " data: " + rec);
                                    continue;
                                }
                                decimal o, h, l, c;
                                long vol;
                                if (!decimal.TryParse(r[2], System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out h))
                                {
                                    v("hist can't parse high: " + r[2] + " data: " + rec);
                                    continue;
                                }
                                else if (!decimal.TryParse(r[3], System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out l))
                                {
                                    v("hist can't parse low: " + r[3] + " data: " + rec);
                                    continue;
                                }
                                else if (!decimal.TryParse(r[4], System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out o))
                                {
                                    v("hist can't parse open: " + r[4] + " data: " + rec);
                                    continue;
                                }
                                else if (!decimal.TryParse(r[5], System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out c))
                                {
                                    v("hist can't parse close: " + r[5] + " data: " + rec);
                                    continue;
                                }
                                else if (!long.TryParse(r[7], System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out vol))
                                {
                                    v("hist can't parse vol: " + r[7] + " data: " + rec);
                                    continue;
                                }
                                // mark iqfeed processing status
                                lastrecordprocessed = i == lastrecordidx;
                                // build bar
                                b = new BarImpl(o, h, l, c, vol, Util.ToTLDate(dt), Util.ToTLTime(dt), br.symbol, br.Interval,br.CustomInterval,br.ID);
                                if (VerboseDebugging)
                                    debug("hist got bar: " + b);

                            }
                        }
                        
                    }
                    catch (Exception ex)
                    {
                        v("hist ohlc parse err: " + ex.Message + ex.StackTrace + " data: " + rec);
                        b = new BarImpl();
                    }
                    // send it
                    if (b.isValid)
                    {
                        var barserial = BarImpl.Serialize(b);
                        if (VerboseDebugging)
                            debug("hist sending response to: "+br.ID+" int: "+ b.Interval + " bar: " + b.ToString() + " to: " + br.Client + " using data: " + rec);
                        try
                        {
                            tl.TLSend(barserial, MessageTypes.BARRESPONSE, br.Client);
                            if (VerboseDebugging)
                                debug("hist sent " + b.Symbol + " bar in response to: " + br.ID);
                        }
                        catch (Exception ex)
                        {
                            debug("hist send error: " + ex.Message + ex.StackTrace + " on: " + barserial + " to: " + br.Client);
                        }
                    }
                    
                }
                if (!lastrecordprocessed)
                {
                    string lastrecord = records[lastrecordidx];
                    var endidx = lastrecord.IndexOf(HISTEND);
                    if (endidx >= 0)
                    {
                        lastrecord = lastrecord.Substring(endidx, HISTEND.Length);
                        v("hist got " + HISTEND);
                    }
                    if (!string.IsNullOrWhiteSpace(lastrecord))
                    {
                        _histbuff = lastrecord;
                        v("hist saving: " + _histbuff + " for more data.");
                    }
                }
                // wait for more historical data
                WaitForData(HISTSOCKET);
            }
            catch (SocketException)
            {
                v("hist connection closed.");
            }
            catch (Exception ex)
            {
                debug(ex.Message + ex.StackTrace);
            }
        }
예제 #37
0
 void processhistory(int lHandle,BarRequest br)
 {
     int numbars = esig.get_GetNumBars(lHandle);
     if (numbars == 0)
     {
         verb("no bars available for reqhandle: " + lHandle);
         return;
     }
     numbars *= -1;
     for (int i = numbars; i<=0; i++)
     {
         try
         {
             BarData bd = esig.get_GetBar(lHandle, i);
             if (VerboseDebugging)
                 verb(br.symbol + " " + bd.dtTime.ToString() + " " + bd.dOpen + " " + bd.dHigh + " " + bd.dLow + " " + bd.dClose + " " + bd.dVolume);
             Bar b = new BarImpl((decimal)bd.dOpen, (decimal)bd.dHigh, (decimal)bd.dLow, (decimal)bd.dClose, (long)bd.dVolume, Util.ToTLDate(bd.dtTime), Util.ToTLTime(bd.dtTime), br.symbol, br.Interval);
             string msg = BarImpl.Serialize(b);
             if (!b.isValid && !AllowSendInvalidBars)
             {
                 debug("Not sending invalid bar: " + b.ToString()+" raw: "+msg);
                 continue;
             }
             tl.TLSend(msg, MessageTypes.BARRESPONSE, br.Client);
         }
         catch (Exception ex)
         {
             verb("error obtaining bar: " + i + " from: " + lHandle);
             verb(ex.Message + ex.StackTrace);
         }
     }
     if (ReleaseBarHistoryAfteRequest)
     {
         try
         {
             esig.ReleaseHistory(lHandle);
             _barhandle2barrequest.Remove(lHandle);
         }
         catch { }
     }
 }
예제 #38
0
        public void m_Hist_OnDataEvent(int lRequestId, object pHist, enumHistEventType evt)
        {
            debug("Processing Id: " + lRequestId + "  evt: " + evt);
            Bar b;
            int date, time; long vol;
            decimal open, high, low, close;
            string symbol;

            // Notice we are using lRequestId in the original SendRequest()s to indicate whether we're
            // dealing with a Day, Min or Tick bar object. Process accordingly.

            BarRequest br;
            int MbtCustInt;

            debug("Unknown barrequest handle: ");

            if (!_barhandle2barrequest.TryGetValue(lRequestId, out br))
            {
                debug("Unknown barrequest handle: " + lRequestId);
                return;
            }

            int lRequestType = lRequestId % 10;

            switch (lRequestType)
            {
                case 1:
                    debug("number of client");
                    MbtHistDayBar mhd = pHist as MbtHistDayBar;
                    mhd.Last();


                    while (!mhd.Bof)
                    {
                        debug("number of client");
                        open = Convert.ToDecimal(mhd.Open, System.Globalization.CultureInfo.InvariantCulture);
                        high = Convert.ToDecimal(mhd.High, System.Globalization.CultureInfo.InvariantCulture);
                        low = Convert.ToDecimal(mhd.Low, System.Globalization.CultureInfo.InvariantCulture);
                        close = Convert.ToDecimal(mhd.Close, System.Globalization.CultureInfo.InvariantCulture);
                        vol = Convert.ToInt64(mhd.TotalVolume, System.Globalization.CultureInfo.InvariantCulture);
                        date = Util.ToTLDate(mhd.CloseDate);
                        time = 0;
                        MbtCustInt = MbtDayInt2CustInt((int)br.Interval / 100);
                        b = new BarImpl(open, high, low, close, vol, date, time, mhd.Symbol, MbtCustInt);

                        debug("number of client" + tl.NumClients);

                        debug("bar" + BarImpl.Serialize(b));
                        tl.TLSend(BarImpl.Serialize(b), MessageTypes.BARRESPONSE, br.Client);

                        mhd.Previous();
                    }
                    //use this mesage to inform that the data for requestID is compeleted
                    tl.TLSend(Convert.ToString(lRequestId), MessageTypes.CUSTOM40, br.Client);
                    break;

                case 2:

                    MbtHistMinBar mhm = pHist as MbtHistMinBar;

                    mhm.Last();

                    while (!mhm.Bof)
                    {
                        open = Convert.ToDecimal(mhm.Open, System.Globalization.CultureInfo.InvariantCulture);
                        high = Convert.ToDecimal(mhm.High, System.Globalization.CultureInfo.InvariantCulture);
                        low = Convert.ToDecimal(mhm.Low, System.Globalization.CultureInfo.InvariantCulture);
                        close = Convert.ToDecimal(mhm.Close, System.Globalization.CultureInfo.InvariantCulture);
                        vol = Convert.ToInt64(mhm.TotalVolume, System.Globalization.CultureInfo.InvariantCulture);
                        date = Util.ToTLDate(mhm.LocalDateTime);
                        time = Util.ToTLTime(mhm.LocalDateTime);
                        MbtCustInt = MbtMinInt2CustInt((int)br.Interval / 100);
                        b = new BarImpl(open, high, low, close, vol, date, time, mhm.Symbol, MbtCustInt);

                        tl.TLSend(BarImpl.Serialize(b), MessageTypes.BARRESPONSE, br.Client);

                        mhm.Previous();
                    }
                    //use this mesage to inform that the data for requestID is compeleted
                    tl.TLSend(Convert.ToString(lRequestId), MessageTypes.CUSTOM40, br.Client);

                    break;



                case 3:

                    MbtHistTick mht = pHist as MbtHistTick;
                    TickImpl k = new TickImpl(mht.Symbol);
                    //MBT default tick data is trade data
                    int lTickFilter = 1;
                    mht.First();

                    switch (lTickFilter)
                    {
                        case 1:

                            while (!mht.Bof)
                            {
                                k.trade = Convert.ToDecimal(mht.Price);
                                k.ex = mht.Exchange;
                                k.size = mht.Volume;
                                k.date = Util.ToTLDate(mht.LocalDateTime);
                                k.time = Util.ToTLTime(mht.LocalDateTime);
                                SendNewTick(k);
                                mht.Previous();
                            }
                            ; break;

                    }
                    break;
            }

            if (_barrequests.hasItems)
            {
                // BarRequest br1= new BarRequest();


                try
                {
                    br = _barrequests.Read();

                    submitBarRequest(br);

                }
                catch (Exception ex)
                {
                    debug("error on historical bar request: " + br.ToString());
                    debug(ex.Message + ex.StackTrace);
                }

            }
            else waitforhistorical2complete = false;
        }
예제 #39
0
 public static Bar GetRandomBar(string sym, int intervaltype, int custinterval, int date, int time)
 {
     // send some bars back
     var b = new BarImpl();
     while (!b.isValid)
     {
         var p = (decimal)r.NextDouble() * 100;
         var d = (decimal)Math.Round(r.NextDouble(), 2);
         var v = r.Next(1000, 100000);
         var dt = Util.ToDateTime(date, time);
         b = new BarImpl(p, p + d * 3, p - d * 5, p - d, v, Util.ToTLDate(dt), Util.ToTLTime(dt), sym, intervaltype,custinterval);
     }
     return b;
 }
예제 #40
0
        public void InsertBar_HistoricalBarsPresent()
        {

            string sym = "FTI";
            int d = 20070926;
            // historical bar filename
            string filename = sym + d + TikConst.DOT_EXT;

            // unit test case 2 existing bars with front insertion (aka historical bar insert)

            var org = BarListImpl.FromTIK(filename);
            Assert.IsTrue(org.isValid, "your original bar is not valid 2");
            var orgcount = org.Count;
            Assert.Greater(orgcount,0);
            // create bar to insert
            var insert = new BarImpl(30, 30, 30, 30, 10000, d, 75500, sym, (int)BarInterval.FiveMin);
            Assert.IsTrue(insert.isValid, "your bar to insert is not valid 2");
            var inserted = BarListImpl.InsertBar(org,insert,0);
            Assert.AreEqual(inserted.Count,orgcount+1);
            var actualinsert = inserted[0];
            Assert.IsTrue(actualinsert.isValid);
            Assert.AreEqual(insert.Close,actualinsert.Close);
            Assert.AreEqual(insert.Open,actualinsert.Open);
            Assert.AreEqual(insert.High,actualinsert.High);
            Assert.AreEqual(insert.Low,actualinsert.Low);
            Assert.AreEqual(insert.Symbol,actualinsert.Symbol);
        }