public override int GetHashCode() { int hash = 1; if (Type != 0) { hash ^= Type.GetHashCode(); } if (AssetClass.Length != 0) { hash ^= AssetClass.GetHashCode(); } if (Quantity != 0L) { hash ^= Quantity.GetHashCode(); } if (Price != 0L) { hash ^= Price.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jo = JObject.Load(reader); AssetClass assetClass = (AssetClass)jo["assetClass"].Value <int>(); switch (assetClass) { case AssetClass.Stock: return(jo.ToObject <Stock>(serializer)); case AssetClass.ETF: return(jo.ToObject <ETF>(serializer)); case AssetClass.Option: return(jo.ToObject <Option>(serializer)); case AssetClass.Cash: return(jo.ToObject <Cash>(serializer)); case AssetClass.Bond: return(jo.ToObject <Bond>(serializer)); default: throw new NotImplementedException($"There is no convertion for asset class='{assetClass.ToString()}'"); } }
internal Broker(Brokers parent, string name, AssetClass assetClass) { this.parent = parent; this.name = name; this.assetClass = assetClass; strategies = new BrokerStrategies(this); }
internal static IList <ITrade> GetOpenTradesByAssetClass(AssetClass ac) { var trades = new List <ITrade>(); try { using var connection = new SqlConnection(Builder.ConnectionString); connection.Open(); const string sql = "SELECT * From Trade INNER JOIN Market ON Trade.MarketId=Market.Id" + " INNER JOIN Strategy ON Trade.StrategyId=Strategy.Id WHERE CloseLevel IS NULL AND Market.AssetClass = @assetClass;"; using (var cmd = new SqlCommand(sql, connection)) { cmd.Parameters.AddWithValue("@assetClass", ac.ToString()); var results = cmd.ExecuteReader(); if (results.HasRows) { while (results.Read()) { trades.Add(ReadTradeIn(results)); } } } connection.Close(); } catch (SqlException e) { Debug.WriteLine(e.ToString()); } return(trades); }
/// <summary> /// Add Update Data /// </summary> /// <param name="model"></param> /// <returns>Jsonresponse</returns> public JsonResponse AddUpdate(AssetClass model) { try { // If these condition true the data was not exsits in the database if (!IsExsits(model.Name, model.ID)) { // If model.ID == 0 the data goes to the Add part. if (model.ID == 0) { model.CreatedOn = DateTime.Now; model.CreatedBy = GetUserID(); _context.Set <AssetClass>().Add(model); int i = _context.SaveChanges(); if (i != 0) { resp.Status = Constants.ResponseStatus.Success; resp.Message = Constants.Service.Data_insert_success; } else { resp.Message = Constants.Service.Data_insert_failed; } } // Else data goes to the Update part. else { resp.Message = Constants.Service.Data_Update_failed; var models = GetData(model.ID); // If the models not null it get the database data belongs to the ID if (models != null) { models.Name = model.Name; models.Code = model.Code; models.IsActive = model.IsActive; models.ModifiedOn = DateTime.Now; models.ModifiedBy = GetUserID(); _context.Set <AssetClass>().Update(models); int i = _context.SaveChanges(); if (i != 0) { resp.Status = Constants.ResponseStatus.Success; resp.Message = Constants.Service.Data_Update_success; } } } } // The data was in the database so, It return the else part else { resp.Message = Constants.ControllerMessage.Data_Exsists; } } catch (Exception ex) { resp.Message = Constants.Service.Common_message; } return(resp); }
public bool TryGetStockSummary(string ticker, Exchange?exchange, AssetClass assetType, out Stock asset, out string errorMessage) { //https://api.nasdaq.com/api/quote/TQQQ/info?assetclass=etf //https://api.nasdaq.com/api/quote/AAPL/info?assetclass=stocks bool ok = NasdaqApiCaller.GetStockSummary(ticker, exchange, assetType, out HttpStatusCode statusCode, out NasdaqResponse nasdaqResponse, out string jsonResponse, out errorMessage); throw new NotImplementedException(); }
/// <summary> /// Returns the class UClass if it is loaded. It is not possible to load the class if it is unloaded since we only have the short name. /// </summary> /// <returns></returns> public UClass GetClass() { if (!IsValid) { return(null); } return(UClass.GetClass(AssetClass.ToString())); }
public Report(IReadOnlyList <AccountReport> accounts, IReadOnlyList <Allocation> allocations, AssetClass cash, IReadOnlyList <AssetClass> equityAssetClasses, IReadOnlyList <Currency> currencies, Currency output) { Accounts = accounts; Allocations = allocations; Cash = cash; EquityAssetClasses = equityAssetClasses; Currencies = currencies; Output = output; }
private static string PreferredDataSource(AssetClass ac) { using(var context = new DBContext()) { var preferredSource = context.DatasourcePreferences.FirstOrDefault(x => x.AssetClass == ac); if (preferredSource == null) return "Interactive Brokers"; return preferredSource.Datasource; } }
private void AddNewItem(object sender, RoutedEventArgs e) { AssetClass asset = new AssetClass() { Class = "new class" }; classes.Add(asset); }
public bool isHoliday(DateTime date, MarketName marketName, AssetClass assetClass) { bool isHoliday = false; List <DateTime> holidayList = marketHolidaysInYear(marketName, assetClass, date.Year); isHoliday = holidayList.Contains(date.Date); return(isHoliday); }
private static string PreferredDataSource(AssetClass ac, List <DatasourcePreference> datasourcePreferences) { var preferredSource = datasourcePreferences.FirstOrDefault(x => x.AssetClass == ac); if (preferredSource == null) { return("Interactive Brokers"); } return(preferredSource.Datasource); }
public void Add_AssetWithNullId_AssetFoundByIndex() { var container = new AssetContainer <AssetClass>(1); var asset = new AssetClass(null); container.Add(asset); Assert.AreEqual(asset, container[0]); }
public static decimal GetCapitalUsageMultiplier(this AssetClass ac) { if (ac == AssetClass.Option || ac == AssetClass.FutureOption) { return(Properties.Settings.Default.optionsCapitalUsageMultiplier); } else { return(1); } }
public void T0(AssetClass assetClass, string expected) { // Arrange var testConverter = new AssetClassToStringConverter(); // Act var actual = testConverter.Convert(assetClass, typeof(object), null !, InvariantCulture); // Assert Assert.Equal(expected, actual); }
public void Save() { Properties.Settings.Default.assumedInterestRate = AssumedInterestRate; Properties.Settings.Default.statementSaveLocation = StatementSaveLocation; Properties.Settings.Default.logLocation = LogLocation; Properties.Settings.Default.flexID = FlexID; Properties.Settings.Default.flexToken = FlexToken; Properties.Settings.Default.preventDuplicateImports = PreventDuplicateImports; Properties.Settings.Default.optionsCapitalUsageMultiplier = OptionsCapitalUsageMultiplier; Properties.Settings.Default.totalCapitalAlwaysUsesAllAccounts = TotalCapitalAlwaysUsesAllAccounts; //QDMS stuff Properties.Settings.Default.qdmsAllowFreshData = QdmsAllowFreshData; Properties.Settings.Default.qdmsHost = QdmsHost; Properties.Settings.Default.qdmsRealTimeRequestPort = QdmsRealTimeRequestPort; Properties.Settings.Default.qdmsRealTimePublishPort = QdmsRealTimePublishPort; Properties.Settings.Default.qdmsInstrumentServerPort = QdmsInstrumentServerPort; Properties.Settings.Default.qdmsHistoricalDataPort = QdmsHistoricalDataPort; Properties.Settings.Default.allowExternalDataSource = AllowExternalDataSource; //MySQL Properties.Settings.Default.mySqlHost = MySqlHost; Properties.Settings.Default.mySqlUsername = MySqlUsername; //SQL Server Properties.Settings.Default.sqlServerUseWindowsAuthentication = SqlServerUseWindowsAuthentication; Properties.Settings.Default.sqlServerUsername = SqlServerUsername; Properties.Settings.Default.sqlServerHost = SqlServerHost; //db selection if (MySqlSelected) { Properties.Settings.Default.databaseType = "MySql"; } else if (SqlServerSelected) { Properties.Settings.Default.databaseType = "SqlServer"; } foreach (var dsp in DatasourcePreferences) { AssetClass ac = dsp.AssetClass; DatasourcePreference existingDsp = _context.DatasourcePreferences.FirstOrDefault(x => x.AssetClass == ac); if (existingDsp == null) { continue; } existingDsp.Datasource = dsp.Datasource; } _context.SaveChanges(); Properties.Settings.Default.Save(); }
private decimal GetCapitalUsageMultiplier(AssetClass ac) { if (ac == AssetClass.Option || ac == AssetClass.FutureOption) { return(_optionsCapitalUsageMultiplier); } else { return(1); } }
// GET: AssetClass public ActionResult Index(int pageNo = 1, int id = 0) { var model = new AssetClass(); if (id > 0) { model = db.AssetClasses.Find(id); } BindList(pageNo); return(View(model)); }
public bool isValidBusinessDay(DateTime date, MarketName marketName, AssetClass assetClass) { bool isValidDay = true; bool isHol = isHoliday(date, marketName, assetClass); if ((date.DayOfWeek == DayOfWeek.Saturday) || (date.DayOfWeek == DayOfWeek.Sunday) || (isHol == true)) { isValidDay = false; } return(isValidDay); }
public void AddRange_AssetsWithDuplicateId_AssetsAssignedUniqueIds() { var container = new AssetContainer <AssetClass>(2); var asset1 = new AssetClass("id"); var asset2 = new AssetClass("id"); container.AddRange(new[] { asset1, asset2 }, _ => _.Id, (a, id) => new AssetClass(id)); Assert.AreEqual(asset1.Id, container[0].Id); Assert.AreNotEqual(asset2.Id, container[1].Id); }
private static string PreferredDataSource(AssetClass ac) { using (var context = new DBContext()) { var preferredSource = context.DatasourcePreferences.FirstOrDefault(x => x.AssetClass == ac); if (preferredSource == null) { return("Interactive Brokers"); } return(preferredSource.Datasource); } }
private void AddAssetClass(string assetClassName) { TableUtility tableUtility = new TableUtility(); tableUtility.CreateTable(AssetClass.GetDefaultValue()); AssetClass assetClass = new AssetClass { Name = assetClassName }; tableUtility.InsertTableRow(assetClass); FormUtility.GetBindingSource(dataGridViewAssetClasses).Add(assetClass); }
public void AddRange_NullId_AssetsAssignedUniqueIds() { var container = new AssetContainer <AssetClass>(2); var asset1 = new AssetClass(null); var asset2 = new AssetClass(null); container.AddRange(new[] { asset1, asset2 }, _ => null, (a, id) => new AssetClass(id)); Assert.NotNull(container[0].Id); Assert.NotNull(container[1].Id); Assert.AreNotEqual(container[0].Id, container[1].Id); }
public bool TryGetLastPrice(string ticker, Exchange?exchange, AssetClass assetType, out HistoricalPrice lastPrice, out string message) { //Last two months??? //https://query1.finance.yahoo.com/v8/finance/chart/AAPL?region=US&lang=en-US&includePrePost=false&interval=2m&range=1d&corsDomain=finance.yahoo.com&.tsrc=finance //Daily, last day //https://query1.finance.yahoo.com/v8/finance/chart/AAPL?lang=en-US&includePrePost=false&interval=1d&range=1d //Daily, last 5 days //https://query1.finance.yahoo.com/v8/finance/chart/AAPL?lang=en-US&includePrePost=false&interval=1d&range=5d int days = 1; YahooChartInterval interval = YahooChartInterval.OneHour; bool ok = YahooApiCaller.GetDailyPrices(ticker, interval, days, out HttpStatusCode statusCode, out YahooChartResponse yahooResponse, out string jsonResponse, out message); if (ok && statusCode == HttpStatusCode.OK && yahooResponse != null && yahooResponse.Chart != null && yahooResponse.Chart.Result != null && yahooResponse.Chart.Result.Length > 0) { var result = yahooResponse.Chart.Result.Last(); int length = result.TimeStampsAsLong.Length; decimal?close = null; int i = length - 1; while (close == null && i > 0) { if (result.Indicators.Quote[0].Close[i].HasValue) { close = result.Indicators.Quote[0].Close[i].Value; } else { i--; } } int index = i; long seconds = result.TimeStampsAsLong[index]; DateTime dt = DATE_1970.AddSeconds(seconds); decimal price = result.Indicators.Quote[0].Close[index].Value; ulong volume = result.Indicators.Quote[0].Volume[index].Value; lastPrice = new HistoricalPrice() { Date = dt, Close = price, Volume = volume, }; return(true); } else { lastPrice = null; return(false); } }
public AssetBase CreateAsset(AssetClass assetClass, string ticker, OptionClass?optionClass = null, string underlyingTicker = null, DateTime?expiration = null, double?strike = null) { switch (assetClass) { case AssetClass.Stock: Stock stock = new Stock(ticker); SaveAsset(stock); return(stock); case AssetClass.ETF: ETF etf = new ETF(ticker); SaveAsset(etf); return(etf); case AssetClass.Bond: Bond bond = new Bond(ticker); SaveAsset(bond); return(bond); case AssetClass.Option: if (optionClass.HasValue) { Option option = new Option(optionClass.Value, ticker); Stock unserlyingAsset = (Stock)GetAssetyBy(AssetClass.Stock, underlyingTicker); if (unserlyingAsset == null) { unserlyingAsset = new Stock(underlyingTicker); SaveAsset(unserlyingAsset); } option.UnderlyingAsset = unserlyingAsset; option.ExpirationDate = expiration.Value; option.Strike = strike.Value; SaveAsset(option); return(option); } else { throw new ArgumentException("Must provide option class (call other put), underlying asset, strike and expiration when asset is an option"); } case AssetClass.Cash: Cash cash = new Cash(ticker); SaveAsset(cash); return(cash); default: throw new NotImplementedException($"There is no DBSet AssetClass={assetClass.ToString()}"); } }
public async Task ImportYahooFinanceCsv(string isin, AssetClass assetClass, string label, Currency currency, IFormFile file) { var model = new InsertAssetModel { Isin = isin, Class = assetClass, Label = label, Currency = currency }; using (var fileStream = file.OpenReadStream()) { await _importMarketPriceService.ImportFromYahooFinanceCsv(model, fileStream); } }
private void AddAssetClass(string assetClassName) { TableUtility tableUtility = new TableUtility(Globals.WatchdogAddIn.Application.ActiveWorkbook); tableUtility.CreateMissingTable(AssetClass.GetDefaultValue()); AssetClass assetClass = new AssetClass { Name = assetClassName }; tableUtility.InsertTableRow(assetClass, new List <string>() { assetClass.Name }); assetClassBindingSource.Add(assetClass); }
private AssetAllocationEntry GetAssetAllocationEntry(AssetClass assetClass, Currency currency) { TableUtility tableUtility = new TableUtility(); List <AssetAllocationEntry> entries = tableUtility.ConvertRangesToObjects <AssetAllocationEntry>(tableUtility.ReadAllRows(AssetAllocationEntry.GetDefaultValue())); var entryQuery = from entry in entries where entry.AssetClass.Name.Equals(assetClass.Name) where entry.Currency.IsoCode.Equals(currency.IsoCode) where entry.Fund.Index == fund.Index select entry; List <AssetAllocationEntry> list = entryQuery.ToList(); if (list.Count == 0) { return(null); } return(entryQuery.ToList()[0]); }
public bool TryGetCompleteAssetData(string ticker, Exchange?exchange, AssetClass assetClass, bool includeOptionChain, bool includeFinancialStatements, out AssetBase asset, out string errorMessage) { if (assetClass != AssetClass.Stock) { throw new NotImplementedException(); } if (assetDataDataSource.TryGetStockSummary(ticker, exchange, assetClass, out Stock stock, out errorMessage) == false) { asset = stock; return(false); } asset = stock; if (includeOptionChain) { if (stock.LastPrice.HasValue) { double lastPrice = (double)stock.LastPrice.Value; if (TryGetOptionsChainWithTheoricalValue(ticker, exchange, lastPrice, out OptionsChain optionsChain, out errorMessage)) { stock.OptionsChain = optionsChain; stock.Volatility = optionsChain.HistoricalVolatility; } } else { if (TryGetOptionsChain(ticker, exchange, out OptionsChain optionsChain, out errorMessage)) { stock.OptionsChain = optionsChain; } } } if (includeFinancialStatements) { if (TryGetFinancialData(ticker, exchange, out FinancialStatements financialData, out errorMessage) == false) { stock.FinancialStatements = financialData; } } return(true); }
public bool Update(int assetAllocationId, out AssetAllocation assetAllocation) { assetAllocation = portfoliosContext.GetAssetAllocationBy(assetAllocationId); AssetClass assetClass = assetAllocation.Asset.AssetClass; string ticker = assetAllocation.Asset.Ticker; Exchange? exchange = assetAllocation.Asset.Exchange; decimal? costs = assetAllocation.Costs.Value; if (assetClass == AssetClass.Stock || assetClass == AssetClass.ETF) { if (dataSource.TryGetLastPrice(ticker, exchange, assetClass, out HistoricalPrice price, out string message)) { decimal?marketValue = assetAllocation.UpdateMarketValue(price, costs); portfoliosContext.Update(assetAllocation); return(true); } else { return(false); } }
public List <DateTime> marketHolidaysInYear(MarketName marketName, AssetClass assetClass, int year) { switch (marketName) { case MarketName.US: switch (assetClass) { case AssetClass.EQUITY: return(yearlyEquityMarketHolidays_US(year)); case AssetClass.BOND: return(yearlyBondMarketHolidays_US(year)); default: return(yearlyEquityMarketHolidays_US(year)); } default: return(yearlyEquityMarketHolidays_US(year)); } }
public static SecurityType GetSecurityType(AssetClass assetClass) { switch (assetClass) { case AssetClass.Stock: return SecurityType.Stock; case AssetClass.Bond: return SecurityType.Bond; case AssetClass.Forex: return SecurityType.Cash; case AssetClass.Future: return SecurityType.Future; case AssetClass.FuturesOption: return SecurityType.FutureOption; case AssetClass.Index: return SecurityType.Index; case AssetClass.Option: return SecurityType.Option; default: return SecurityType.Undefined; } }
private decimal GetCapitalUsageMultiplier(AssetClass ac) { if (ac == AssetClass.Option || ac == AssetClass.FutureOption) { return _optionsCapitalUsageMultiplier; } else { return 1; } }
public List<BarData> RetrieveData(Symbol symbol, int frequency, AssetClass assetClass, double? strikePrice, DateTime? expirationDate, ContractType? contract, DateTime startDate, DateTime endDate) { ClearError(); bool bWasConnected = connected; try { if (!connected) { if (!Connect(ServiceConnectOptions.HistoricalData)) return null; } TimeSpan interval = new TimeSpan(0, frequency, 0); OEC.API.Contract oecContract = GetContractFromSymbol(symbol); if (oecContract == null) { lastError = "Historical data is not available for the specified symbol: " + symbol; return null; } histDoneHandle.Reset(); bGettingHistData = true; if (endDate > DateTime.Today) { endDate = DateTime.Today; } Trace.WriteLine("Requesting OEC historical data..."); oecClient.RequestBars(oecContract, startDate, endDate, interval); //oecClient.RequestHistory(oecContract, startDate, endDate); Application.Run(); //if (!histDoneHandle.WaitOne(new TimeSpan(0, 1, 0), true)) //{ // lastError = "Timed out."; // return null; //} if (!CheckError()) { return null; } List<BarData> ret = histBarData; histBarData = null; return ret; } finally { bGettingHistData = false; if (!bWasConnected && connected) { string tempError = lastError; Disconnect(); if (CheckError()) { lastError = tempError; } } } }