public void UpdateRow(Tick k) { // bool exist = GridViewModel.QuoteGridList.Any(x => x.Symbol == k.FullSymbol); var item = QuoteGridList.FirstOrDefault(i => i.Symbol == k.FullSymbol); if (item != null) { if (k.HasBid) { item.BidPair = new QuoteGridLine.QuotePair(item.BidPair._newvalue, k.BidPrice); item.BidSize = k.BidSize; } if (k.HasAsk) { item.AskPair = new QuoteGridLine.QuotePair(item.AskPair._newvalue, k.AskPrice); item.AskSize = k.AskSize; } if (k.IsTrade) { // decimal old_trade = (decimal)item.TradePair._newvalue; item.TradePair = new QuoteGridLine.QuotePair(item.TradePair._newvalue, k.TradePrice); item.Size = k.TradeSize; //item.TradeColor = k.TradePrice > old_trade ? System.Windows.Media.Colors.Green // : (k.TradePrice == old_trade ? System.Windows.Media.Colors.White : System.Windows.Media.Colors.Red); if (item.PreClose != 0m) { item.Change = k.TradePrice - item.PreClose; item.ChangePercentage = String.Format("{0:P3}.", k.TradePrice / item.PreClose - 1); } } } }
/// <summary> /// Write in the following sequence: Date Time trade bid ask depth /// Empty quote is Tick field default value, which is 0 /// </summary> public void newTick(Tick k) { // get types _outstream.WriteLine(k.ToString()); // write to disk _outstream.Flush(); // count it _count++; }
public static Tick NewTrade(string fullsym, int date, int time, decimal trade, int size) { Tick t = new Tick(fullsym); t.Date = date; t.Time = time; t.TradePrice = trade; t.TradeSize = size; t.BidPrice = 0m; t.AskPrice = 0m; return t; }
public void UpdateViews(Tick k) { if ((GridViewModel != null) && k.IsValid) { // _uidispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher; System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)(() => { GridViewModel.UpdateRow(k); }), DispatcherPriority.Background); System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)(() => { PlotViewModel.GotTick(k); }),DispatcherPriority.Background); } }
public override void GotTick(Tick tick) { // ignore quotes // after fill, tick size is adjusted. So use tick price to judge if (tick.TradePrice == 0) return; // get current position Position p = RetrievePosition(tick.FullSymbol); // if we're flat, enter if (p.isFlat && _isactive) { SendDebug("entering long"); SendOrder(new MarketOrder(tick.FullSymbol, _entrysize, _idtracker.NextOrderId)); } // otherwise if we're up 10/th of a point, flat us else if ((Calc.OpenPT(tick.TradePrice, p) > _profittarget) && _isactive) { SendDebug("hit profit target"); SendOrder(new MarketOrderFlat(p,_idtracker.NextOrderId)); } }
public override void GotTick(Tick k) { if (IsActive) { if ((k.Time >= 93000) && (k.Time <= 160200)) _barlisttracker.NewTick(k); else if (k.Time > 160200) Shutdown(); if (k.Time > sentouttime_[emailsent_] + 1) { emailsent_++; if (emailsent_ == sentouttime_.Length) Shutdown(); // send out email StringBuilder sb = new StringBuilder(); sb.Append("<table>"); sb.Append("<tr><td>Symbol</td><td>Open</td><td>High</td><td>Low</td><td>Close</td><td>Change</td><td>Change(%)</td></tr>"); foreach (string s in _symbols) { string[] symbol = s.Split(' '); BarList bl = _barlisttracker[s, 86400]; try { sb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td></tr>", symbol[0], (bl.Open()[0]).ToString("N2"), (bl.High()[0]).ToString("N2"), (bl.Low()[0]).ToString("N2"), (bl.Close()[0]).ToString("N2"), (bl.Close()[0] - _precloseDict[s]).ToString("N2"), (bl.Close()[0] / _precloseDict[s] - 1).ToString("0.##%")); } catch { } } sb.Append("<table>"); string subject = "Current Market @ " + sentouttime_[emailsent_ - 1]; Util.Sendemail(subject, sb.ToString(), true); } } }
public void GotTick(Tick k) { string s = k.FullSymbol; if (!_trades.ContainsKey(s)) { _bids.Add(s, 0); _asks.Add(s,0); _bidsizes.Add(s,0); _asksizes.Add(s,0); _trades.Add(s,0); _tradesizes.Add(s,0); _lastdates.Add(s,0); _lasttimes.Add(s,0); } _lastdates[s] = k.Date; _lasttimes[s] = k.Time; if (k.IsTrade) { _trades[s] = k.TradePrice; _tradesizes[s] = k.TradeSize; } if (k.HasAsk) { _asks[s] = k.AskPrice; _asksizes[s] = k.AskSize; } if (k.HasBid) { _bids[s] = k.BidPrice; _bidsizes[s] = k.BidSize; } }
/// <summary> /// call this function from GotTick /// </summary> /// <param name="k"></param> public void newTick(Tick k) { _tw.newTick(k); }
public override void GotTick(Tick k) { if (_isactive) SendDebug("Hello World."); }
/// <summary> /// must pass ticks as received to this function, in order to have trailing stops executed at proper time. /// </summary> /// <param name="k"></param> public void newTick(Tick k) { // see if we're turned on if (!isValid) return; // see if we can exit when trail is broken if (SendOrder == null) return; // see if we have anything to trail against if (_pt[k.FullSymbol].isFlat) return; // // pass along as point if (k.IsTrade && !UseBidAskExitPrices) newPoint(k.FullSymbol, k.TradePrice); if (UseBidAskExitPrices && _pt[k.FullSymbol].isLong && k.HasBid) newPoint(k.FullSymbol, k.BidPrice); else if (UseBidAskExitPrices && _pt[k.FullSymbol].isShort && k.HasAsk) newPoint(k.FullSymbol, k.AskPrice); }
/// <summary> /// should be called from GotTick, when ticks arrive. /// If cancels are not processed on fill updates, they will be resent each tick until they are processed. /// </summary> /// <param name="k"></param> public void newTick(Tick k) { // otherwise update the offsets for this tick's symbol doupdate(k.symbol); }
public override void GotTick(Tick k) { _currenttime = k.Time; if (_currenttime > _shutdowntime) { Shutdown(); return; } _barlisttracker.NewTick(k); // blt rejects symbols that it doesn't track // ignore anything that is not a trade if (!k.IsTrade) return; // exit conditon if ((Calc.OpenPL(k.TradePrice, _positiontracker[k.FullSymbol]) + _positiontracker[k.FullSymbol].ClosedPL > TotalProfitTarget) || (Calc.OpenPL(k.TradePrice, _positiontracker[k.FullSymbol]) + _positiontracker[k.FullSymbol].ClosedPL < TotalLossTolerance)) { Shutdown(k.FullSymbol); } }
public bool newTick(Tick t) { if (_stopped) return false; if ((t.FullSymbol == null) || (t.FullSymbol == "")) return false; TickWriter tw; // prepare last date of tick int lastdate = t.Date; lastdate = _datedict.GetOrAdd(t.FullSymbol, t.Date); // see if we need a new day bool samedate = lastdate == t.Date; // see if we have stream already bool havestream = _filedict.TryGetValue(t.FullSymbol, out tw); // if no changes, just save tick if (samedate && havestream) { try { tw.newTick((Tick)t); return true; } catch (IOException) { return false; } } else { try { // if new date, close stream if (!samedate) { try { tw.Close(); } catch (IOException) { } } // ensure file is writable string file = Util.SafeFilename(t.FullSymbol, _folderpath, t.Date); if (TickUtil.IsFileWritetable(file)) { // open new stream tw = new TickWriter(_folderpath, t.FullSymbol, t.Date); // save tick tw.newTick((Tick)t); // save stream if (!havestream) _filedict.Add(t.FullSymbol, tw); else _filedict[t.FullSymbol] = tw; // save date if changed if (!samedate) { _datedict[t.FullSymbol] = t.Date; } } } catch (IOException) { return false; } catch (Exception) { return false; } } return false; }
void _backtestengine_GotTickEvent(Tick t) { if (_showticks) { _date = t.Date; _time = t.Time; // don't display ticks for unmatched exchanges string trade = ""; string bid = ""; string ask = ""; string ts = ""; string bs = ""; string os = ""; if (t.IsIndex) { trade = t.TradePrice.ToString(_dps); } else if (t.IsTrade) { trade = t.TradePrice.ToString(_dps); ts = t.TradeSize.ToString(); } if (t.HasBid) { bs = t.BidSize.ToString(); bid = t.BidSize.ToString(_dps); } if (t.HasAsk) { ask = t.AskPrice.ToString(_dps); os = t.AskSize.ToString(); } // add tick to grid System.Windows.Application.Current.Dispatcher.Invoke(() => { _ticktable.Rows.Add(new string[] { t.Date.ToString(), _time.ToString(), t.FullSymbol, trade, ts, bs, bid, ask, os }); }); } }
void OnGotTick(Tick k) { if (GotTickDelegate != null) GotTickDelegate(k); }
public virtual void updateMktDepthL2(int tickerId, int position, string marketMaker, int operation, int side, double price, int size) { if (tickerId < 0 || tickerId > _marketDataRequests.Count) { OnDebug("can't match market data ticker."); return; } Tick k = new Tick(); DateTime ct = DateTime.Now; k.Date = ct.Year * 10000 + ct.Month * 100 + ct.Day; k.Time = ct.Hour * 10000 + ct.Minute * 100 + ct.Second; k.FullSymbol = _marketDataRequests[tickerId].FullSymbol; if (side == 1) // side 0 for ask, 1 for bid { // why L1 bid price is updated with L2? //_marketDataRequests[tickerId].bid = (decimal)price; k.BidPrice = (decimal)price; k.BidSize = size; } if (side == 0) // side 0 for ask, 1 for bid { //_marketDataRequests[tickerId].ask = (decimal)price; k.AskPrice = (decimal)price; k.AskSize = size; } else { return; } k.Depth= position; if (k.IsValid) { OnGotTick(k); } }
public virtual void tickSize(int tickerId, int field, int size) { if (tickerId < 0 || tickerId > _marketDataRequests.Count) { OnDebug("can't match market data ticker."); return; } Tick k = new Tick(); DateTime ct = DateTime.Now; k.Date = ct.Year * 10000 + ct.Month * 100 + ct.Day; k.Time = ct.Hour * 10000 + ct.Minute * 100 + ct.Second; k.FullSymbol = _marketDataRequests[tickerId].FullSymbol; // this will be removed Security sec = Security.Deserialize(k.FullSymbol); bool hundrednorm = (sec.SecurityType == "STK") || (sec.SecurityType == "NIL"); if (field == (int)TickType.LastSize) { _marketDataRequests[tickerId].TradeSize = size; // not adjusted by hundreds k.TradeSize = _marketDataRequests[tickerId].TradeSize; k.TradePrice = _marketDataRequests[tickerId].TradePrice; } else if (field == (int)TickType.BidSize) { _marketDataRequests[tickerId].BidSize = size; k.BidPrice = _marketDataRequests[tickerId].BidPrice; k.BidSize = _marketDataRequests[tickerId].BidSize; } else if (field == (int)TickType.AskSize) { _marketDataRequests[tickerId].AskSize = size; k.AskSize = _marketDataRequests[tickerId].AskSize; k.AskPrice = _marketDataRequests[tickerId].AskPrice; } else { return; } if (k.IsValid) { OnGotTick(k); } }
public virtual void tickPrice(int tickerId, int field, double price, int canAutoExecute) { if (tickerId < 0 || tickerId > _marketDataRequests.Count) { OnDebug("can't match market data ticker."); return; } Tick k = new Tick(); DateTime ct = DateTime.Now; k.Date = ct.Year * 10000 + ct.Month * 100 + ct.Day; k.Time = ct.Hour * 10000 + ct.Minute * 100 + ct.Second; k.FullSymbol = _marketDataRequests[tickerId].FullSymbol; if (field == (int)TickType.LastPrice) { _marketDataRequests[tickerId].TradePrice = (decimal)price; k.TradePrice = (decimal)price; k.TradeSize = _marketDataRequests[tickerId].TradeSize; } else if (field == (int)TickType.BidPrice) { _marketDataRequests[tickerId].BidPrice = (decimal)price; k.BidPrice = (decimal)price; k.BidSize = _marketDataRequests[tickerId].BidSize; } else if (field == (int)TickType.AskPrice) { _marketDataRequests[tickerId].AskPrice = (decimal)price; k.AskPrice = (decimal)price; k.AskSize = _marketDataRequests[tickerId].AskSize; } else { return; } if (k.IsValid) { OnGotTick(k); } }
//********************************* Outgoing Messages *************************************// #region Outgoing Messages /// <summary> /// Request market data for a basket of securities according to their FullNames /// </summary> /// <param name="b"></param> public void RequestMarketData(Basket b) { // Connection is verified in _ibSocket.reqMktData for (int i = 0; i < b.Count; i++) { Contract contract; contract = SecurityFullNameToContract(b[i]); bool exist = false; foreach (var t in _marketDataRequests) { if (t.FullSymbol == b[i]) exist = true; } if (exist) continue; else { Tick tick = new Tick(); // tick symbol is security full name tick.FullSymbol = b[i]; _marketDataRequests.Add(tick); _ibSocket.reqMktData(_marketDataRequests.Count - 1, contract, null, false); } } }
/// <summary> /// Executes any open orders allowed by the specified tick. /// </summary> /// <param name="tick">The tick.</param> /// <returns>the number of orders executed using the tick.</returns> public int Execute(Tick tick) { if (_pendingorders == 0) { return(0); } if (!tick.IsTrade && !_usebidaskfill) { return(0); } int filledorders = 0; Account[] accts = new Account[_masterorders.Count]; _masterorders.Keys.CopyTo(accts, 0); // go through each account for (int idx = 0; idx < accts.Length; idx++) { Account a = accts[idx]; // if account has requested no executions, skip it if (!a.Execute) { continue; } // make sure we have a record for this account if (!_mastertrades.ContainsKey(a.ID)) { _mastertrades.Add(a.ID, new List <Trade>()); } // track orders being removed and trades that need notification List <int> notifytrade = new List <int>(); List <int> remove = new List <int>(); // go through each order in the account for (int i = 0; i < _masterorders[a].Count; i++) { Order o = _masterorders[a][i]; //make sure tick is for the right stock if (tick.FullSymbol != o.FullSymbol) { continue; } bool filled = false; if (UseHighLiquidityFillsEOD) { Order oi = (Order)o; filled = oi.FillHighLiquidityEOD(tick, _usebidaskfill, false); } else if (o.TIF <= TimeInForce.GTC) { filled = o.Fill(tick, _usebidaskfill, false); // fill our trade } else if (o.TIF == TimeInForce.OPG) { // if it's already opened, we missed our shot if (_hasopened.Contains(o.FullSymbol)) { continue; } // otherwise make sure it's really the opening //if (tick.Exchange == OPGEX) { // it's the opening tick, so fill it as an opg filled = o.Fill(tick, _usebidaskfill, true); // mark this symbol as already being open _hasopened.Add(tick.FullSymbol); } } // other orders fill normally, except MOC orders which are at 4:00PM else if (o.TIF == TimeInForce.MOC) { if (tick.Time >= 160000) { filled = o.Fill(tick, _usebidaskfill, false); // fill our trade } } else { filled = o.Fill(tick, _usebidaskfill, false); // fill our trade } if (filled) { // get copy of trade for recording Trade trade = new Trade((Trade)o); // remove filled size from size available in trade if (_adjustincomingticksize) { if (_usebidaskfill) { if (o.Side) { tick.AskSize -= trade.UnsignedSize; } else { tick.BidSize -= trade.UnsignedSize; } } else { tick.TradeSize -= trade.UnsignedSize; } } // if trade represents entire requested order, mark order for removal if (trade.UnsignedSize == o.UnsignedSize) { remove.Add(i); } else // otherwise reflect order's remaining size { o.OrderSize = (o.UnsignedSize - trade.UnsignedSize) * (o.OrderSide ? 1 : -1); } // record trade _mastertrades[a.ID].Add(trade); // mark it for notification notifytrade.Add(_mastertrades[a.ID].Count - 1); // count the trade filledorders++; } } int rmcount = remove.Count; // remove the filled orders for (int i = remove.Count - 1; i >= 0; i--) { _masterorders[a].RemoveAt(remove[i]); } // unmark filled orders as pending _pendingorders -= rmcount; if (_pendingorders < 0) { _pendingorders = 0; } // notify subscribers of trade if (a.Notify) { for (int tradeidx = 0; tradeidx < notifytrade.Count; tradeidx++) { OnGotFill(_mastertrades[a.ID][notifytrade[tradeidx]]); } } } return(filledorders); }
private void OnGotTick(Tick k) { var handler = GotTickHanlder; if (handler != null) handler(k); }
public override void GotTick(Tick k) { //SendDebug("Hello World."); }
void _histsim_GotTick(Tick t) { _date = t.Date; _time = t.Time; /// Note that for stocks, the total size is 100* that in tick file if (t.FullSymbol.Contains("STK")) { t.BidSize *= 100; t.AskSize *= 100; t.TradeSize *= 100; } // execute pending orders _simbroker.Execute(t); // notify strategy if (_strategy != null) _strategy.GotTick(t); // tell others, e.g. TickTable GotTick(t); }
public void NewTick(Tick k) { // ignore quotes if (k.TradePrice == 0) return; // get the barcount long barid = GetBarId(k.Time, k.Date, intervallength); int baridx; //(barid != curr_barid) // what if ticks arrive a bit out of sequence? // Live datafeeds generally have no requirement that tick timestamps are strictly ordered. // as Level1 aggregates data from multiple venues, if timestamp is the exchange timestamp, // it is quite possible the order is different from aggregator "received" timestamp // The datavendors as a rule don't perform "re-sorting" of ticks based on timestamp // to ensure strict ordering as it is both expensive and arguably unnecessary. if (barid > curr_barid) // true new bar needs to be formed { // create a new one NewBar(barid); // mark it _isRecentNew = true; // make it current curr_barid = barid; // set time orders[orders.Count - 1] = GetOrder(k.Time,intervallength); // set date dates[dates.Count - 1] = k.Date; baridx = Last(); } else if (isOldTickBackfillEnabled && (barid < curr_barid)) // out-of sequence tick, already formed bar needs updating { baridx = ids.IndexOf(barid); _isRecentNew = false; } else // bar formed; update tick values { baridx = Last(); _isRecentNew = false; } // blend tick into bar // open if (baridx >= 0) { if (opens[baridx] == 0) opens[baridx] = k.TradePrice; // high if (k.TradePrice > highs[baridx]) highs[baridx] = k.TradePrice; // low if (k.TradePrice < lows[baridx]) lows[baridx] = k.TradePrice; // close closes[baridx] = k.TradePrice; // volume if (k.TradeSize >= 0) vols[baridx] += k.TradeSize; } // notify barlist if (_isRecentNew) OnNewBar(k.FullSymbol, intervallength); }
/// <summary> /// should be called from GotTick, when ticks arrive. /// If cancels are not processed on fill updates, they will be resent each tick until they are processed. /// </summary> /// <param name="k"></param> public void newTick(Tick k) { // otherwise update the offsets for this tick's symbol doupdate(k.FullSymbol); }
//********************************* Incoming Messages *************************************// #region Incoming Messages /// <summary> /// Post and Get HTTP requests /// GotTick /// </summary> private void GetQuoteLoop(CancellationToken token) { string query; // it is called after market data request, // so SecurityFullNameToGoogleSymbol is not empty query = string.Join(",", SecurityFullNameToGoogleSymbol.Select(x => x.Value).ToArray()); query = url + query; while (true) { if (token.IsCancellationRequested) { break; } try { // Create a request for the URL. HttpWebRequest grequest = (HttpWebRequest)WebRequest.Create(query); // If required by the server, set the credentials. grequest.Credentials = CredentialCache.DefaultCredentials; // Get the response. HttpWebResponse gresponse = (HttpWebResponse)grequest.GetResponse(); // Display the status. // Console.WriteLine(((HttpWebResponse)gresponse).StatusDescription); // Get the stream containing content returned by the server. Stream gdatastream = gresponse.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader greader = new StreamReader(gdatastream); // Read the content. string quotestr = greader.ReadToEnd(); // Display the content. // Console.WriteLine(quotestr); quotestr = quotestr.Replace("//", ""); // Clean up the streams and the response. greader.Close(); gdatastream.Close(); gresponse.Close(); var quote = JsonConvert.DeserializeObject<List<RealTimeData>>(quotestr); DateTime ct = DateTime.Now; int i = 0; // quote has the same order as that in securities; use this logic to retrieve symbol directly foreach (var sec in SecurityFullNameToGoogleSymbol) { Tick k = new Tick(); // it should create a new tick. Otherwise it overrides. k.Date = ct.Year * 10000 + ct.Month * 100 + ct.Day; k.Time = ct.Hour * 10000 + ct.Minute * 100 + ct.Second; //DateTime dt = DateTime.SpecifyKind(DateTime.Parse(quote[0].lt_dts), DateTimeKind.Utc); // Z shouldn't refer to local time //dt = dt.ToLocalTime(); //k.Date = Util.ToIntDate(dt); //k.Time = Util.ToIntTime(dt); k.FullSymbol = sec.Key; k.TradePrice = Convert.ToDecimal(quote[i].l); k.TradeSize = Convert.ToInt32(quote[i++].s); k.TradeSize = 1000; // overwrite. It seems that google hasn't provided size yet. SecurityFullNameToLastPrice[sec.Key] = k.TradePrice; if (k.IsValid) { if (GotTickDelegate != null) GotTickDelegate(k); } } } catch (Exception ex) { Debug("GoogleClient error: " + ex.Message); } // Sleep 30 seconds // Console.WriteLine("Time .... " + Util.ToIntTime(DateTime.Now)); System.Threading.Thread.Sleep(new TimeSpan(0, 0, 0, 0, RefreshInterval)); } }
public void GotTick(Tick k) { newTick(k); }
public Tick this[string symbol] { get { if (!IsTracked(symbol)) return new Tick(); Tick k = new Tick(symbol); k.Date = _lastdates[symbol]; k.Time = _lasttimes[symbol]; k.TradePrice = _trades[symbol]; k.TradeSize = _tradesizes[symbol]; k.BidPrice = _bids[symbol]; k.BidSize = _bidsizes[symbol]; k.AskPrice = _asks[symbol]; k.AskSize = _asksizes[symbol]; return k; } }
void GotTick(Tick k) { if (GotTickEvent != null) GotTickEvent(k); }
public override void GotTick(Tick k) { _currenttime = k.Time; if (_currenttime > _shutdowntime) { Shutdown(); return; } _barlisttracker.NewTick(k); // blt rejects symbols that it doesn't track // ignore anything that is not a trade if (!k.IsTrade) return; // exit condition if ((Calc.OpenPL(k.TradePrice, _positiontracker[k.FullSymbol]) + _positiontracker[k.FullSymbol].ClosedPL > TotalProfitTarget) || (Calc.OpenPL(k.TradePrice, _positiontracker[k.FullSymbol]) + _positiontracker[k.FullSymbol].ClosedPL < TotalLossTolerance)) { Shutdown(k.FullSymbol); } // potential orders int idx = _symbols.IndexOf(k.FullSymbol); //if (_isHigherTimeFrameBullBear[idx] == _isLowerTimeFrameBullBear[idx]) { } }
void _client_GotTickDelegate(Tick k) { // Enqueue // blocking without cancellation _tickqueue.Add(k); }
public void GotTick(Tick k) { if (_configmanager.RealTimePlot) { if (_tickseriesdict.ContainsKey(k.FullSymbol) && k.IsTrade) { try { _tickseriesdict[k.FullSymbol].Points.Add(new DataPoint(OxyPlot.Axes.DateTimeAxis.ToDouble(DateTime.Now), (double)k.TradePrice)); } catch (Exception) {} } } }