コード例 #1
0
        string IWatchListManager.GetLongName(string symbolName)
        {
            TraderContext db       = new TraderContext();
            string        longname = db.Symbols.Where(x => x.name.Equals(symbolName)).Select(x => x.CompanyName).FirstOrDefault();

            return(longname);
        }
コード例 #2
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();
        }
コード例 #3
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();
        }
コード例 #4
0
        /// <summary>
        /// Gets the open positions and transactions.
        /// </summary>
        private void generatePositions()
        {
            openpositions.Clear();
            allpositions.Clear();
            transactions.Clear();
            openpositions      = portfolio.GetOpenPositions().ToList();
            AvailableCash.Text = String.Format("{0:C}", portfolio.getAvailableCash());

            TraderContext db    = new TraderContext();
            var           query = db.Positions.Select(x => x.SymbolName);

            foreach (string s in query)
            {
                PositionMessage msg = portfolio.GetPosition(s);
                allpositions.Add(msg);
            }

            // get the transactions
            var transquery = db.Trades.Select(x => x);

            foreach (Trade t in transquery)
            {
                transactions.Add(t);
            }
        }
コード例 #5
0
        public double getAvailableCash()
        {
            TraderContext db = DbContext;
            Portfolio     pf = db.Portfolios.FirstOrDefault();

            return(pf.Cash);
        }
コード例 #6
0
        /// <summary>
        /// Button event that removes an item from a Watchlist.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRemove_Click(object sender, EventArgs e)
        {
            bool   success  = false;
            string symbol   = ((Button)sender).Attributes["Symbol"];
            string listName = ((Button)sender).Attributes["ListName"];

            if (symbol.Length > 0 && listName.Length > 0)
            {
                IWatchList wl = new WatchList();
                success = wl.RemoveFromList(new Symbol(symbol), listName);

                if (success)
                {
                    setStatus(String.Format("{0} removed from list \"{1}.\"", symbol, listName), true);
                }

                //check if all instances of that symbol are removed before strategy stops watching it
                TraderContext db = new TraderContext();
                if (db.WatchListItems.Where(x => x.SymbolName.Equals(symbol)).Count() == 0 && db.Positions.Where(x => x.SymbolName.Equals(symbol) && x.status == AlgoTrader.Interfaces.positionStatus.Open).Count() == 0)
                {
                    strategy.stopWatching(symbol);
                }
            }
            updateList(true);
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: Kamil4921/Trader-bit
        static void Main()
        {
            using var context = new TraderContext();
            var indexes = new List <string> {
            };

            string data_directory = @"D:\studia\NETiJava\Fintech\DATA\BitBay";
            var    paths          = Directory.EnumerateFiles(data_directory, "BTCPLN*.json");

            foreach (string path in paths.Take(3))
            {
                Console.WriteLine(path);
                string jsonString = File.ReadAllText(path);
                var    trades     = JsonConvert.DeserializeObject <Trade[]>(jsonString);
                foreach (var trade in trades)
                {
                    if (!context.Trades.Any(t => t.Tid == trade.Tid) &&
                        !indexes.Contains(trade.Tid))
                    {
                        indexes.Add(trade.Tid);
                        context.Trades.Add(trade);
                    }
                }
                context.SaveChanges();
                indexes.Clear();
            }
        }
コード例 #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString.AllKeys.Contains("s"))
            {
                SymbolLabel.Text = Request.QueryString["s"];
            }

            if (Request.QueryString.AllKeys.Contains("t"))
            {
                if (Request.QueryString["t"].Equals("Buy"))
                {
                    BuySellPicker.SelectedIndex = 0;
                }
                if (Request.QueryString["t"].Equals("Sell"))
                {
                    BuySellPicker.SelectedIndex = 1;
                }
            }

            if (Request.QueryString.AllKeys.Contains("s"))
            {
                string        symbol = Request.QueryString["s"];
                TraderContext db     = new TraderContext();
                var           query  = db.Quotes.Where(x => x.SymbolName.Equals(symbol)).OrderByDescending(x => x.timestamp).Select(x => x.price).FirstOrDefault();
                PriceLabel.Text = String.Format("{0:C}", query.ToString());
            }
            else
            {
                PriceLabel.Text = "$1.25";
            }
        }
コード例 #9
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();
        }
コード例 #10
0
        /// <summary>
        /// Creates a table for all of the Trades associated with a specific Position.
        /// </summary>
        /// <param name="pm">PositionMessage</param>
        /// <returns>Table</returns>
        private Table createTradeTable(PositionMessage pm)
        {
            string[] theaders = { "", "Date", "Shares", "Price / Gain / Gain %", "Fees", "Type", "" };
            Table    tbl      = new Table();

            TableHeaderRow header = new TableHeaderRow();

            for (int i = 0; i < tcolumns; i++)
            {
                TableHeaderCell cell = new TableHeaderCell();
                cell.Text  = theaders[i];
                cell.Width = new Unit(widths[i]);
                header.Cells.Add(cell);
            }
            tbl.Rows.Add(header);

            TraderContext db          = new TraderContext();
            double        latestQuote = db.Quotes.Where(x => x.SymbolName.Equals(pm.SymbolName)).OrderByDescending(x => x.timestamp).Select(x => x.price).FirstOrDefault();

            foreach (TradeMessage t in pm.Trades.OrderByDescending(x => x.Timestamp).Where((x) => x.Quantity > 0 && x.Type == Portfolio.Client.tradeTypes.Buy))
            {
                double gain        = 0;
                double gainPercent = 0;
                string classname   = string.Empty;

                TableRow trow = new TableRow();
                for (int i = 0; i < tcolumns; i++)
                {
                    TableCell cell = new TableCell();
                    trow.Cells.Add(cell);
                }

                gain        = latestQuote - t.Price;
                gainPercent = gain / t.Price;
                if (gain > 0)
                {
                    classname = "green";
                }
                if (gain < 0)
                {
                    classname = "red";
                }

                trow.Cells[1].Text     = String.Format("{0:d} at {0:T}", t.Timestamp);                                                   // symbol name
                trow.Cells[1].Text    += new HtmlString(String.Format(" <span class='subtext'>({0})</span>", getTimeSpan(t.Timestamp))); // date
                trow.Cells[2].Text     = String.Format("{0:N0}", t.Quantity);                                                            // quantity
                trow.Cells[3].Text     = new HtmlString(String.Format("{0:C} / <span class='{3}'>{1:C}</span> / <span class='{3}'>{2:P2}</span>", t.Price, gain, gainPercent, classname)).ToString();
                trow.Cells[4].Text     = String.Format("{0:C}", t.PaidCommission);                                                       // broker fee
                trow.Cells[5].Text     = t.Type.ToString();
                trow.Cells[5].CssClass = getCssClass(t.Type.ToString());

                tbl.Rows.Add(trow);
            }

            // css stuff
            tbl.CssClass = "sub";

            return(tbl);
        }
コード例 #11
0
 public void DeletePlayer(Player player)
 {
     using (var db = new TraderContext())
     {
         db.Players.Remove(player);
         db.SaveChanges();
     }
 }
コード例 #12
0
 public void Jump(Player player)
 {
     using (var db = new TraderContext())
     {
         db.Players.Update(player);
         db.SaveChanges();
     }
 }
コード例 #13
0
        /// <summary>
        /// Here we create a new database, you need 1.2GB RAM, and TradeDangerous.prices System.csv from http://www.davek.com.au/td/
        /// Put in `Project\Data` folder, the parse is in FParsec
        /// </summary>

        public void NewDatabase()
        {
            var folder = "..\\..\\Data\\";

            using (var db = new TraderContext())
            {
                var SysDict = new Dictionary <string, StarSystem>();
                //var StaDict = new Dictionary<string, Station>();

                foreach (string line in File.ReadLines(folder + "System.csv").Skip(1))
                {
                    var sysout = Parsers.runSystemCSVParser(line, new Model.StarSystem()
                    {
                        Stations = new List <Station>()
                    });
                    var distance = Math.Abs(Math.Pow(sysout.X - 0, 2) + Math.Pow(sysout.Y - 0, 2) + Math.Pow(sysout.Z - 0, 2));
                    if (distance < 10000)
                    {
                        SysDict.Add(sysout.StarName, sysout);
                    }
                }


                var stations = Parsers.runPricesFileParser(folder + "TradeDangerous.prices", new System.Text.UTF8Encoding());

                foreach (var stationR in stations)
                {
                    var uniqueName  = stationR.UniqueName.Split('/');
                    var systemName  = uniqueName[0];
                    var stationName = uniqueName[1];

                    Console.WriteLine(systemName + ": " + stationName);
                    Model.StarSystem star;
                    if (SysDict.TryGetValue(systemName, out star))
                    {
                        var station = new Model.Station()
                        {
                            StationName = stationName, StarSystem = star, Commodities = stationR.commodities
                        };

                        star.Stations.Add(station);
                    }
                }

                foreach (var star in SysDict.Values)
                {
                    foreach (var s in star.Stations.Select(a => a.StationName))
                    {
                        Console.Write(s + ": :");
                    }
                    Console.WriteLine();
                    db.StarSystems.Add(star);
                }

                var count = db.SaveChanges();
            }
        }
コード例 #14
0
        public List <Player> ListPlayers()
        {
            List <Player> players;

            using (var db = new TraderContext())
            {
                players = db.Players.ToList();
            }
            return(players);
        }
コード例 #15
0
        /// <summary>
        /// Button event that adds cash to the user's available cash.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddCash_Click(object sender, EventArgs e)
        {
            double        value = double.Parse(InputAddCash.Value);
            TraderContext db    = new TraderContext();

            db.Portfolios.FirstOrDefault().Cash += value;
            AvailableCash.Text = String.Format("{0:C}", (double.Parse(AvailableCash.Text.TrimStart('$')) + value));
            db.SaveChanges();
            update();
        }
コード例 #16
0
 protected void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (db != null)
         {
             db.Dispose();
             db = null;
         }
     }
 }
コード例 #17
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();
                }
            }
        }
コード例 #18
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();
        }
コード例 #19
0
        public List <AlertMessage> getPendingAlerts()
        {
            List <AlertMessage> pending = new List <AlertMessage>();
            TraderContext       db      = DbContext;

            foreach (IAlert a in db.Alerts.Include("Symbol").Where(x => x.ResponseCode == responseCodes.Pending))
            {
                pending.Add(new AlertMessage(a));
            }
            return(pending);
        }
コード例 #20
0
 public Player GetPlayer(string name)
 {
     using (var db = new TraderContext())
     {
         return(db.Players
                .Where(player => player.PName == name)
                .Include(a => a.Location)
                .Include(a => a.Location.StarSystem)
                .Include(a => a.Cargo)
                .Single());
     }
 }
コード例 #21
0
 /// <summary>
 /// Here we get all locations 12 Ly's of the current player location, and sort by distance.
 /// Include is needed because of lack of Lazy loading
 /// </summary>
 /// <param name="star"></param>
 /// <returns></returns>
 public List <Tuple <StarSystem, double> > GetJumps(StarSystem star)
 {
     using (var db = new TraderContext())
     {
         return(db.StarSystems
                .Include(s => s.Stations)
                .Select(s => new Tuple <StarSystem, double>(s, Math.Sqrt(Math.Abs(Math.Pow(s.X - star.X, 2.0) + Math.Pow(s.Y - star.Y, 2.0) + Math.Pow(s.Z - star.Z, 2.0)))))
                .Where(t => t.Item2 < 12.0)
                .OrderBy(t => t.Item2)
                .ToList());
     }
 }
コード例 #22
0
        public List <PositionMessage> GetOpenPositions()
        {
            TraderContext          db     = DbContext;
            Portfolio              pf     = db.Portfolios.FirstOrDefault();
            var                    q      = pf.Positions.Where(p => p.status == positionStatus.Open).Select(p => p);
            List <PositionMessage> result = new List <PositionMessage>();

            foreach (IPosition p in q)
            {
                result.Add(new PositionMessage(p));
            }
            return(result);
        }
コード例 #23
0
        List <Quote> IWatchListManager.GetQuotes(string symbolName)
        {
            TraderContext db     = new TraderContext();
            var           query  = db.Quotes.Where(x => x.SymbolName.Equals(symbolName));
            List <Quote>  result = new List <Quote>();

            foreach (Quote q in query)
            {
                result.Add(q);
            }

            return(result);
        }
コード例 #24
0
        List <WatchList> IWatchListManager.GetAllWatchLists()
        {
            TraderContext    db     = new TraderContext();
            var              query  = db.WatchLists.OrderBy(x => x.ListName);
            List <WatchList> result = new List <WatchList>();

            foreach (WatchList w in query)
            {
                result.Add(w);
            }

            return(result);
        }
コード例 #25
0
        IWatchList IWatchListManager.GetWatchList(string listName)
        {
            TraderContext db     = new TraderContext();
            var           query  = db.WatchListItems.Where(x => x.ListName.Equals(listName));
            IWatchList    result = new WatchList();

            foreach (WatchListItem q in query)
            {
                result.items.Add(q);
            }

            return(result);
        }
コード例 #26
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();
        }
コード例 #27
0
        /// <summary>
        /// Gets the username to be displayed in the greeting.
        /// </summary>
        protected void getUsername()
        {
            TraderContext db    = new TraderContext();
            var           query = db.SystemSettings.Where(x => x.Name.Equals("USERNAME")).Select(x => x);

            if (query.Count() > 0)
            {
                username = query.First().Value;
            }
            else
            {
                username = "******";
            }
        }
コード例 #28
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();
        }
コード例 #29
0
        /// <summary>
        /// New players are spawned @ SOL/Titan City with 1000 credit.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public Player NewPlayer(string name)
        {
            using (var db = new TraderContext())
            {
                var star    = db.StarSystems.Where(s => s.StarName == "SOL").Include(s => s.Stations).Single();
                var station = star.Stations.ToList().Where(s => s.StationName == "Titan City").Single();
                var player  = new Player()
                {
                    PName = name, Credit = 1000, Location = station
                };
                db.Players.Add(player);
                db.SaveChanges();

                return(player);
            }
        }
コード例 #30
0
        bool IWatchListManager.DeleteWatchList(string listName)
        {
            TraderContext db    = new TraderContext();
            string        l     = listName;
            var           query = db.WatchLists.Where(x => x.ListName.Equals(l)).ToList();

            if (query.Count > 0)
            {
                foreach (WatchList w in query)
                {
                    db.WatchLists.Remove(w);
                }
                db.SaveChanges();
                return(true);
            }
            return(false);
        }