コード例 #1
0
        public void GetTradeDate_WhenTradeDateExists_ReturnsTradeDate()
        {
            // Arrange
            DateTime date = new DateTime(2018, 12, 31);

            Mock <ITradeDateRepository> tradeDateRepository = new Mock <ITradeDateRepository>();
            TradeDate tradeDate = new TradeDate(new DateTime(2018, 12, 31), true, true, true);

            tradeDateRepository.Setup(r => r.GetTradeDate(date))
            .Returns(Maybe.Create <TradeDate>(tradeDate));

            // Act
            TradeDateService service = new TradeDateService(tradeDateRepository.Object);
            var result = service.GetTradeDate(date);

            // Assert
            result.IsSuccess.Should().BeTrue();
            result.Value.Should().Be(tradeDate);
        }
コード例 #2
0
ファイル: Trade.cs プロジェクト: radtek/Gradual
        public traderBean ToBean()
        {
            traderBean bean = new traderBean();

            bean.ID            = RecordNumber.ToString();
            bean.DATA_NEGOCIO  = TradeDate.ToString("yyyy-MM-dd");
            bean.HORA_NEGOCIO  = HoraNegocio;
            bean.NR_NEGOCIO    = TradeID;
            bean.CODNEG        = Papel;
            bean.SERPAP        = Serie;
            bean.OPERACAO      = Orientation;
            bean.QTDADE        = NumberOfContracts.ToString();
            bean.PDENEG        = Price.ToString(ciEn);
            bean.FC_NOME       = BuyerName;
            bean.NM_EMIT_ORDEM = TraderName;
            bean.MERCADO       = SegmentoBolsa;

            return(bean);
        }
コード例 #3
0
 public InvestmentAccount LoadInvestmentAccount(String accountNumber, TradeDate tradeDate)
 {
     return(this.dbContext.Accounts
            .Include(account => account.AccountType)
            .Where(account => account.AccountNumber == accountNumber)
            .Select(acct => new
     {
         Account = acct,
         MarketValue = this.dbContext.AccountMarketValues
                       .Where(mv => mv.AccountNumber == acct.AccountNumber && mv.Date == tradeDate.Date)
                       .Sum(mv => mv.MarketValue)
     }
                    ).AsEnumerable()
            .Select(x =>
     {
         x.Account.MarketValue = x.MarketValue;
         return x.Account;
     }).FirstOrDefault());
 }
コード例 #4
0
        public IActionResult Get([FromQuery] DateTime?date)
        {
            TradeDate tradeDate = null;

            if (date.HasValue)
            {
                var tradeDates = this.tradeDateRepository.LoadTradeDates();
                tradeDate = tradeDates.FirstOrDefault(td => td.Date == date.Value);
                if (tradeDate == null)
                {
                    return(BadRequest($"The date {date:yyyy-mm-DD} is not a valid trade date"));
                }
            }
            else
            {
                tradeDate = this.tradeDateRepository.GetLatestTradeDate();
            }


            var prices = this.pricesRepository.LoadSecurityPrices(tradeDate);

            var results = prices.Select(p => new
            {
                symbol        = p.Symbol,
                name          = p.Security.Name,
                sector        = p.Security.Sector,
                industry      = p.Security.Industry,
                open          = p.OpenPrice,
                close         = p.ClosePrice,
                low           = p.DailyLow,
                high          = p.DailyHigh,
                change        = p.Change,
                changePercent = p.ChangePercent,
                date          = p.Date,
                volume        = p.Volume,
                description   = p.Security.Description
            });



            return(Ok(results));
        }
コード例 #5
0
        internal Result <SecurityPrice> GetSecurityPrice(string ticker, TradeDate tradeDate)
        {
            Maybe <Security> security = _securityRepository.GetSecurity(ticker);

            if (!security.HasValue)
            {
                return(Result.Failure <SecurityPrice>(new TickerNotFoundError(ticker)));
            }

            if (tradeDate.Date.Date < security.Value.FirstTradeDate.Date || tradeDate.Date.Date > security.Value.LastTradeDate)
            {
                return(Result.Failure <SecurityPrice>(new InvalidDateForTickerError(tradeDate, security.Value)));
            }

            var securityPrice = _securityPriceRepository.GetSecurityPrice(ticker, tradeDate);

            return(securityPrice.Eval <Result <SecurityPrice> >(
                       value => Result.Success <SecurityPrice>(value),
                       () => Result.Failure <SecurityPrice>(new MissingDataError($"No data found for ticker {ticker} on trade date {tradeDate.Date}"))));
        }
        public List <SecurityPrice> LoadSecurityPrices(TradeDate date)
        {
            var sql = $"{SQL} WHERE p.TradeDate = @TradeDate";

            using (IDbConnection con = this.GetConnection())
            {
                con.Open();
                var data = con.Query <SecurityPrice, TradeDate, Security, SecurityType, SecurityPrice>(sql,
                                                                                                       map: (p, d, s, t) =>
                {
                    p.TradeDate    = d;
                    s.SecurityType = t;
                    p.Security     = s;
                    return(p);
                },
                                                                                                       splitOn: "Date, Ticker, SecurityTypeCode",
                                                                                                       param: new { TradeDate = date });
                return(data.ToList());
            }
        }
        public async Task <StockIndexInfo> GetStockIndexPrice(String indexCode, TradeDate date)
        {
            String url        = $"api/StockIndexPrices/{indexCode}?tradeDate={date.Date.ToString("yyyy-MM-dd")}";
            var    httpClient = httpClientFactory.CreateClient("StockIndexApi");

            using (CustomTiming timing = MiniProfiler.Current.CustomTiming("http", String.Empty, "GET"))
            {
                var response = await httpClient.GetAsync(url);

                timing.CommandString = $"URL : {url}\n\nRESPONSE CODE: {response.StatusCode}";
                if (response.IsSuccessStatusCode)
                {
                    return(await response.Content.ReadAsAsync <StockIndexInfo>());
                }
                else
                {
                    return(await Task.FromResult <StockIndexInfo>(null));
                }
            }
        }
コード例 #8
0
        public IEnumerable <InvestmentAccount> LoadInvestmentAccounts(TradeDate tradeDate)
        {
            //return this.dbContext.Accounts
            //    .Include(account => account.AccountType)
            //    .Include(account => account.Positions)
            //    .ThenInclude(position => position.Security)
            //    .Select(account => new
            //    {
            //        account,
            //        Positions = account.Positions
            //            .Where(p => p.Date == tradeDate.Date),
            //        MarketValue = account.Positions
            //            .Where(p => p.Date == tradeDate.Date)
            //            .Sum(p => p.MarketValue)
            //    })
            //    .AsEnumerable()
            //    .Select(x =>
            //    {
            //        x.account.Positions = x.Positions.ToList();
            //        x.account.MarketValue = x.MarketValue;
            //        return x.account;
            //    })
            //    .ToList();

            return(this.dbContext.Accounts
                   .Include(account => account.AccountType)
                   .Select(acct => new
            {
                Account = acct,
                MarketValue = this.dbContext.AccountMarketValues
                              .Where(mv => mv.AccountNumber == acct.AccountNumber && mv.Date == tradeDate.Date)
                              .Sum(mv => mv.MarketValue)
            }
                           ).AsEnumerable()
                   .Select(x =>
            {
                x.Account.MarketValue = x.MarketValue;
                return x.Account;
            }).ToList());
        }
コード例 #9
0
        public TradeDate GetLatestTradeDate()
        {
            TradeDate tradeDate = null;

            using (IDbConnection con = this.GetConnection())
            {
                con.Open();

                using (IDbCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = CURRENT_TRADE_DATE_SQL;
                    using (IDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            tradeDate = this.DecodeRow(reader);
                        }
                    }
                }
            }

            return(tradeDate);
        }
コード例 #10
0
        internal Result <List <SecurityPrice> > GetSecurityPrices(TradeDate tradeDate, IEnumerable <string> tickers)
        {
            // Validate the tickers are real.  Either all the tickers are real and have data for this date or we
            // return a failure (there is no partial success).
            var securities = _securityRepository.GetSecurities(tickers);

            var unknownTickers = tickers.Except(securities.Select(s => s.Ticker));

            if (unknownTickers.Any())
            {
                return(Result.Failure <List <SecurityPrice> >(new TickerNotFoundError(unknownTickers)));
            }

            var invalidDateSecurities = securities.Where(s => tradeDate.Date <s.FirstTradeDate.Date || tradeDate.Date> s.LastTradeDate);

            if (invalidDateSecurities.Any())
            {
                return(Result.Failure <List <SecurityPrice> >(new InvalidDateForTickerError(tradeDate, invalidDateSecurities)));
            }

            var securityPrices = _securityPriceRepository.GetSecurityPrices(tradeDate, tickers);

            return(Result <List <SecurityPrice> > .Success(securityPrices));
        }
コード例 #11
0
        public SecurityPrice DecodeRow(IDataReader reader)
        {
            var date             = reader.GetDateTime(0);
            var ticker           = reader.GetString(1);
            var openPrice        = reader.GetDecimal(2);
            var closePrice       = reader.GetDecimal(3);
            var dailyHigh        = reader.GetDecimal(4);
            var dailyLow         = reader.GetDecimal(5);
            var volume           = reader.GetInt64(6);
            var change           = reader.GetDecimal(7);
            var changePercent    = reader.GetDecimal(8);
            var isMonthEnd       = reader.GetBoolean(9);
            var isQuarterEnd     = reader.GetBoolean(10);
            var isYearEnd        = reader.GetBoolean(11);
            var securityTypeCode = reader.GetString(12);
            var securityName     = reader.GetString(13);
            var exchange         = reader.GetNullableString(14);
            var description      = reader.GetNullableString(15);
            var ceo              = reader.GetNullableString(16);
            var sector           = reader.GetString(17);
            var industry         = reader.GetNullableString(18);
            var website          = reader.GetNullableString(19);
            var issueType        = reader.GetNullableString(20);
            var securityTypeName = reader.GetString(21);

            TradeDate tradeDate = new TradeDate()
            {
                Date         = date,
                IsMonthEnd   = isMonthEnd,
                IsQuarterEnd = isQuarterEnd,
                IsYearEnd    = isYearEnd
            };

            SecurityType securityType = new SecurityType()
            {
                Code = securityTypeCode,
                Name = securityTypeName
            };

            Security security = new Security()
            {
                Symbol           = ticker,
                SecurityType     = securityType,
                Name             = securityName,
                Exchange         = exchange,
                Description      = description,
                Ceo              = ceo,
                Sector           = sector,
                Industry         = industry,
                Website          = website,
                SecurityTypeCode = securityTypeCode
            };

            SecurityPrice securityPrice = new SecurityPrice()
            {
                Date          = date,
                TradeDate     = tradeDate,
                Symbol        = ticker,
                Security      = security,
                ClosePrice    = closePrice,
                OpenPrice     = openPrice,
                DailyHigh     = dailyHigh,
                DailyLow      = dailyLow,
                Volume        = volume,
                Change        = change,
                ChangePercent = changePercent
            };

            return(securityPrice);
        }
コード例 #12
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (BrokerId.Length != 0)
            {
                hash ^= BrokerId.GetHashCode();
            }
            if (InvestorId.Length != 0)
            {
                hash ^= InvestorId.GetHashCode();
            }
            if (InstrumentId.Length != 0)
            {
                hash ^= InstrumentId.GetHashCode();
            }
            if (OrderRef.Length != 0)
            {
                hash ^= OrderRef.GetHashCode();
            }
            if (UserId.Length != 0)
            {
                hash ^= UserId.GetHashCode();
            }
            if (TradeId.Length != 0)
            {
                hash ^= TradeId.GetHashCode();
            }
            if (Direction != 0)
            {
                hash ^= Direction.GetHashCode();
            }
            if (OffsetFlag != 0)
            {
                hash ^= OffsetFlag.GetHashCode();
            }
            if (HedgeFlag != 0)
            {
                hash ^= HedgeFlag.GetHashCode();
            }
            if (Price != 0D)
            {
                hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(Price);
            }
            if (Volume != 0)
            {
                hash ^= Volume.GetHashCode();
            }
            if (TradeDate.Length != 0)
            {
                hash ^= TradeDate.GetHashCode();
            }
            if (TradeTime.Length != 0)
            {
                hash ^= TradeTime.GetHashCode();
            }
            if (OrderLocalId.Length != 0)
            {
                hash ^= OrderLocalId.GetHashCode();
            }
            if (TradingDay.Length != 0)
            {
                hash ^= TradingDay.GetHashCode();
            }
            if (BrokerOrderSeq != 0)
            {
                hash ^= BrokerOrderSeq.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
コード例 #13
0
        /// <summary>
        /// Gera um subset XML completo com as informacoes deste
        /// </summary>
        /// <returns></returns>
        public string ToXML()
        {
            string response = "";
            string xml      = "<trade>";

            xml += "<trade-date>" + TradeDate.ToString("yyyy-MM-dd") + "</trade-date>";
            xml += "<trade-id>" + TradeID + "</trade-id>";

            if ((DMASource != null && DMASource.Length > 0) &&
                (DMATrade != null && DMATrade.Length > 0) &&
                (DMATradeID != null && DMATradeID.Length > 0))
            {
                xml += "<dma>";
                xml += "<dma-source>" + DMASource + "</dma-source>";
                xml += "<dma-trader>" + DMATrade + "</dma-trader>";
                xml += "<dma-trade-id>" + DMATradeID + "</dma-trade-id>";
                xml += "</dma>";
            }
            //else
            //    xml += "<dma/>";

            xml += "<record-type>" + RecordType + "</record-type>";
            xml += "<product-id>" + ProductID + "</product-id>";
            xml += "<market-id>" + MarketID + "</market-id>";
            xml += "<serie>" + Serie + "</serie>";
            xml += "<maturity-date>" + MaturityDate.ToString("yyyy-MM-dd") + "</maturity-date>";
            xml += "<hedge-long-maturity>" + HedgeLongMaturity.ToString("yyyy-MM-dd") + "</hedge-long-maturity>";
            xml += "<trade-timestamp>" + TradeTimestamp.ToString("yyyy-MM-ddTHH:mm:ss") + "</trade-timestamp>";
            //xml += "<trade-timestamp>" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + "</trade-timestamp>";
            xml += "<negotiation-channel>" + NegotiationChannel + "</negotiation-channel>";
            xml += "<after-hours>" + AfterHours.ToString().ToLowerInvariant() + "</after-hours>";
            xml += "<orientation>" + Orientation + "</orientation>";
            xml += "<number-of-contracts>" + NumberOfContracts + "</number-of-contracts>";
            xml += "<price>" + Price.ToString(ciEn) + "</price>";

            if (OptionType != null && OptionType.Length > 0)
            {
                xml += "<option-type>" + OptionType + "</option-type>";
            }

            if (ValReference1 != 0)
            {
                xml += "<val-reference-1>" + ValReference1 + "</val-reference-1>";
            }

            if (ValReference2 != 0)
            {
                xml += "<val-reference-2>" + ValReference2 + "</val-reference-2>";
            }

            if (ValDelta != 0)
            {
                xml += "<val-delta>" + ValDelta + "</val-delta>";
            }

            response += xml;

            if (TradeDetails.Count > 0)
            {
                xml = "<additional-details>";
                foreach (TradeDetail detail in TradeDetails)
                {
                    xml += detail.ToXML();
                }
                xml += "</additional-details>";
            }
            else
            {
                xml = "<additional-details/>";
            }

            response += xml;

            xml  = "<buyer>";
            xml += "<buyer-code>{0}</buyer-code>";
            xml += "<buyer-name>{1}</buyer-name>";
            xml += "</buyer>";

            xml += "<broker>";
            xml += "<broker-code>{2}</broker-code>";
            xml += "<broker-name>{3}</broker-name>";
            xml += "</broker>";

            xml += "<seller>";
            xml += "<seller-code>{4}</seller-code>";
            xml += "<seller-name>{5}</seller-name>";
            xml += "</seller>";

            xml += "<trader>";
            xml += "<trader-code>{6}</trader-code>";
            xml += "<trader-name>{7}</trader-name>";
            xml += "</trader>";

            response += string.Format(xml,
                                      BuyerCode,
                                      BuyerName,
                                      BrokerCode,
                                      BrokerName,
                                      SellerCode,
                                      SellerName,
                                      TraderCode,
                                      TraderName);

            response += "</trade>";

            return(response);
        }
コード例 #14
0
 private void FormInit()
 {
     this.esiTitle.Text = $@"{TradeDate.Split(' ')[0]}  [{AccountInfo}] - [{StockCode} - {StockName}] (总金额:{ActualAmount})";
     this.gridView1.SetLayout(showAutoFilterRow: false, showCheckBoxRowSelect: true, editable: false, readOnly: true, rowIndicatorWidth: 30);
     this.btnOk.Enabled = false;
 }