Example #1
0
        private void RetrieveCurrentData(TransactionGroup grp)
        {
            decimal currentValue       = 0;
            decimal previousCloseValue = 0;

            try
            {
                // retrieve and cache current data from tastyworks for this a subsequent passes
                if (twpositions == null)
                {
                    if (TastyWorks.ActiveSession())
                    {
                        List <string> symbols = new List <string>();

                        twpositions = new Dictionary <string, TWPositions>();
                        foreach (Account a in accounts)
                        {
                            if (a.Active)
                            {
                                // retrieve Tastyworks positions for given account
                                TWPositions pos = TastyWorks.Positions(a.ID);
                                twpositions.Add(a.ID, pos);

                                if (pos != null)
                                {
                                    foreach (KeyValuePair <string, TWPosition> p in pos)
                                    {
                                        if (!symbols.Contains(p.Value.Symbol))
                                        {
                                            symbols.Add(p.Value.Symbol);
                                        }
                                    }
                                }
                            }
                        }

                        twmarketinfo = TastyWorks.MarketInfo(symbols);  // get IV's
                    }
                }

                // ensure that positions got instanciated AND that the particular account isn't empty
                if ((twpositions != null) && (twpositions.Count > 0) && (twpositions[grp.Account] != null))
                {
                    foreach (KeyValuePair <string, Position> item in grp.Holdings)
                    {
                        Position pos = item.Value;

                        // this loop could be eliminated if the long symbol name gets persisted in database
                        foreach (KeyValuePair <string, TWPosition> p in twpositions[grp.Account])
                        {
                            TWPosition twpos = p.Value;
                            if ((pos.Symbol == twpos.Symbol) && (pos.Type == twpos.Type) && (pos.Strike == twpos.Strike) && (pos.ExpDate == twpos.ExpDate))
                            {
                                //Debug.WriteLine(twpos.Market);
                                currentValue       += pos.Quantity * twpos.Market;
                                previousCloseValue += pos.Quantity * twpos.PreviousClose * twpos.Multiplier;

                                // capture current details while we have it
                                pos.Market          = twpos.Market;
                                pos.Multiplier      = twpos.Multiplier;
                                pos.UnderlyingPrice = twpos.UnderlyingPrice;

                                // capture the underlying price from the first position for the overall group
                                if (grp.UnderlyingPrice == 0)
                                {
                                    grp.UnderlyingPrice = twpos.UnderlyingPrice;
                                }

                                // update groups order status based on any of items constituent holdings
                                grp.OrderActive = twpos.OrderActive;
                            }
                        }
                    }
                }

                grp.CurrentValue            = currentValue;
                grp.PreviousCloseValue      = previousCloseValue;
                grp.ChangeFromPreviousClose = currentValue - previousCloseValue;
                if (twmarketinfo.ContainsKey(grp.ShortSymbol))
                {
                    grp.ImpliedVolatility     = twmarketinfo[grp.ShortSymbol].ImpliedVolatility;
                    grp.ImpliedVolatilityRank = twmarketinfo[grp.ShortSymbol].ImpliedVolatilityRank;
                    grp.DividendYield         = twmarketinfo[grp.ShortSymbol].DividendYield;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("RetrieveCurrentData: " + ex.Message);
            }
        }
Example #2
0
        public string ValidateCurrentHoldings()
        {
            string returnValue = "";
            Dictionary <string, TWPositions> overallPositions = null;

            // always start with clean data
            if (TastyWorks.ActiveSession())
            {
                overallPositions = new Dictionary <string, TWPositions>();
                foreach (Account a in accounts)
                {
                    if (a.Active)
                    {
                        // retrieve Tastyworks positions for given account
                        TWPositions pos = TastyWorks.Positions(a.ID);
                        overallPositions.Add(a.ID, pos);
                    }
                }
            }
            else
            {
                MessageBox.Show("Login to TastyWorks failed", "Error");
                return("LoginFailed");
            }


            foreach (KeyValuePair <string, TWPositions> item  in overallPositions)
            {
                // cycle thru each account
                TWPositions accountPositions = item.Value;

                // skip if the account is empty of positions
                // and confirm each aligns with what is in current database by
                // iterating thru all the positions in the current account
                //
                int i = 0;
                while ((accountPositions != null) && (i < accountPositions.Count))
                {
                    TWPosition position = accountPositions.ElementAt(i).Value;

                    // iterate thru each group
                    foreach (KeyValuePair <int, TransactionGroup> grpItem in this)
                    {
                        TransactionGroup grp = grpItem.Value;

                        // examine closer if right account and underlying
                        if ((item.Key == grp.Account) && (position.Symbol == grp.Symbol))
                        {
                            // iterate thru everthing in the group
                            int j = 0;
                            while ((j < grp.Holdings.Count) && (position.Quantity != 0))
                            {
                                Position dbpos = grp.Holdings[grp.Holdings.Keys.ElementAt(j)];

                                // look for matching security
                                if ((position.Type == dbpos.Type) && (position.Strike == dbpos.Strike) && (position.ExpDate == dbpos.ExpDate))
                                {
                                    position.Quantity -= dbpos.Quantity;
                                    grp.Holdings.Remove(grp.Holdings.Keys.ElementAt(j));
                                }
                                else
                                {
                                    j++;
                                }
                            }
                        }
                    }

                    if (position.Quantity == 0)
                    {
                        accountPositions.Remove(accountPositions.ElementAt(i).Key);
                    }
                    else
                    {
                        i++;
                    }
                }
            }


            // catch anything left over in database
            foreach (KeyValuePair <int, TransactionGroup> grpItem in this)
            {
                TransactionGroup grp = grpItem.Value;

                if (grp.Holdings.Count > 0)
                {
                    // something left
                    if (returnValue.Length == 0)
                    {
                        returnValue = "Unmatched positons in the database:\n";
                    }
                    returnValue += grp.Holdings.ToString();
                }
            }
            // add anything left from the TW query
            foreach (KeyValuePair <string, TWPositions> positionsPair in overallPositions)
            {
                bool firstPass = true;

                // nothing to do if account is empty
                if (positionsPair.Value != null)
                {
                    foreach (KeyValuePair <string, TWPosition> p in positionsPair.Value)
                    {
                        TWPosition pos = p.Value;

                        if (firstPass)
                        {
                            firstPass = false;
                            if (returnValue.Length > 0)
                            {
                                returnValue += "\n";
                            }
                            returnValue += "Unmatched from TastyWorks account:\n";
                        }
                        returnValue += (pos.Type == "Stock") ? pos.Symbol : pos.Symbol + pos.ExpDate.ToString("yyMMdd") + pos.Strike.ToString("0000.0") + pos.Type + " : " + pos.Quantity.ToString() + "\n";
                    }
                }
            }


            return(returnValue);
        }
Example #3
0
        public static void Load(Accounts accounts)
        {
            try
            {
                // establish db connection
                App.OpenConnection();

                if (TastyWorks.InitiateSession(Config.GetEncryptedProp("Username"), Config.GetEncryptedProp("Password")))
                {
                    // cache the current positions for details required to establish default risk and capreq
                    twpositions = new Dictionary <string, TWPositions>();
                    twMarginReq = new Dictionary <string, TWMargins>();
                    foreach (Account a in accounts)
                    {
                        if (a.Active)
                        {
                            // retrieve Tastyworks positions for given account
                            TWPositions pos = TastyWorks.Positions(a.ID);
                            twpositions.Add(a.ID, pos);

                            TWMargins mar = TastyWorks.MarginData(a.ID);
                            twMarginReq.Add(a.ID, mar);
                        }
                    }

                    // proceed with transactions from all accounts
                    foreach (Account a in accounts)
                    {
                        if (a.Active)
                        {
                            Debug.WriteLine(a.ID);

                            // retrieve Tastyworks transactions for the past month
                            TWTransactions transactions = TastyWorks.Transactions(a.ID, DateTime.Today.AddDays(-30), null);

                            SaveTransactions(transactions);  // transfer transaction array to database

                            // save latest transaction for next upload
                            SQLiteCommand cmd = new SQLiteCommand("SELECT max(time) FROM transactions WHERE Account = @ac", App.ConnStr);
                            cmd.Parameters.AddWithValue("ac", a.ID);
                            SQLiteDataReader rdr      = cmd.ExecuteReader();
                            string           propName = "LastDate-" + a.ID;
                            if (rdr.Read())
                            {
                                Config.SetProp(propName, rdr[0].ToString());
                            }
                        }
                    }

                    UpdateNewTransactions();  // matches unassociated asignments and exercises
                }
                else
                {
                    MessageBox.Show("Login to TastyWorks failed", "Error");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR DataLoader: " + ex.Message);
                MessageBox.Show(ex.Message, "Sync Error");
            }
        }