//rest of the code void OnStockTick(object sender, StockTick stockTick) { const decimal maxChangeRatio = 0.1m; StockInfo stockInfo; var quoteSymbol = stockTick.QuoteSymbol; lock (_stockTickLocker) { var stockInfoExists = _stockInfos.TryGetValue(quoteSymbol, out stockInfo); if (stockInfoExists) { var priceDiff = stockTick.Price - stockInfo.PrevPrice; var changeRatio = Math.Abs(priceDiff / stockInfo.PrevPrice); //#A the percentage of change if (changeRatio > maxChangeRatio) { Console.WriteLine("Stock:{0} has changed with {1} ratio, Old Price:{2} New Price:{3}", quoteSymbol, changeRatio, stockInfo.PrevPrice, stockTick.Price); } _stockInfos[quoteSymbol].PrevPrice = stockTick.Price; } else { _stockInfos[quoteSymbol] = new StockInfo(quoteSymbol, stockTick.Price); } } }
public static void Main(string[] args) { LoggerNLog.BasicConfig(); LoggerNLog.Register(); if (args.Length < 1) { Console.Out.WriteLine("Arguments are: <numberOfEvents>"); Environment.Exit(-1); } int events; try { events = int.Parse(args[0]); } catch (NullReferenceException) { Console.Out.WriteLine("Invalid numberOfEvents:" + args[0]); Environment.Exit(-2); return; } // Prime a few assemblies into memory var tempA = new StockTick(null, 0.0); var tempB = new PriceLimit(null, null, 0.0); // Run the sample var autoIdSimMain = new AutoIdSimMain(events, "AutoIDSim"); autoIdSimMain.Run(); }
public IActionResult SaveStockPrices([FromBody] StockPriceUpdate request) { try { List <StockTick> ticks = new List <StockTick>(); foreach (var stk in request.Stocks) { StockTick tick = new StockTick() { StockId = stk.Currency.Replace("/", "_"), TimeStamp = UnixTimeStampToDateTime(stk.Timestamp), Rate = stk.Rate, Ask = stk.Ask, Bid = stk.Bid, Close = stk.Close, High = stk.High, Low = stk.Low, Open = stk.Open }; ticks.Add(tick); } // Save Data _dbManager.StockTicks.AddRange(ticks); _dbManager.SaveChanges(); return(Ok(ticks)); } catch (Exception es) { _logger.LogError(es, "Failed to add the requested stock records to the system ..."); return(StatusCode(500, "Failed to add the requested stock records to the system ...")); } }
public static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); if (args.Length < 1) { Console.Out.WriteLine("Arguments are: <numberOfEvents>"); Environment.Exit(-1); } int events; try { events = Int32.Parse(args[0]); } catch (NullReferenceException) { Console.Out.WriteLine("Invalid numberOfEvents:" + args[0]); Environment.Exit(-2); return; } // Prime a few assemblies into memory StockTick tempA = new StockTick(null, 0.0); PriceLimit tempB = new PriceLimit(null, null, 0.0); // Run the sample AutoIdSimMain autoIdSimMain = new AutoIdSimMain(events, "AutoIDSim"); autoIdSimMain.Run(); }
static async Task Start(IEndpointInstance endpointInstance) { var rand = new Random(); Console.WriteLine("Press any key to start publishing"); Console.ReadKey(true); do { while (!Console.KeyAvailable) { var stockSymbol = Symbols[rand.Next(0, Symbols.Length - 1)]; var stockTick = new StockTick { Symbol = stockSymbol, Timestamp = DateTime.UtcNow }; await endpointInstance.Publish(stockTick) .ConfigureAwait(false); await Task.Delay(500) .ConfigureAwait(false); Console.WriteLine($"Published StockTick Event with Symbol {stockSymbol}. Press escape to stop publishing events."); } } while (Console.ReadKey(true).Key != ConsoleKey.Escape); }
protected void WriteTick(StockTick tick) { lock (gate) { var output = new System.Text.StringBuilder(); Action<string> traceStrategy; if (tick.Change > 0) { output.Append('↑'); output.Append(' '); traceStrategy = TraceStatus; } else if (tick.Change < 0) { output.Append('↓'); output.Append(' '); traceStrategy = TraceWarning; } else { output.Append('-'); output.Append(' '); traceStrategy = TraceLine; } output.Append(tick); traceStrategy(output.ToString()); } }
private void Compute(StockTick newTick, StockTick oldTick) { _count++; var change = newTick.Price - oldTick.Price; if (_count <= _period) { if (change > 0) { Log.Info(".Count " + _count + " Advance " + change); _adv.Add(change); } else { Log.Info(".Count " + _count + " Decline " + change); _decl.Add(change); } } if (_count >= _period) { if (_count == _period) { _avgLoss = AvgValueList(_decl); _avgGain = AvgValueList(_adv); } else { _adv.Clear(); _decl.Clear(); var adv = 0.0; var decl = 0.0; if (change > 0) { Log.Info(".Count " + _count + " Advance " + change); adv = change; } else { Log.Info(".Count " + _count + " Decline " + change); decl = change; } _avgGain = ((_avgGain * (_period - 1)) + adv) / _period; _avgLoss = ((_avgLoss * (_period - 1)) + decl) / _period; } if (_avgLoss == 0) { _rs = 100.0; _rsi = 100.0; } else { _rs = Math.Abs(_avgGain / _avgLoss); var to1 = 1.0 + _rs; var to100 = 100.0 / to1; _rsi = 100.0 - to100; } } }
public LimitAlert(StockTick tick, PriceLimit limit, double initialPrice) { Tick = tick; PriceLimit = limit; InitialPrice = initialPrice; }
public RSIEvent(StockTick tick_, double avgLoss_, double avgGain_, double rs_, double rsi_) { _tick = tick_; _avgLoss = avgLoss_; _avgGain = avgGain_; _rs = rs_; _rsi = rsi_; }
public List <StockTick> Get(string ticker) { string url = AlphaVantageApi.GetTimeSeriesUrl(AlphaVantageApi.TIME_SERIES.TIME_SERIES_DAILY, ticker); JObject result = JObject.Parse(client.GetStringAsync(url).Result); JObject stockPrices = result[$"Time Series ({AlphaVantageApi.GetDescription(AlphaVantageApi.TIME_INTERVALS.Daily)})"].Value <JObject>(); return(StockTick.ParseArrayPrice(stockPrices, 50)); }
public StockAlert(IEnumerable<StockTick> prefix, StockTick tick) { Contract.Requires(prefix != null); this.tick = tick; this.prefixAsString = prefix.Aggregate( new StringBuilder(), (builder, t) => builder.Append(t.Value).Append(','), builder => (builder.Length == 0) ? string.Empty : builder.ToString(0, builder.Length - 1)); }
private void CheckMargin(StockTick newTick, StockInfo oldStockInfo) { var ratio = Math.Abs((newTick.Price - oldStockInfo.PrevPrice) / oldStockInfo.PrevPrice); if (ratio > maxChangeRatio) { Console.WriteLine($"Stock:{newTick.QuoteSymbol} has changed with {ratio} " + $"ratio,Old Price:{ oldStockInfo.PrevPrice} New Price:{newTick.Price}"); } }
public StockTickerAlertListener( EPRuntime runtime, PriceLimit limit, StockTick initialPriceTick, StockTickerResultListener stockTickerResultListener) { _limit = limit; _initialPriceTick = initialPriceTick; _stockTickerResultListener = stockTickerResultListener; }
public void Update(Object sender, UpdateEventArgs e) { EventBean[] newEvents = e.NewEvents; Object eventBean = newEvents[0]["Tick"]; StockTick tick = (StockTick)eventBean; Log.Info(" Stock " + tick.StockSymbol + " Price " + tick.Price); eventBean = newEvents[0]["AvgLoss"]; _avgLoss = (Double)eventBean; if (_avgLoss == Double.MinValue) { Log.Info(" Not Meaningful "); } else { _avgLoss = To1tenthPrecision((Double)eventBean); Log.Info(" AvgLoss " + _avgLoss); } eventBean = newEvents[0]["AvgGain"]; _avgGain = (Double)eventBean; if (_avgGain == Double.MinValue) { Log.Info(" Not Meaningful "); } else { _avgGain = To1tenthPrecision((Double)eventBean); Log.Info(" AvgGain " + _avgGain); } eventBean = newEvents[0]["RS"]; _rs = (Double)eventBean; if (_rs == Double.MinValue) { Log.Info(" Not Meaningful "); } else { _rs = To1tenthPrecision((Double)eventBean); Log.Info(" RS " + _rs); } eventBean = newEvents[0]["RSI"]; _rsi = (Double)eventBean; if (_rsi == Double.MinValue) { Log.Info(" Not Meaningful "); } else { _rsiCount++; _rsi = To1tenthPrecision((Double)eventBean); Log.Info(" RSI " + _rsi); } }
public void RecordPrice(StockTick stockTick) { LatestPrice = new StockPrice { Open = stockTick.Open, Last = stockTick.Last, AsAtDate = stockTick.Date, High = stockTick.High, Low = stockTick.Low }; }
public IList <object> MakeEventStream(int numberOfTicks, int ratioOutOfLimit, int numberOfStocks, double priceLimitPctLowerLimit, double priceLimitPctUpperLimit, double priceLowerLimit, double priceUpperLimit, bool isLastTickOutOfLimit) { var stream = new List <object>(); var limitBeans = MakeLimits( "example_user", numberOfStocks, priceLimitPctLowerLimit, priceLimitPctUpperLimit); for (var i = 0; i < limitBeans.Length; i++) { stream.Add(limitBeans[i]); } // The first stock ticker sets up an initial price var initialPrices = MakeInitialPriceStockTicks(limitBeans, priceLowerLimit, priceUpperLimit); for (var i = 0; i < initialPrices.Length; i++) { stream.Add(initialPrices[i]); } for (var i = 0; i < numberOfTicks; i++) { var index = i % limitBeans.Length; var tick = MakeStockTick(limitBeans[index], initialPrices[index]); // Generate an out-of-limit price if (i % ratioOutOfLimit == 0) { tick = new StockTick(tick.StockSymbol, -1); } // Last tick is out-of-limit as well if (i == numberOfTicks - 1 && isLastTickOutOfLimit) { tick = new StockTick(tick.StockSymbol, 9999); } stream.Add(tick); } return(stream); }
public void Update(Object sender, UpdateEventArgs e) { EventBean[] newEvents = e.NewEvents; Object eventBean = newEvents[0]["tick"]; StockTick newTick = (StockTick)eventBean; Log.Info(".update for stock=" + newTick.StockSymbol + " price=" + newTick.Price); if (_oldEvents != null) { eventBean = _oldEvents[0]["tick"]; StockTick oldTick = (StockTick)eventBean; Compute(newTick, oldTick); _epService.EPRuntime.SendEvent(new RSIEvent(newTick, _avgLoss, _avgGain, _rs, _rsi)); } _oldEvents = newEvents; }
public StockTick[] MakeInitialPriceStockTicks(PriceLimit[] limitBeans, double price_lower_boundary, double price_upper_boundary) { var stockTickBeans = new StockTick[limitBeans.Length]; for (int i = 0; i < stockTickBeans.Length; i++) { String stockSymbol = limitBeans[i].StockSymbol; // Determine a random price double diff = price_upper_boundary - price_lower_boundary; double price = price_lower_boundary + _random.NextDouble() * diff; stockTickBeans[i] = new StockTick(stockSymbol, To1tenthPrecision(price)); } return(stockTickBeans); }
private void OnStockTick(object sender, StockTick tick) { StockInfo stockInfo; lock (_locker) { var quoteSymbol = tick.QuoteSymbol; var prevQuote = concurStockInfos.TryGetValue(quoteSymbol, out stockInfo); if (stockInfo != null) { CheckMargin(tick, stockInfo); concurStockInfos[quoteSymbol].PrevPrice = tick.Price; } else { //stockInfos.Add(quoteSymbol, new StockInfo(quoteSymbol, tick.Price)); concurStockInfos.AddOrUpdate(quoteSymbol, new StockInfo(quoteSymbol, tick.Price), (k, v) => { return(null); }); } } }
public StockTick MakeStockTick(PriceLimit limitBean, StockTick initialPrice) { String stockSymbol = limitBean.StockSymbol; double range = initialPrice.Price * limitBean.LimitPct / 100; double price = (initialPrice.Price - range + (range * 2 * _random.NextDouble())); double priceReducedPrecision = To1tenthPrecision(price); if (priceReducedPrecision < (initialPrice.Price - range)) { priceReducedPrecision = initialPrice.Price; } if (priceReducedPrecision > (initialPrice.Price + range)) { priceReducedPrecision = initialPrice.Price; } return(new StockTick(stockSymbol, priceReducedPrecision)); }
public StockTick MakeStockTick(PriceLimit limitBean, StockTick initialPrice) { var stockSymbol = limitBean.StockSymbol; var range = initialPrice.Price * limitBean.LimitPct / 100; var price = initialPrice.Price - range + range * 2 * _random.NextDouble(); var priceReducedPrecision = To1tenthPrecision(price); if (priceReducedPrecision < initialPrice.Price - range) { priceReducedPrecision = initialPrice.Price; } if (priceReducedPrecision > initialPrice.Price + range) { priceReducedPrecision = initialPrice.Price; } return(new StockTick(stockSymbol, priceReducedPrecision)); }
public void TestFlow() { var generator = new StockTickerEventGenerator(); PriceLimit[] limitBeans = generator.MakeLimits("nunit", NUM_STOCK_NAMES, PRICE_LIMIT_PCT_LOWER_LIMIT, PRICE_LIMIT_PCT_UPPER_LIMIT); Assert.IsTrue(limitBeans.Length == NUM_STOCK_NAMES); Assert.IsTrue(limitBeans[0].UserId.Equals("nunit")); for (int i = 0; i < limitBeans.Length; i++) { Assert.IsTrue(limitBeans[i].LimitPct >= PRICE_LIMIT_PCT_LOWER_LIMIT); Assert.IsTrue(limitBeans[i].LimitPct <= PRICE_LIMIT_PCT_UPPER_LIMIT); } StockTick[] initialPrices = generator.MakeInitialPriceStockTicks(limitBeans, PRICE_LOWER_LIMIT, PRICE_LOWER_LIMIT); Assert.IsTrue(initialPrices.Length == NUM_STOCK_NAMES); for (int i = 0; i < initialPrices.Length; i++) { Assert.IsTrue(initialPrices[i].Price >= PRICE_LOWER_LIMIT); Assert.IsTrue(initialPrices[i].Price <= PRICE_UPPER_LIMIT); } for (int i = 0; i < 100000; i++) { StockTick tick = generator.MakeStockTick(limitBeans[0], initialPrices[0]); double initialPrice = initialPrices[0].Price; double range = initialPrice * limitBeans[0].LimitPct / 100; Assert.IsTrue(tick.Price > (initialPrice - range) - 1); Assert.IsTrue(tick.Price < (initialPrice + range) + 1); } }
private void SendEvent(String symbol, double price) { StockTick eventBean = new StockTick(symbol, price); _epService.EPRuntime.SendEvent(eventBean); }
private void SendEvent(StockTick @event) { _stockTickSender.SendEvent(@event); }
public StockTickerAlertListener(EPServiceProvider epService, PriceLimit limit, StockTick initialPriceTick, StockTickerResultListener stockTickerResultListener) { _limit = limit; _initialPriceTick = initialPriceTick; _stockTickerResultListener = stockTickerResultListener; }
private void SendEvent(String symbol, double price) { var eventBean = new StockTick(symbol, price); _runtime.EventService.SendEventBean(eventBean, eventBean.GetType().FullName); }