public void MySqlDbIsCreatedSuccessfully() { using (var conn = new MySqlConnection(GetMySqlConnString(_mySqlUsername, _mySqlPassword, _mySqlHost))) { conn.Open(); using (var cmd = new MySqlCommand("", conn)) { cmd.CommandText = @"DROP DATABASE IF EXISTS qpas_test; CREATE DATABASE qpas_test;"; cmd.ExecuteNonQuery(); } } SetConnectionString("qpasEntities", GetMySqlConnString(_mySqlUsername, _mySqlPassword, _mySqlHost, "qpas_test"), "MySql.Data.MySqlClient"); ConfigurationManager.RefreshSection("connectionStrings"); DbConfiguration.SetConfiguration(new MySqlEFConfiguration()); using (var ctx = new DBContext()) { ctx.Database.Initialize(true); Seed.DoSeed(); } }
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 ParseStatement(XElement xml, ProgressDialogController progress, DBContext context, bool skipLastDateCheck) { const int totalActions = 12; progress.SetProgress(1.0 / totalActions); ParseSecuritiesInfo(xml, context); string accountId = xml.Attribute("accountId").Value; Account account = context.Accounts.First(x => x.AccountId == accountId); DateTime lastDate = context.CashTransactions.Any(x => x.AccountID == account.ID) ? context.CashTransactions.Max(x => x.TransactionDate) : new DateTime(1, 1, 1); progress.SetProgress(2.0 / totalActions); ParseCashTransactions(xml, context, skipLastDateCheck, lastDate, account); progress.SetProgress(3.0 / totalActions); ParseCFDCharges(xml, context, skipLastDateCheck, lastDate, account); progress.SetProgress(4.0 / totalActions); ParseOrders(xml, context, skipLastDateCheck, account); progress.SetProgress(5.0 / totalActions); ParseExecutions(xml, context, skipLastDateCheck, account); progress.SetProgress(6.0 / totalActions); ParseEquitySummaries(xml, context, account); progress.SetProgress(7.0 / totalActions); ParseOpenPositions(xml, context, account); progress.SetProgress(8.0 / totalActions); ParseFXRates(xml, context); progress.SetProgress(9.0 / totalActions); ParsePriorPeriodPositions(xml, context, skipLastDateCheck, account); progress.SetProgress(10.0 / totalActions); ParseOpenDividendAccruals(xml, context, account); progress.SetProgress(11.0 / totalActions); ParseFXPositions(xml, context, account); progress.SetProgress(12.0 / totalActions); ParseFXTransactions(xml, context, skipLastDateCheck, account); }
public MainWindow() { string[] args = Environment.GetCommandLineArgs(); if(args.Length < 3) { var logger = LogManager.GetCurrentClassLogger(); logger.Log(LogLevel.Error, "Tried to launch script editor without providing connection string details."); Close(); return; } SetConnectingString(args[1], args[2]); var context = new DBContext(); InitializeComponent(); ViewModel = new ScriptingViewModel(context, DialogCoordinator.Instance); DataContext = ViewModel; }
public void Parse(string flexXML, ProgressDialogController progress) { progress.SetMessage("Parsing Flex File"); var context = new DBContext(); context.Configuration.AutoDetectChangesEnabled = false; bool skipLastDateCheck = !Properties.Settings.Default.preventDuplicateImports; XDocument xml = XDocument.Parse(flexXML); ParseAccounts(xml, context); IEnumerable<XElement> flexStatements = xml.Descendants("FlexStatement"); foreach(XElement flexStatement in flexStatements) { ParseStatement(flexStatement, progress, context, skipLastDateCheck); } context.Configuration.AutoDetectChangesEnabled = true; context.Dispose(); }
public static void DoSeed() { var context = new DBContext(); var currencies = new List<Currency> { new Currency { Name = "USD" }, new Currency { Name = "CAD" }, new Currency { Name = "GBP" }, new Currency { Name = "EUR" }, new Currency { Name = "CHF" }, new Currency { Name = "JPY" }, new Currency { Name = "AUD" }, new Currency { Name = "SEK" }, new Currency { Name = "HKD" }, new Currency { Name = "NOK" }, new Currency { Name = "HUF" }, new Currency { Name = "SAR" }, new Currency { Name = "BGL" }, new Currency { Name = "TWD" }, new Currency { Name = "CZK" }, new Currency { Name = "DKK" }, new Currency { Name = "ILS" }, new Currency { Name = "ISK" }, new Currency { Name = "KRW" }, new Currency { Name = "PLN" }, new Currency { Name = "BRL" }, new Currency { Name = "ROL" }, new Currency { Name = "RUR" }, new Currency { Name = "HRK" }, new Currency { Name = "ALL" }, new Currency { Name = "THB" }, new Currency { Name = "TRY" }, new Currency { Name = "PKR" }, new Currency { Name = "IDR" }, new Currency { Name = "UAH" }, new Currency { Name = "BYB" }, new Currency { Name = "EEK" }, new Currency { Name = "LVL" }, new Currency { Name = "LTL" }, new Currency { Name = "IRR" }, new Currency { Name = "VND" }, new Currency { Name = "AMD" }, new Currency { Name = "AZM" }, new Currency { Name = "MKD" }, new Currency { Name = "ZAR" }, new Currency { Name = "GEL" }, new Currency { Name = "INR" }, new Currency { Name = "MYR" }, new Currency { Name = "KZT" }, new Currency { Name = "KGS" }, new Currency { Name = "KES" }, new Currency { Name = "UZS" }, new Currency { Name = "MNT" }, new Currency { Name = "SYP" }, new Currency { Name = "MVR" }, new Currency { Name = "IQD" }, new Currency { Name = "CNY" }, new Currency { Name = "MXN" }, new Currency { Name = "CSD" }, new Currency { Name = "BNd" }, new Currency { Name = "EGP" }, new Currency { Name = "LYD" }, new Currency { Name = "SGD" }, new Currency { Name = "GTQ" }, new Currency { Name = "DZD" }, new Currency { Name = "MOP" }, new Currency { Name = "NZD" }, new Currency { Name = "CRC" }, new Currency { Name = "MAD" }, new Currency { Name = "PAB" }, new Currency { Name = "TND" }, new Currency { Name = "DOP" }, new Currency { Name = "OMR" }, new Currency { Name = "JMD" }, new Currency { Name = "VEB" }, new Currency { Name = "YER" }, new Currency { Name = "COP" }, new Currency { Name = "BZD" }, new Currency { Name = "PEN" }, new Currency { Name = "JOD" }, new Currency { Name = "TTD" }, new Currency { Name = "ARS" }, new Currency { Name = "LBP" }, new Currency { Name = "ZWD" }, new Currency { Name = "KWD" }, new Currency { Name = "PHP" }, new Currency { Name = "CLP" }, new Currency { Name = "AED" }, new Currency { Name = "UYU" }, new Currency { Name = "BHD" }, new Currency { Name = "PYG" }, new Currency { Name = "QAR" }, new Currency { Name = "BOB" }, new Currency { Name = "HNL" }, new Currency { Name = "NIO" }, new Currency { Name = "ETB" }, new Currency { Name = "AFN" }, new Currency { Name = "BDT" }, new Currency { Name = "XOF" }, new Currency { Name = "RWF" }, new Currency { Name = "RUB" }, new Currency { Name = "NPR" }, new Currency { Name = "RSD" }, new Currency { Name = "LKR" }, new Currency { Name = "LAK" }, new Currency { Name = "KHR" }, new Currency { Name = "TMT" }, new Currency { Name = "BAM" }, new Currency { Name = "TJS" }, new Currency { Name = "CNH" } }; context.Currencies.AddRange(currencies); context.SaveChanges(); var tags = new List<Tag> { new Tag { Name = "Side: Long" }, new Tag { Name = "Side: Short" }, new Tag { Name = "Side: Long/Short" }, new Tag { Name = "Market: Developed" }, new Tag { Name = "Market: Emerging" }, new Tag { Name = "Length: Intraday" }, new Tag { Name = "Length: Overnight" }, new Tag { Name = "Length: Swing" }, new Tag { Name = "Length: Long Term" }, new Tag { Name = "Asset class: Equities" }, new Tag { Name = "Asset class: Futures" }, new Tag { Name = "Asset class: Options" }, new Tag { Name = "Asset class: Bonds" }, new Tag { Name = "Asset class: Other" } }; context.Tags.AddRange(tags); var preferredDatasources = new List<DatasourcePreference> { new DatasourcePreference { AssetClass = AssetClass.Bag, Datasource = "Interactive Brokers"}, new DatasourcePreference { AssetClass = AssetClass.Bill, Datasource = "Interactive Brokers"}, new DatasourcePreference { AssetClass = AssetClass.Bond, Datasource = "Interactive Brokers"}, new DatasourcePreference { AssetClass = AssetClass.Cash, Datasource = "Interactive Brokers"}, new DatasourcePreference { AssetClass = AssetClass.CFD, Datasource = "Interactive Brokers"}, new DatasourcePreference { AssetClass = AssetClass.Commodity, Datasource = "Interactive Brokers"}, new DatasourcePreference { AssetClass = AssetClass.Future, Datasource = "Interactive Brokers"}, new DatasourcePreference { AssetClass = AssetClass.FutureOption, Datasource = "Interactive Brokers"}, new DatasourcePreference { AssetClass = AssetClass.Index, Datasource = "Interactive Brokers"}, new DatasourcePreference { AssetClass = AssetClass.Option, Datasource = "Interactive Brokers"}, new DatasourcePreference { AssetClass = AssetClass.Stock, Datasource = "Yahoo"}, new DatasourcePreference { AssetClass = AssetClass.Warrant, Datasource = "Interactive Brokers"}, new DatasourcePreference { AssetClass = AssetClass.Undefined, Datasource = "Interactive Brokers"}, }; context.DatasourcePreferences.AddRange(preferredDatasources); context.SaveChanges(); context.Dispose(); }
/// <summary> /// generate EC and other curves for a benchmark /// </summary> public static EquityCurve GetBenchmarkReturns( int benchmarkID, DBContext context, List<DateTime> datesInPeriod, IDataSourcer dataSourcer, out Dictionary<DateTime, double> benchmarkSeries, out List<double> benchmarkReturns) { Logger logger = LogManager.GetCurrentClassLogger(); List<BenchmarkComponent> components = context.BenchmarkComponents.Where(x => x.BenchmarkID == benchmarkID).ToList(); DateTime earliestDate = datesInPeriod[0].Date; DateTime latestDate = datesInPeriod.Last(); Dictionary<int, TimeSeries> data = components .ToDictionary( component => component.QDMSInstrumentID, component => new TimeSeries( dataSourcer.GetExternalData(component.QDMSInstrumentID, earliestDate, latestDate))); Dictionary<int, decimal> weights = components.ToDictionary(x => x.QDMSInstrumentID, x => (decimal)x.Weight); benchmarkSeries = new Dictionary<DateTime, double>(); benchmarkReturns = new List<double>(); var benchmarkEC = new EquityCurve(1, null); decimal equity = 1; bool first = true; foreach (DateTime today in datesInPeriod) { decimal ret = 0; foreach (var kvp in data) { var ts = kvp.Value; ts.ProgressTo(today); if (ts.CurrentBar > 0) { decimal todayClose = ts[0].AdjClose.HasValue ? ts[0].AdjClose.Value : ts[0].Close; decimal lastClose = ts[1].AdjClose.HasValue ? ts[1].AdjClose.Value : ts[1].Close; ret += weights[kvp.Key] * (todayClose / lastClose - 1); #if DEBUG logger.Log(LogLevel.Trace, "Benchmark component: Date: {0} Close: {1} PrevClose: {2} Ret: {3}", today, todayClose, lastClose, ret); #endif } } benchmarkEC.AddReturn((double)ret, today); if (first) { first = false; benchmarkReturns.Add((double)(1 + ret)); benchmarkSeries.Add(today, (double)equity); continue; } equity *= 1 + ret; benchmarkReturns.Add((double)(1 + ret)); benchmarkSeries.Add(today, (double)equity); } return benchmarkEC; }
private void NextBtn_Click(object sender, RoutedEventArgs e) { string accountId = AccountIdTextBox.Text; if(String.IsNullOrEmpty(accountId)) { MessageBox.Show("Cannot use an empty account."); return; } using(var context = new DBContext()) { //check if this account exists, otherwise add it Account account; if(context.Accounts.Any(x => x.AccountId == accountId)) { account = context.Accounts.First(x => x.AccountId == accountId); } else { account = new Account { AccountId = accountId }; context.Accounts.Add(account); context.SaveChanges(); } //Now that we have the account, set it everywhere foreach(EquitySummary es in context.EquitySummaries) { es.Account = account; } foreach (DividendAccrual da in context.DividendAccruals) { da.Account = account; } foreach(Order o in context.Orders) { o.Account = account; } foreach(Execution ex in context.Executions) { ex.Account = account; } foreach(FXTransaction fxt in context.FXTransactions) { fxt.Account = account; } foreach(FXPosition fxp in context.FXPositions) { fxp.Account = account; } foreach(CashTransaction ct in context.CashTransactions) { ct.Account = account; } foreach (OpenPosition op in context.OpenPositions) { op.Account = account; } foreach(PriorPosition pp in context.PriorPositions) { pp.Account = account; } context.SaveChanges(); } _appliedChanges = true; MessageBox.Show("Success!"); Close(); }
public override void Refresh() { //Necessary hack, openpositions are deleted in another context when importing statements //so we need to detach and reload everything OpenPositions.Clear(); FXPositions.Clear(); using (var context = new DBContext()) { if (SelectedAccount.AccountId == "All") { OpenPositions.AddRange(context.OpenPositions.Include(x => x.Instrument).Include(x => x.Currency).ToList()); FXPositions.AddRange(context.FXPositions.Include(x => x.FXCurrency).ToList()); } else if (SelectedAccount != null) { OpenPositions.AddRange(context.OpenPositions.Where(x => x.AccountID == SelectedAccount.ID).Include(x => x.Instrument).Include(x => x.Currency).ToList()); FXPositions.AddRange(context.FXPositions.Where(x => x.AccountID == SelectedAccount.ID).Include(x => x.FXCurrency).ToList()); } //Add any accounts that exist in the db but are missing here var tmpAccounts = context.Accounts.ToList(); var newAccounts = tmpAccounts.Except(Accounts, new LambdaEqualityComparer<Account>((x, y) => x.ID == y.ID)); Accounts.AddRange(newAccounts); } UpdateChartSeries(); }
private void ParseAccounts(XContainer xml, DBContext context) { IEnumerable<XElement> statements = xml.Descendants("FlexStatement"); foreach(XElement e in statements) { var accountId = e.Attribute("accountId").Value; if(!context.Accounts.Any(x => x.AccountId == accountId)) { context.Accounts.Add(new Account { AccountId = accountId}); } } context.SaveChanges(); }
public void SqlServerDbIsCreatedSuccessfully() { using (var conn = new SqlConnection(GetSqlServerConnString("master", _sqlServerHost, _sqlServerUsername, _sqlServerPassword, false, _useWindowsAuthentication))) { conn.Open(); using (var cmd = new SqlCommand("", conn)) { cmd.CommandText = @"IF EXISTS(SELECT name FROM sys.databases WHERE name = 'qpas_test') DROP DATABASE qpas_test"; cmd.ExecuteNonQuery(); cmd.CommandText = "CREATE DATABASE qpas_test"; cmd.ExecuteNonQuery(); } } SetConnectionString("qpasEntities", GetSqlServerConnString("qpas_test", _sqlServerHost, _sqlServerUsername, _sqlServerPassword, false, _useWindowsAuthentication), "System.Data.SqlClient"); ConfigurationManager.RefreshSection("connectionStrings"); using (var ctx = new DBContext()) { ctx.Database.Initialize(true); Seed.DoSeed(); } }
public MainWindow() { //make sure we have a database connection and stuff, otherwise show the dialog to set db settings try { DBUtils.CheckDBConnection(); } catch { App.Splash.LoadComplete(); var dbDetailsWindow = new DBPicker(); dbDetailsWindow.ShowDialog(); } //initialize logging InitializeLogging(); //Log unhandled exceptions AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException; //set the connection string DBUtils.SetConnectionString(); //set EF configuration, necessary for MySql to work DBUtils.SetDbConfiguration(); Context = new DBContext(); //create db if it doesn't exist Context.Database.Initialize(false); //check for any currencies, seed the db with initial values if nothing is found if (!Context.Currencies.Any()) { Seed.DoSeed(); } //check for empty account fields if(Context.EquitySummaries.Any(x => x.AccountID == null)) { App.Splash.LoadComplete(); var accountMigrationWindow = new AccountMigrationWindow(); accountMigrationWindow.ShowDialog(); } var qdmsSource = new ExternalDataSources.QDMS(); Datasourcer = new DataSourcer(Context, qdmsSource, Properties.Settings.Default.allowExternalDataSource); TradesRepository = new TradesRepository(Context, Datasourcer, Properties.Settings.Default.optionsCapitalUsageMultiplier); ViewModel = new MainViewModel(Context, Datasourcer, DialogCoordinator.Instance); //Load user scripts ScriptLoader.LoadUserScriptTypes(); ///////////////////////////////////////////////////////// InitializeComponent(); ///////////////////////////////////////////////////////// DataContext = ViewModel; //Create the load statement menus using the loaded plugins PopulateStatementMenus(); //Restore column ordering, widths, and sorting LoadDataGridLayouts(); //A hack to force the heavy stuff to load, //providing snappier navigation at the expense of longer startup time #if !DEBUG ViewModel.TradesPageViewModel.Refresh(); TradesGrid.Measure(new Size(500, 500)); ViewModel.OrdersPageViewModel.Refresh(); OrdersGrid.Measure(new Size(500, 500)); ViewModel.CashTransactionsPageViewModel.Refresh(); CashTransactionsGrid.Measure(new Size(500, 500)); #endif //hiding the tab headers Style s = new Style(); s.Setters.Add(new Setter(VisibilityProperty, Visibility.Collapsed)); MainTabCtl.ItemContainerStyle = s; //load the open positions page data ViewModel.RefreshCurrentPage(); //close the slash screen App.Splash.LoadComplete(); ShowChangelog(); }