Beispiel #1
0
        //This method is called from TimingManager and manages the excutions of Algorythemic Traders
        public static async void RunTrader()
        {
            //Get the trader ids from the database
            MySqlDataReader reader          = threadDataBaseHandler.GetData("SELECT ID FROM AlgoTrader");
            List <int>      TradersInDB     = new List <int>();
            List <int>      TradersToDelete = new List <int>();

            //Checks which traders we have stored locally
            //if the id exists in the DB but not in this program them grab from the DB and create local version
            //else if if it exists in this local version but not in the DB then delete the local instance
            while (reader.Read())
            {
                TradersInDB.Add((int)reader["ID"]);
            }
            for (int i = 0; i < Traders.Count; i++)
            {
                if (!TradersInDB.Contains(Traders[i].ID))
                {
                    TradersToDelete.Add(i);
                }
            }
            for (int i = 0; i < TradersInDB.Count; i++)
            {
                if (!Traders.Exists((t) => t.ID == TradersInDB[i]))
                {
                    reader = threadDataBaseHandler.GetData("SELECT * FROM AlgoTrader WHERE ID = " + TradersInDB[i]);
                    while (reader.Read())
                    {
                        Traders.Add(new AlgorithmsTrader1(TradersInDB[i], (string)reader["Target"], (int)reader["UserId"], (double)reader["ShortRequirement"], (double)reader["LongRequirement"], (int)reader["MinAmount"], (int)reader["MaxAmount"], (double)reader["Aggresion"]));
                    }
                }
            }
            while (TradersToDelete.Count > 0)
            {
                threadDataBaseHandler.SetData("DELETE FROM Users WHERE ID = " + Traders[TradersToDelete[0]].UserID);
                threadDataBaseHandler.SetData("UPDATE Inventories SET UserID = 1 WHERE UserID = " + Traders[TradersToDelete[0]].UserID);
                threadDataBaseHandler.SetData("DELETE FROM AlgoTrader WHERE ID = " + Traders[TradersToDelete[0]].ID);
                Traders.Remove(Traders[TradersToDelete[0]]);
                TradersToDelete.RemoveAt(0);
            }
            //Now we have all the correct traders stored locally we can run a turn on them
            foreach (AlgoTrader t in Traders)
            {
                try {
                    t.RunTurn();
                } catch {
                    Console.WriteLine("Error with DB Connectiom, Will retry next turn");
                }
            }
            //Basic traders are the ones create by the user which just excute traders if certain criteria is met
            BasicTraders();
            TimingManager.TraderTimer.Start();
            Console.WriteLine("Traders Completed");
        }
        public static void CreateTrade(ref BidsAndOffers Bid, ref BidsAndOffers Offer, int Quantity, ThreadDataBaseHandler threadDataBaseHandler)
        {
            //Get the total quantity that the user can sell
            int StockAvailable = threadDataBaseHandler.GetCount(string.Format("SELECT COUNT(Quantity) FROM Inventories WHERE StockName = '{0}' AND UserID = {1}", Offer.StockName, Offer.User));

            if (Quantity > StockAvailable)
            {
                //If the quantity if the sale is greater than that the user can offer limit to the max amount the user could sell
                Quantity = StockAvailable;
            }
            //If the Quantity is not greater than one we can skip trade creation
            if (Quantity > 0)
            {
                //Checking to see if the bid user has an entry in the iventory table
                if (threadDataBaseHandler.GetCount("SELECT COUNT(UserID) FROM Inventories WHERE UserID = " + Bid.User + " AND StockName = '" + Bid.StockName + "'") == 0)
                {
                    //If not then an entry for the bid user for this stock is inserted into inventories
                    threadDataBaseHandler.SetData(string.Format("INSERT INTO Inventories(UserID, StockName, Quantity, LastTradedPrice) VALUES({0}, '{1}', {2}, {3})", Bid.User, Bid.StockName, 0, 0));
                }
                //Update the database reflect the new trade
                threadDataBaseHandler.SetData(string.Format("INSERT INTO Trades(StockName, BuyerID, SellerID, Price, Quantity) VALUES('{0}', {1}, {2}, {3}, {4})", Bid.StockName, Bid.User, Offer.User, Offer.Price, Quantity));
                threadDataBaseHandler.SetData(string.Format("UPDATE Inventories set LastTradedPrice = {0}, Quantity = Quantity - {1} WHERE StockName = '{2}' AND UserID = {3}", Offer.Price, Quantity, Offer.StockName, Offer.User));
                threadDataBaseHandler.SetData(string.Format("UPDATE Inventories set LastTradedPrice = {0}, Quantity = Quantity + {1} WHERE StockName = '{2}' AND UserID = {3}", Offer.Price, Quantity, Offer.StockName, Bid.User));
                threadDataBaseHandler.SetData(string.Format("UPDATE Stock SET VolumeTraded = VolumeTraded + {0} WHERE StockName = '{1}'", Quantity, Offer.StockName));
                threadDataBaseHandler.SetData(string.Format("UPDATE Users SET Balance = Balance + {0} WHERE ID = {1}", Offer.Price * Quantity, Offer.User));
                threadDataBaseHandler.SetData(string.Format("UPDATE Users SET Balance = Balance - {0} WHERE ID = {1}", Offer.Price * Quantity, Bid.User));
            }
            else if (Quantity < 0)
            {
                throw new Exception("Error with trade, quantity is less than 0");
            }
            //Checking if trade went ahead
            if (Quantity != 0)
            {
                //If it did then we are updating are local version of the bids and offfers in the server pool
                //This allows the matchmaking algorythim to continue without having to grab the new trade data
                //from the database
                Bid.Quantity   -= Quantity;
                Offer.Quantity -= Quantity;
                //Update database to reflect new trade
                threadDataBaseHandler.SetData(string.Format("Update Pool set Quantity = {0} WHERE Type = {1} AND TimePlaced = '{2}' AND Price = {3} AND User = {4} AND StockName = '{5}'", Bid.Quantity, Bid.Type, Bid.TimePlaced.ToString("yyyy-MM-dd HH:mm:ss"), Bid.Price, Bid.User, Bid.StockName));
                threadDataBaseHandler.SetData(string.Format("Update Pool set Quantity = {0} WHERE Type = {1} AND TimePlaced = '{2}' AND Price = {3} AND User = {4} AND StockName = '{5}'", Offer.Quantity, Offer.Type, Offer.TimePlaced.ToString("yyyy-MM-dd HH:mm:ss"), Offer.Price, Offer.User, Offer.StockName));
            }
            else
            {
                //If they couldn't supply any stock to sell then set the offer quantity to be zero
                Offer.Quantity = 0;
            }
            //Close the connection to the DB so that DB connection thread can be open for the next thread
            threadDataBaseHandler.CloseCon();
        }
        public static void RemoveFromPool(BidsAndOffers Trade, ThreadDataBaseHandler threadDataBaseHandler)
        {
            //When a bid or offer is ready to be removed it passed to this method which removes it from DB
            string command = string.Format("DELETE FROM Pool WHERE Type = {0} AND TimePlaced = '{1}' AND Price = {2} AND User = {3} AND StockName = '{4}'", Trade.Type, Trade.TimePlaced.ToString("yyyy-MM-dd HH:mm:ss"), Trade.Price, Trade.User, Trade.StockName);

            threadDataBaseHandler.SetData(command);
            threadDataBaseHandler.CloseCon();
        }
        /// <summary>
        /// Reduces the frequency of data for a stock the older the data is in order to keep the DB at a reasonable size
        /// </summary>
        static void PricingThinner(string StockName, ThreadDataBaseHandler threadDataBaseHandler)
        {
            MySqlDataReader reader      = threadDataBaseHandler.GetData(string.Format("SELECT Time From PricingHistory WHERE StockName = '{0}' AND Time < '{1}' ORDER BY Time ASC", StockName, DateTime.Now.AddSeconds(-10).ToString("yyyy-MM-dd HH:mm:ss")));
            List <DateTime> LastHour    = new List <DateTime>();
            List <DateTime> Last12Hours = new List <DateTime>();
            List <DateTime> LastDay     = new List <DateTime>();
            List <DateTime> LastWeek    = new List <DateTime>();
            List <DateTime> LastMonth   = new List <DateTime>();
            List <DateTime> Longer      = new List <DateTime>();

            while (reader.Read())
            {
                DateTime time = (DateTime)reader["Time"];
                if (time > DateTime.Now.AddHours(-1))
                {
                    LastHour.Add(time);
                }
                else if (time > DateTime.Now.AddHours(-12))
                {
                    Last12Hours.Add(time);
                }
                else if (time > DateTime.Now.AddDays(-1))
                {
                    LastDay.Add(time);
                }
                else if (time > DateTime.Now.AddDays(-7))
                {
                    LastWeek.Add(time);
                }
                else if (time > DateTime.Now.AddMonths(-1))
                {
                    LastMonth.Add(time);
                }
                else
                {
                    Longer.Add(time);
                }
            }
            //For each time period there is a set gap which entries need to be apart by.
            //If the gap is not the right size then the entry is removed from the DB
            List <DateTime> ToBeDeleted = new List <DateTime>();
            DateTime        last        = DateTime.MinValue;

            for (int i = 0; i < LastHour.Count; i++)
            {
                if (i == 0)
                {
                    last = LastHour[i];
                    continue;
                }
                if ((LastHour[i] - last).Seconds < 10)
                {
                    ToBeDeleted.Add(LastHour[i]);
                }
                else
                {
                    last = LastHour[i];
                }
            }
            last = DateTime.MinValue;
            for (int i = 0; i < Last12Hours.Count; i++)
            {
                if (i == 0)
                {
                    last = Last12Hours[i];
                    continue;
                }
                if ((Last12Hours[i] - last).Minutes < 2)
                {
                    ToBeDeleted.Add(Last12Hours[i]);
                }
                else
                {
                    last = Last12Hours[i];
                }
            }
            last = DateTime.MinValue;
            for (int i = 0; i < LastDay.Count; i++)
            {
                if (i == 0)
                {
                    last = LastDay[i];
                    continue;
                }
                if ((LastDay[i] - last).Minutes < 10)
                {
                    ToBeDeleted.Add(LastDay[i]);
                }
                else
                {
                    last = LastDay[i];
                }
            }
            last = DateTime.MinValue;
            for (int i = 0; i < LastWeek.Count; i++)
            {
                if (i == 0)
                {
                    last = LastWeek[i];
                    continue;
                }
                if ((LastWeek[i] - last).Hours < 1)
                {
                    ToBeDeleted.Add(LastWeek[i]);
                }
                else
                {
                    last = LastWeek[i];
                }
            }
            last = DateTime.MinValue;
            for (int i = 0; i < LastMonth.Count; i++)
            {
                if (i == 0)
                {
                    last = LastMonth[i];
                    continue;
                }
                if ((LastMonth[i] - last).Hours < 6)
                {
                    ToBeDeleted.Add(LastMonth[i]);
                }
                else
                {
                    last = LastMonth[i];
                }
            }
            last = DateTime.MinValue;
            for (int i = 0; i < Longer.Count; i++)
            {
                if (i == 0)
                {
                    last = Longer[i];
                    continue;
                }
                if ((Longer[i] - last).Days < 7)
                {
                    ToBeDeleted.Add(Longer[i]);
                }
                else
                {
                    last = Longer[i];
                }
            }
            for (int i = 0; i < ToBeDeleted.Count; i++)
            {
                threadDataBaseHandler.SetData("DELETE FROM PricingHistory WHERE StockName = '" + StockName + "' AND Time = '" + ToBeDeleted[i].ToString("yyyy-MM-dd HH:mm:ss") + "'");
            }
        }
 //Place offer into pool
 private void ShortTermShort(int Quanity, double Price)
 {
     threadDataBaseHandler.SetData(string.Format("INSERT INTO Pool (Type, Price, User, StockName, Quantity) VALUES ({0}, {1}, {2}, '{3}', {4})", (int)BidOffer.offer, Price, client, TargetStock, Quanity));
     Console.WriteLine("Places short with " + Quanity);
 }