public void TestGetIndex() { var ts = new TickSeries("test"); for (int i = 0; i < 10; ++i) ts.Add(new Tick { DateTime = new DateTime(2000, 1, 1, 10, i, 30) }); var firstDt = new DateTime(2000, 1, 1, 10, 3, 30); var firstTick = new Tick { DateTime = firstDt }; var lastDt = new DateTime(2000, 1, 1, 10, 9, 30); var lastTick = new Tick { DateTime = lastDt }; // DateTime is in the middle; Assert.Equal(3, ts.GetIndex(firstDt, IndexOption.Null)); Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 25), IndexOption.Null)); Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 30), IndexOption.Null)); Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 30), IndexOption.Prev)); Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 30), IndexOption.Next)); Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 25), IndexOption.Null)); Assert.Equal(3, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 25), IndexOption.Prev)); Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 25), IndexOption.Next)); Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 40), IndexOption.Null)); Assert.Equal(4, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 40), IndexOption.Prev)); Assert.Equal(5, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 40), IndexOption.Next)); // DateTime > LastDateTime Assert.Equal(5, ts.GetIndex(new DateTime(2000, 1, 1, 10, 4, 40), IndexOption.Next)); Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 11, 30), IndexOption.Null)); Assert.Equal(9, ts.GetIndex(new DateTime(2000, 1, 1, 10, 11, 30), IndexOption.Prev)); Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 10, 11, 30), IndexOption.Next)); // DateTime < FirstDateTime Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 9, 31, 30), IndexOption.Null)); Assert.Equal(-1, ts.GetIndex(new DateTime(2000, 1, 1, 9, 31, 30), IndexOption.Prev)); Assert.Equal(0, ts.GetIndex(new DateTime(2000, 1, 1, 9, 31, 30), IndexOption.Next)); }
/// <summary> /// passes ticks from a response to the form GUI elements, so user /// can see the tick /// </summary> /// <param name="k"></param> public void newTick(Tick k) { // update the screen with the tick // if arriving from background thread, // windows makes us update GUI elements by 'invoking' // from the GUI's thread. so we test for this when performing the update. if (InvokeRequired) { try { Invoke(new TickDelegate(newTick), new object[] { k }); } catch (ObjectDisposedException) { return; } } else { // make sure tick matches symbol we requested if (k.symbol != _sym.Text) return; // put data in the form if (k.hasAsk) _ask.Text = k.ask.ToString("N2"); if (k.hasBid) _bid.Text = k.bid.ToString("N2"); if (k.isTrade) _last.Text = k.trade.ToString("N2"); // refresh form's screen area Invalidate(true); } }
/// <summary> /// 收到tick事件,在这里添加策略逻辑。我们简单的每10个tick开仓/平仓,以最新价下单。 /// </summary> /// <param name="tick"></param> public override void OnTick(Tick tick) { Console.WriteLine( "tick {0}: time={1} symbol={2} last_price={3} :", HGStaUtil.getTickZF(tick), tick.utc_time, tick.sec_id, tick.last_price); double cutZf = 0; //大盘涨幅达到1的时候买入头寸 if (HGStaUtil.isSHTick(tick) && HGStaUtil.getTickZF(tick) >= 1 && !buyFlag) { cutZf = HGStaUtil.getTickZFFrmLastBuy(tick, lastDpZf); if (lastDpZs == 0 || cutZf >= 1) { buyFlag = true; Console.WriteLine("lastDpZs {0} cutZf {1}:", lastDpZs, cutZf); } } else if (!HGStaUtil.isSHTick(tick) && buyFlag) { Console.WriteLine("buyFlag {0} buycode {1}:", buyFlag, tick.sec_id); OpenLong(tick.exchange, tick.sec_id, tick.last_price, 100); //最新价开仓一手 buyFlag = false; } lastDpZs = tick.last_price; }
protected override void OnRenderFrame(FrameEventArgs e) { Tick tick = new Tick(); base.OnRenderFrame(e); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); GL.MatrixMode(MatrixMode.Modelview); m_camera.UpdateCameraView(); List<CoordinateEngine.RelativisticObject> ros = universe.GetNPCs(); lock (ros) { foreach (CoordinateEngine.RelativisticObject ro in ros) { DrawRelativisticObject (ro); } } lock(universe.bro){ m_camera.camera_position = CoordinateEngine.toVector3(universe.bro.x);//Loses accuracy in this... } //DrawRelativisticObject(universe.bro, false);//Don't draw bro if the camera is at bro. DrawHUD(); stats.AddValue(FPS_TAG, tick.Tock()); this.SwapBuffers(); Thread.Sleep(1); }
public void GotTick(Tick tick) { // we want to see if this trade is one of the top 10 biggest // get symbol from first tick if we haven't gotten one yet if (sym == "") sym = tick.symbol; else if (tick.symbol != sym) return; // ignore it if it's not a trade if (!tick.isTrade) return; // if we don't have 10 trades yet, add it if (dt.Rows.Count < 10) { dt.Rows.Add(tick.time, tick.trade, tick.size, tick.ex); ui.dg.Invalidate(true); // update the grid return; } // otherwise, go through list and check to see if it's bigger for (int i = 0; i < dt.Rows.Count; i++) if ((int)dt.Rows[i]["TradeSize"] < tick.size) { dt.Rows[i].ItemArray = new object[] { tick.time, tick.trade, tick.size, tick.ex }; ui.dg.InvalidateRow(i); // update the grid return; } }
public StockQuote(string symbol, double price, DateTime date, Tick tick) { _symbol = symbol; _price = price; _date = date; _tick = tick; }
public bool newTick(Tick t) { if ((t.symbol==null) || (t.symbol=="")) return false; TikWriter tw; if (filedict.TryGetValue(t.symbol, out tw)) { try { tw.newTick(t); } catch (IOException) { return false; } } else { try { tw = new TikWriter(_path, t.symbol, t.date); tw.newTick(t); filedict.Add(t.symbol, tw); } catch (IOException) { return false; } catch (Exception) { return false; } } return true; }
/// <summary> /// if new ticks are passed to this ticket, ticket will automatically update the price of limit and stops orders for opposing side. /// </summary> /// <param name="tick"></param> public void newTick(Tick tick) { if (this.InvokeRequired) { try { Invoke(new TickDelegate(newTick), new object[] { tick }); } catch (ObjectDisposedException) { return; } } else { if ((tick == null) || (tick.symbol != work.symbol)) return; if (touched) return; decimal changedval = obuybut.Checked ? (limitbut.Checked ? tick.ask : tick.bid) : (limitbut.Checked ? tick.bid : tick.ask); if (changedval != 0) { if (this.oprice.InvokeRequired) { this.Invoke(new TickDelegate(newTick), new object[] { tick }); } else oprice.Value = (decimal)changedval; } } }
public override void GotTick(Tick tick) { // track order ids _orderid.addindex(tick.symbol,0); // track ticks _kt.newTick(tick); // see if we need to send an order if (_orderid[tick.symbol] == 0) { // get complete last tick for this symbol Tick k = _kt[tick.symbol]; // see if we have proper info to place order if ((Side && k.hasBid) || (!Side && k.hasAsk)) { _orderid[tick.symbol] = _idt.NextId; D(tick.symbol + " sending limit order: " + _orderid[tick.symbol]); sendorder(new LimitOrder(tick.symbol, Side, Ordersize, Side ? k.bid - Distance : k.ask + Distance, _idt.AssignId)); } } else // otherwise increment counter _tickcounter[tick.symbol]++; // see if we need to cancel if (_tickcounter[tick.symbol] > Frequency) { D(tick.symbol + " hit frequency, canceling: " + _orderid[tick.symbol]); sendcancel(_orderid[tick.symbol]); } }
public override void GotTick(Tick tick) { // create bars from ticks _blt.newTick(tick); // make sure we have enough bars our indicator if (!_blt[tick.symbol].Has(MINBARS)) return; // get highs from our bar decimal[] highs = _blt[tick.symbol].High(); // get lows decimal[] lows = _blt[tick.symbol].Low(); // compute high low ranges decimal[] hlrange = Calc.Subtract(highs, lows); // compute average range decimal avghl = Calc.Avg(hlrange); // ignore volatile symbols if (avghl > MAXVOL) return; // compute MA decimal ma = Calc.Avg(_blt[tick.symbol].Close()); // trading rule if (_pt[tick.symbol].isFlat && (_blt[tick.symbol].RecentBar.Close > ma)) sendorder(new BuyMarket(tick.symbol, 100)); // exit rule if (_pt[tick.symbol].isLong && (_blt[tick.symbol].RecentBar.Close < ma)) sendorder(new MarketOrderFlat(_pt[tick.symbol])); }
// GotTick is called everytime a new quote or trade occurs public override void GotTick(Tick tick) { // make sure every tick has bars blt.newTick(tick); // if we don't have enough bars, wait for more ticks if (!blt[tick.symbol].Has(BarsBack)) return; // if we don't have a trade, wait to calculate indicators here if (!tick.isTrade) return; // this is a grey box that manages exits, so wait until we have a position if (!pt[tick.symbol].isFlat) return; // calculate the MA from closing bars decimal MA = Calc.Avg(Calc.Closes(blt[tick.symbol], BarsBack)); // if we're short, a cross is when market moves above MA // if we're long, cross is when market goes below MA bool cross = pt[tick.symbol].isShort ? (tick.trade > MA) : (tick.trade < MA); // if we have a cross, then flat us for the requested size if (cross) sendorder(new MarketOrderFlat(pt[tick.symbol],exitpercent)); // notify gauntlet and kadina about our moving average and cross sendindicators(new string[] { MA.ToString(), cross.ToString() } ); }
/// <summary> /// Converts the tick to a string-equivalent that can be written to an EPF file. /// </summary> /// <param name="t">The t.</param> /// <returns></returns> public static string ToEPF(Tick t) { string s = ""; if (!t.isTrade) s = "Q," + epfdate(t.date) + "," + epftime(t.time) + "," + t.bid + "," + t.ask + "," + t.bs + "," + t.os + "," + t.be + "," + t.oe; else s = "T," + epfdate(t.date) + "," + epftime(t.time) + "," + t.trade + "," + (t.size) + "," + t.ex; return s; }
public override void OnTick(Tick tick) { // if pre-market tick, don't do anything if (tick.Time < new TimeSpan(9, 30, 00)) return; // send the market order; this should get filled immediately Order value; if (!Markets.TryGetValue(tick.Symbol, out value)) { Order MktOrder = new Order(OrderSide.Buy, OrderType.Market, tick.Symbol, 100); Markets.Add(tick.Symbol, MktOrder); PlaceOrder(MktOrder); log.DebugFormat("{0} {1}: Sent market order from within Strategy. Price: {2} Size: {3}", MktOrder.Timestamp, MktOrder.Symbol, MktOrder.Price, MktOrder.Size); } // send the limit order; this should be expensive enough that it never gets filled if(!Limits.TryGetValue(tick.Symbol, out value)) { Order LimitOrder = new Order(OrderSide.Sell, OrderType.Limit, tick.Symbol, 100, 500); Limits.Add(tick.Symbol, LimitOrder); PlaceOrder(LimitOrder); log.DebugFormat("{0} {1}: Sent limit order from within Strategy. Price: {2} Size: {3}", LimitOrder.Timestamp, LimitOrder.Symbol, LimitOrder.Price, LimitOrder.Size); } }
public void GotTick(Tick k) { // ignore trades if (k.isTrade) return; // make sure depth is valid for this book if ((k.depth < 0) || (k.depth >= maxbook)) return; if (Sym == null) Sym = k.symbol; // make sure symbol matches if (k.symbol != Sym) return; // if depth is zero, must be a new book if (k.depth == 0) Reset(); // update buy book if (k.hasBid) { bidprice[k.depth] = k.bid; bidsize[k.depth] = k.BidSize; bidex[k.depth] = k.be; if (k.depth > ActualDepth) ActualDepth = k.depth; } // update sell book if (k.hasAsk) { askprice[k.depth] = k.ask; asksize[k.depth] = k.AskSize; askex[k.depth] = k.oe; if (k.depth > ActualDepth) ActualDepth = k.depth; } }
public override void GotTick(Tick k) { // update offsets ot.newTick(k); // build bars from ticks blt.newTick(k); }
// here is where a line is converted public static Tick[] parseline(string line, string sym) { // split line line=line.Remove(8, 1); line=line.Insert(8, ";"); string[] r = line.Split(';'); // create tick for this symbol Tick[] result = new Tick[4]; Tick high = new TickImpl(sym); Tick low = new TickImpl(sym); Tick open = new TickImpl(sym); Tick close = new TickImpl(sym); long dt = 0; int tt; if (long.TryParse(r[DATE], out dt)) { open.date = (int)(dt); high.date = (int)(dt); low.date = (int)(dt); close.date = (int)(dt); } //r[TIME]=r[TIME].Substring(0, 4); if (int.TryParse(r[TIME], out tt)) { if (tt < 040000) tt += 120000; open.time = tt; close.time = tt; high.time = tt; low.time = tt; open.datetime = dt * 1000000 + tt; high.datetime = dt * 1000000 + tt; low.datetime = dt * 1000000 + tt; close.datetime = dt * 1000000 + tt; } int size = 0; if (int.TryParse(r[VOL], out size)) { high.size = Math.Max(1, size / 4); low.size = Math.Max(1, size / 4); open.size = Math.Max(1, size / 4); close.size = Math.Max(1, size/4); } decimal price = 0.0M; if (decimal.TryParse(r[HIGH], out price)) high.trade = price; if (decimal.TryParse(r[OPEN], out price)) open.trade = price; if (decimal.TryParse(r[LOW], out price)) low.trade = price; if (decimal.TryParse(r[CLOSE], out price)) close.trade = price; result[0] = open; result[1] = high; result[2] = low; result[3] = close; return result; }
public Quote(string symbol, double price, int volume, DateTime date, Tick tick) { _symbol = symbol; _price = price; _volume = volume; _date = date; _tick = tick; }
public void newTick(Tick k) { if (k.time > _lasttime) { _lasttime = k.time; checktifs(); } }
/// <summary> /// 上次买入后的涨幅 /// </summary> /// <param name="gp"></param> /// <returns></returns> public static double getTickZFFrmLastBuy(Tick gp, double lastBuy) { if (lastBuy > 0) { return Math.Round(((gp.last_price - lastBuy) / lastBuy) * 100, 2); //涨幅 } return 0; }
/// <summary> /// 涨幅 /// </summary> /// <param name="gp"></param> /// <returns></returns> public static double getTickZF(Tick gp) { if (gp.pre_close > 0) { return Math.Round(((gp.last_price - gp.pre_close) / gp.pre_close) * 100,2); //涨幅 } return 0; }
public override void GotTick(Tick k) { // get index from symbol, add if it doesn't exist int idx = PRIMARY.addindex(k.symbol,k.symbol); // build bars blt.newTick(k); // update whether entries are allowed entryok[idx] = expectedsize[idx] == pt[idx].Size; }
protected override void gotnewtick(Tick k) { // save in memory if (_greedy) _mem.Add(k); // notify user base.gotnewtick(k); }
/// <summary> /// give any ticks to this symbol and tracker will create barlists automatically /// </summary> /// <param name="k"></param> public void newTick(Tick k) { BarListImpl bl; if (!_bdict.TryGetValue(k.symbol, out bl)) { bl = new BarListImpl(k.symbol,_requested); bl.DefaultInterval = _default; bl.GotNewBar+=new SymBarIntervalDelegate(bl_GotNewBar); _bdict.Add(k.symbol, bl); } bl.newTick(k); }
public override void GotTick(Tick tick) { if (RequestedForSymbol.getindex(tick.symbol) == GenericTracker.UNKNOWN || RequestedForSymbol[tick.symbol] == false) { RequestedForSymbol.addindex(tick.symbol, true); Order myOrder = new MOCOrder(tick.symbol, true, 100); sendorder(myOrder); //senddebug(myOrder.TIF); senddebug("Sent Order: " + myOrder); } }
public override void GotTick(Tick k) { // if we don't have bar data, request historical data if (_blt[k.symbol].Count == 0) { D(k.symbol + " no bars found, requesting..."); sendmessage(MessageTypes.BARREQUEST, BarRequest.BuildBarRequest(k.symbol, BarInterval.Hour)); } D(k.symbol + " bar count: " + _blt[k.symbol].Count); // update whatever data we have with ticks _blt.newTick(k); }
public void GotTick(Tick k) { if (!k.isTrade) return; if (k.symbol == _symb) _pb = k.trade; if (k.symbol == _syma) _pa = k.trade; if (!hasPrices) return; _parel = _pa * _ratio; int spread = Spread; if ((Math.Abs(spread) > _spreadbound) && (SpreadOutsideBounds != null)) SpreadOutsideBounds(spread); }
public TermAndDistance(Tick tick) { if (tick < 0) { Distance = tick; Term = Term._1; } else { Distance = (Tick)((int)tick % (int)Const.Term); Term = (Term)(((int)tick / (int)Const.Term) % SPRPG.Const.SkillSlotSize); } }
private void Push(Tick tick) { xsTick.Add(tick); // set maxprice if (tick.last_price > maxprice) maxprice = tick.last_price; // set stopLosssPrice; if (posTrace != null && maxprice > posTrace.price * 1.05) { stopLossPrice = posTrace.price * 0.95; } }
// here is where a line is converted public static Tick[] parseline(string line, string sym) { // split line string[] r = line.Split(','); sym = r[SYMBOL]; // create tick for this symbol Tick[] result = new Tick[4]; Tick high = new TickImpl(sym); Tick low = new TickImpl(sym); Tick open = new TickImpl(sym); Tick close = new TickImpl(sym); long dt=0; if (long.TryParse(r[DATETIME], out dt)) { open.datetime = dt; high.datetime = dt; low.datetime = dt; close.datetime = dt; open.date = (int)(dt/10000); high.date = (int)(dt/10000); low.date = (int)(dt/10000); close.date = (int)(dt/10000); open.time = ((int)open.datetime - open.date * 10000)*100; close.time = ((int)close.datetime - close.date * 10000)*100; high.time = ((int)high.datetime - high.date * 10000)*100; low.time = ((int)low.datetime - low.date * 10000)*100; } int size = 0; if (int.TryParse(r[VOL], out size)) { high.size = Math.Max(1, size / 4); low.size = Math.Max(1, size / 4); open.size = Math.Max(1, size / 4); close.size = Math.Max(1, size / 4); } decimal price = 0.0M; if (decimal.TryParse(r[HIGH], out price)) high.trade = price; if (decimal.TryParse(r[OPEN], out price)) open.trade = price; if (decimal.TryParse(r[LOW], out price)) low.trade = price; if (decimal.TryParse(r[CLOSE], out price)) close.trade = price; result[0] = open; result[1] = high; result[2] = low; result[3] = close; return result; }
public RailClient() { RailConnection.IsServer = false; this.serverPeer = null; this.localTick = Tick.START; this.Room.Initialize(Tick.INVALID); this.pendingEntities = new Dictionary<EntityId, RailEntity>(EntityId.Comparer); this.knownEntities = new Dictionary<EntityId, RailEntity>(EntityId.Comparer); this.toRemove = new List<RailEntity>(); }
public void 处理tick(Tick tick) { 计算开平多空(tick); 处理盘口(tick); 计算局部涨跌(); }
public void ExecuteTick(TimeSpan elapsedTime) { Tick?.Invoke(this, new TimerTickEventArgs(elapsedTime)); }
private void Sync_RPC(Tick tick, int hash) { this.statesHistoryModule.SetSyncHash(tick, hash); }
private void tr2_gotTick(Tick t) { _readdata2.Add(t); }
public void RemoteDataDoesNotIncreaseNumberOfSlices() { Config.Set("quandl-auth-token", "QUANDL-TOKEN"); var startDate = new DateTime(2018, 4, 2); var endDate = new DateTime(2018, 4, 19); var algorithm = new QCAlgorithm(); var timeProvider = new ManualTimeProvider(TimeZones.NewYork); timeProvider.SetCurrentTime(startDate); var dataQueueHandler = new FuncDataQueueHandler(fdqh => { var time = timeProvider.GetUtcNow().ConvertFromUtc(TimeZones.NewYork); var tick = new Tick(time, Symbols.SPY, 1.3m, 1.2m, 1.3m) { TickType = TickType.Trade }; var tick2 = new Tick(time, Symbols.AAPL, 1.3m, 1.2m, 1.3m) { TickType = TickType.Trade }; return(new[] { tick, tick2 }); }); CreateDataFeed(dataQueueHandler); var dataManager = new DataManagerStub(algorithm, _feed); algorithm.SubscriptionManager.SetDataManager(dataManager); var symbols = new List <Symbol> { algorithm.AddData <Quandl>("CBOE/VXV", Resolution.Daily).Symbol, algorithm.AddData <QuandlVix>("CBOE/VIX", Resolution.Daily).Symbol, algorithm.AddEquity("SPY", Resolution.Daily).Symbol, algorithm.AddEquity("AAPL", Resolution.Daily).Symbol }; algorithm.PostInitialize(); var cancellationTokenSource = new CancellationTokenSource(); var dataPointsEmitted = 0; var slicesEmitted = 0; RunLiveDataFeed(algorithm, startDate, symbols, timeProvider, dataManager); Thread.Sleep(5000); // Give remote sources a handicap, so the data is available in time // create a timer to advance time much faster than realtime and to simulate live Quandl data file updates var timerInterval = TimeSpan.FromMilliseconds(100); var timer = Ref.Create <Timer>(null); timer.Value = new Timer(state => { // stop the timer to prevent reentrancy timer.Value.Change(Timeout.Infinite, Timeout.Infinite); var currentTime = timeProvider.GetUtcNow().ConvertFromUtc(TimeZones.NewYork); if (currentTime.Date > endDate.Date) { _feed.Exit(); cancellationTokenSource.Cancel(); return; } timeProvider.Advance(TimeSpan.FromHours(3)); // restart the timer timer.Value.Change(timerInterval, timerInterval); }, null, TimeSpan.FromSeconds(2), timerInterval); try { foreach (var timeSlice in _synchronizer.StreamData(cancellationTokenSource.Token)) { if (timeSlice.Slice.HasData) { slicesEmitted++; dataPointsEmitted += timeSlice.Slice.Values.Count; Assert.IsTrue(timeSlice.Slice.Values.Any(x => x.Symbol == symbols[0]), $"Slice doesn't contain {symbols[0]}"); Assert.IsTrue(timeSlice.Slice.Values.Any(x => x.Symbol == symbols[1]), $"Slice doesn't contain {symbols[1]}"); Assert.IsTrue(timeSlice.Slice.Values.Any(x => x.Symbol == symbols[2]), $"Slice doesn't contain {symbols[2]}"); Assert.IsTrue(timeSlice.Slice.Values.Any(x => x.Symbol == symbols[3]), $"Slice doesn't contain {symbols[3]}"); } } } catch (Exception exception) { Log.Trace($"Error: {exception}"); } timer.Value.Dispose(); dataManager.RemoveAllSubscriptions(); Assert.AreEqual(14, slicesEmitted); Assert.AreEqual(14 * symbols.Count, dataPointsEmitted); }
private void ProcessJsonObject(string json) { try { var dataList = JsonConvert.DeserializeObject <List <StreamResponseStocksUS> >(json); foreach (var item in dataList) { var symbolString = item.Symbol; Symbol symbol; if (!_symbols.TryGetValue(symbolString, out symbol)) { // Symbol is no loner in dictionary, it may be the stream not has been updated yet, // and the old client is still sending messages for unsubscribed symbols - // so there can be residual messages for the symbol, which we must skip continue; } var lastPrice = item.IexRealtimePrice ?? 0; var lastSize = item.IexRealtimeSize ?? 0; // Refers to the last update time of iexRealtimePrice in milliseconds since midnight Jan 1, 1970 UTC or -1 or 0. // If the value is -1 or 0, IEX has not quoted the symbol in the trading day. var lastUpdateMillis = item.IexLastUpdated ?? 0; if (lastUpdateMillis <= 0) { continue; } // (!) Epoch timestamp in milliseconds of the last market hours trade excluding the closing auction trade. var lastTradeMillis = item.LastTradeTime ?? 0; if (lastTradeMillis <= 0) { continue; } // If there is a last trade time but no last price or size - this is an error if (lastPrice == 0 || lastSize == 0) { throw new InvalidOperationException("ProcessJsonObject(): Invalid price & size."); } // Check if there is a kvp entry for a symbol long value; var isInDictionary = _iexLastTradeTime.TryGetValue(symbolString, out value); // We should update with trade-tick if: // - there exist an entry for a symbol and new trade time is different from time in dictionary // - not in dictionary, means the first trade-tick case if (isInDictionary && value != lastTradeMillis || !isInDictionary) { var lastTradeDateTime = UnixEpoch.AddMilliseconds(lastTradeMillis); var lastTradeTimeNewYork = lastTradeDateTime.ConvertFromUtc(TimeZones.NewYork); var tradeTick = new Tick() { Symbol = symbol, Time = lastTradeTimeNewYork, TickType = TickType.Trade, Value = lastPrice, Quantity = lastSize }; _aggregator.Update(tradeTick); _iexLastTradeTime[symbolString] = lastTradeMillis; } } } catch (Exception err) { Log.Error("IEXDataQueueHandler.ProcessJsonObject(): " + err.Message); } }
public override void Close(Tick <Audience> tick) { }
public void OnMessage(Tick message) { this.Messages.Add(message); }
/// <summary> /// Closes an order based on a tick value /// </summary> public void CloseOrder(Tick data) { }
public override NodeState ParticularTick(Tick tick) { _shopaholic.Idle(); return(NodeState.SUCCESS); }
private void OnMessage(object sender, WebSocketMessage e) { var jObject = JObject.Parse(e.Message); var type = jObject["type"].ToString(); switch (type) { case "trade": { var trade = jObject.ToObject <TradeMessage>(); var item = new Tick { Symbol = _symbolMapper.GetLeanSymbol(trade.SymbolId, SecurityType.Crypto, string.Empty), Time = trade.TimeExchange, Value = trade.Price, Quantity = trade.Size, TickType = TickType.Trade }; lock (_locker) { _ticks.Add(item); } _connectionHandler.KeepAlive(DateTime.UtcNow); break; } case "quote": { var quote = jObject.ToObject <QuoteMessage>(); var tick = new Tick { Symbol = _symbolMapper.GetLeanSymbol(quote.SymbolId, SecurityType.Crypto, string.Empty), Time = quote.TimeExchange, AskPrice = quote.AskPrice, AskSize = quote.AskSize, BidPrice = quote.BidPrice, BidSize = quote.BidSize, TickType = TickType.Quote }; lock (_locker) { // only emit quote ticks if bid price or ask price changed Tick previousQuote; if (!_previousQuotes.TryGetValue(tick.Symbol, out previousQuote) || tick.AskPrice != previousQuote.AskPrice || tick.BidPrice != previousQuote.BidPrice) { _previousQuotes[tick.Symbol] = tick; _ticks.Add(tick); } } _connectionHandler.KeepAlive(DateTime.UtcNow); break; } // not a typo :) case "hearbeat": // just in case the typo will be fixed in the future case "heartbeat": _connectionHandler.KeepAlive(DateTime.UtcNow); break; case "error": { var error = jObject.ToObject <ErrorMessage>(); Log.Error(error.Message); break; } default: Log.Trace(e.Message); break; } }
/// <summary> /// Raises the <see cref="Tick"/> event on the dispatcher thread. /// </summary> private void InternalTick() { Dispatcher.UIThread.EnsurePriority(_priority); Tick?.Invoke(this, EventArgs.Empty); }
protected virtual void OnTick(TickEventArgs e) => Tick?.Invoke(this, e);
public void 计算开平多空(Tick tick) { io++; if (preTick != null) { 现手 = tick.Volume - preTick.Volume; 仓 = tick.OpenInterest - preTick.OpenInterest; if (tick.LastPrice >= preTick.AskPrice1) { 多or空 = true; } else { 多or空 = false; } if (多or空) { 多空.多量 += 现手; if (仓 > 0) { 多空.开多数 += 仓; } else { 多空.平空数 -= 仓; } } else { 多空.空量 += 现手; if (仓 > 0) { 多空.开空数 += 仓; } else { 多空.平多数 -= 仓; } } } else { 多空.多量 = 0; 多空.空量 = 0; 多空.开多数 = 0; 多空.开空数 = 0; 多空.平多数 = 0; 多空.平空数 = 0; } if (tick.Volume != 0) { 均价 = tick.Turnover / tick.Volume; preTick = tick; } else { 均价 = tick.PreSettlementPrice; } #region 显示 #endregion }
public void GotTick(Tick k) { int idx = addindex(k.symbol); this[idx] = k.isTrade; }
public override void OnTick(Tick tick) { TickBuffer.Add(tick); 处理tick(tick); openan(); }
protected override void Exit(Tick <Audience> tick) { return; }
public void GotTick(Tick k) { newTick(k); }
protected override B3Status OnTick(Tick tick) { ai.RandomDir(); return(B3Status.SUCCESS); }
/// <summary> /// Handle a new price update packet: /// </summary> private void OnLevel1SummaryUpdateEvent(object sender, Level1SummaryUpdateEventArgs e) { // if ticker is not found, unsubscribe if (e.NotFound) { Unsubscribe(e.Symbol); } // only update if we have a value if (e.Last == 0) { return; } // only accept trade and B/A updates if (e.TypeOfUpdate != Level1SummaryUpdateEventArgs.UpdateType.ExtendedTrade && e.TypeOfUpdate != Level1SummaryUpdateEventArgs.UpdateType.Trade && e.TypeOfUpdate != Level1SummaryUpdateEventArgs.UpdateType.Bid && e.TypeOfUpdate != Level1SummaryUpdateEventArgs.UpdateType.Ask) { return; } count++; var time = FeedTime; var last = (decimal)(e.TypeOfUpdate == Level1SummaryUpdateEventArgs.UpdateType.ExtendedTrade ? e.ExtendedTradingLast : e.Last); var symbol = GetLeanSymbol(e.Symbol); TickType tradeType; switch (symbol.ID.SecurityType) { // the feed time is in NYC/EDT, convert it into EST case SecurityType.Forex: time = FeedTime.ConvertTo(TimeZones.NewYork, TimeZones.EasternStandard); // TypeOfUpdate always equal to UpdateType.Trade for FXCM, but the message contains B/A and last data tradeType = TickType.Quote; break; // for all other asset classes we leave it as is (NYC/EDT) default: time = FeedTime; tradeType = e.TypeOfUpdate == Level1SummaryUpdateEventArgs.UpdateType.Bid || e.TypeOfUpdate == Level1SummaryUpdateEventArgs.UpdateType.Ask ? TickType.Quote : TickType.Trade; break; } var tick = new Tick(time, symbol, last, (decimal)e.Bid, (decimal)e.Ask) { AskSize = e.AskSize, BidSize = e.BidSize, Quantity = e.IncrementalVolume, TickType = tradeType, DataType = MarketDataType.Tick }; Emit(tick); _prices[e.Symbol] = e.Last; if (symbol.ID.SecurityType == SecurityType.Option || symbol.ID.SecurityType == SecurityType.Future) { if (!_openInterests.ContainsKey(e.Symbol) || _openInterests[e.Symbol] != e.OpenInterest) { var oi = new OpenInterest(time, symbol, e.OpenInterest); Emit(oi); _openInterests[e.Symbol] = e.OpenInterest; } } }
protected override void OnOpen(Tick tick) { ai = tick.Target as PlayerAIExt; }
protected virtual void OnTick(string message) { Tick?.Invoke(message); }
public override void GotTick(Tick tick) { // pass the tick to the form q.newTick(tick); }
public void GotTick(Tick k) { int idx = addindex(k.symbol); this[idx] = k.hasAsk; }
protected override void onNewTick(Symbol symbol, Bar partialBar, Tick tick) { }
/// <summary> /// Called when tick received from <see cref="MarketDataListener"/> /// </summary> /// <param name="tick"></param> private void OnTickArrived(Tick tick) { _orderExecutor.TickArrived(tick); _tradeHubStrategy.OnTickArrived(tick); }
private Yield OnTick(SymbolInfo symbol, Tick tick) { if (quotePacketQueue.Count > 10) { return(Yield.NoWork.Repeat); } if (trace) { log.Trace("Sending tick: " + tick); } var packet = quoteSocket.CreatePacket(); StringBuilder sb = new StringBuilder(); if (tick.IsTrade) { sb.Append("3|"); // Trade } else { sb.Append("1|"); // Level 1 } sb.Append("2026=USD;"); //Currency sb.Append("1003="); //Symbol sb.Append(symbol.Symbol); sb.Append(';'); sb.Append("2037=0;"); //Open Interest sb.Append("2085=.144;"); //Unknown sb.Append("2048=00/00/2009;"); //Unknown sb.Append("2049=00/00/2009;"); //Unknown if (tick.IsTrade) { sb.Append("2002="); //Last Trade. sb.Append(tick.Price); sb.Append(';'); sb.Append("2007="); sb.Append(tick.Size); sb.Append(';'); } sb.Append("2050=0;"); //Unknown sb.Append("2003="); // Last Bid sb.Append(tick.Bid); sb.Append(';'); sb.Append("2051=0;"); //Unknown sb.Append("2004="); //Last Ask sb.Append(tick.Ask); sb.Append(';'); sb.Append("2052=00/00/2010;"); //Unknown sb.Append("2005="); sb.Append(Math.Max((int)tick.AskLevel(0), 1)); sb.Append(';'); sb.Append("2053=00/00/2010;"); //Unknown sb.Append("2006="); sb.Append(Math.Max((int)tick.BidLevel(0), 1)); sb.Append(';'); sb.Append("2008=0.0;"); // Yesterday Close sb.Append("2056=0.0;"); // Unknown sb.Append("2009=0.0;"); // High today sb.Append("2057=0;"); // Unknown sb.Append("2010=0.0"); // Low today sb.Append("2058=1;"); // Unknown sb.Append("2011=0.0;"); // Open Today sb.Append("2012=6828928;"); // Volume Today sb.Append("2013=20021;"); // Up/Down Tick sb.Append("2014="); // Time sb.Append(tick.UtcTime.TimeOfDay); sb.Append("."); sb.Append(tick.UtcTime.Microsecond); sb.Append(';'); sb.Append("2015="); sb.Append(tick.UtcTime.Month.ToString("00")); sb.Append('/'); sb.Append(tick.UtcTime.Day.ToString("00")); sb.Append('/'); sb.Append(tick.UtcTime.Year); sb.Append('\n'); var message = sb.ToString(); if (trace) { log.Trace("Tick message: " + message); } packet.DataOut.Write(message.ToCharArray()); if (packet == null) { throw new NullReferenceException(); } quotePacketQueue.Enqueue(packet); return(Yield.DidWork.Return); }
/// <summary> /// MarketDataSnapshot message handler /// </summary> private void OnMarketDataSnapshot(MarketDataSnapshot message) { var instrument = message.getInstrument(); var securityType = _symbolMapper.GetBrokerageSecurityType(instrument.getSymbol()); var symbol = _symbolMapper.GetLeanSymbol(instrument.getSymbol(), securityType, Market.FXCM); var isHistoryResponse = _pendingHistoryRequests.Contains(message.getRequestID()); if (isHistoryResponse) { var time = FromJavaDate(message.getDate().toDate()); // history timestamps must be in exchange time zone DateTimeZone exchangeTimeZone; if (_symbolExchangeTimeZones.TryGetValue(symbol, out exchangeTimeZone)) { time = time.ConvertFromUtc(exchangeTimeZone); } // append ticks/bars to history if (message.getFXCMTimingInterval() == FXCMTimingIntervalFactory.TICK) { var bidPrice = Convert.ToDecimal(message.getBidClose()); var askPrice = Convert.ToDecimal(message.getAskClose()); var tick = new Tick(time, symbol, bidPrice, askPrice); _lastHistoryChunk.Add(tick); } else { var bar = new QuoteBar( time, symbol, new Bar( Convert.ToDecimal(message.getBidOpen()), Convert.ToDecimal(message.getBidHigh()), Convert.ToDecimal(message.getBidLow()), Convert.ToDecimal(message.getBidClose()) ), 0, new Bar( Convert.ToDecimal(message.getAskOpen()), Convert.ToDecimal(message.getAskHigh()), Convert.ToDecimal(message.getAskLow()), Convert.ToDecimal(message.getAskClose()) ), 0); _lastHistoryChunk.Add(bar); } } else { // update the current prices for the instrument lock (_locker) { _rates[instrument.getSymbol()] = message; } // if instrument is subscribed, add ticks to list if (_subscribedSymbols.Contains(symbol)) { // For some unknown reason, messages returned by SubscriptionRequestTypeFactory.SUBSCRIBE // have message.getDate() rounded to the second, so we use message.getMakingTime() instead var time = FromJavaDate(new java.util.Date(message.getMakingTime())); // live ticks timestamps must be in exchange time zone DateTimeZone exchangeTimeZone; if (_symbolExchangeTimeZones.TryGetValue(symbol, out exchangeTimeZone)) { time = time.ConvertFromUtc(exchangeTimeZone); } var bidPrice = Convert.ToDecimal(message.getBidClose()); var askPrice = Convert.ToDecimal(message.getAskClose()); var tick = new Tick(time, symbol, bidPrice, askPrice); lock (_ticks) { _ticks.Add(tick); } } } if (message.getRequestID() == _currentRequest) { if (message.getFXCMContinuousFlag() == IFixValueDefs.__Fields.FXCMCONTINUOUS_END) { _mapRequestsToAutoResetEvents[_currentRequest].Set(); _mapRequestsToAutoResetEvents.Remove(_currentRequest); if (isHistoryResponse) { _pendingHistoryRequests.Remove(_currentRequest); } } } }
private void tr_gotTick(Tick t) { _readdata.Add(t); }
/** * Open method. * * @method open * @param {Tick} tick A tick instance. **/ protected override void OnOpen(Tick tick) { _loopTimes = 0; }