internal Account CreateDerivativeAccount(int accountType, string typename, string accountname) { var acType = AccountType.Find(accountType, typename); var account = CreateAccount(acType, accountname); return(account); }
internal Account CreateAccount(string typename, string accountname) { var acType = AccountType.Find(typename); var account = CreateAccount(acType, accountname); return(account); }
/// <summary> /// Contra Journal Entries /// </summary> /// <param name="env"></param> /// <param name="element"></param> /// <param name="tags"></param> /// <param name="from"></param> /// <param name="to"></param> /// <param name="value"></param> internal static void GenerateJournalEntries(PostingEngineEnvironment env, Transaction element, List <Tag> tags, string from, string to, double value) { var fromAccount = new AccountUtils().CreateAccount(AccountType.Find(from), tags, element); var toAccount = new AccountUtils().CreateAccount(AccountType.Find(to), tags, element); new AccountUtils().SaveAccountDetails(env, fromAccount); new AccountUtils().SaveAccountDetails(env, toAccount); var debitJournal = new Journal(element) { Account = fromAccount, When = env.ValueDate, StartPrice = 0, EndPrice = 0, CreditDebit = env.DebitOrCredit(fromAccount, value), Value = env.SignedValue(fromAccount, toAccount, true, value), FxRate = element.TradePrice, Event = Event.REALIZED_PNL, Fund = env.GetFund(element), }; var creditJournal = new Journal(debitJournal) { Account = toAccount, CreditDebit = env.DebitOrCredit(toAccount, value), Value = env.SignedValue(fromAccount, toAccount, false, value), }; env.Journals.AddRange(new[] { debitJournal, creditJournal }); }
public Account GetAccount(PostingEngineEnvironment env, string accountType, List <string> tags) { var account = CreateAccount(AccountType.Find(accountType), tags); SaveAccountDetails(env, account); return(account); }
public AccountToFrom GetAccounts(PostingEngineEnvironment env, string fromType, string toType, List <string> tags) { var fromAccount = CreateAccount(AccountType.Find(fromType), tags); var toAccount = CreateAccount(AccountType.Find(toType), tags); SaveAccountDetails(env, fromAccount); SaveAccountDetails(env, toAccount); return(new AccountToFrom { From = fromAccount, To = toAccount }); }
internal Account DeriveMTMCorrectAccount(Account from, Transaction element, List <Tag> tags, double unrealizedPnl) { Account account = from; var accountCategoryId = unrealizedPnl > 0 ? AccountCategory.AC_ASSET : AccountCategory.AC_LIABILITY; switch (element.SecurityType) { case "CROSS": case "FORWARD": case "Physical index future.": case "Equity Swap": account = CreateAccount(AccountType.Find(accountCategoryId, "Derivative contracts, at fair value"), tags, element); break; } return(account); }
private AccountToFrom GetSettlementFromToAccount(Transaction element) { var listOfFromTags = new List <Tag> { Tag.Find("CustodianCode"), Tag.Find("Symbol") }; var listOfToTags = new List <Tag> { Tag.Find("CustodianCode"), Tag.Find("Symbol") }; Account fromAccount = null; // Debiting Account Account toAccount = null; // Crediting Account switch (element.Side.ToLowerInvariant()) { case "credit": // Contribution if (element.Symbol.Equals("ZZ_CASH_DIVIDENDS")) { fromAccount = new AccountUtils().CreateAccount(AccountType.Find("Settled Cash"), listOfToTags, element); toAccount = new AccountUtils().CreateAccount(AccountType.Find("DIVIDENDS RECEIVABLE"), listOfFromTags, element); } else // Default Action { fromAccount = new AccountUtils().CreateAccount(AccountType.Find("DUE FROM/(TO) PRIME BROKERS ( Unsettled Activity )"), listOfToTags, element); toAccount = new AccountUtils().CreateAccount(AccountType.Find("SHORT POSITIONS AT COST"), listOfFromTags, element); } break; } return(new AccountToFrom { From = fromAccount, To = toAccount }); }
internal static void PostRealizedPnl(PostingEngineEnvironment env, Transaction element, double realizedPnl, string from, string to) { var listOfTags = new List <Tag> { Tag.Find("SecurityType"), Tag.Find("CustodianCode") }; var fromAccount = new AccountUtils().CreateAccount(AccountType.Find(from), listOfTags, element); var toAccount = new AccountUtils().CreateAccount(AccountType.Find(to), listOfTags, element); new AccountUtils().SaveAccountDetails(env, fromAccount); new AccountUtils().SaveAccountDetails(env, toAccount); var debitJournal = new Journal(element) { Account = fromAccount, When = env.ValueDate, StartPrice = 0, EndPrice = 0, CreditDebit = env.DebitOrCredit(fromAccount, realizedPnl), Value = env.SignedValue(fromAccount, toAccount, true, realizedPnl), FxRate = element.TradePrice, Event = Event.REALIZED_PNL, Fund = env.GetFund(element), }; var creditJournal = new Journal(element, toAccount, Event.REALIZED_PNL, env.ValueDate) { StartPrice = 0, EndPrice = 0, FxRate = element.TradePrice, CreditDebit = env.DebitOrCredit(toAccount, realizedPnl), Value = env.SignedValue(fromAccount, toAccount, false, realizedPnl), Fund = env.GetFund(element), }; env.Journals.AddRange(new[] { debitJournal, creditJournal }); }
private AccountToFrom GetFromToAccount(Transaction element) { Account fromAccount = null; // Debiting Account Account toAccount = null; // Crediting Account var symbol = element.Symbol; symbol = FakeJournals._codeMap.ContainsKey(symbol) ? FakeJournals._codeMap[symbol] : symbol; var fromAccountType = AccountType.Find("PREPAID EXPENSES"); var toTags = new List <Tag> { Tag.Find("CustodianCode") }; switch (element.Side.ToLowerInvariant()) { case "debit": fromAccount = new AccountUtils().CreateAccount(AccountType.Find("Settled Cash"), toTags, element); toAccount = new AccountUtils().CreateAccount(fromAccountType, symbol + " Paid", element); break; case "credit": break; default: break; } return(new AccountToFrom { From = fromAccount, To = toAccount }); }
public bool Run(PostingEngineEnvironment env) { var sqlHelper = new SqlHelper(env.ConnectionString); var sqlParams = new SqlParameter[] { new SqlParameter("@year", env.ValueDate.Year - 1), }; var journals = new List <Journal>(); var dataTable = sqlHelper.GetDataTables("EndOfYear", CommandType.StoredProcedure, sqlParams); var valueDate = env.ValueDate; var prevValueDate = env.PreviousValueDate; foreach (DataRow row in dataTable[0].Rows) { int offset = 0; var yearEndResult = new { AccountCategory = Convert.ToString(row[offset++]), AccountType = Convert.ToString(row[offset++]), Fund = Convert.ToString(row[offset++]), Debit = Convert.ToDecimal(row[offset++]), Credit = Convert.ToDecimal(row[offset++]), }; var credit = Convert.ToDouble(yearEndResult.Credit); var debit = Convert.ToDouble(yearEndResult.Debit); var balance = Convert.ToDouble(yearEndResult.Debit - yearEndResult.Credit); var netIncomePrev = $"Retained Earnings {(valueDate.Year - 1)}"; var netIncomeCurrent = $"Net Income Current Year"; if (AccountType.Find(AccountCategory.AC_EQUITY, netIncomePrev, false) == null) { // Need to create the Account Type var createdAccountType = AccountType.FindOrCreate(AccountCategory.AC_EQUITY, netIncomePrev); new AccountUtils().Save(env, createdAccountType); } if (AccountType.Find(AccountCategory.AC_EQUITY, netIncomeCurrent, false) == null) { // Need to create the Account Type var createdAccountType = AccountType.FindOrCreate(AccountCategory.AC_EQUITY, netIncomeCurrent); new AccountUtils().Save(env, createdAccountType); } var accountName = $"[{yearEndResult.AccountCategory}]{yearEndResult.AccountType}"; journals.AddRange(ReverseCredit(env, valueDate, yearEndResult, yearEndResult.AccountType, netIncomePrev, accountName, credit)); journals.AddRange(ReverseDebit(env, valueDate, yearEndResult, yearEndResult.AccountType, netIncomePrev, accountName, debit)); } if (journals.Count() > 0) { env.CollectData(journals); journals.Clear(); } return(true); }
private AccountToFrom GetFromToAccount(Transaction element) { Account fromAccount = null; // Debiting Account Account toAccount = null; // Crediting Account var au = new AccountUtils(); switch (element.Side.ToLowerInvariant()) { case "debit": { if (element.Symbol.Equals("ZZ_INVESTOR_WITHDRAWALS")) { var fromTags = new List <Tag> { Tag.Find("CustodianCode") }; var toTags = new List <Tag> { Tag.Find("CustodianCode") }; fromAccount = au.CreateAccount(AccountType.Find("CONTRIBUTED CAPITAL"), fromTags, element); toAccount = au.CreateAccount(AccountType.Find("Settled Cash"), toTags, element); } else if (element.Symbol.Equals("ZZ_CASH_DIVIDENDS")) { var fromTags = new List <Tag> { Tag.Find("CustodianCode") }; var toTags = new List <Tag> { Tag.Find("CustodianCode") }; fromAccount = au.CreateAccount(AccountType.Find("DIVIDENDS RECEIVABLE"), fromTags, element); toAccount = au.CreateAccount(AccountType.Find("DIVIDEND INCOME"), toTags, element); } else { var symbol = element.Symbol; symbol = _codeMap.ContainsKey(symbol) ? _codeMap[symbol] : symbol; var paidAccount = AccountType.Find("Expenses Paid"); var payableAccount = AccountType.Find("ACCRUED EXPENSES"); fromAccount = new AccountUtils().CreateAccount(paidAccount, symbol, element); toAccount = new AccountUtils().CreateAccount(payableAccount, symbol + " Payable", element); } break; } case "credit": // Contribution if (element.Symbol.Equals("ZZ_INVESTOR_CONTRIBUTIONS")) { var fromTags = new List <Tag> { Tag.Find("CustodianCode") }; var toTags = new List <Tag> { Tag.Find("CustodianCode") }; fromAccount = new AccountUtils().CreateAccount(AccountType.Find("Settled Cash"), fromTags, element); toAccount = new AccountUtils().CreateAccount(AccountType.Find("CONTRIBUTED CAPITAL"), toTags, element); } else if (element.Symbol.Equals("ZZ_CASH_DIVIDENDS")) { var fromTags = new List <Tag> { Tag.Find("CustodianCode") }; var toTags = new List <Tag> { Tag.Find("CustodianCode") }; fromAccount = new AccountUtils().CreateAccount(AccountType.Find("DIVIDENDS RECEIVABLE"), fromTags, element); toAccount = new AccountUtils().CreateAccount(AccountType.Find("DIVIDEND INCOME"), toTags, element); } else // Default Action { var symbol = element.Symbol; symbol = _codeMap.ContainsKey(symbol) ? _codeMap[symbol] : symbol; var paidAccount = AccountType.Find("Expenses Paid"); var payableAccount = AccountType.Find("ACCRUED EXPENSES"); fromAccount = new AccountUtils().CreateAccount(paidAccount, symbol, element); toAccount = new AccountUtils().CreateAccount(payableAccount, symbol + " Payable", element); } break; } return(new AccountToFrom { From = fromAccount, To = toAccount }); }
public bool Run(PostingEngineEnvironment env) { var dates = "select minDate = min([when]), maxDate = max([when]) from vwJournal"; env.CallBack?.Invoke("ExpencesAndRevenues Calculation Started"); var table = new DataTable(); // read the table structure from the database using (var adapter = new SqlDataAdapter(dates, new SqlConnection(env.ConnectionString))) { adapter.Fill(table); adapter.Dispose(); }; var valueDate = Convert.ToDateTime(table.Rows[0]["minDate"]); var endDate = Convert.ToDateTime(table.Rows[0]["maxDate"]); using (var cc = new SqlConnection(env.ConnectionString)) { cc.Open(); SetupEnvironment.Setup(cc); cc.Close(); } var journals = new List <Journal>(); var connection = new SqlConnection(env.ConnectionString); connection.Open(); var transaction = connection.BeginTransaction(); var sqlHelper = new SqlHelper(env.ConnectionString); var rowsCompleted = 1; var numberOfDays = (endDate - valueDate).Days; while (valueDate <= endDate) { if (!valueDate.IsBusinessDate()) { valueDate = valueDate.AddDays(1); rowsCompleted++; continue; } try { var sqlParams = new SqlParameter[] { new SqlParameter("@startDate", new DateTime(valueDate.Year, 1, 1)), new SqlParameter("@businessDate", valueDate), new SqlParameter("@prevbusinessDate", valueDate.PrevBusinessDate()), }; var dataTable = sqlHelper.GetDataTables("DayOverDayIncome", CommandType.StoredProcedure, sqlParams.ToArray()); foreach (DataRow row in dataTable[0].Rows) { int offset = 0; var expencesAndRevenues = new { Fund = Convert.ToString(row[offset++]), Credit = Convert.ToDecimal(row[offset++]), Debit = Convert.ToDecimal(row[offset++]), Balance = Convert.ToDecimal(row[offset++]), }; var accountType = $"Net Income Current Year"; if (AccountType.Find(AccountCategory.AC_EQUITY, accountType, false) == null) { // Need to create the Account Type var createdAccountType = AccountType.FindOrCreate(AccountCategory.AC_EQUITY, accountType); new AccountUtils().Save(env, createdAccountType); } var balance = Convert.ToDouble(expencesAndRevenues.Balance); var account = new AccountUtils().GetAccount(env, accountType, new string[] { env.BaseCurrency }.ToList()); var debit = new Journal(account, "expences-revenues", valueDate) { Source = "calculated-data", Fund = expencesAndRevenues.Fund, Quantity = balance, FxCurrency = env.BaseCurrency, Symbol = env.BaseCurrency, SecurityId = -1, FxRate = 0, StartPrice = 0, EndPrice = 0, // If this number is +ve then its actually a Debit and this is going into a Equity account which needs to be -ve and not +ve Value = balance * -1, CreditDebit = env.DebitOrCredit(account, balance * -1), }; journals.AddRange(new List <Journal>(new[] { debit })); } } catch (Exception ex) { env.CallBack?.Invoke($"Exception on {valueDate.ToString("MM-dd-yyyy")}, {ex.Message}"); } env.CallBack?.Invoke($"Completed ExpencesAndRevenues for {valueDate.ToString("MM-dd-yyyy")}", numberOfDays, rowsCompleted++); valueDate = valueDate.AddDays(1); } if (journals.Count() > 0) { env.CollectData(journals); journals.Clear(); } transaction.Commit(); connection.Close(); return(true); }
public Forward() { atSettledCash = AccountType.Find("Settled Cash"); unrealizedAccountType = AccountType.Find("Change in Unrealized Derivatives Contracts at Fair Value"); realizedAccountType = AccountType.Find("REALIZED GAIN/(LOSS)"); }
internal static void GenerateCloseOutPostings(PostingEngineEnvironment env, TaxLotDetail lot, TaxLot taxlot, Transaction element, TaxLotStatus taxlotStatus, string fund) { double multiplier = 1.0; if (env.SecurityDetails.ContainsKey(element.BloombergCode)) { multiplier = env.SecurityDetails[element.BloombergCode].Multiplier; } double fxrate = 1.0; // Lets get fx rate if needed if (!element.SettleCurrency.Equals(env.BaseCurrency)) { fxrate = Convert.ToDouble(FxRates.Find(env.ValueDate, element.SettleCurrency).Rate); } var prevPrice = MarketPrices.GetPrice(env, env.PreviousValueDate, lot.Trade).Price; var unrealizedPnl = Math.Abs(taxlotStatus.Quantity) * (element.SettleNetPrice - prevPrice) * multiplier; unrealizedPnl = Math.Abs(unrealizedPnl) * CommonRules.DetermineSign(taxlotStatus.Trade); var buyTrade = env.FindTrade(lot.Trade.LpOrderId); ReverseUnrealizedPnl( env, buyTrade, element, unrealizedPnl, MarketPrices.GetPrice(env, env.PreviousValueDate, lot.Trade).Price, element.SettleNetPrice, fxrate); var PnL = taxlot.RealizedPnl; PostRealizedPnl( env, buyTrade, PnL, taxlot.TradePrice, taxlot.CostBasis, fxrate); var listOfFromTags = new List <Tag> { Tag.Find("SecurityType"), Tag.Find("CustodianCode") }; Account fromAccount = null; Account toAccount = null; if (element.IsDerivative()) { return; } else { var accountType = (buyTrade.IsShort() || buyTrade.IsCover()) ? "SHORT POSITIONS AT COST" : "LONG POSITIONS AT COST"; var markToMarketAccount = (buyTrade.IsShort() || buyTrade.IsCover()) ? "Mark to Market Shorts" : "Mark to Market Longs"; fromAccount = new AccountUtils().CreateAccount(AccountType.Find(accountType), listOfFromTags, element); toAccount = new AccountUtils().CreateAccount(AccountType.Find(markToMarketAccount), listOfFromTags, element); } new AccountUtils().SaveAccountDetails(env, fromAccount); new AccountUtils().SaveAccountDetails(env, toAccount); // Now Generate Entries var fromJournal = new Journal(element) { Account = fromAccount, CreditDebit = env.DebitOrCredit(fromAccount, PnL), When = env.ValueDate, StartPrice = taxlot.TradePrice, EndPrice = taxlot.CostBasis, Value = PnL, FxRate = 1, Event = Event.REALIZED_PNL, Fund = env.GetFund(element), }; var toJournal = new Journal(fromJournal) { Account = toAccount, CreditDebit = env.DebitOrCredit(toAccount, PnL * -1), Value = PnL * -1, }; env.Journals.AddRange(new[] { fromJournal, toJournal }); }