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(); }
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(); } }
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(); }
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(); }
public void DeletePlayer(Player player) { using (var db = new TraderContext()) { db.Players.Remove(player); db.SaveChanges(); } }
public void Jump(Player player) { using (var db = new TraderContext()) { db.Players.Update(player); db.SaveChanges(); } }
/// <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(); } }
/// <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(); }
public void SaveChanges() { try { db.SaveChanges(); } catch (Exception e) { throw new Exception("coulnt save changes to db: " + e.Message); } }
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(); }
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(); } } }
/// <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); } }
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); }
protected void btnResetDefault_Click(object sender, EventArgs e) { try { string module = "ThreeDuckStrategy"; // Remove the old settings TraderContext db = new TraderContext(); var query = db.SystemSettings.Where(x => x.Module.Equals(module)).Select(x => x); foreach (SystemSetting setting in query) { db.SystemSettings.Remove(setting); } var q_username = db.SystemSettings.Where(x => x.Name.Equals("USERNAME")).Select(x => x); if (q_username.Count() > 0) { SystemSetting s = q_username.FirstOrDefault(); db.SystemSettings.Remove(s); } // Restore the default settings SystemSetting _duck1 = new SystemSetting(module, "FIRST_DUCK_SECONDS", "300"); SystemSetting _duck2 = new SystemSetting(module, "SECOND_DUCK_SECONDS", "3600"); SystemSetting _duck3 = new SystemSetting(module, "THIRD_DUCK_SECONDS", "14400"); SystemSetting _movingavg = new SystemSetting(module, "MOVING_AVERAGE_WINDOW", "60"); db.SystemSettings.Add(_duck1); db.SystemSettings.Add(_duck2); db.SystemSettings.Add(_duck3); db.SystemSettings.Add(_movingavg); db.SaveChanges(); // Display success message setStatus("Settings saved successfully.", true); } catch { // Display fail message setStatus("Settings could not be saved. Please try again.", false); } }
/// <summary> /// Saves the changes made to the settings. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSave_Click(object sender, EventArgs e) { try { string module = "ThreeDuckStrategy"; // Remove the old settings TraderContext db = new TraderContext(); var query = db.SystemSettings.Where(x => x.Module.Equals(module)).Select(x => x); foreach (SystemSetting setting in query) { db.SystemSettings.Remove(setting); } var q_username = db.SystemSettings.Where(x => x.Name.Equals("USERNAME")).Select(x => x); if (q_username.Count() > 0) { SystemSetting s = q_username.FirstOrDefault(); db.SystemSettings.Remove(s); } // Add the new settings SystemSetting _duck1 = new SystemSetting(module, "FIRST_DUCK_SECONDS", InputFirstDuck.Value); SystemSetting _duck2 = new SystemSetting(module, "SECOND_DUCK_SECONDS", InputSecondDuck.Value); SystemSetting _duck3 = new SystemSetting(module, "THIRD_DUCK_SECONDS", InputThirdDuck.Value); SystemSetting _movingavg = new SystemSetting(module, "MOVING_AVERAGE_WINDOW", InputAvgWindow.Value); SystemSetting _username = new SystemSetting("User", "USERNAME", InputName.Value); db.SystemSettings.Add(_duck1); db.SystemSettings.Add(_duck2); db.SystemSettings.Add(_duck3); db.SystemSettings.Add(_movingavg); db.SystemSettings.Add(_username); db.SaveChanges(); setStatus("Settings saved successfully.", true); } catch { setStatus("Settings could not be saved. Please try again.", false); } }
bool IWatchListManager.AddWatchList(string listName) { TraderContext db = new TraderContext(); string l = listName; if (listName.Length == 0) { l = "Default"; } var query = db.WatchLists.Where(x => x.ListName.Equals(l)); if (query.Count() == 0) { WatchList w = new WatchList(l); db.WatchLists.Add(w); db.SaveChanges(); return(true); } return(false); }
public void Add(Trader trader) { traderContext.Traders.Add(trader); traderContext.SaveChanges(); }
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(); }