예제 #1
0
        public void buy(string symbolName, int quantity)
        {
            TraderContext db        = DbContext;
            Quote         lastQuote = db.Quotes.Where(x => x.SymbolName == symbolName).OrderByDescending(y => y.timestamp).FirstOrDefault();

            if (lastQuote == null)
            {
                // if we have no prices, the operation cannot complete
                return;
            }
            Portfolio p = db.Portfolios.FirstOrDefault();

            Position pos = db.Positions.Where(x => x.PortfolioId == p.PortfolioId && x.SymbolName == symbolName).FirstOrDefault();
            Trade    t   = db.Trades.Create();

            try
            {
                ProcessBuyTrade(t, symbolName, quantity, lastQuote.price, pos, p);
            }
            catch (InsufficientFunds insuf)
            {
                // user does not have enough free cash to complete the requested transaction
                throw new System.ServiceModel.FaultException <InsufficientFundsFault>(new InsufficientFundsFault(double.Parse(insuf.Data["TransactionAmount"].ToString()), double.Parse(insuf.Data["AvailableFunds"].ToString())));
            }
            catch (AllocationViolation alloc)
            {
                // the requested transaction would violate one of the user's risk-management rules
                throw new System.ServiceModel.FaultException <AllocationViolationFault>(new AllocationViolationFault());
            }

            db.Trades.Add(t);
            db.SaveChanges();
            db.Dispose();
        }
예제 #2
0
        public void processAlertResponse(string alertID, responseCodes alertResponseCode, string alertResponse)
        {
            ILog log = Logger;

            log.DebugFormat("Alert generated: {0} {1}", alertID, alertResponse);
            TraderContext db        = DbContext;
            Guid          alertGuid = Guid.Parse(alertID);
            Alert         alert     = db.Alerts.Where(x => x.AlertId == alertGuid).FirstOrDefault();

            if (alert == null)
            {
                log.WarnFormat("Alert not found: {0}", alertID);
                return;
            }
            alert.ResponseCode = alertResponseCode;
            alert.Response     = alertResponse;
            db.SaveChanges();

            if (alert.ResponseCode == responseCodes.Accept)
            {
                PortfolioManager pm = new PortfolioManager();
                pm.LoadSettings();
                if (alert.Type == tradeTypes.Buy)
                {
                    pm.buy(alert.Symbol.name, alert.Quantity);
                }
                else
                {
                    pm.sell(alert.Symbol.name, alert.Quantity);
                }
            }
            db.Dispose();
        }
예제 #3
0
        public void generateAlert(string symbolName, tradeTypes type, int quantity, double price)
        {
            ILog log = Logger;

            log.DebugFormat("Alert generated: {0} {1} {2} {3}", symbolName, type.ToString(), quantity.ToString(), price.ToString());

            TraderContext db = DbContext;
            Symbol        s  = db.Symbols.Where(x => x.name == symbolName).FirstOrDefault();
            Alert         a  = new Alert();

            a.AlertId      = Guid.NewGuid();
            a.Timestamp    = DateTime.Now;
            a.Symbol       = s;
            a.Type         = type;
            a.Quantity     = quantity;
            a.Price        = price;
            a.ResponseCode = responseCodes.Pending;
            db.Alerts.Add(a);
            db.SaveChanges();

            IEmail email      = new EmailSender();
            string to_address = db.SystemSettings.Where(x => x.Module == "UserAgent" && x.Name == "ALERTS_EMAIL_ADDRESS_TO").FirstOrDefault().Value;

            if (to_address == null)
            {
                throw new Exception("Unable to load user email address for alerts.");
            }
            email.sendEmail(to_address, symbolName, price.ToString(), type, a.Quantity);
            db.Dispose();
        }
예제 #4
0
        public void sell(string symbolName, int quantity)
        {
            if (quantity < 1)
            {
                throw new System.ServiceModel.FaultException <ArgumentException>(new ArgumentException("Quantity must be greater than zero.", "quantity"));
            }

            TraderContext db = DbContext;
            Symbol        s  = db.Symbols.Where(x => x.name == symbolName).FirstOrDefault();

            if (s == null)
            {
                throw new System.ServiceModel.FaultException <ArgumentException>(new ArgumentException("Symbol not found.", "symbol"));
            }
            Quote lastPrice = db.FindLastQuoteFor(s);

            if (lastPrice == null)
            {
                // if we have no prices, the operation cannot complete
                return;
            }
            Portfolio portfolio = db.Portfolios.FirstOrDefault();
            Position  pos       = portfolio.Positions.Where(x => x.Symbol == s && x.status == positionStatus.Open).FirstOrDefault();

            if (pos == null || pos.quantity < quantity)
            {
                // the user does not own enough shares to complete the requested sell transaction
                throw new System.ServiceModel.FaultException <InsufficientQuantityFault>(new InsufficientQuantityFault(quantity, pos.quantity));
            }
            // figure out which shares to sell to get the best price
            List <Trade> byProfit       = pos.Trades.Where(t => t.type == tradeTypes.Buy).OrderByDescending(o => (lastPrice.price - o.price)).ToList <Trade>();
            List <Trade> toSell         = new List <Trade>();
            string       transaction_id = Guid.NewGuid().ToString();

            foreach (Trade t in byProfit)
            {
                int   remaining = quantity - toSell.Sum(x => x.quantity);
                Trade next      = t.sell(Math.Min(t.quantity, remaining));
                next.price         = lastPrice.price;
                next.TransactionId = transaction_id;
                toSell.Add(next);
                if (toSell.Sum(x => x.quantity) == quantity)
                {
                    break;
                }
            }
            pos.Trades.AddRange(toSell);
            // update subtotals in the postition to reflect the new transaction
            pos.Recalculate();
            // add the proceeds of the sale to our available cash
            portfolio.Cash += toSell.Sum(x => (x.price * x.quantity) - x.PaidCommission);
            db.SaveChanges();
            db.Dispose();
        }
예제 #5
0
        private async void LoadTrades_Click(object sender, RoutedEventArgs e)
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile   sampleFile    = await storageFolder.CreateFileAsync("sample.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);

            var trademodels = await TradeProcessor.LoadTrades();

            using (StreamWriter streamW = new StreamWriter(sampleFile.Path, true))
            {
                streamW.WriteLine($"{DateTime.Now} Wczytano 300 tradow");
            }

            Price.Text    = $"Cena: {trademodels[0].R}";
            Amoundof.Text = $"Ilosc: {trademodels[0].A}";
            Time.Text     = $"Czas: {trademodels[0].T}";
            Type.Text     = $"Typ: {trademodels[0].Ty}";
            Id.Text       = $"Id: {trademodels[0].Id}";
            using (StreamWriter streamW = new StreamWriter(sampleFile.Path, true))
            {
                streamW.WriteLine($"{DateTime.Now} Wyświetlono ostatni trade");
            }
            var trades = new List <Trade>();

            foreach (var trade in trademodels)
            {
                trades.Add(trade.ToTrade());
            }

            TraderContext context = null;

            try
            {
                context = new TraderContext();
                foreach (var trade in trades)
                {
                    if (!context.Trades.Any(t => t.Tid == trade.Tid))
                    {
                        context.Trades.Add(trade);
                        using (StreamWriter streamW = new StreamWriter(sampleFile.Path, true))
                        {
                            streamW.WriteLine($"{DateTime.Now} Dodano do bazy trade {trade}");
                        }
                    }
                }
                context.SaveChanges();
            }
            finally
            {
                if (context != null)
                {
                    context.Dispose();
                }
            }
        }
예제 #6
0
 protected void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (db != null)
         {
             db.Dispose();
             db = null;
         }
     }
 }
예제 #7
0
        public void LoadSettings()
        {
            Dictionary <string, string> config = new Dictionary <string, string>();
            TraderContext db       = DbContext;
            var           settings = from s in db.SystemSettings where s.Module == "Portfolio" select s;

            foreach (var i in settings)
            {
                config.Add(i.Name, i.Value);
            }
            LoadSettings(config);
            db.Dispose();
        }
예제 #8
0
        public void OnTick(object source, ElapsedEventArgs e)
        {
            TraderContext db     = new TraderContext();
            List <Quote>  quotes = db.Quotes.Include("Symbol").Where(x => x.timestamp > _lastPeek).OrderBy(y => y.timestamp).ToList <Quote>();

            _lastPeek = quotes.Max(x => x.timestamp);
            List <QuoteMessage> msg = new List <QuoteMessage>();

            foreach (Quote q in quotes)
            {
                msg.Add(new QuoteMessage(q));
            }
            _owner.NewQuotes(msg);
            db.Dispose();
        }
예제 #9
0
        static void Main(string[] args)
        {
            Console.WriteLine("Testing the entity framework...");
            TraderContext db = new TraderContext();


            Console.WriteLine("Clearing the database...");
            var d_quotes = from q in db.Quotes select q;

            foreach (var i in d_quotes)
            {
                db.Quotes.Remove(i);
            }
            var d_symbol = from s in db.Symbols select s;

            foreach (var i in d_symbol)
            {
                db.Symbols.Remove(i);
            }
            var d_position = from p in db.Positions select p;

            foreach (var i in d_position)
            {
                db.Positions.Remove(i);
            }
            var d_trade = from t in db.Trades select t;

            foreach (var i in d_trade)
            {
                db.Trades.Remove(i);
            }


            Console.WriteLine("Adding records to database...");
            db.Symbols.Add(new Symbol("GOOG"));
            db.Symbols.Add(new Symbol("LNC"));

            db.SaveChanges();

            Quote q1 = new Quote();

            q1.timestamp = DateTime.Now;
            q1.price     = 50.47;
            q1.Symbol    = db.Symbols.First();
            db.Quotes.Add(q1);

            Position p1 = new Position();

            p1.SymbolName = "GOOG";
            p1.price      = 5000;
            p1.quantity   = 150;
            p1.status     = positionStatus.Open;
            db.Positions.Add(p1);

            db.SaveChanges();

            Trade t1 = new Trade();

            t1.timestamp  = DateTime.Now;
            t1.quantity   = 40;
            t1.price      = 10.10;
            t1.type       = tradeTypes.Buy;
            t1.SymbolName = "GOOG";
            db.Trades.Add(t1);


            var      q_addtopos = from p in db.Positions.Include("Trades") where p.SymbolName == "GOOG" select p;
            Position goog_pos   = q_addtopos.FirstOrDefault();

            goog_pos.Trades.Add(t1);

            db.SaveChanges();

            WatchList w = new WatchList();

            w.ListName = "Default";
            db.WatchLists.Add(w);
            db.SaveChanges();

            WatchListItem wi1 = new WatchListItem();

            wi1.ListName   = "Default";
            wi1.SymbolName = "GOOG";
            db.WatchListItems.Add(wi1);

            WatchListItem wi2 = new WatchListItem();

            wi2.ListName   = "Default";
            wi2.SymbolName = "LNC";
            db.WatchListItems.Add(wi2);

            db.SaveChanges();

            Console.WriteLine("Retrieving records from database...");
            Console.WriteLine("\nSymbols");
            var query = from s in db.Symbols orderby s.name select s;

            foreach (var i in query)
            {
                Console.WriteLine("Symbol: " + i.name);
            }

            Console.WriteLine("\nQuotes");
            var q_search = from q in db.Quotes select q;

            foreach (var i in q_search)
            {
                Console.WriteLine("Record: " + i.QuoteId.ToString());
                Console.WriteLine("Symbol: " + i.Symbol.name);
                Console.WriteLine("Timestamp: " + i.timestamp.ToString());
                Console.WriteLine("Price: " + i.price.ToString());
            }

            Console.WriteLine("\nPositions");
            var p_search = from p in db.Positions select p;

            foreach (var i in p_search)
            {
                Console.WriteLine("Record: " + i.PositionId.ToString());
                Console.WriteLine("Symbol: " + i.Symbol.name);
                Console.WriteLine("Trade count: " + i.Trades.Count.ToString());
                foreach (var t in i.Trades)
                {
                    Console.WriteLine("\tTrade Id: " + t.TradeId.ToString());
                    Console.WriteLine("\tType: " + t.type.ToString());
                    Console.WriteLine("\tPrice: " + t.price.ToString());
                    Console.WriteLine("\tQuantity: " + t.quantity.ToString());
                    Console.WriteLine("\tTimestamp: " + t.timestamp.ToString());
                }
            }


            Console.WriteLine("\nWatchlist");
            var       wlist   = from l in db.WatchLists.Include("Items") select l;
            WatchList deflist = wlist.FirstOrDefault();

            foreach (var i in deflist.Items)
            {
                Console.WriteLine("\t" + i.Symbol.name);
            }
            Console.WriteLine("\nTesting complete.");
            Console.ReadLine();
            db.Dispose();
        }