private void OnElapsedTime(object source, ElapsedEventArgs e) { LOG.Log(Environment.NewLine + "> Service RECALLED at " + DateTime.Now); if (!starting) { List <TaskScheduleModel> tasks = TaskManagerService.GetPendingTasks(); LOG.Log($">> Pending Tasks: {tasks.Count()} at " + DateTime.Now); foreach (TaskScheduleModel task in tasks) { LOG.Log($">> Processing Task: {task.Description} at " + DateTime.Now); bool taskResult = RunTask(task); LOG.Log($">> Processed Task: {task.Description} at " + DateTime.Now); if (taskResult) { TaskManagerService.RemoveTask(task.TaskId); LOG.Log($">> Removed Task: {task.Description} at " + DateTime.Now); } else { TaskManagerService.MarkAsPendingTask(task.TaskId, 555); LOG.Log($">> Pending Task: {task.Description} at " + DateTime.Now); } } } else { LOG.Log("===> Service STARTED at " + DateTime.Now); starting = false; } LOG.Log("< Service ENDED at " + DateTime.Now); }
private void VerifyUserTypeExpiration() { LOG.Log($" >> VERIFY USER TYPE EXPIRATION Starting - {DateTime.Now}"); if (DateTime.Now.Hour == 1) { UserService.ValidateUserTypeExpiration(DateTime.Now.Date); } LOG.Log($" << VERIFY USER TYPE EXPIRATION End - {DateTime.Now}"); }
private void UpdateUserTypeExpirationFromMercadoPago() { DateTime marketTime = MarketService.GetMarketCurrentLocalTime("BCBA"); LOG.Log($" >> MERCADO PAGO: UPDATE USER TYPE EXPIRATION Starting - {DateTime.Now}"); if (marketTime.Hour == 1) { UserService.UpdateUserTypeExpirationFromMercadoPago(DateTime.Now.Date); } LOG.Log($" << MERCADO PAGO: UPDATE USER TYPE EXPIRATION End - {DateTime.Now}"); }
private void InitializeConfigs() { this.configs = new Configs(); this.configs.ConnectionString = ConfigurationManager.AppSettings["connectionString"]; LOG.Log($"ConnectionString: {this.configs.ConnectionString}"); this.configs.Timer = new Timer(); this.configs.Timer.Elapsed += new ElapsedEventHandler(OnElapsedTime); this.configs.Timer.Interval = int.Parse(ConfigurationManager.AppSettings["timerInterval"]); this.configs.Timer.Enabled = true; this.dbcontext = new DBContext(this.configs); }
private void UpdateReportData() { DateTime marketTime = MarketService.GetMarketCurrentLocalTime("BCBA"); if (marketTime.Hour == 3) { LOG.Log($" >> REPORT Starting - {DateTime.Now}"); DateTime reportNextSync = DateTime.Parse(ConfigService.GetConfig("ReportDATA_NextSync").ConfigValue); LOG.Log($" >> REPORT reportNextSync - {reportNextSync}"); if (MarketService.GetMarketCurrentLocalTime("BCBA") > reportNextSync) { ReportData_Generator generator = new ReportData_Generator(); generator.GenerateReportData(true); } LOG.Log($" << REPORT End - {DateTime.Now}"); } }
private void UpdateMarketRealTimeQuotes(string providerName, string marketName, string data) { Configs_Market marketConfigs = this.dbcontext.GetMarketConfig(marketName); LOG.Log($">>> MARKET Configs: {marketConfigs.Name}|{marketConfigs.LastSync}|{marketConfigs.NextSync}|{marketConfigs.UTCOffset}|{marketConfigs.QuotesUpdatesActive}|"); DateTime date = DateTime.UtcNow.AddHours(marketConfigs.UTCOffset); if (Configs_Market.QuoteUpdateAvailabe(marketConfigs, this.dbcontext.IsHoliday, date)) { QuotesProvider quotesProvider = QuotesProvider.GetQuotesProviderInstance(providerName); Tuple <List <IRealTimeQuote>, List <IHistoricalQuote> > quotes = quotesProvider.GetQuotesFromJson(data); this.dbcontext.SaveRealTimeQuoteV1(quotes.Item1); this.dbcontext.SaveHistoricalQuoteV1(quotes.Item2); this.dbcontext.UpdateConfig($"{marketName}_LastSync", date.ToString()); } this.dbcontext.UpdateConfig($"{marketName}_NextSync", date.AddMinutes(15).ToString()); }
public bool IsHoliday(DateTime date, string marketName) { using (SqlConnection connection = new SqlConnection(this.configs.ConnectionString)) { try { connection.Open(); string queryString = $"SELECT 1 FROM Holidays h INNER JOIN Market m ON h.market_id = m.Id WHERE h.date = '{date.ToString("yyyy-MM-dd")}' AND m.name = '{marketName}'"; SqlCommand command = new SqlCommand(queryString, connection); SqlDataReader reader = command.ExecuteReader(); return(reader.HasRows); } catch (Exception ex) { LOG.Log($"Error (IsHoliday): {ex.Message}{Environment.NewLine} date={date}|marketName={marketName}|"); } } return(false); }
private void UpdateMarketRealTimeQuotes(string marketName) { LOG.Log($" >> {marketName} Starting - {DateTime.Now}"); Configs_Market marketConfigs = this.dbcontext.GetMarketConfig(marketName); LOG.Log($" MARKET: {marketConfigs.Name}|{marketConfigs.LastSync}|{marketConfigs.NextSync}|{marketConfigs.UTCOffset}|{marketConfigs.QuotesUpdatesActive}|"); Configs_QuoteDataProvider dataproviderConfigs = this.dbcontext.GetQuoteDataProviderConfig(marketConfigs.QuoteProviderName); LOG.Log($" QUOTES:{dataproviderConfigs.Name}|{dataproviderConfigs.APIToken}|{dataproviderConfigs.HistoricalURL}|{dataproviderConfigs.RealTimeURL}|"); List <mdlStock> stocks = this.dbcontext.GetMarketActiveStocks(marketName); LOG.Log($" STOCKS: Count={stocks.Count}|"); DateTime date = DateTime.UtcNow.AddHours(marketConfigs.UTCOffset); if (Configs_Market.QuoteUpdateAvailabe(marketConfigs, this.dbcontext.IsHoliday, date)) { QuotesDataProvider quotesDataProvider = QuotesDataProvider.GetQuoteDataProvider(dataproviderConfigs, marketConfigs); List <HistoricalQuoteDBModel> historical; List <RealTimeQuoteDBModel> realtime = quotesDataProvider.GetRealTimeQuotes(stocks, date, this.dbcontext, out historical); LOG.Log($" REALTIME: Count={realtime.Count}|"); LOG.Log($" HISTORICAL: Count={historical.Count}|"); this.dbcontext.SaveRealTimeQuote(realtime); this.dbcontext.SaveHistoricalQuote(historical); this.dbcontext.UpdateConfig($"{marketName}_LastSync", date.ToString()); } this.dbcontext.UpdateConfig($"{marketName}_NextSync", date.AddMinutes(15).ToString()); if (date.Hour == 5) { string result = this.dbcontext.DeleteIntradiaryQuotes(); LOG.Log($" {result}"); } LOG.Log($" << {marketName} End - {DateTime.Now}"); }
private bool RunTask(TaskScheduleModel task) { //if (task.TaskType == TaskScheduleType.UpdateIntradiaryBOLSAR) //{ // try // { // if (String.IsNullOrEmpty(task.Data)) // UpdateMarketRealTimeQuotes("BCBA"); // else // { // LOG.Log($"!!!BOLSAR(BCBA): Data => {task.Data}{Environment.NewLine}"); // UpdateMarketRealTimeQuotes("BOLSAR", "BCBA", task.Data); // } // } // catch (Exception ex) // { // LOG.Log($"???ERROR(BCBA): Message=>{ex.Message}{Environment.NewLine}"); // return false; // } //} //if(task.TaskType == TaskScheduleType.UpdateIntradiaryBOLSARINDEX) //{ // try // { // if (!String.IsNullOrEmpty(task.Data)) // { // LOG.Log($"!!!BOLSARINDEX(BCBA): Data => {task.Data}{Environment.NewLine}"); // UpdateMarketRealTimeQuotes("BOLSARINDEX", "BCBA", task.Data); // } // } // catch (Exception ex) // { // LOG.Log($"???ERROR(BCBAINDEX): Message=>{ex.Message}{Environment.NewLine}"); // return false; // } //} //if(task.TaskType == TaskScheduleType.UpdateIntradiaryEOD) //{ // try // { // if (String.IsNullOrEmpty(task.Data)) // { // try { UpdateMarketRealTimeQuotes("NYSE"); } catch (Exception ex) { LOG.Log($"???ERROR(NYSE): Message=>{ex.Message}{Environment.NewLine}"); return false; } // try { UpdateMarketRealTimeQuotes("NASDAQ"); } catch (Exception ex) { LOG.Log($"???ERROR(NASDAQ): Message=>{ex.Message}{Environment.NewLine}"); return false; } // } // else // UpdateMarketRealTimeQuotes("EOD","NYSE", task.Data); // } // catch (Exception ex) // { // LOG.Log($"???ERROR(EOD): Message=>{ex.Message}{Environment.NewLine}"); // return false; // } //} if (task.TaskType == TaskScheduleType.DailyStockTechnicalReport) { try { UpdateReportData(); } catch (Exception ex) { LOG.Log($"???ERROR(REPORT): Message=>{ex.Message}{Environment.NewLine}"); return(false); } } if (task.TaskType == TaskScheduleType.TenantTypeExpirationValidation) { try { VerifyUserTypeExpiration(); } catch (Exception ex) { LOG.Log($"???ERROR(VERIFY USER TYPE EXPIRATION): Message=>{ex.Message}{Environment.NewLine}"); return(false); } try { UpdateUserTypeExpirationFromMercadoPago(); } catch (Exception ex) { LOG.Log($"???ERROR(MERCADO PAGO: UPDATE USER TYPE EXPIRATION): Message=>{ex.Message}{Environment.NewLine}"); return(false); } } if (task.TaskType == TaskScheduleType.DeleteIntradiaryBOLSAR) { try { DeleteIntradiaryData("BCBA"); } catch (Exception ex) { LOG.Log($"???ERROR(DeleteIntradiaryData=BOLSAR): Message=>{ex.Message}{Environment.NewLine}"); return(false); } } if (task.TaskType == TaskScheduleType.DeleteIntradiaryEOD) { try { DeleteIntradiaryData("NASDAQ"); } catch (Exception ex) { LOG.Log($"???ERROR(DeleteIntradiaryData=NASDAQ): Message=>{ex.Message}{Environment.NewLine}"); return(false); } try { DeleteIntradiaryData("NYSE"); } catch (Exception ex) { LOG.Log($"???ERROR(DeleteIntradiaryData=NYSE): Message=>{ex.Message}{Environment.NewLine}"); return(false); } } return(true); }
protected override void OnStop() { LOG.Log("<=== Service is STOPPED at " + DateTime.Now); }
protected override void OnStart(string[] args) { this.InitializeConfigs(); LOG.Log("===> ServiceV1 is onSTART at " + DateTime.Now); this.OnElapsedTime(null, null); }
public override List <RealTimeQuoteDBModel> GetRealTimeQuotes(List <mdlStock> stocks, DateTime date, DBContext dbContext, out List <HistoricalQuoteDBModel> historical) { List <RealTimeQuoteDBModel> result = new List <RealTimeQuoteDBModel>(); historical = new List <HistoricalQuoteDBModel>(); using (WebClient web = new WebClient()) { //homologacion //string url = String.Format("https://hs-wss-bolsar-bcba.sba.com.ar/Seguridad.svc/sg?us={0}&tk={1}", "grau", ComputeHash("53bpueDi")); //Login prod string url = $"{this.QuoteDataProviderConfigs.LoginURL}?us={this.QuoteDataProviderConfigs.Username}&tk={this.ComputeHash(this.QuoteDataProviderConfigs.APIToken)}"; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) { var strResponse = reader.ReadToEnd(); LOG.Log($" ===>Login Response: {strResponse}"); dynamic loginResult = JsonConvert.DeserializeObject <dynamic>(strResponse); //homologacion //request = (HttpWebRequest)HttpWebRequest.Create("https://hs-wss-bolsar-bcba.sba.com.ar/Cotizaciones.svc/ssEspecies"); //prod request = (HttpWebRequest)HttpWebRequest.Create(this.QuoteDataProviderConfigs.RealTimeURL); request.Headers["Authorization"] = loginResult.Resultado; response = (HttpWebResponse)request.GetResponse(); using (Stream stream2 = response.GetResponseStream()) { using (StreamReader reader2 = new StreamReader(stream2)) { strResponse = reader2.ReadToEnd(); //parse strResponse List <jsonmdlBOLSARRealTime> data = JsonConvert.DeserializeObject <List <jsonmdlBOLSARRealTime> >(strResponse); List <jsonmdlBOLSARRealTime> data48hrs = data.Where(x => x.Vencimiento == "48hs" && stocks.Any(s => s.StockSymbol == x.Simbolo)).ToList <jsonmdlBOLSARRealTime>(); //INTRADIARY DATA result = data48hrs.Select(rt => new RealTimeQuoteDBModel() { ask = rt.PrecioVenta, ask_size = rt.CantidadNominalVenta, bid = rt.PrecioCompra, bid_size = rt.CantidadNominalCompra, change = rt.Tendencia, change_percent = rt.Variacion, datetime = date, last_trade_date = DateTime.Now, last_trade_price = rt.Ultimo, last_trade_size = 0, last_trade_time = "", opening = rt.Ultimo, prev_closing = rt.CierreAnterior, stock_id = stocks.Where(s => s.StockSymbol == rt.Simbolo).First().StockId }).ToList <RealTimeQuoteDBModel>(); //HISTORICAL DATA historical = data48hrs.Select(h => new HistoricalQuoteDBModel() { adj_close = 0, closing = h.Ultimo, date_round = date, maximun = h.Maximo, minimun = h.Minimo, opening = h.Apertura, stock_id = stocks.Where(s => s.StockSymbol == h.Simbolo).First().StockId, volume = h.VolumenNominal }).ToList <HistoricalQuoteDBModel>(); } } //INDICES request = (HttpWebRequest)HttpWebRequest.Create(this.QuoteDataProviderConfigs.IndexURL); request.Headers["Authorization"] = loginResult.Resultado; response = (HttpWebResponse)request.GetResponse(); using (Stream stream3 = response.GetResponseStream()) { using (StreamReader reader3 = new StreamReader(stream3)) { strResponse = reader3.ReadToEnd(); //parse strResponse List <jsonmdlBOLSARIndex> indexData = JsonConvert.DeserializeObject <List <jsonmdlBOLSARIndex> >(strResponse).Where(d => stocks.Any(s => s.StockSymbol == d.Symbol)).ToList <jsonmdlBOLSARIndex>(); //INTRADIARY DATA result.AddRange(indexData.Select(rt => new RealTimeQuoteDBModel() { ask = 0, ask_size = 0, bid = 0, bid_size = 0, change = rt.Tendencia, change_percent = rt.Variacion, datetime = date, last_trade_date = DateTime.Now, last_trade_price = rt.Ultimo, last_trade_size = 0, last_trade_time = "", opening = rt.Ultimo, prev_closing = rt.Apertura, stock_id = stocks.Where(s => s.StockSymbol == rt.Symbol).First().StockId }).ToList <RealTimeQuoteDBModel>()); //HISTORICAL DATA historical.AddRange(indexData.Select(h => new HistoricalQuoteDBModel() { adj_close = 0, closing = h.Ultimo, date_round = date, maximun = h.Maximo_Valor, minimun = h.Minimo_Valor, opening = h.Apertura, stock_id = stocks.Where(s => s.StockSymbol == h.Symbol).First().StockId, volume = 0 }).ToList <HistoricalQuoteDBModel>()); } } } } } return(result); }
public void SaveHistoricalQuoteV1(List <IHistoricalQuote> quotes) { string connectionString = this.configs.ConnectionString; SqlConnection connection = new SqlConnection(connectionString); List <SqlCommand> commands = new List <SqlCommand>(); string queryString = $@"IF NOT EXISTS(SELECT 1 FROM Stock_Quote WHERE stock_id = @stock_id AND date_round = CONVERT(date,@date_round)) BEGIN INSERT INTO [dbo].[Stock_Quote] ([stock_id],[opening],[closing],[minimun],[maximun],[volume],[date_round],[adj_close])VALUES(@stock_id, @opening, @closing, @minimun, @maximun, @volume, @date_round, @adj_close); END ELSE BEGIN UPDATE [dbo].[Stock_Quote] SET [opening] = @opening, [closing] = @closing, [minimun] = @minimun, [maximun] = @maximun, [volume] = @volume, [date_round] = @date_round, [adj_close] = @adj_close WHERE [stock_id] = @stock_id AND date_round = CONVERT(date, @date_round); END"; string errorProcesingData = string.Empty; string errorSavingData = string.Empty; foreach (IHistoricalQuote quote in quotes) { try { SqlCommand command = new SqlCommand(queryString, connection); SqlParameter sqlParameter = new SqlParameter("@stock_id", SqlDbType.Int); sqlParameter.Value = quote.stock_id; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@opening", SqlDbType.Float); sqlParameter.Value = quote.opening; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@closing", SqlDbType.Float); sqlParameter.Value = quote.closing; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@minimun", SqlDbType.Float); sqlParameter.Value = quote.minimun; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@maximun", SqlDbType.Float); sqlParameter.Value = quote.maximun; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@volume", SqlDbType.Decimal); sqlParameter.Value = quote.volume; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@date_round", SqlDbType.DateTime); sqlParameter.Value = quote.date_round; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@adj_close", SqlDbType.Float); sqlParameter.Value = quote.adj_close; command.Parameters.Add(sqlParameter); commands.Add(command); } catch (Exception ex) { errorProcesingData += $"Error: {ex.Message}{Environment.NewLine}StockID:{quote.stock_id}{Environment.NewLine}opening={quote.opening}|closing={quote.closing}|minimun={quote.minimun}|maximun={quote.maximun}|volume={quote.volume}|date_round={quote.date_round}|adj_close={quote.adj_close}|"; } } if (!string.IsNullOrEmpty(errorProcesingData)) { LOG.Log("ERROR-ProcesingData (SaveHistoricalQuoteV1):" + errorProcesingData); } using (connection) { connection.Open(); foreach (SqlCommand command in commands) { try { command.ExecuteNonQuery(); } catch (Exception ex) { errorSavingData += $"Error:{ex.Message}{Environment.NewLine}"; foreach (SqlParameter param in command.Parameters) { errorSavingData += $"{param.ParameterName}={param.Value}|"; } } } connection.Close(); } if (!string.IsNullOrEmpty(errorSavingData)) { LOG.Log("ERROR-SavingData (SaveHistoricalQuoteV1):" + errorSavingData); } }
public void SaveRealTimeQuoteV1(List <IRealTimeQuote> quotes) { string connectionString = this.configs.ConnectionString; SqlConnection connection = new SqlConnection(connectionString); List <SqlCommand> commands = new List <SqlCommand>(); string queryString = $@"INSERT INTO [dbo].[Stock_Quote_Intradiary] ([stock_id],[opening],[prev_closing],[ask],[ask_size],[bid],[bid_size],[change],[change_percent],[last_trade_time],[last_trade_price],[last_trade_size],[last_trade_date],[datetime]) VALUES(@stock_id, @opening, @prev_closing, @ask, @ask_size, @bid, @bid_size, @change, @change_percent, @last_trade_time, @last_trade_price, @last_trade_size, @last_trade_date, @datetime);"; string errorProcesingData = string.Empty; string errorSavingData = string.Empty; foreach (IRealTimeQuote quote in quotes) { try { SqlCommand command = new SqlCommand(queryString, connection); SqlParameter sqlParameter = new SqlParameter("@stock_id", SqlDbType.Int); sqlParameter.Value = quote.stock_id; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@opening", SqlDbType.Float); sqlParameter.Value = quote.opening; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@prev_closing", SqlDbType.Float); sqlParameter.Value = quote.prev_closing; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@ask", SqlDbType.Float); sqlParameter.Value = quote.ask; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@ask_size", SqlDbType.Float); sqlParameter.Value = quote.ask_size; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@bid", SqlDbType.Float); sqlParameter.Value = quote.bid; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@bid_size", SqlDbType.Float); sqlParameter.Value = quote.bid_size; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@change", SqlDbType.Float); sqlParameter.Value = quote.change; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@change_percent", SqlDbType.Float); sqlParameter.Value = quote.change_percent; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@last_trade_time", SqlDbType.NVarChar, 20); sqlParameter.Value = quote.last_trade_time; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@last_trade_price", SqlDbType.Float); sqlParameter.Value = quote.last_trade_price; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@last_trade_size", SqlDbType.Decimal); sqlParameter.Value = quote.last_trade_size; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@last_trade_date", SqlDbType.DateTime); sqlParameter.Value = quote.last_trade_date; command.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter("@datetime", SqlDbType.DateTime); sqlParameter.Value = quote.datetime; command.Parameters.Add(sqlParameter); commands.Add(command); } catch (Exception ex) { errorProcesingData += $"Error: {ex.Message}{Environment.NewLine}StockID:{quote.stock_id}{Environment.NewLine}opening={quote.opening}|prev_closing={quote.prev_closing}|ask={quote.ask}|ask_size={quote.ask_size}|bid={quote.bid}|bid_size={quote.bid_size}|change={quote.change}|change_percent={quote.change_percent}|last_trade_time={quote.last_trade_time}|last_trade_price={quote.last_trade_price}|last_trade_size={quote.last_trade_size}|last_trade_date={quote.last_trade_date}|datetime={quote.datetime}|"; } } if (!string.IsNullOrEmpty(errorProcesingData)) { LOG.Log("ERROR-ProcesingData (SaveRealTimeQuoteV1):" + errorProcesingData); } using (connection) { connection.Open(); foreach (SqlCommand command in commands) { try { command.ExecuteNonQuery(); } catch (Exception ex) { errorSavingData += $"Error:{ex.Message}{Environment.NewLine}"; foreach (SqlParameter param in command.Parameters) { errorSavingData += $"{param.ParameterName}={param.Value}|"; } } } connection.Close(); } if (!string.IsNullOrEmpty(errorSavingData)) { LOG.Log("ERROR-SavingData (SaveRealTimeQuoteV1):" + errorSavingData); } }