Esempio n. 1
0
 public BaseData(CountryKind country, IDateTimeTool2 variableDateTimeTool, ITurtleLogger logger, ISystemConfig systemConfig)
 {
     Country       = country;
     _dateTimeTool = variableDateTimeTool;
     _logger       = logger;
     SystemConfig  = systemConfig;
 }
Esempio n. 2
0
        public async Task WriteToErrorLogAsync(CountryKind country, DateTime time, string workerKind, Exception ex)
        {
            if (ex == null ||
                string.IsNullOrEmpty(workerKind) ||
                !_canWriteLog)
            {
                return;
            }

            string        fileName           = $"{country.GetShortName()}-TT2ErrorLog-{time:yyyyMMdd}.csv";
            string        filePath           = Path.Combine(_logFolderPath, fileName);
            StringBuilder errorStringBuilder = new StringBuilder();

            errorStringBuilder.Append("Exception message = ").AppendLine(ex.Message);
            errorStringBuilder.Append("Exception stack trace = ").AppendLine(ex.StackTrace);

            if (ex.InnerException != null)
            {
                errorStringBuilder.Append("  Inner exception message = ").AppendLine(ex.InnerException.Message);
                errorStringBuilder.Append("  Inner exception stack trace = ").AppendLine(ex.InnerException.StackTrace);
            }

            string data = $"{time:HH:mm:ss},{workerKind}, {errorStringBuilder}";

            await WriteContentToLogAsync(data, filePath).ConfigureAwait(false);
        }
Esempio n. 3
0
 public Stock(CountryKind country, string stockID, string stockName, string stockExchangeID)
 {
     Country         = country;
     StockId         = stockID;
     StockName       = stockName;
     StockExchangeID = stockExchangeID;
 }
Esempio n. 4
0
        public static IBaseData CreateBaseDataWithVariableDateTimeTool(CountryKind country, DateTime startDate, ITurtleLogger logger, ISystemConfig systemConfig)
        {
            VariableDateTimeTool dateTool = new VariableDateTimeTool();

            dateTool.SetTime(startDate);

            return(new BaseData(country, dateTool, logger, systemConfig));
        }
        public Task AddMemberBuyStockAsync(string memberEmail, CountryKind country, string stockID, decimal buyPrice, decimal N, BuySellStrategyType strategy, DateTime buyDate)
        {
            IMemberBuyStock memberBuyStock = new MemberBuyStock(memberEmail, country, stockID, buyPrice, N, buyPrice - (2 * N), StockBuyState.Buy, strategy, buyDate);

            MemberBuyStockTable.Add(memberBuyStock);

            return(Task.CompletedTask);
        }
 public HistoricalDataWaitingEntry(CountryKind country, string stockId, HistoricalDataWaitingState state, DateTime startDate, DateTime endDate)
 {
     Country       = country;
     StockId       = stockId;
     State         = state;
     DataStartDate = startDate;
     DataEndDate   = endDate;
 }
Esempio n. 7
0
 public BaseData(CountryKind country, ITurtleLogger logger, ISystemConfig systemConfig, bool runInTestMode = false)
 {
     Country       = country;
     _dateTimeTool = DateTimeFactory.GenerateDateTimeTool(country);
     _logger       = logger;
     SystemConfig  = systemConfig;
     RunInTestMode = runInTestMode;
 }
        public Task AddMemberStockAsync(string memberEmail, CountryKind country, string stockID, BuySellStrategyType strategy, bool isNotify)
        {
            MemberStock stock = new MemberStock(memberEmail, country, stockID, isNotify, strategy);

            MemberStockTable.Add(stock);

            return(Task.CompletedTask);
        }
 public Task <IReadOnlyList <IStockPriceHistory> > GetStockPriceHistoryAsync(CountryKind country, string stockID, DateTime dateBefore, int recordNumber)
 {
     return(Task.FromResult <IReadOnlyList <IStockPriceHistory> >(StockPriceHistoryTable.Where(a => a.Country == country &&
                                                                                               string.Equals(a.StockId, stockID, StringComparison.OrdinalIgnoreCase) &&
                                                                                               a.TradeDateTime < dateBefore)
                                                                  .OrderByDescending(a => a.TradeDateTime)
                                                                  .Take(recordNumber)
                                                                  .ToList()));
 }
        public Task <IStockPriceHistory> GetStockPriceHistoryAsync(CountryKind country, string stockID, DateTime date)
        {
            IStockPriceHistory priceHistory = StockPriceHistoryTable.Find(a => a.Country == country &&
                                                                          string.Equals(a.StockId, stockID, StringComparison.OrdinalIgnoreCase) &&
                                                                          a.TradeDateTime.Year == date.Year &&
                                                                          a.TradeDateTime.Month == date.Month &&
                                                                          a.TradeDateTime.Day == date.Day);

            return(Task.FromResult(priceHistory));
        }
        public Task DeleteStockPriceHistoryAsync(CountryKind country, string stockId)
        {
            IEnumerable <IStockPriceHistory> entries = StockPriceHistoryTable.Where(a => a.Country == country &&
                                                                                    string.Equals(a.StockId, stockId, StringComparison.OrdinalIgnoreCase));

            foreach (IStockPriceHistory item in entries)
            {
                StockPriceHistoryTable.Remove(item);
            }

            return(Task.CompletedTask);
        }
Esempio n. 12
0
 public MemberBuyStock(string memberEmail, CountryKind country, string stockID, decimal buyPrice, decimal N, decimal stopPrice, StockBuyState state, BuySellStrategyType strategy, DateTime buyDate)
 {
     MemberEmail = memberEmail;
     Country     = country;
     StockId     = stockID;
     BuyPrice    = buyPrice;
     StopPrice   = stopPrice;
     State       = state;
     BuyDate     = buyDate;
     NValue      = N;
     Strategy    = strategy;
 }
        public Task UpdateMemberBuyStockAsync(string memberEmail, CountryKind country, string stockId, decimal stopPrice, StockBuyState newState)
        {
            IMemberBuyStock memberStock = MemberBuyStockTable.Find(a => string.Equals(a.MemberEmail, memberEmail, StringComparison.OrdinalIgnoreCase) && a.Country == country);

            if (memberStock != null && memberStock is MemberBuyStock mStock)
            {
                mStock.StopPrice = stopPrice;
                mStock.State     = newState;
            }

            return(Task.CompletedTask);
        }
        private Task SetWaitingEntryToStateInternalAsync(CountryKind country, string stockId, HistoricalDataWaitingState state)
        {
            IHistoricalDataWaitingEntry entry = HistoricalDataWaitingEntryTable.Find(a => a.Country == country &&
                                                                                     string.Equals(a.StockId, stockId, StringComparison.OrdinalIgnoreCase));

            if (entry is HistoricalDataWaitingEntry tempEntry)
            {
                tempEntry.State = state;
            }

            return(Task.CompletedTask);
        }
Esempio n. 15
0
        public bool TryGetItem(CountryKind country, string stockId, out ICurrentPrice item)
        {
            string stockFullId = $"{country.GetShortName()}.{stockId}";

            if (_storage.TryGetValue(stockFullId, out ICurrentPrice target))
            {
                item = target;
                return(true);
            }

            item = null;
            return(false);
        }
Esempio n. 16
0
        public void AddOrUpdateItem(CountryKind country, string stockId, ICurrentPrice item)
        {
            string stockFullId = $"{country.GetShortName()}.{stockId}";

            if (_storage.ContainsKey(stockFullId) &&
                _storage[stockFullId] == item)
            {
                return;
            }

            _storage[stockFullId] = item;
            IsAddedOrUpdated      = true;
        }
Esempio n. 17
0
        public async Task WriteToHeartBeatLogAsync(CountryKind country, DateTime time, string workerKind)
        {
            if (string.IsNullOrEmpty(workerKind) || !_canWriteLog)
            {
                return;
            }

            string fileName = $"{country.GetShortName()}-TT2HeartBeat-{time:yyyyMMdd}.csv";
            string filePath = Path.Combine(_logFolderPath, fileName);
            string data     = $"{time:HH:mm:ss},{workerKind } sent a heart beat";

            await WriteContentToLogAsync(data, filePath).ConfigureAwait(false);
        }
Esempio n. 18
0
 public AllPricesEntry(CountryKind country,
                       string stockID,
                       decimal lowPrice,
                       decimal highPrice,
                       decimal closePrice,
                       decimal openPrice,
                       DateTime tradeDateTime,
                       string yearRange,
                       int volume,
                       decimal?atr,
                       decimal?n20,
                       decimal?highIn20,
                       decimal?lowIn10,
                       decimal?n40,
                       decimal?highIn40,
                       decimal?lowIn15,
                       decimal?n60,
                       decimal?highIn60,
                       decimal?lowIn20,
                       decimal?ma20,
                       decimal?ma40,
                       decimal?ma60,
                       decimal?ma120,
                       decimal?ma240)
 {
     Country       = country;
     StockId       = stockID;
     LowPrice      = lowPrice;
     HighPrice     = highPrice;
     ClosePrice    = closePrice;
     OpenPrice     = openPrice;
     TradeDateTime = tradeDateTime;
     YearRange     = yearRange;
     Volume        = volume;
     ATR           = atr;
     N20           = n20;
     HighIn20      = highIn20;
     LowIn10       = lowIn10;
     N40           = n40;
     HighIn40      = highIn40;
     LowIn15       = lowIn15;
     N60           = n60;
     HighIn60      = highIn60;
     LowIn20       = lowIn20;
     MA20          = ma20;
     MA40          = ma40;
     MA60          = ma60;
     MA120         = ma120;
     MA240         = ma240;
 }
        public Task SetMemberBuyStockBuyStateAsync(string memberEmail, CountryKind country, string stockID, StockBuyState buyState)
        {
            IMemberBuyStock stock = MemberBuyStockTable.FirstOrDefault(a => string.Equals(a.MemberEmail, memberEmail, StringComparison.OrdinalIgnoreCase) &&
                                                                       a.Country == country &&
                                                                       string.Equals(a.StockId, stockID, StringComparison.OrdinalIgnoreCase));

            if (!(stock is MemberBuyStock target))
            {
                return(Task.CompletedTask);
            }

            target.State = buyState;

            return(Task.CompletedTask);
        }
        public Task AddWaitingEntryAsync(CountryKind country, string stockId, DateTime startDate, DateTime endDate)
        {
            IHistoricalDataWaitingEntry entry = HistoricalDataWaitingEntryTable.Find(a => a.Country == country &&
                                                                                     string.Equals(a.StockId, stockId, StringComparison.OrdinalIgnoreCase));

            if (entry != null)
            {
                return(Task.CompletedTask);
            }

            entry = new HistoricalDataWaitingEntry(country, stockId, HistoricalDataWaitingState.Waiting, startDate, endDate);
            HistoricalDataWaitingEntryTable.Add(entry);

            return(Task.CompletedTask);
        }
Esempio n. 21
0
        public async Task WriteToCurrentPriceLogAsync(CountryKind country, string data)
        {
            if (string.IsNullOrEmpty(data) ||
                country == CountryKind.Test ||
                country == CountryKind.Test2 ||
                country == CountryKind.Unknown ||
                !_canWriteLog)
            {
                return;
            }

            string fileName = $"{country.GetShortName()}-CurrentPrice.csv";
            string filePath = Path.Combine(_logFolderPath, fileName);

            await WriteContentToLogAsync(data, filePath, false).ConfigureAwait(false);
        }
        public Task SetMemberStockAsync(string memberEmail, CountryKind country, string stockId, BuySellStrategyType strategy, bool isNotify)
        {
            IMemberStock stock = MemberStockTable.Find(a => string.Equals(a.MemberEmail, memberEmail, StringComparison.OrdinalIgnoreCase) &&
                                                       a.Country == country &&
                                                       string.Equals(a.StockId, stockId, StringComparison.OrdinalIgnoreCase));

            if (!(stock is MemberStock target))
            {
                return(Task.CompletedTask);
            }

            target.Strategy = strategy;
            target.IsNotify = isNotify;

            return(Task.CompletedTask);
        }
Esempio n. 23
0
        public static IDateTimeTool2 GenerateDateTimeTool(CountryKind country)
        {
            IDateTimeTool2 tool;

            switch (country)
            {
            case CountryKind.Taiwan:
            case CountryKind.HK:
                tool = new TaiwanDateTimeTool();
                break;

            default:
                tool = new USAEastDateTimeTool();
                break;
            }
            return(tool);
        }
        public static Country ConvertToTTStockQuoteSourceCountry(this CountryKind country)
        {
            switch (country)
            {
            case CountryKind.Taiwan:
                return(Country.Taiwan);

            case CountryKind.USA:
                return(Country.USA);

            case CountryKind.HK:
                return(Country.HK);

            default:
                return(Country.Test);
            }
        }
        public Task DeleteMemberBuyStockAsync(string memberEmail, CountryKind country, string stockId)
        {
            IEnumerable <IMemberBuyStock> items = MemberBuyStockTable.Where(a => string.Equals(a.MemberEmail, memberEmail, StringComparison.OrdinalIgnoreCase) &&
                                                                            a.Country == country &&
                                                                            string.Equals(a.StockId, stockId, StringComparison.OrdinalIgnoreCase));

            if (!items.Any())
            {
                return(Task.CompletedTask);
            }

            foreach (IMemberBuyStock item in items)
            {
                MemberBuyStockTable.Remove(item);
            }

            return(Task.CompletedTask);
        }
Esempio n. 26
0
        public Task SendEmailAsync(CountryKind country, DateTime time, IEmailTemplate template)
        {
            return(Task.Run(() =>
            {
                if (template == null)
                {
                    return;
                }

                if (string.IsNullOrEmpty(template.ReceipentEmail))
                {
                    _logger?.WriteToErrorLogAsync(country, time, _workerKind, new Exception("template.ReceipentEmail is null or empty."));
                    return;
                }

                if (_smtpInfo == null)
                {
                    _logger?.WriteToErrorLogAsync(country, time, _workerKind, new Exception("SMTPInfo is emtpy so email can't be sent."));
                    return;
                }

                try
                {
                    SmtpClient client = new SmtpClient(_smtpInfo.SMTPServer, _smtpInfo.SMTPTCPPort)
                    {
                        Credentials = new NetworkCredential(_smtpInfo.SenderEmail, _smtpInfo.SenderPassword),
                        EnableSsl = true
                    };

                    MailMessage body = new MailMessage(_smtpInfo.SenderEmail, template.ReceipentEmail, template.Subject, template.HtmlContent)
                    {
                        IsBodyHtml = true,
                        BodyEncoding = Encoding.UTF8
                    };

                    client.SendAsync(body, null);
                    _logger.WriteToEmailLogAsync(country, time, _workerKind, template.HtmlContent);
                }
                catch (Exception ex)
                {
                    _logger?.WriteToErrorLogAsync(country, time, _workerKind, ex);
                }
            }));
        }
        ///<summary>
        /// Example: TW 08-11 12:30
        /// </summary>
        /// <param name="date"></param>
        /// <param name="country"></param>
        /// <returns></returns>
        public static string GetShortTime(this CountryKind country)
        {
            DateTime temp = GetLocalTime(country);

            switch (country)
            {
            case CountryKind.USA:
                return($"US {temp.ToString("MM-dd HH:mm")}");

            case CountryKind.Taiwan:
                return($"TW {temp.ToString("MM-dd HH:mm")}");

            case CountryKind.HK:
                return($"HK {temp.ToString("MM-dd HH:mm")}");

            default:
                return(temp.ToString("MM-dd HH:mm"));
            }
        }
        public Task SendEmailAsync(CountryKind country, DateTime time, IEmailTemplate template)
        {
            if (template == null)
            {
                return(Task.CompletedTask);
            }

            try
            {
                BackTestBuySellRecord record = JsonConvert.DeserializeObject <BackTestBuySellRecord>(template.HtmlContent);
                _records.Add(record);
            }
            catch (Exception ex)
            {
                _logger?.WriteToErrorLogAsync(country, time, "BackTestNotificationService", ex);
            }

            return(Task.CompletedTask);
        }
        public Task AddStockAsync(CountryKind country, string stockId, string stockName, string stockExchangeName, string stockDescription, string stockExchangeID)
        {
            IEnumerable <IStock> stocks = StockTable.Where(a => a.Country == country &&
                                                           string.Equals(a.StockId, stockId, StringComparison.OrdinalIgnoreCase));

            if (stocks.Any())
            {
                return(Task.CompletedTask);
            }

            Stock stock = new Stock(country, stockId, stockName, stockExchangeID)
            {
                StockExchangeName = stockExchangeName,
                Description       = stockDescription
            };

            StockTable.Add(stock);

            return(Task.CompletedTask);
        }
        private static DateTime GetLocalTime(this CountryKind country)
        {
            DateTime result;

            switch (country)
            {
            case CountryKind.USA:
                result = GetTime("Eastern Standard Time");
                break;

            case CountryKind.Taiwan:
            case CountryKind.HK:
                result = GetTime("Taipei Standard Time");
                break;

            default:
                result = DateTime.Now;
                break;
            }
            return(result);
        }