public Asteroid(string size, float rotation, Vector2f pos, World parent, int value, bool spawned = false, bool add = true) : base(Rsc.Tex("rsc/Asteroid" + size + ".png"), pos, parent, value, add) { Rotation = Rand.RandInt(0, 360); MoveRot = rotation; Origin = Center; Size = size; Col = new Color(255, 200, 200, 100); var t = new Ticker(Parent, new TimeSpan(0, 0, 2), null); t.OnTick = delegate { t.Destroy(); Col = Color.White; Active = true; }; Active = !spawned; if (Active) { Col = Color.White; } if(DangerManager.Instance.UsedDP > DangerManager.Instance.MaxDP) { Destroy(); } }
public void Ticker_WhenStarted_TickEventInvoked() { this.ticker = null; base.BeginExecuteTest(); Assert.NotNull(ticker); }
public void TestEquals() { var t0 = new Ticker {InstrumentType = "Common Stock", Symbol = "NFLX:US", Country = "USA"}; var t1 = new Ticker {InstrumentType = "Common Stock", Symbol = "NFLX:US", Country = "USA"}; Assert.IsTrue(t0.Equals(t1)); }
private void AtualizarVariaveisBF(Ticker ticker, ref BlackFin dados) { if (dados.iMAXDC == 0 || ticker.iMaximo > dados.iMAXDC) dados.iMAXDC = ticker.iMaximo; if (dados.iMINDC == 0 || ticker.iMinimo < dados.iMINDC) dados.iMINDC = ticker.iMinimo; }
private void AddTicker(Ticker ticker) { //var allTickers = incomingTickers as IList<Ticker> ?? incomingTickers.ToList(); //if (!allTickers.Any()) //{ // // empty list of trades means we are disconnected // stale = true; //} //else //{ // if (stale) // { // stale = false; // } //} //foreach (var ticker in allTickers) //{ // Tickers.Single(x => x.Name == ticker.Name) // .AcceptNewPrice(ticker.Price); //} Tickers.Single(x => x.Name == ticker.Name) .AcceptNewPrice(ticker.Price); }
public void BaseInit(int moduleId, int instanceId, GameObject root) { m_wiInfo = WindowInfoMgr.GetWindowInfo(moduleId); m_iInstanceID = instanceId; m_objInstanceRoot = root; m_transInstanceRoot = root.GetComponent<RectTransform>(); m_ticker = m_objInstanceRoot.AddComponent<Ticker>(); }
protected override void OnViewLoaded(object view) { ticker = new Ticker<TickerItemView>(((MainView)view).LayoutRoot); ticker.Speed = new TimeSpan(0, 2, 0); ticker.ItemDisplayed += ticker_ItemDisplayed; manager.Start(); ticker.Start(); }
static void Main() { Ticker ticker = new Ticker(Timer.Action); // delegate -> action while (true) { Thread.Sleep(1000); ticker(); } }
public static void Main() { Timer obj = new Timer(); Ticker timer = new Ticker(obj.TickerPross); while (true) { Thread.Sleep(1000); timer(0); } }
static void Main() { Timer timerObj = new Timer(); Ticker timer = new Ticker(timerObj.TickerProcess); while (true) { Thread.Sleep(500); timer(0); } }
public Bolt(Vector2f pos, float rotation, World parent, bool add = true) : base(Rsc.Tex("rsc/Bolt.png"), pos, parent, add) { Rotation = rotation; Origin = Center; var ticker = new Ticker(Parent, new TimeSpan(0,0,0,2), null); ticker.OnTick = delegate { _start = true; ticker.Destroy(); }; }
public void testTicker() { Ticker JPM = new Ticker(); JPM.AddDay("JPM,20150102,62.62,62.96,62.07,62.49,12599900"); StockRow row = JPM[Utilities.toDate("20150102")]; string date = "Date: " + row.date; string high = "High: $" + row.high; Console.Out.WriteLine(date); Console.Out.WriteLine(high); } //raw hardcoded single string
public UFO(Vector2f pos, float rotation, World parent, bool add = true) : base(Rsc.Tex("rsc/UFO.png"), pos, parent, 80, add) { MoveRot = rotation; Col = new Color(255, 200, 200, 100); var t = new Ticker(Parent, new TimeSpan(0, 0, 2), null); t.OnTick = delegate { t.Destroy(); Col = Color.White; Active = true; }; Active = false; Origin = Center; }
/// <summary> /// Derived classes must override this method to implement their test logic. /// Note: this method is invoked on a worker thread which has an active Dispatcher. /// </summary> protected override void ExecuteTestAsync() { ticker = new Ticker(); bool tickEventInvoked = false; ticker.Tick += ((sender, e) => { tickEventInvoked = true; }); ticker.Start(); Assert.True(tickEventInvoked); base.WaitWithoutBlockingDispatcher(TimeSpan.FromMilliseconds(300)); // Let the base class know that the test is over // so that it can turn off the worker thread's // message pump. base.EndExecuteTest(); }
private void CreateRootCanvas() { m_objRootCanvas = new GameObject(); m_objRootCanvas.name = "RootCanvas"; m_objRootCanvas.layer = GameLayer.UI; m_transRootCanvas = m_objRootCanvas.AddComponent<RectTransform>(); m_compRootCanvas = m_objRootCanvas.AddComponent<Canvas>(); m_compRootCanvasScaler = m_objRootCanvas.AddComponent<CanvasScaler>(); m_compRootGraphicRaycaster = m_objRootCanvas.AddComponent<GraphicRaycaster>(); m_compTicker = m_objRootCanvas.AddComponent<Ticker>(); m_compTicker.onUpdate += OnTryOpenBufferedWindow; GameObject.DontDestroyOnLoad(m_objRootCanvas); m_compRootCanvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; m_compRootCanvasScaler.referenceResolution = new Vector2(1920, 1080); }
private void btOpenFile_Click(object sender, EventArgs e) { //openFileDialog1.Multiselect = true; openFileDialog1.InitialDirectory = @"C:\Users\Pedro\Investimentos"; //openFileDialog1.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 1; openFileDialog1.RestoreDirectory = true; if (DialogResult.OK == openFileDialog1.ShowDialog()) { //szOpenFiles = openFileDialog1.FileNames; fiOpenFile = new FileInfo(openFileDialog1.FileName); //textBox1.Text = fiOpenFile.FullName; } //carrega os dados StreamReader readFile = new StreamReader(fiOpenFile.FullName); string line; string[] lineCampos = new string[7]; readFile.ReadLine(); /*dia = new DiaNegocio[300*4]; DateTime data = new DateTime(1, 1, 1, 0, 0, 0); tsInicioTrade = TimeSpan.Parse(cbHorarioEntrada.SelectedItem.ToString()); tsSaidaTrade = TimeSpan.Parse(cbHorarioSaida.SelectedItem.ToString()); */ for (int i = 0, d = -1, t = 0; (line = readFile.ReadLine()) != null; i++) { lineCampos = line.Split(';'); dados[i] = new Ticker(); //dia[d].Ticker[i].sAtivo = lineCampos[0]; dados[i].dtData = DateTime.Parse(lineCampos[0] + " " + lineCampos[1]); //dia[d].Ticker[i].dtData.Date = DateTime.Parse(lineCampos[0]); //dia[d].Ticker[i].dtData.TimeOfDay = DateTime.Parse(lineCampos[1]); dados[i].iAbertura = Convert.ToInt32(lineCampos[2]); dados[i].iMaximo = Convert.ToInt32(lineCampos[3]); dados[i].iMinimo = Convert.ToInt32(lineCampos[4]); dados[i].iFechamento = Convert.ToInt32(lineCampos[5]); //dia[d].Ticker[i].dtData = DateTime.Parse(lineCampos[5]); } }
public void TestTickerCompare() { var testTickers = new Ticker[] { new Ticker {InstrumentType = "Common Stock", Symbol = "NFLX:US", Country = "USA"}, new Ticker {InstrumentType = "BDR", Symbol = "NFLX34:BZ", Country = "Brazil"}, new Ticker {InstrumentType = "Common Stock", Symbol = "NFC:GR", Country = "Germany"}, new Ticker {InstrumentType = "Common Stock", Symbol = "NFLX:SW", Country = "Switzerland"}, new Ticker {InstrumentType = "Common Stock", Symbol = "NFLX*:MM", Country = "Mexico"}, }; var testSubject = new TickerComparer("NETFLIX INC"); var testInput = testTickers.ToList(); testInput.Sort(testSubject); var testResult = testInput.First(); Assert.IsTrue(testResult.Equals(new Ticker {InstrumentType = "Common Stock", Symbol = "NFLX:US", Country = "USA"})); }
public static void Init(IEnumerable <Assembly> rendererAssemblies = null) { if (IsInitialized) { return; } string assemblyName = Assembly.GetExecutingAssembly().GetName().Name; Log.Listeners.Add(new DelegateLogListener((c, m) => Console.WriteLine("[{0}] {1}", m, c))); Registrar.ExtraAssemblies = rendererAssemblies?.ToArray(); Device.SetTargetIdiom(TargetIdiom.Desktop); Device.PlatformServices = new AvaloniaPlatformServices(); Device.Info = new AvaloniaUIDeviceInfo(); ExpressionSearch.Default = new AvaloniaUIExpressionSearch(); Registrar.RegisterAll(new[] { typeof(ExportRendererAttribute), typeof(ExportCellAttribute), typeof(ExportImageSourceHandlerAttribute) }); Ticker.SetDefault(new AvaloniaUITicker()); Device.SetIdiom(TargetIdiom.Desktop); IsInitialized = true; }
public void TestTickerLoopWithExitChan() { var start = DateTime.Now; var ticker = new Ticker(TimeSpan.FromSeconds(1)); var listOfTimes = new List <TimeSpan>(); var exitChan = new Chan <bool>(); var lookupdRecheckChan = new Chan <bool>(); bool doLoop = true; using (var select = Select .CaseReceive(ticker.C, o => listOfTimes.Add(DateTime.Now - start)) .CaseReceive(lookupdRecheckChan, o => listOfTimes.Add(DateTime.Now - start)) .CaseReceive(exitChan, o => doLoop = false) .NoDefault(defer: true)) { // ReSharper disable once LoopVariableIsNeverChangedInsideLoop while (doLoop) { select.Execute(); if (listOfTimes.Count >= 10) { GoFunc.Run(() => exitChan.Send(true), "exit notifier"); } } } ticker.Stop(); var duration = DateTime.Now - start; Assert.AreEqual(10, listOfTimes.Count, "listOfTimes.Count"); Assert.GreaterOrEqual(duration, TimeSpan.FromSeconds(10), "duration"); Assert.Less(duration, TimeSpan.FromSeconds(11)); }
public void TestTickerStopRaceCondition() { // NOTE: This race condition was difficult to reproduce in Release but occurs // almost immediately in Debug. var wg = new WaitGroup(); var rand = new Random(); const int tries = 1000; wg.Add(tries); for (int i = 0; i < tries; i++) { var time = rand.Next(1, 500); var ticker = new Ticker(TimeSpan.FromMilliseconds(time)); Time.AfterFunc(TimeSpan.FromMilliseconds(time), () => { ticker.Close(); wg.Done(); }); } wg.Wait(); }
public void Ticker_Current(string key) { var ticker = new Ticker(); var tracks = new List <ExampleTrack> { new ExampleTrack { Start = DateTime.Now.AddSeconds(-1), Stop = DateTime.Now.AddSeconds(3), Title = "1" }, new ExampleTrack { Start = DateTime.Now.AddSeconds(3), Stop = DateTime.Now.AddSeconds(5), Title = "2" }, new ExampleTrack { Start = DateTime.Now.AddSeconds(5), Stop = DateTime.Now.AddSeconds(7), Title = "3" } }; ticker.AddChannel(key, tracks); ticker.Start(); var playlist = ticker[key]; playlist.Should().NotBeNull(); playlist.Title.Should().Be(key); ((ExampleTrack)playlist.Current()).Title.Should().Be("1"); }
public static void Init(IActivatedEventArgs launchActivatedEventArgs) { if (s_isInitialized) { return; } var accent = (SolidColorBrush)Windows.UI.Xaml.Application.Current.Resources["SystemColorControlAccentBrush"]; Color.SetAccent(Color.FromRgba(accent.Color.R, accent.Color.G, accent.Color.B, accent.Color.A)); Log.Listeners.Add(new DelegateLogListener((c, m) => Debug.WriteLine(LogFormat, c, m))); Windows.UI.Xaml.Application.Current.Resources.MergedDictionaries.Add(GetPhoneResources()); Device.PlatformServices = new WindowsPhonePlatformServices(Window.Current.Dispatcher); Device.Info = new WindowsDeviceInfo(); Device.SetIdiom(TargetIdiom.Phone); Ticker.SetDefault(new WindowsTicker()); ExpressionSearch.Default = new WindowsExpressionSearch(); Registrar.RegisterAll(new[] { typeof(ExportRendererAttribute), typeof(ExportCellAttribute), typeof(ExportImageSourceHandlerAttribute) }); MessagingCenter.Subscribe <Page, bool> (Device.PlatformServices, Page.BusySetSignalName, OnPageBusy); HardwareButtons.BackPressed += OnBackPressed; s_isInitialized = true; s_state = launchActivatedEventArgs.PreviousExecutionState; }
/// <summary> /// Descents to node. /// </summary> internal static void DescentToNode(PGameObject nodeToHarvest) { var ticker = new Ticker(6000); if (ObjectManager.MyPlayer.InVashjir) { MoveHelper.Down(true); DescentToNodeVashir(nodeToHarvest); MoveHelper.Down(false); } else { if (!ObjectManager.MyPlayer.IsFlying) //To avoid sitting on the ground { return; } MoveHelper.Down(true); while (ObjectManager.MyPlayer.IsFlying && !ticker.IsReady) { Thread.Sleep(10); } MoveHelper.Down(false); } }
//Ugly ugly ugly but we have to support vashir internal static void DescentToSchool(PGameObject nodeToHarvest) { var ticker = new Ticker(20 * 1000); var timerDiff = new Ticker(500); float diffSelf = 3; Location oldPos = ObjectManager.MyPlayer.Location; float diffZ = MoveHelper.NegativeValue(nodeToHarvest.Location.Z - ObjectManager.MyPlayer.Location.Z); while (ObjectManager.MyPlayer.IsFlying && diffZ > 2 && !ticker.IsReady && diffSelf > 0.3) { if (FlyingBlackList.IsBlacklisted(nodeToHarvest)) { return; } diffZ = MoveHelper.NegativeValue(ObjectManager.MyPlayer.Location.Z - nodeToHarvest.Location.Z); if (timerDiff.IsReady) { diffSelf = MoveHelper.NegativeValue(oldPos.Z - ObjectManager.MyPlayer.Location.Z); timerDiff.Reset(); oldPos = ObjectManager.MyPlayer.Location; } Thread.Sleep(10); } }
public override Ticker GetTicker(string _pair) { string _url = $"/v1/market/ticker?market={_pair.ToUpper()}"; JToken _token = base.HttpCall(HttpCallMethod.Get, "GET", _url, false); if (_token == null) { return(null); } try { JObject _value = _token["ticker"].Value <JObject>(); Ticker _ticker = new Ticker(); _ticker.Pair = _pair; _ticker.LastPrice = _value["last"].Value <decimal>(); _ticker.BidPrice = _value["buy"].Value <decimal>(); _ticker.BidAmount = _value["buy_amount"].Value <decimal>(); _ticker.AskPrice = _value["sell"].Value <decimal>(); _ticker.AskAmount = _value["sell_amount"].Value <decimal>(); _ticker.Open24H = _value["open"].Value <decimal>(); _ticker.High24H = _value["high"].Value <decimal>(); _ticker.Low24H = _value["low"].Value <decimal>(); _ticker.Volume24H = _value["vol"].Value <decimal>(); return(_ticker); } catch (Exception _ex) { Console.WriteLine(_token.ToString(Newtonsoft.Json.Formatting.None)); Console.WriteLine(_ex.ToString()); return(null); } }
public async Task <IActionResult> GetMonthStatistics( [FromRoute] int year, [FromRoute] int month, [FromRoute] Ticker ticker) { log.Info($"Received a request \"{Request.Path}\""); if (!DateTimeExtensions.TryParse(year, month, 1, out var selectedDate)) { log.Warn($"Invalid date {year}/{month}"); return(BadRequest($"Invalid date {year}/{month}")); } var months = new List <Trade[]>(); foreach (var exchange in new[] { ExchangeTitle.Binance, ExchangeTitle.Bitfinex, ExchangeTitle.Bitstamp }) { var result = await manager.ReadForMonthAsync(exchange, ticker, selectedDate).ConfigureAwait(false); if (result.IsFail) { log.Error($"Failed to read trades from {exchange.ToString()} for {year}/{month}: {result.Error}"); } else { months.Add(result); } } return(Ok(new TradesMonthStatisticsResponse { AsksAmount = months.SelectMany(t => t).Where(t => t.IsSale).Sum(t => t.Amount), BidsAmount = months.SelectMany(t => t).Where(t => t.IsBuy).Sum(t => t.Amount) })); }
public async Task <IActionResult> GetTrades( [FromRoute] int year, [FromRoute] int month, [FromRoute] int day, [FromRoute] Ticker ticker, [FromRoute] ExchangeTitle exchange) { log.Info($"Received a request \"{Request.Path}\""); if (!DateTimeExtensions.TryParse(year, month, day, out var selectedDate)) { log.Warn($"Invalid date {year}/{month}/{day}"); return(BadRequest($"Invalid date {year}/{month}/{day}")); } var result = await manager.ReadForDayAsync(exchange, ticker, selectedDate).ConfigureAwait(false); if (result.IsFail) { return(NotFound(result.Error)); } return(Ok(result.Value.Select(TradeResponse.FromTrade))); }
private int SaveTickerPackage(long[] model, Ticker Ticker) { try { int dl = cms_db.DeleteContentPackage(Ticker.TickerId, (int)EnumCore.ObjTypeId.ticker); foreach (int _val in model) { ContentPackage tmp = new ContentPackage(); tmp.ContentId = Ticker.TickerId; tmp.ContentName = Ticker.TickerName; tmp.ContentType = (int)EnumCore.ObjTypeId.ticker; tmp.PackageId = _val; tmp.PackageName = cms_db.GetPackageName(_val); cms_db.CreateContentPackage(tmp); } return((int)EnumCore.Result.action_true); } catch (Exception e) { cms_db.AddToExceptionLog("SaveTickerPackage", "TickerManager", e.ToString(), long.Parse(User.Identity.GetUserId())); return((int)EnumCore.Result.action_false); } }
public void Update(Ticker ticker, IncrementalUpdateInfo info) { foreach (string[] item in info.BidsUpdates) { ticker.OrderBook.ApplyIncrementalUpdate(OrderBookEntryType.Bid, item[1], item[2]); } foreach (string[] item in info.AsksUpdates) { ticker.OrderBook.ApplyIncrementalUpdate(OrderBookEntryType.Ask, item[1], item[2]); } foreach (string[] item in info.TradeUpdates) { TradeInfoItem trade = new TradeInfoItem(null, ticker) { Type = item[0][0] == 'S' ? TradeType.Sell : TradeType.Buy, RateString = item[1], AmountString = item[2], Time = new DateTime(Convert.ToInt64(item[3])).ToLocalTime() }; ticker.TradeHistory.Insert(0, trade); CandleStickChartHelper.UpdateVolumes(ticker.CandleStickData, trade, ticker.CandleStickPeriodMin); } ticker.OnApplyIncrementalUpdate(); }
public RotaryControl() { iAlphaRing = 0.0f; iBlendStateRing = EBlendState.eUnknown; iTickerRing = new Ticker(); iAlphaCentre = 0.0f; iBlendStateCentre = EBlendState.eUnknown; iTickerCentre = new Ticker(); iTimer = new System.Threading.Timer(TimerElapsed); iTimer.Change(Timeout.Infinite, Timeout.Infinite); Text = String.Empty; iPenArc = new Pen(Color.FromArgb(128, Color.Red), 4); iAngle = 0; iStepSize = 30; InitialiseRing(); InitializeComponent(); }
public async Task <IEnumerable <Symbol> > GetTickerData(Ticker ticker) { try { var url = $"https://api.iextrading.com/1.0/stock/{ticker.Symbol}/chart/1y?filter=date,high,low,open,close,volume"; HttpResponseMessage response = await HttpClient.GetAsync(url); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); if (responseBody == "Unknown symbol") { throw new HttpRequestException(); } var tickerData = JsonConvert.DeserializeObject <IEnumerable <Symbol> >(responseBody); return(tickerData); } catch (HttpRequestException hre) { throw new HttpRequestException("Could not retrieve ticker", hre); } }
bool UpdateOrderBook(Ticker ticker, byte[] bytes) { if (bytes == null) { return(false); } int startIndex = 0; // skip { List <string[]> items = JSonHelper.Default.DeserializeArrayOfObjects(bytes, ref startIndex, OrderBookItems); List <OrderBookEntry> bids = ticker.OrderBook.Bids; List <OrderBookEntry> asks = ticker.OrderBook.Asks; List <OrderBookEntry> iasks = ticker.OrderBook.AsksInverted; foreach (string[] item in items) { OrderBookEntry entry = new OrderBookEntry(); entry.Id = FastValueConverter.ConvertPositiveLong(item[1]); entry.ValueString = item[4]; entry.AmountString = item[3]; if (item[2][0] == 'S') { iasks.Add(entry); asks.Insert(0, entry); } else { bids.Add(entry); } } ticker.OrderBook.UpdateEntries(); return(true); }
/// <summary> /// Fetch current best bid and ask, as well as the last trade price. /// </summary> /// <param name="base_name">The type of trading base-currency of which information you want to query for.</param> /// <param name="quote_name">The type of trading quote-currency of which information you want to query for.</param> /// <param name="args">Add additional attributes for each exchange</param> /// <returns></returns> public override async Task <Ticker> FetchTicker(string base_name, string quote_name, Dictionary <string, object> args = null) { var _result = new Ticker(base_name, quote_name); var _market = await this.LoadMarket(_result.marketId); if (_market.success == true) { publicClient.ExchangeInfo.ApiCallWait(TradeType.Public); var _params = publicClient.MergeParamsAndArgs(args); var _json_value = await publicClient.CallApiGet1Async($"/v1/pubticker/{_market.result.symbol}", _params); #if DEBUG _result.rawJson = _json_value.Content; #endif var _json_result = publicClient.GetResponseMessage(_json_value.Response); if (_json_result.success == true) { var _ticker = publicClient.DeserializeObject <BTickerItem>(_json_value.Content); { _ticker.symbol = _market.result.symbol; _result.result = _ticker; } } _result.SetResult(_json_result); } else { _result.SetResult(_market); } return(_result); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <remarks> /// json示例: /// { /// "result":"true","last":13.19,"high":13.45,"low":12.68,"avg":13.08,"sell":13.35,"buy":13.18,"vol_ltc":939.5685,"vol_cny":12291.28 /// } /// </remarks> private void DownloadTickerCompleted(object sender, DownloadStringCompletedEventArgs e) { Ticker ticker = e.UserState as Ticker; if (e.Error != null) { EventSourceLogger.Logger.DownloadDataAsyncError(DataTypeDict["Ticker"], Exchange.Name, ticker.CurrencyPair.Code, e.Error.Message); return; } try { string jsonText = e.Result; JObject jObject = JObject.Parse(jsonText); var bterTicker = new { result = false, last = 0m, high = 0m, low = 0m, avg = 0m, sell = 0m, buy = 0m }; var result = JsonConvert.DeserializeAnonymousType(jsonText, bterTicker); ticker.LastTradePrice = result.last; ticker.HighPrice = result.high; ticker.LowPrice = result.low; ticker.AskPrice = result.sell; ticker.BidPrice = result.buy; JObject volObject = JObject.Parse(jsonText); string volName = "vol_" + ticker.CurrencyPair.Base.Code.ToLower(); string volText = volObject[volName].ToString(); ticker.Volume = Convert.ToDecimal(volText); EventSourceLogger.Logger.UpdateDataSuccess(DataTypeDict["Ticker"], Exchange.Name, ticker.CurrencyPair.Code); } catch (Exception ex) { EventSourceLogger.Logger.UpdateDataException(DataTypeDict["Ticker"], Exchange.Name, ticker.CurrencyPair.Code, ex.Message); return; } }
public Task Start(CancellationToken cancellationToken) { new RealtimeApi().Subscribe <Ticker>(PubnubChannel.TickerFxBtcJpy, ticker => { _lastReceivedTime = DateTime.UtcNow; _latestTicker = ticker; }, message => { Logger.LogInformation(message); }, (message, ex) => { if (ex != null) { Logger.LogInformation(ex, message); } else { Logger.LogInformation(message); } }); return(Task.Factory.StartNew(CoreLoop, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default)); }
private void ExecuteTestAsync() { Debug.Assert(base.IsRunningOnWorkerThread); // Note: The object which creates a DispatcherTimer // must create it with the Dispatcher for the worker // thread. Creating the Ticker on the worker thread // ensures that its DispatcherTimer uses the worker // thread's Dispatcher. _ticker = new Ticker(_settings); // Tell the Ticker to start ticking. _ticker.Start(); // Give the Ticker some time to do its work. TimeSpan waitTime = this.CalculateWaitTime(); base.WaitWithoutBlockingDispatcher(waitTime); // Let the base class know that the test is over // so that it can turn off the worker thread's // message pump. base.EndExecuteTest(); }
public static Ticker BuildTicker(CountdownItem item) { DateTime eventDate = new DateTime(item.EventDateTime.Ticks, DateTimeKind.Local); Ticker myTicker = new Ticker(); LocalDateTime fromDate = new LocalDateTime(); LocalDateTime toDate = new LocalDateTime(); //Period timePeriod = null; PeriodBuilder pendingPeriod = new PeriodBuilder(); //TimeSpan timeElapsed = timePeriod; switch (item.Type) { case "Countdown": if (eventDate > DateTime.Now) { // Future Date //timeElapsed = new TimeSpan(eventDate.Subtract(DateTime.Now).Ticks); fromDate = GetLocalDateTimeFromDateTime(DateTime.Now); toDate = GetLocalDateTimeFromDateTime(eventDate); myTicker.Phrase = "Until " + item.EventName; } else { // Past Date //timeElapsed = new TimeSpan(DateTime.Now.Subtract(eventDate).Ticks); //timePeriod = Period.Between(GetLocalDateTimeFromDateTime(DateTime.Now), GetLocalDateTimeFromDateTime(eventDate)); fromDate = GetLocalDateTimeFromDateTime(DateTime.Now); toDate = GetLocalDateTimeFromDateTime(eventDate); myTicker.Phrase = "Since " + item.EventName; } break; case "Anniversary": if (eventDate > DateTime.Now) { // Future Date //timeElapsed = new TimeSpan(eventDate.AddYears(1).Subtract(DateTime.Now).Ticks); //timePeriod = Period.Between(GetLocalDateTimeFromDateTime(DateTime.Now), GetLocalDateTimeFromDateTime(eventDate.AddYears(1))); fromDate = GetLocalDateTimeFromDateTime(DateTime.Now); toDate = GetLocalDateTimeFromDateTime(eventDate.AddYears(1)); myTicker.Phrase = "Until " + item.EventName + " 1st Anniversary"; } else { // Past Date int n = 1; while (eventDate.AddYears(n) < DateTime.Now) { n++; } //timeElapsed = new TimeSpan(eventDate.AddYears(n).Subtract(DateTime.Now).Ticks); //timePeriod = Period.Between(GetLocalDateTimeFromDateTime(DateTime.Now), GetLocalDateTimeFromDateTime(eventDate.AddYears(n))); fromDate = GetLocalDateTimeFromDateTime(DateTime.Now); toDate = GetLocalDateTimeFromDateTime(eventDate.AddYears(n)); myTicker.Phrase = "Until " + item.EventName + " " + n + "th Anniversary"; } break; } //timePeriod. //timePeriod = Period.Between(fromDate, toDate); //timePeriod. // (item.YearFlag)?PeriodUnits.Years|: "" // (item.YearFlag)?PeriodUnits.Months:| // (item.YearFlag)?PeriodUnits.Weeks:| // (item.YearFlag)?PeriodUnits.Days:| // (item.YearFlag)?PeriodUnits.Hours:| // (item.YearFlag)?PeriodUnits.Minutes:| // (item.YearFlag)?PeriodUnits.Seconds:| // PeriodUnits.None // ); //timePeriod = pendingPeriod = new PeriodBuilder(Period.Between(fromDate, toDate, ((item.YearFlag) ? PeriodUnits.Years : PeriodUnits.None) | ((item.MonthFlag) ? PeriodUnits.Months : PeriodUnits.None) | ((item.WeekFlag) ? PeriodUnits.Weeks : PeriodUnits.None) | ((item.DayFlag) ? PeriodUnits.Days : PeriodUnits.None) | ((item.HourFlag) ? PeriodUnits.Hours : PeriodUnits.None) | ((item.MinuteFlag) ? PeriodUnits.Minutes : PeriodUnits.None) | ((item.SecondFlag || item.HeartbeatFlag) ? PeriodUnits.Seconds : PeriodUnits.None) | PeriodUnits.None )); if (item.YearFlag) { ////int yy = Period.Between(fromDate, toDate, PeriodUnits.Years).Years; myTicker.Year = pendingPeriod.Years.ToString("00"); //pendingPeriod.Years = 0; //fromDate.PlusYears(1); } if (item.MonthFlag) { //pendingPeriod = new PeriodBuilder(Period.Between(fromDate, toDate, PeriodUnits.Months)); myTicker.Month = pendingPeriod.Months.ToString("00"); //pendingPeriod.Months = 0; } if (item.WeekFlag) { //pendingPeriod = new PeriodBuilder(Period.Between(fromDate, toDate, PeriodUnits.Years)); myTicker.Week = pendingPeriod.Weeks.ToString("00"); //pendingPeriod.Weeks = 0; } if (item.DayFlag) { //pendingPeriod = new PeriodBuilder(Period.Between(fromDate, toDate, PeriodUnits.Years)); myTicker.Day = pendingPeriod.Days.ToString("00"); //pendingPeriod.Days = 0; } if (item.HourFlag) { //pendingPeriod = new PeriodBuilder(Period.Between(fromDate, toDate, PeriodUnits.Years)); myTicker.Hour = pendingPeriod.Hours.ToString("00"); //pendingPeriod.Hours = 0; } if (item.MinuteFlag) { //pendingPeriod = new PeriodBuilder(Period.Between(fromDate, toDate, PeriodUnits.Years)); myTicker.Minute = pendingPeriod.Minutes.ToString("00"); //pendingPeriod.Minutes = 0; } if (item.SecondFlag) { //pendingPeriod = new PeriodBuilder(Period.Between(fromDate, toDate, PeriodUnits.Years)); myTicker.Second = pendingPeriod.Seconds.ToString("00"); } if (item.HeartbeatFlag) { //pendingPeriod = new PeriodBuilder(Period.Between(fromDate, toDate, PeriodUnits.Years)); myTicker.Heartbeat = (pendingPeriod.Seconds * item.HeartbeatCount/60).ToString("00"); } myTicker.YearFlag = item.YearFlag; myTicker.MonthFlag = item.MonthFlag; myTicker.WeekFlag = item.WeekFlag; myTicker.DayFlag = item.DayFlag; myTicker.HourFlag = item.HourFlag; myTicker.MinuteFlag = item.MinuteFlag; myTicker.SecondFlag = item.SecondFlag; myTicker.HeartbeatFlag = item.HeartbeatFlag; return myTicker; }
public LevelManager(World parent, bool add = true) : base(null, new Vector2f(0, 0), parent, add) { ChangeLevel = new Ticker(parent, new TimeSpan(0, 0, 0, (int)(DangerManager.Instance.MaxDP / 2f)), NextLevel); Level = 1; }
private void btTest_Click(object sender, EventArgs e) { //criar array dados 3m Ticker [] dados_3m = new Ticker[145000]; for (int i = 0, m = 0, i2 = 0; dados[i] != null; i++) { if (m == 0) { dados_3m[i2] = new Ticker(); //mais facil copiar a estrutura inteira dados_3m[i2].dtData = dados[i].dtData; dados_3m[i2].iAbertura = dados[i].iAbertura; dados_3m[i2].iFechamento = dados[i].iFechamento; dados_3m[i2].iMaximo = dados[i].iMaximo; dados_3m[i2].iMinimo = dados[i].iMinimo; } else { dados_3m[i2].iFechamento = dados[i].iFechamento; dados_3m[i2].iMaximo = (dados[i].iMaximo > dados_3m[i2].iMaximo) ? dados[i].iMaximo : dados_3m[i2].iMaximo; dados_3m[i2].iMinimo = (dados[i].iMinimo < dados_3m[i2].iMinimo) ? dados[i].iMinimo : dados_3m[i2].iMinimo; } if (dados[i + 1] != null && dados[i].dtData.DayOfYear != dados[i + 1].dtData.DayOfYear || m == 2) { m = 0; i2++; } else// if (m < 2) m++; } StreamWriter writeFile = new StreamWriter(@"C:\Users\Pedro\Investimentos\dados_3m.csv"); writeFile.WriteLine("{0};{1};{2};{3};{4}", "DATA", "OPEN", "HIGH", "LOW", "CLOSE"); for (int i = 0; dados_3m[i] != null; i++) writeFile.WriteLine("{0};{1};{2};{3};{4}", dados_3m[i].dtData, dados_3m[i].iAbertura, dados_3m[i].iMaximo, dados_3m[i].iMinimo, dados_3m[i].iFechamento); writeFile.Flush(); writeFile.Close(); //criar o array heikin ashi 3m Ticker [] dados_heikinashi_3m = new Ticker[145000]; for (int i = 0; dados_3m[i] != null; i++) { dados_heikinashi_3m[i] = new Ticker(); dados_heikinashi_3m[i].dtData = dados_3m[i].dtData; if (i > 0) dados_heikinashi_3m[i].iAbertura = (int)Math.Round(((dados_heikinashi_3m[i - 1].iAbertura + dados_heikinashi_3m[i - 1].iFechamento) / 2) / 5.0) * 5; else dados_heikinashi_3m[i].iAbertura = (int)Math.Round(((dados_3m[i].iAbertura + dados_3m[i].iFechamento) / 2) / 5.0) * 5; dados_heikinashi_3m[i].iFechamento = (int)Math.Round(((dados_3m[i].iAbertura + dados_3m[i].iFechamento + dados_3m[i].iMaximo + dados_3m[i].iMinimo)/4) / 5.0) * 5; dados_heikinashi_3m[i].iMaximo = Math.Max(dados_3m[i].iMaximo,Math.Max(dados_heikinashi_3m[i].iAbertura,dados_heikinashi_3m[i].iFechamento)); dados_heikinashi_3m[i].iMinimo = Math.Min(dados_3m[i].iMinimo,Math.Min(dados_heikinashi_3m[i].iAbertura,dados_heikinashi_3m[i].iFechamento)); } //escrever array HK para conferencia num arquivo writeFile = new StreamWriter(@"C:\Users\Pedro\Investimentos\dados_heikinashi_3m.csv"); writeFile.WriteLine("{0};{1};{2};{3};{4}", "DATA", "xOPEN", "xHIGH", "xLOW", "xCLOSE"); for (int i = 0; dados_heikinashi_3m[i] != null; i++) writeFile.WriteLine("{0};{1};{2};{3};{4}", dados_heikinashi_3m[i].dtData, dados_heikinashi_3m[i].iAbertura, dados_heikinashi_3m[i].iMaximo, dados_heikinashi_3m[i].iMinimo, dados_heikinashi_3m[i].iFechamento); writeFile.Flush(); writeFile.Close(); /* * public class Trade { public DateTime dtData; enum tipo {COMPRA, VENDA}; public int iValorEntrada; public int iMaxGanho; public int iMaxPerda; }*/ Trade[] hstTrade = new Trade[100000]; //testar a estrategia for (int i = 2, t = 0 ; dados_heikinashi_3m[i] != null; i++) { //da a entrada if ( dados_heikinashi_3m[i - 1].iAbertura == dados_heikinashi_3m[i - 1].iMinimo && dados_heikinashi_3m[i - 2].iAbertura == dados_heikinashi_3m[i - 2].iMinimo && dados_heikinashi_3m[i].dtData.Hour >= 10 && ( t == 0 || ( hstTrade[t-1] != null && ( /*( hstTrade[t-1].tpTrade == tipo.VENDA && hstTrade[t-1].bNoMercado ) ||*/ !hstTrade[t-1].bNoMercado ) ) ) ) { /*compra*/ /*if (t > 0) { hstTrade[t - 1].bNoMercado = false; hstTrade[t - 1].iResultado = hstTrade[t - 1].iValorEntrada - dados_3m[i].iAbertura; }*/ hstTrade[t] = new Trade(); hstTrade[t].dtData = dados_heikinashi_3m[i].dtData; hstTrade[t].tpTrade = tipo.COMPRA; hstTrade[t].bNoMercado = true; hstTrade[t].iValorEntrada = dados_3m[i].iAbertura; hstTrade[t].iMaxGanho = hstTrade[t].iMaxPerda = 0; t++; } else if ( dados_heikinashi_3m[i - 1].iAbertura == dados_heikinashi_3m[i - 1].iMaximo && dados_heikinashi_3m[i - 2].iAbertura == dados_heikinashi_3m[i - 2].iMaximo && dados_heikinashi_3m[i].dtData.Hour >= 10 && (t == 0 || ( hstTrade[t-1] != null && ( /*( hstTrade[t-1].tpTrade == tipo.COMPRA && hstTrade[t-1].bNoMercado ) ||*/ !hstTrade[t-1].bNoMercado ) ) ) ) { /*venda*/ /*if (t > 0) { hstTrade[t - 1].bNoMercado = false; hstTrade[t - 1].iResultado = dados_3m[i].iAbertura - hstTrade[t - 1].iValorEntrada; }*/ hstTrade[t] = new Trade(); hstTrade[t].dtData = dados_heikinashi_3m[i].dtData; hstTrade[t].tpTrade = tipo.VENDA; hstTrade[t].bNoMercado = true; hstTrade[t].iValorEntrada = dados_3m[i].iAbertura; hstTrade[t].iMaxGanho = hstTrade[t].iMaxPerda = 0; t++; } //atualiiza lucro ou perda for (int i2 = 0; hstTrade[i2] != null; i2++) { if ( hstTrade[i2].bNoMercado ) { if (hstTrade[i2].tpTrade == tipo.COMPRA ) { if (dados_3m[i].iMaximo > hstTrade[i2].iValorEntrada) hstTrade[i2].iMaxGanho = ((dados_3m[i].iMaximo - hstTrade[i2].iValorEntrada) > hstTrade[i2].iMaxGanho) ? (dados_3m[i].iMaximo - hstTrade[i2].iValorEntrada) : hstTrade[i2].iMaxGanho; else if (dados_3m[i].iMinimo < hstTrade[i2].iValorEntrada) hstTrade[i2].iMaxPerda = ((dados_3m[i].iMinimo - hstTrade[i2].iValorEntrada) < hstTrade[i2].iMaxPerda) ? (dados_3m[i].iMinimo - hstTrade[i2].iValorEntrada) : hstTrade[i2].iMaxPerda; } else { if (dados_3m[i].iMaximo > hstTrade[i2].iValorEntrada) hstTrade[i2].iMaxPerda = ((hstTrade[i2].iValorEntrada - dados_3m[i].iMaximo) < hstTrade[i2].iMaxPerda) ? (hstTrade[i2].iValorEntrada - dados_3m[i].iMaximo) : hstTrade[i2].iMaxPerda; else if (dados_3m[i].iMinimo < hstTrade[i2].iValorEntrada) hstTrade[i2].iMaxGanho = ((hstTrade[i2].iValorEntrada - dados_3m[i].iMinimo) > hstTrade[i2].iMaxGanho) ? (hstTrade[i2].iValorEntrada - dados_3m[i].iMinimo) : hstTrade[i2].iMaxGanho; } } } if (t > 0 && hstTrade[t - 1] != null && hstTrade[t - 1].bNoMercado) { if (hstTrade[t - 1].iMaxGanho >= 100) { hstTrade[t - 1].iResultado = 100; hstTrade[t - 1].bNoMercado = false; //t++; } else if (hstTrade[t - 1].iMaxPerda <= -50) { hstTrade[t - 1].iResultado = -50; hstTrade[t - 1].bNoMercado = false; //t++; } } //se acabou o dia, fecha todos trades if ( /*hstTrade[t-1] != null &&*/ (dados_heikinashi_3m[i + 1] != null && dados_heikinashi_3m[i].dtData.DayOfYear != dados_heikinashi_3m[i + 1].dtData.DayOfYear)) //foreach ( Trade trade in hstTrade ) // trade.bNoMercado = false; { if (hstTrade[t - 1].bNoMercado) { hstTrade[t - 1].bNoMercado = false; if (hstTrade[t - 1].tpTrade == tipo.VENDA) hstTrade[t - 1].iResultado = hstTrade[t - 1].iValorEntrada - dados_3m[i].iAbertura; else hstTrade[t - 1].iResultado = dados_3m[i].iAbertura - hstTrade[t - 1].iValorEntrada; //t++; } } } //escrever array HK para conferencia num arquivo writeFile = new StreamWriter(@"C:\Users\Pedro\Investimentos\trades_heikinashi_3m.csv"); writeFile.WriteLine("{0};{1};{2};{3};{4};{5}", "DATA", "Entrada", "Resultado", "DrawUp", "DrawDown", "Tipo" ); for (int i = 0; hstTrade[i] != null; i++) writeFile.WriteLine("{0};{1};{2};{3};{4};{5}", hstTrade[i].dtData, hstTrade[i].iValorEntrada, hstTrade[i].iResultado, hstTrade[i].iMaxGanho, hstTrade[i].iMaxPerda, hstTrade[i].tpTrade.ToString()); writeFile.Flush(); writeFile.Close(); }
// https://developer.apple.com/library/mac/documentation/networking/Reference/AFP_Reference/Reference/reference.html#//apple_ref/c/func/FPOpenDir void T2(object state) { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; Encoding enc = Encoding.GetEncoding(932); ManualResetEvent evExit = new ManualResetEvent(false); try { using (TcpClient tcp = (TcpClient)state) { NetworkStream st = tcp.GetStream(); StreamWriter wr = new StreamWriter(st, Encoding.UTF8); StreamReader rr = new StreamReader(st, Encoding.UTF8, false); ConDyn cd = new ConDyn(cc); String syst = ""; using (MyDSI3 comm = new MyDSI3(afp)) { TransmitRes res = comm.Transmit(new DSIGetStatus()); if (res.pack.IsResponse && res.pack.ErrorCode == 0) { GetSrvrInfoPack pack = new GetSrvrInfoPack(res.br); if (pack.AFPVersionsList.Contains("AFP2.2")) { } if (pack.AFPVersionsList.Contains("AFPX03")) { cd.AFP30 = true; } if (pack.AFPVersionsList.Contains("AFP3.1")) { cd.AFP31 = true; } syst += " Server: " + pack.ServerName + "\n"; syst += " AFPVer:"; foreach (String ver in pack.AFPVersionsList) syst += " <" + ver + ">"; syst += "\n"; syst += " UAM:"; foreach (String ver in pack.UAMsList) syst += " <" + ver + ">"; } else { Ut.WriteRes(wr, 500, "AFP server failed: " + new DSIException(res.pack.ErrorCode, res.pack)); return; } } String U = String.Empty; String P = String.Empty; IDir root = new DisconnetedRoot(); IDir pwd = root; DataConn dc = new DataConn(); Int64 ftpRest = 0; IEnt rnfr = null; using (MyDSI3 comm = new MyDSI3(afp)) { Ticker ti = new Ticker(comm, evExit); Ut.WriteRes(wr, 220, "FTP4AFP in UTF-8"); while (true) { try { String row = rr.ReadLine(); if (row == null) break; Match M; M = Regex.Match(row, "^QUIT", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { Ut.WriteRes(wr, 221, "Goodbye!"); break; } M = Regex.Match(row, "^USER\\s+(?<a>.+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { U = M.Groups["a"].Value; Ut.WriteRes(wr, 331, "Proceed to password."); continue; } M = Regex.Match(row, "^PASS\\s+(?<a>.+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { P = M.Groups["a"].Value; Uta a = new Uta(); root = pwd = a.Login(comm, cd, U, P); Ut.WriteRes(wr, 230, "User logged in, proceed."); continue; } M = Regex.Match(row, "^SYST", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { Ut.WriteRes(wr, 215, typeof(AFPServ).AssemblyQualifiedName + "\n" + Environment.OSVersion + "\n" + "\n" + syst); continue; } M = Regex.Match(row, "^(XPWD|PWD)", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { MLoc m = MLoc.Ut.Get(pwd); Ut.WriteRes(wr, 257, "\"" + m.UnixPath + "\" is current directory."); continue; } M = Regex.Match(row, "^TYPE\\s+(?<a>A|I)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { String mode = M.Groups["a"].Value.ToUpperInvariant(); if (mode == "I") dc.TypeI(); if (mode == "A") dc.TypeA(); Ut.WriteRes(wr, 200, "Ok."); continue; } M = Regex.Match(row, "^PASV", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { dc.Pasv(tcp.Client.LocalEndPoint); Ut.WriteRes(wr, 227, "Entering Passive Mode (" + dc.GetPasv() + ")"); continue; } M = Regex.Match(row, "^PORT\\s+(?<a>\\d+,\\d+,\\d+,\\d+,\\d+,\\d+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { dc.Port(M.Groups["a"].Value); Ut.WriteRes(wr, 200, "PORT command successful."); continue; } M = Regex.Match(row, "^LIST(\\s+(?<a>.+))?\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { String cwd = M.Groups["a"].Value; try { IDir newwd = (cwd.Length == 0) ? pwd : TravUt.Cwd(pwd, cwd); StringWriter ww = new StringWriter(); foreach (IEnt o in newwd.GetEnts()) { bool isDir = o is IDir; ww.WriteLine("{0}rw-r--r-- 1 0 0 {1,10} {2,-12} {3}" , isDir ? "d" : "-" , isDir ? "0" : o.Size.ToString() , DUt.Format(o.Mt) , o.Name ); } // http://blog.livedoor.jp/kumagai_nori/archives/51660940.html // http://ash.jp/net/ftp_command.htm // http://www.atmarkit.co.jp/ait/articles/0307/11/news001.html // http://www.atmarkit.co.jp/fnetwork/rensai/netpro10/ftp-responsecode.html // http://maruo.dyndns.org:81/hidesoft/hidesoft_2/x17565.html // http://www.nsftools.com/tips/MSFTP.htm#dir Ut.WriteRes(wr, 150, "Opening " + dc.Mode + " mode data connection for LIST"); dc.SendData(wr.Encoding.GetBytes(ww.ToString())); Ut.WriteRes(wr, 226, "Transfer complete"); continue; } catch (EntNotFoundException err) { Ut.WriteRes(wr, 501, err.Message); continue; } } M = Regex.Match(row, "^MLSD(\\s+(?<a>.+))?\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { String cwd = M.Groups["a"].Value; try { IDir newwd = (cwd.Length == 0) ? pwd : TravUt.Cwd(pwd, cwd); StringWriter ww = new StringWriter(); foreach (IEnt o in newwd.GetEnts()) { bool isDir = o is IDir; ww.WriteLine("modify={0};perm={1};size={2};type={3}; {4}" , o.Mt.HasValue ? String.Format("{0:yyyy}{0:MM}{0:dd}{0:HH}{0:mm}{0:ss}", o.Mt.Value) : "" , isDir ? "cdelmp" : "dlrw" , Math.Max(o.Size, 0) , isDir ? "dir" : "file" , o.Name ); } Ut.WriteRes(wr, 150, "Opening " + dc.Mode + " mode data connection for MLSD"); dc.SendData(wr.Encoding.GetBytes(ww.ToString())); Ut.WriteRes(wr, 226, "Transfer complete"); continue; } catch (EntNotFoundException err) { Ut.WriteRes(wr, 501, err.Message); continue; } } M = Regex.Match(row, "^CWD\\s+(?<a>.+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { String cwd = M.Groups["a"].Value; try { IDir newwd = TravUt.Cwd(pwd, cwd); pwd = newwd; Ut.WriteRes(wr, 250, "Directory successfully changed."); continue; } catch (EntNotFoundException err) { Ut.WriteRes(wr, 550, err.Message); continue; } } M = Regex.Match(row, "^CDUP", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { IDir newwd = pwd.ParentDir; if (newwd == null) { Ut.WriteRes(wr, 250, "We are already at root directory."); continue; } else { pwd = newwd; Ut.WriteRes(wr, 250, "Directory successfully changed."); continue; } } M = Regex.Match(row, "^OPTS\\s+UTF8\\s+ON\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { Ut.WriteRes(wr, 200, "It is in UTF8 mode."); wr = new StreamWriter(st, Encoding.UTF8); rr = new StreamReader(st, Encoding.UTF8, false); continue; } M = Regex.Match(row, "^OPTS\\s+UTF8\\s+OFF\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { Ut.WriteRes(wr, 200, "It is in " + enc.BodyName + " mode."); wr = new StreamWriter(st, enc); rr = new StreamReader(st, enc, false); continue; } M = Regex.Match(row, "^OPTS\\s+FORKMODE\\s+(?<a>\\d+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { int i = int.Parse(M.Groups["a"].Value); cd.ForkMode = i; Ut.WriteRes(wr, 200, "It is in fork mode " + i + "."); continue; } M = Regex.Match(row, "^FEAT", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { Ut.WriteRes(wr, 211, "Features:| UTF8| MLST modify*;perm*;size*;type*;| FORKMODE| END".Replace("|", "\n")); continue; } M = Regex.Match(row, "^RETR\\s+(?<a>.+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { String cwd = M.Groups["a"].Value; try { IEnt source = TravUt.Find(pwd, cwd, false); if (source is ICanDL) { using (Stream si = ((ICanDL)source).OpenRead()) { Ut.WriteRes(wr, 150, "Opening " + dc.Mode + " mode data connection for " + cwd); si.Position = ftpRest; dc.SendSt(si); } } else { Ut.WriteRes(wr, 550, "We can't get \"" + cwd + "\"."); continue; } ftpRest = 0; Ut.WriteRes(wr, 226, "Transfer complete"); continue; } catch (EntNotFoundException err) { Ut.WriteRes(wr, 550, err.Message); continue; } } M = Regex.Match(row, "^STOR\\s+(?<a>.+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { String cwd = M.Groups["a"].Value; try { using (Stream os = TravUt.Createf(pwd, cwd, cd)) { Ut.WriteRes(wr, 150, "Opening " + dc.Mode + " mode data connection for " + cwd); os.SetLength(ftpRest); os.Position = ftpRest; dc.RecvSt(os); } ftpRest = 0; Ut.WriteRes(wr, 226, "Transfer complete"); continue; } catch (EntNotFoundException err) { Ut.WriteRes(wr, 550, err.Message); continue; } } M = Regex.Match(row, "^APPE\\s+(?<a>.+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { String cwd = M.Groups["a"].Value; try { using (Stream os = TravUt.Createf(pwd, cwd, cd)) { Ut.WriteRes(wr, 150, "Opening " + dc.Mode + " mode data connection for " + cwd); os.Seek(0, SeekOrigin.End); dc.RecvSt(os); } Ut.WriteRes(wr, 226, "Transfer complete"); continue; } catch (EntNotFoundException err) { Ut.WriteRes(wr, 550, err.Message); continue; } } M = Regex.Match(row, "^MKD\\s+(?<a>.+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { String cwd = M.Groups["a"].Value; try { TravUt.CreateDir(pwd, cwd); Ut.WriteRes(wr, 250, "\"" + cwd + "\" created successfully."); continue; } catch (EntNotFoundException err) { Ut.WriteRes(wr, 550, "\"" + cwd + "\": Unable to create directory. \n" + err.Message); continue; } } M = Regex.Match(row, "^RMD\\s+(?<a>.+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { String cwd = M.Groups["a"].Value; try { TravUt.RMDir(pwd, cwd); Ut.WriteRes(wr, 250, "\"" + cwd + "\" removed successfully."); continue; } catch (EntNotFoundException err) { Ut.WriteRes(wr, 550, "\"" + cwd + "\": Unable to remove directory. \n" + err.Message); continue; } } M = Regex.Match(row, "^DELE\\s+(?<a>.+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { String cwd = M.Groups["a"].Value; try { TravUt.Dele(pwd, cwd, cd); Ut.WriteRes(wr, 250, "\"" + cwd + "\" removed successfully."); continue; } catch (EntNotFoundException err) { Ut.WriteRes(wr, 550, "\"" + cwd + "\": Unable to remove directory. \n" + err.Message); continue; } } M = Regex.Match(row, "^REST\\s+(?<a>\\d+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { ftpRest = Int64.Parse(M.Groups["a"].Value); Ut.WriteRes(wr, 200, "Ok."); continue; } M = Regex.Match(row, "^RNFR\\s+(?<a>.+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { String cwd = M.Groups["a"].Value; try { rnfr = TravUt.Find(pwd, cwd, false); Ut.WriteRes(wr, 350, "The file exists, continue with RNTO."); continue; } catch (EntNotFoundException err) { Ut.WriteRes(wr, 550, err.Message); continue; } } M = Regex.Match(row, "^RNTO\\s+(?<a>.+)\\s*$", RegexOptions.Singleline | RegexOptions.IgnoreCase); if (M.Success) { String cwd = M.Groups["a"].Value; try { MLoc mfrm = MLoc.Ut.Get(rnfr); String fpfrm = mfrm.UnixPath; MLoc m = MLoc.Ut.Get(pwd); String fp2 = UtPLoc.Getfp(m.UnixPath, cwd, cd); PLoc p1 = new PLoc(fpfrm); PLoc p2 = new PLoc(fp2); if (!p1.volume.Equals(p2.volume)) throw new ApplicationException("We have different volumes."); if (!p1.dir.Equals(p2.dir)) { MLoc m2 = new MLoc(); m2.VolID = mfrm.VolID; m2.DirID = mfrm.DirID; m2.MacVol = mfrm.MacVol; m2.MacPath = p2.dir.Replace("/", "\0"); Utcmd.Move(comm, mfrm, m2, p2.fname); } else { Utcmd.Rename(comm, mfrm, p2.fname); } Ut.WriteRes(wr, 200, "Ok."); continue; } catch (EntNotFoundException err) { Ut.WriteRes(wr, 550, err.Message); continue; } } Ut.WriteRes(wr, 500, "NotImpl Error."); } catch (Exception err) { if (tcp.Connected) { try { Ut.WriteRes(wr, 500, err.ToString()); } catch (IOException) { } } else break; } } } tcp.Close(); } } finally { evExit.Set(); } }
public TradingSettings(Ticker ticker) { Enabled = false; Ticker = ticker; }
private void TimerOnTick(object sender, EventArgs e) { foreach (var item in Alerts) { ITickerApi tickerApi = apiManager.GetApi <ITickerApi>(item.ExchangeAbbrName); ExchangeApi exchangeApi = apiManager.GetApi <ExchangeApi>(item.ExchangeAbbrName); Ticker ticker = exchangeApi.SelectedTickers[item.PairCode]; tickerApi.UpdateTicker(ref ticker); item.Price = Utility.GetPrice(item.PriceType, ticker); if (!item.IsOpen) { item.State = MonitorState.Pause; item.BackgroundColor = Colors.Transparent; continue; } if (item.Price == 0m) { item.State = MonitorState.DataError; item.BackgroundColor = Colors.Gray; continue; } if (item.IsHighThan) { if (item.Price > item.ComparePrice) { item.State = MonitorState.Triggered; item.BackgroundColor = item.AlertColor; if (item.IsPlaySound) { MediaPlayer player = new MediaPlayer(); Uri uri = new Uri("Media\\" + item.SoundFile, UriKind.Relative); player.Open(uri); player.Play(); } } else { item.State = MonitorState.NotTriggered; item.BackgroundColor = Colors.Transparent; } } else { if (item.Price < item.ComparePrice) { item.State = MonitorState.Triggered; item.BackgroundColor = item.AlertColor; if (item.IsPlaySound) { MediaPlayer player = new MediaPlayer(); Uri uri = new Uri("Media\\" + item.SoundFile, UriKind.Relative); player.Open(uri); player.Play(); } } else { item.State = MonitorState.NotTriggered; item.BackgroundColor = Colors.Transparent; } } } }
public static ResizeableArray <TradeInfoItem> DownloadTradeHistory(Ticker ticker, DateTime time) { return(ticker.Exchange.GetTrades(ticker, time)); }
private static string[] ExtractOnlyValuesFromTicker(List <string> inputColumnNames, Ticker inputTicker) { return(inputColumnNames.Select(v => inputTicker[v].ToString(CultureInfo.InvariantCulture)).ToArray()); }
public ValueOrError<RawFile> Save(Ticker ticker) { return executor.SafeExecute<RawFile>(engine => engine.GetVariable("Save")(ticker)); }
private Ticker ConvertToModel(TickerDto tickerDto) { var ticker = new Ticker(); ticker.Active = tickerDto.Active; ticker.BCFirstDate = tickerDto.BCFirstDate; ticker.BH = tickerDto.BH; // public System.Data.Objects.DataClasses.EntityCollection<Buy> Buys { get; set; } ticker.CBSFirstDate = tickerDto.CBSFirstDate; ticker.Comments = tickerDto.Comments; ticker.component = tickerDto.component; ticker.current = tickerDto.current; ticker.DateAdded = tickerDto.DateAdded; ticker.DateModified = tickerDto.DateModified; ticker.endDate = tickerDto.endDate; ticker.FirstBuy = tickerDto.FirstBuy; ticker.Id = tickerDto.Id; ticker.InceptionDate = tickerDto.InceptionDate; ticker.LastSell = tickerDto.LastSell; ticker.MCFirstDate = tickerDto.MCFirstDate; ticker.Name = tickerDto.Name; ticker.priceDecimal = tickerDto.priceDecimal; // public System.Data.Objects.DataClasses.EntityCollection<Sell> Sells { get; set; } ticker.shareDecimal = tickerDto.shareDecimal; ticker.startDate = tickerDto.startDate; ticker.Symbol = tickerDto.Symbol; ticker.TickerBC = tickerDto.TickerBC; ticker.TickerBH = tickerDto.TickerBH; ticker.tickerGUID = tickerDto.tickerGUID; ticker.TickerYahoo = tickerDto.TickerYahoo; ticker.type = tickerDto.Type; return ticker; }
public bool AddBuy(BuyDto buyDto) { try { var accountEntity = context.Account.FirstOrDefault(p => p.Id == buyDto.AccountId); var buyEntity = new Buy { Account = accountEntity, TransactionTypeId = buyDto.TransactionTypeId, TranType = buyDto.TransactionType, AddedBy = buyDto.AddedBy, AmtInv = buyDto.AmtInv, BuyCommission = buyDto.BuyCommission, BuyDate = buyDto.BuyDate, BuyPrice = buyDto.BuyPrice, BuyType = buyDto.BuyType, Comments = buyDto.Comments, DividendAmount = buyDto.DividendAmount, ModifiedBy = buyDto.ModifiedBy, NumShares = buyDto.NumShares, orderby = buyDto.orderby, OriginalBuyGUID = buyDto.OriginalBuyGUID, refID = buyDto.refID, DateAdded = DateTime.Now, DateModified = DateTime.Now, BuyGUID = Guid.NewGuid(), InvestmentClassification = accountEntity.InvestmentClassification, InvestmentClassificationGuid = accountEntity.InvestmentClassificationGuid, SubAccount = accountEntity.SubAccount, SubAccountGuid = accountEntity.SubAccountGuid, Broker = accountEntity.Broker, BrokerGUID = accountEntity.BrokerGUID, }; Ticker tickerEntity; // public Ticker Ticker1 { get; set; } if (buyDto.Ticker.Length > 0) { tickerEntity = context.Tickers.FirstOrDefault(p => p.Symbol == buyDto.Ticker); if (tickerEntity == null) { tickerEntity = new Ticker { Symbol = buyDto.Ticker, tickerGUID = Guid.NewGuid(), type = "", current = true }; } } else { tickerEntity = context.Tickers.FirstOrDefault(p => p.Id == buyDto.TickerId); } buyEntity.Ticker1 = (tickerEntity != null) ? tickerEntity : new Ticker { Symbol = buyDto.Ticker, tickerGUID = Guid.NewGuid(), type = "", current = true }; buyEntity.Ticker = buyDto.Ticker; buyEntity.TickerGUID = tickerEntity.tickerGUID; buyEntity.Transactions.Add(new Transaction { AmtInv = buyDto.AmtInv, NumShares = buyDto.NumShares, buySplitPercent = 1, DateAdded = DateTime.Now, DateUpdated = DateTime.Now}); context.SaveChanges(); return true; } catch(Exception ex) { throw; } }
public Clock(TextBox displayBox) { pulsed = new Ticker(); this.display = displayBox; }
private void Form1_Load(object sender, EventArgs e) { tick=new Ticker(); tick.Start(); }
public static bool BaseTickerEqual(Ticker x, Ticker y) { return x.TickerType == y.TickerType && Math.Abs(x.LastPrice - y.LastPrice) < epsilon && Math.Abs(x.BuyPrice - y.BuyPrice) < epsilon && Math.Abs(x.SellPrice - y.SellPrice) < epsilon; }
public async Task UpdatePrice(Ticker ticker) { await _cryptoBroker.UpdatePrice(ticker); }
public Task OnTickerReceivedAsync(string instrumentName, Ticker ticker) { throw new NotImplementedException(); }
static void SetupInit( Context activity, Assembly resourceAssembly, InitializationOptions?maybeOptions = null ) { Profile.FrameBegin(); Registrar.RegisterRendererToHandlerShim(RendererToHandlerShim.CreateShim); if (!IsInitialized) { // Only need to get this once; it won't change ApplicationContext = activity.ApplicationContext; } #pragma warning disable 618 // Still have to set this up so obsolete code can function Context = activity; #pragma warning restore 618 if (!IsInitialized) { // Only need to do this once Profile.FramePartition("ResourceManager.Init"); ResourceManager.Init(resourceAssembly); } Profile.FramePartition("Color.SetAccent()"); // We want this to be updated when we have a new activity (e.g. on a configuration change) // This could change if the UI mode changes (e.g., if night mode is enabled) Color.SetAccent(GetAccentColor(activity)); _ColorButtonNormalSet = false; if (!IsInitialized) { // Only need to do this once Profile.FramePartition("Log.Listeners"); Internals.Log.Listeners.Add(new DelegateLogListener((c, m) => Trace.WriteLine(m, c))); } // We want this to be updated when we have a new activity (e.g. on a configuration change) // because AndroidPlatformServices needs a current activity to launch URIs from Profile.FramePartition("Device.PlatformServices"); var androidServices = new AndroidPlatformServices(activity); Device.PlatformServices = androidServices; Device.PlatformInvalidator = androidServices; // use field and not property to avoid exception in getter if (Device.info != null) { ((AndroidDeviceInfo)Device.info).Dispose(); Device.info = null; } // We want this to be updated when we have a new activity (e.g. on a configuration change) // because Device.Info watches for orientation changes and we need a current activity for that Profile.FramePartition("create AndroidDeviceInfo"); Device.Info = new AndroidDeviceInfo(activity); Profile.FramePartition("setFlags"); Device.SetFlags(s_flags); Profile.FramePartition("AndroidTicker"); Ticker.SetDefault(null); Profile.FramePartition("RegisterAll"); if (!IsInitialized) { if (maybeOptions.HasValue) { var options = maybeOptions.Value; var handlers = options.Handlers; var flags = options.Flags; var effectScopes = options.EffectScopes; //TODO: ExportCell? //TODO: ExportFont // renderers Registrar.RegisterRenderers(handlers); // effects if (effectScopes != null) { for (var i = 0; i < effectScopes.Length; i++) { var effectScope = effectScopes[0]; Registrar.RegisterEffects(effectScope.Name, effectScope.Effects); } } // css Registrar.RegisterStylesheets(flags); } else { // Only need to do this once Registrar.RegisterAll(new[] { typeof(ExportRendererAttribute), typeof(ExportCellAttribute), typeof(ExportImageSourceHandlerAttribute), typeof(ExportFontAttribute) }); } } Profile.FramePartition("Epilog"); var currentIdiom = TargetIdiom.Unsupported; // First try UIModeManager using (var uiModeManager = UiModeManager.FromContext(ApplicationContext)) { try { var uiMode = uiModeManager?.CurrentModeType ?? UiMode.TypeUndefined; currentIdiom = DetectIdiom(uiMode); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"Unable to detect using UiModeManager: {ex.Message}"); } } // Then try Configuration if (TargetIdiom.Unsupported == currentIdiom) { var configuration = activity.Resources.Configuration; if (configuration != null) { var minWidth = configuration.SmallestScreenWidthDp; var isWide = minWidth >= TabletCrossover; currentIdiom = isWide ? TargetIdiom.Tablet : TargetIdiom.Phone; } else { // Start clutching at straws var metrics = activity.Resources?.DisplayMetrics; if (metrics != null) { var minSize = Math.Min(metrics.WidthPixels, metrics.HeightPixels); var isWide = minSize * metrics.Density >= TabletCrossover; currentIdiom = isWide ? TargetIdiom.Tablet : TargetIdiom.Phone; } } } Device.SetIdiom(currentIdiom); if (SdkInt >= BuildVersionCodes.JellyBeanMr1) { Device.SetFlowDirection(activity.Resources.Configuration.LayoutDirection.ToFlowDirection()); } if (ExpressionSearch.Default == null) { ExpressionSearch.Default = new AndroidExpressionSearch(); } IsInitialized = true; Profile.FrameEnd(); }
/// <summary> /// ログ1行1テロップに対して判定する /// </summary> /// <param name="telop">テロップ</param> /// <param name="log">ログ</param> public void MatchCore( Ticker telop, string log) { var matched = false; var regex = telop.Regex; var regexToHide = telop.RegexToHide; // マッチング計測開始 telop.StartMatching(); // 開始条件を確認する if (ConditionUtility.CheckConditionsForTelop(telop)) { // 通常マッチ if (regex == null) { var keyword = telop.KeywordReplaced; if (!string.IsNullOrWhiteSpace(keyword)) { if (log.Contains(keyword, StringComparison.OrdinalIgnoreCase)) { var messageReplaced = ConditionUtility.GetReplacedMessage(telop); // PC名を置換する messageReplaced = XIVPluginHelper.Instance.ReplacePartyMemberName( messageReplaced, Settings.Default.PCNameInitialOnDisplayStyle); if (!telop.AddMessageEnabled) { telop.MessageReplaced = messageReplaced; } else { telop.MessageReplaced += string.IsNullOrWhiteSpace(telop.MessageReplaced) ? messageReplaced : Environment.NewLine + messageReplaced; } telop.ForceHide = false; telop.Delayed = false; telop.MatchedLog = log; telop.MatchDateTime = DateTime.Now; // マッチング計測終了 telop.EndMatching(); telop.Play(telop.MatchSound, telop.MatchAdvancedConfig); telop.Play(telop.MatchTextToSpeak, telop.MatchAdvancedConfig); matched = true; } } } // 正規表現マッチ else { var match = regex.Match(log); if (match.Success) { var messageReplaced = ConditionUtility.GetReplacedMessage(telop); messageReplaced = match.Result(messageReplaced); // PC名を置換する messageReplaced = XIVPluginHelper.Instance.ReplacePartyMemberName( messageReplaced, Settings.Default.PCNameInitialOnDisplayStyle); if (!telop.AddMessageEnabled) { telop.MessageReplaced = messageReplaced; } else { telop.MessageReplaced += string.IsNullOrWhiteSpace(telop.MessageReplaced) ? messageReplaced : Environment.NewLine + messageReplaced; } telop.ForceHide = false; telop.Delayed = false; telop.MatchedLog = log; telop.MatchDateTime = DateTime.Now; // マッチング計測終了 telop.EndMatching(); telop.Play(telop.MatchSound, telop.MatchAdvancedConfig); if (!string.IsNullOrWhiteSpace(telop.MatchTextToSpeak)) { var tts = match.Result(telop.MatchTextToSpeak); telop.Play(tts, telop.MatchAdvancedConfig); } matched = true; } } } if (matched) { // ディレイサウンドをスタートさせる telop.StartDelayedSoundTimer(); SpellsController.Instance.UpdateNormalSpellTimerForTelop(telop, telop.ForceHide); SpellsController.Instance.NotifyNormalSpellTimerForTelop(telop.Title); return; } // 通常マッチ(強制非表示) if (regexToHide == null) { var keyword = telop.KeywordToHideReplaced; if (!string.IsNullOrWhiteSpace(keyword)) { if (log.Contains(keyword, StringComparison.OrdinalIgnoreCase)) { telop.ForceHide = true; matched = true; } } } // 正規表現マッチ(強制非表示) else { if (regexToHide.IsMatch(log)) { telop.ForceHide = true; matched = true; } } if (matched) { SpellsController.Instance.UpdateNormalSpellTimerForTelop(telop, telop.ForceHide); SpellsController.Instance.NotifyNormalSpellTimerForTelop(telop.Title); } }
void OnExecuteOrder() { if (Mode == ActionMode.Notify) { //TelegramBot.Default.SendNotification(Ticker.Exchange + " - " + Ticker.Name + " - Order done!!"); State = TrailingState.Done; } else if (Mode == ActionMode.Execute) { TradingResult res = Type == TrailingType.Sell ? Ticker.MarketSell(SellAmount) : Ticker.MarketBuy(BuyAmount); if (res != null) { State = TrailingState.Done; } //else //TelegramBot.Default.SendNotification($"{Ticker.Exchange}. Error!! Can't sell {Ticker.Name}"); } Ticker.Events.Add(new TickerEvent() { Time = DateTime.UtcNow, Text = "Stoploss!" }); }
public void Ticker_OnInitialization_DefaultIntervalIs100Milliseconds() { Ticker t = new Ticker(); Assert.Equal(100, t.Interval); }
public async Task <Ticker[]> FetchTickers(string[] symbols = null) { var markets = await FetchMarkets().ConfigureAwait(false); var response = await Request(new Base.Request() { BaseUri = ApiV1Public, Path = "market/tickers", ApiType = "public", Method = HttpMethod.Get }).ConfigureAwait(false); var responseJson = JsonSerializer.Deserialize <HuobiTickersResponse>(response.Text); var result = new List <Ticker>(); foreach (var item in responseJson.data) { Ticker ticker = new Ticker(); ticker.Timestamp = responseJson.ts; ticker.DateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ticker.Timestamp); var market = markets.FirstOrDefault(m => m.Id == item.symbol); if (market == null) { continue; } ticker.Symbol = market.Symbol; ticker.High = item.high; ticker.Low = item.low; ticker.Bid = item.bid; ticker.BidVolume = item.bidSize; ticker.Ask = item.ask; ticker.AskVolume = item.askSize; ticker.Open = item.open; ticker.Close = item.close; ticker.Last = item.close; ticker.Average = (ticker.Open + ticker.Close) / 2; ticker.BaseVolume = item.amount; ticker.QuoteVolume = item.vol; if (ticker.BaseVolume != 0) { ticker.Vwap = ticker.QuoteVolume / ticker.BaseVolume; } ticker.Change = ticker.Close - ticker.Open; if (ticker.Open != 0) { ticker.Percentage = ticker.Change / ticker.Open * 100; } ticker.Info = item; result.Add(ticker); } if (symbols == null) { return(result.ToArray()); } else { return(result.Where(m => symbols.Contains(m.Symbol)).ToArray()); } }
public IndieAnimation(int animationSpeed, Rectangle[] sources) : base(animationSpeed, sources) { ticker = new Ticker(animationSpeed * sources.Length); }
private void transactionCleanup() { // clean up transactions we can easily account for var wg = new WaitGroup(); wg.Add(_transactions.Count); foreach (var t in _transactions) { var t1 = t; GoFunc.Run(() => { t1.Error = new ErrNotConnected(); t1.finish(); wg.Done(); }, "transactionCleanup: drain _transactions"); } _transactions.Clear(); // spin and free up any writes that might have raced // with the cleanup process (blocked on writing // to transactionChan) // give the runtime a chance to schedule other racing goroutines var ticker = new Ticker(TimeSpan.FromMilliseconds(100)); bool doLoop = true; using (var select = Select .CaseReceive(_transactionChan, t => { wg.Add(1); GoFunc.Run(() => { t.Error = new ErrNotConnected(); t.finish(); wg.Done(); }, "transactionCleanup: finish transaction from _transactionChan"); }) .CaseReceive(ticker.C, _ => { // keep spinning until there are 0 concurrent producers if (_concurrentProducers == 0) { doLoop = false; return; } log(LogLevel.Warning, string.Format( "waiting for {0} concurrent producers to finish", _concurrentProducers)); }) .NoDefault(defer: true) ) { while (doLoop) { select.Execute(); } } ticker.Close(); wg.Wait(); }
public IAsyncResult<Ticker> Transform(Ticker ticker) { return executor.SafeExecuteAsync<Ticker>(engine => engine.GetVariable("Transform")(ticker)); }