コード例 #1
0
ファイル: Global.asax.cs プロジェクト: y-a-r/BuySellStats
 protected void Application_Start()
 {
     try
     {
         _logger.Info("App is starting...");
         //
         AreaRegistration.RegisterAllAreas();
         FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
         RouteConfig.RegisterRoutes(RouteTable.Routes);
         BundleConfig.RegisterBundles(BundleTable.Bundles);
         // DB
         Database.SetInitializer(new CreateDatabaseIfNotExists<DataModelContext>());
         var ctx = new DataModelContext();
         try
         {
             _logger.Info("Database inited. Version: {0}", ctx.GetDbVersion());
             _logger.Info("Transactions count: {0}", this.Application["TransactionsCount"] = ctx.GetTransactionsCount());
         } finally
         {
             ctx.Dispose();
         }
         //
         StatsExample.ValidPeriod = Settings.Default.ExampleValidPeriod;
         //
         _logger.Info("App started.");
     } catch(Exception ex)
     {
         _logger.Error(ex);
         throw;
     }
 }
コード例 #2
0
ファイル: AdminController.cs プロジェクト: y-a-r/BuySellStats
        public ActionResult CreateStatsExample(long typeId, [DataSourceRequest] DataSourceRequest request, StatsExampleModel model)
        {
            if(model != null && this.ModelState.IsValid)
            {
                try
                {
                    var guid = Guid.NewGuid().ToString("N");
                    using(var ctx = new DataModelContext())
                    {
                        var newExample = new StatsExample
                        {
                            Timestamp = DateTime.Now,
                            Name = model.Name,
                            IdLink = guid,
                            StatsTypeId = typeId
                        };
                        ctx.StatsExamples.Add(newExample);
                        //
                        ctx.SaveChanges();
                    }
                } catch(Exception ex)
                {
                    LogManager.GetCurrentClassLogger().Error(ex);
                    this.ModelState.AddModelError("save_error", ex.Message);
                }
            }

            return this.Json(new[] {model}.ToDataSourceResult(request, this.ModelState));
        }
コード例 #3
0
ファイル: AdminController.cs プロジェクト: y-a-r/BuySellStats
 public ActionResult CreateStatsType([DataSourceRequest] DataSourceRequest request, StatsTypeModel model)
 {
     if(model != null && this.ModelState.IsValid)
     {
         try
         {
             using(var ctx = new DataModelContext())
             {
                 ctx.StatsTypes.Add(new StatsType
                 {
                     Name = model.Name,
                     TypeId = model.TypeConfig.Id
                 });
                 //
                 ctx.SaveChanges();
             }
         } catch(Exception ex)
         {
             LogManager.GetCurrentClassLogger().Error(ex);
             this.ModelState.AddModelError("save_error", ex.Message);
         }
     }
     this.ViewData["TransactionTypes"] = GetAllTypesConfig();
     //
     return this.Json(new[] {model}.ToDataSourceResult(request, this.ModelState));
 }
コード例 #4
0
ファイル: HomeController.cs プロジェクト: y-a-r/BuySellStats
 public JsonResult Buy(long id, int idx)
 {
     using(var ctx = new DataModelContext())
     {
         using(var client = new OrderServiceClient())
         {
             var order = ctx.Orders.SingleOrDefault(o => o.StatsExampleId == id && o.Index == idx);
             // Open order
             if(order == null)
             {
                 var openResponse = client.OpenOrder(new OpenOrderRequest
                 {
                     ExampleId = id,
                     OrderType = OrderTypes.Buy
                 });
                 if(!string.IsNullOrEmpty(openResponse.Error))
                 {
                     LogManager.GetCurrentClassLogger().Error(openResponse.Error);
                     //
                     return this.Json(new {Response = SetOrderErrors.Other});
                 }
                 //
                 return this.Json(new {Response = openResponse.SetOrderErrors});
             }
             // Close order
             var closeResponse = client.CloseOrder(new CloseOrderRequest {ExampleId = id, Index = idx});
             if(!string.IsNullOrEmpty(closeResponse.Error))
             {
                 LogManager.GetCurrentClassLogger().Error(closeResponse.Error);
                 //
                 return this.Json(new {Response = SetOrderErrors.Other});
             }
             //
             return this.Json(new {Response = closeResponse.SetOrderErrors});
         }
     }
 }
コード例 #5
0
ファイル: HomeController.cs プロジェクト: y-a-r/BuySellStats
 public JsonResult GetPrice(string id, long exampleId, int openOrdersFlags, int closeOrdersFlags)
 {
     using(var ctx = new DataModelContext())
     {
         using(var client = new OrderServiceClient())
         {
             var orders = ctx.Orders.Where(o => o.StatsExampleId == exampleId).OrderBy(o => o.Index).ToList();
             var idxsForReload = new List<int>();
             // Check orders state
             foreach(var order in orders)
             {
                 if(((openOrdersFlags >> order.Index) & 1) == 0)
                 {
                     idxsForReload.Add(order.Index);
                     continue;
                 }
                 if(order.ClosePrice.HasValue && ((closeOrdersFlags >> order.Index) & 1) == 0)
                     idxsForReload.Add(order.Index);
             }
             var lastOrder = orders.LastOrDefault();
             if(lastOrder != null && lastOrder.ClosePrice.HasValue && idxsForReload.Contains(lastOrder.Index) && lastOrder.Index < ctx.GetTransactionsCount() - 1 && !idxsForReload.Contains(lastOrder.Index + 1))
                 idxsForReload.Add(lastOrder.Index + 1);
             //
             var response = client.GetPrice(new GetPriceDataContractRequest {SymbolId = id});
             if(response.MarketIsClosed)
                 return this.Json(new {MarketIsClosed = true}, JsonRequestBehavior.AllowGet);
             //
             return this.Json(new
             {
                 response.Price,
                 TotalPips = orders.Count == 0 ? 0 : orders.Sum(o => o.Pips),
                 IdxsForReload = idxsForReload
             }, JsonRequestBehavior.AllowGet);
         }
     }
 }
コード例 #6
0
ファイル: ServerStarter.cs プロジェクト: y-a-r/BuySellStats
 public static bool Start()
 {
     try
     {
         // DB init
         _logger.Info("Database initialization started...");
         Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataModelContext, Configuration>());
         var ctx = new DataModelContext();
         try
         {
             _logger.Info("Database inited. Version: {0}", ctx.GetDbVersion());
             _logger.Info("Transactions count: {0}", ctx.GetTransactionsCount());
         } finally
         {
             ctx.Dispose();
         }
         //
         StatsExample.ValidPeriod = Settings.Default.ExampleValidPeriod;
         // Start WCF hosts
         StartHosts();
         // Start schedulers
         StartSchedulers();
         //
         PricesProvider.Start();
         OrderManager.Start();
         //
         return true;
     } catch(Exception ex)
     {
         _logger.Info(string.Format("Error while starting server: {0}", ex));
         //
         Stop();
         //
         return false;
     }
 }
コード例 #7
0
ファイル: OrderManager.cs プロジェクト: y-a-r/BuySellStats
 private static void PricesProvider_PriceChanged(object sender, PriceChangedEventArgs e)
 {
     lock(_openOrders)
     {
         var orders = _openOrders.Where(o => o.SymbolId == e.SymbolId).ToList();
         var closedOrders = new List<OpenOrder>();
         foreach(var openOrder in orders)
         {
             // Check if example is not valid
             if(!openOrder.Order.StatsExample.IsValid)
             {
                 closedOrders.Add(openOrder);
                 //
                 continue;
             }
             //
             if(openOrder.Order.OrderType == OrderTypes.Buy)
             {
                 // Take profit
                 if(openOrder.Order.TakeProfit.HasValue && openOrder.Order.TakeProfit.Value <= e.SellPrice)
                 {
                     // Auto-close order
                     using(var ctx = new DataModelContext())
                     {
                         var order = ctx.Orders.Find(openOrder.Order.Id);
                         // Check if order was closed already
                         if(order.ClosePrice.HasValue)
                         {
                             LogManager.GetCurrentClassLogger().Warn("Take-profit for order [{0}] but order was closed already.", order.Id);
                             continue;
                         }
                         //
                         order.ClosePrice = e.SellPrice;
                         order.Pips = PricesProvider.CalculatePips(e.SymbolId, order.OpenPrice, order.ClosePrice.Value);
                         // logs
                         ctx.OrderLogs.Add(OrderLog.CreateLog(order, OrderLogTypes.TakeProfitInvoke));
                         ctx.OrderLogs.Add(OrderLog.CreateLog(order, OrderLogTypes.Close));
                         //
                         ctx.SaveChanges();
                         closedOrders.Add(openOrder);
                         //
                         LogManager.GetCurrentClassLogger().Debug("Take-profit for order [{0}]", order.Id);
                     }
                     // Stop loss
                 } else if(openOrder.Order.StopLoss.HasValue && openOrder.Order.StopLoss.Value >= e.SellPrice)
                 {
                     // Auto-close order
                     using(var ctx = new DataModelContext())
                     {
                         var order = ctx.Orders.Find(openOrder.Order.Id);
                         // Check if order was closed already
                         if(order.ClosePrice.HasValue)
                         {
                             LogManager.GetCurrentClassLogger().Warn("Stop-loss for order [{0}] but order was closed already.", order.Id);
                             continue;
                         }
                         //
                         order.ClosePrice = e.SellPrice;
                         order.Pips = PricesProvider.CalculatePips(e.SymbolId, order.OpenPrice, order.ClosePrice.Value);
                         // log
                         ctx.OrderLogs.Add(OrderLog.CreateLog(order, OrderLogTypes.StopLossInvoke));
                         ctx.OrderLogs.Add(OrderLog.CreateLog(order, OrderLogTypes.Close));
                         //
                         ctx.SaveChanges();
                         closedOrders.Add(openOrder);
                         //
                         LogManager.GetCurrentClassLogger().Debug("Stop-loss for order [{0}]", order.Id);
                     }
                 }
             } else
             {
                 // Take profit
                 if(openOrder.Order.TakeProfit.HasValue && openOrder.Order.TakeProfit.Value >= e.BuyPrice)
                 {
                     // Auto-close order
                     using(var ctx = new DataModelContext())
                     {
                         var order = ctx.Orders.Find(openOrder.Order.Id);
                         // Check if order was closed already
                         if(order.ClosePrice.HasValue)
                         {
                             LogManager.GetCurrentClassLogger().Warn("Take-profit for order [{0}] but order was closed already.", order.Id);
                             continue;
                         }
                         //
                         order.ClosePrice = e.BuyPrice;
                         order.Pips = PricesProvider.CalculatePips(e.SymbolId, order.ClosePrice.Value, order.OpenPrice);
                         // log
                         ctx.OrderLogs.Add(OrderLog.CreateLog(order, OrderLogTypes.TakeProfitInvoke));
                         ctx.OrderLogs.Add(OrderLog.CreateLog(order, OrderLogTypes.Close));
                         //
                         ctx.SaveChanges();
                         closedOrders.Add(openOrder);
                         //
                         LogManager.GetCurrentClassLogger().Debug("Take-profit for order [{0}]", order.Id);
                     }
                     // Stop loss
                 } else if(openOrder.Order.StopLoss.HasValue && openOrder.Order.StopLoss.Value <= e.BuyPrice)
                 {
                     // Auto-close order
                     using(var ctx = new DataModelContext())
                     {
                         var order = ctx.Orders.Find(openOrder.Order.Id);
                         // Check if order was closed already
                         if(order.ClosePrice.HasValue)
                         {
                             LogManager.GetCurrentClassLogger().Warn("Stop-loss for order [{0}] but order was closed already.", order.Id);
                             continue;
                         }
                         //
                         order.ClosePrice = e.BuyPrice;
                         order.Pips = PricesProvider.CalculatePips(e.SymbolId, order.ClosePrice.Value, order.OpenPrice);
                         // log
                         ctx.OrderLogs.Add(OrderLog.CreateLog(order, OrderLogTypes.StopLossInvoke));
                         ctx.OrderLogs.Add(OrderLog.CreateLog(order, OrderLogTypes.Close));
                         //
                         ctx.SaveChanges();
                         closedOrders.Add(openOrder);
                         //
                         LogManager.GetCurrentClassLogger().Debug("Stop-loss for order [{0}]", order.Id);
                     }
                 }
             }
         }
         // Remove closed orders
         _openOrders.RemoveAll(closedOrders.Contains);
     }
 }
コード例 #8
0
ファイル: AdminController.cs プロジェクト: y-a-r/BuySellStats
 public ActionResult UpdateStatsExample([DataSourceRequest] DataSourceRequest request, StatsExampleModel model)
 {
     if(model != null && this.ModelState.IsValid)
     {
         try
         {
             using(var ctx = new DataModelContext())
             {
                 var example = ctx.StatsExamples.Find(model.Id);
                 example.Name = model.Name;
                 ctx.SaveChanges();
             }
         } catch(Exception ex)
         {
             LogManager.GetCurrentClassLogger().Error(ex);
             this.ModelState.AddModelError("save_error", ex.Message);
         }
     }
     //
     return this.Json(new[] {model}.ToDataSourceResult(request, this.ModelState));
 }
コード例 #9
0
ファイル: HomeController.cs プロジェクト: y-a-r/BuySellStats
 public ActionResult Index(string id)
 {
     using(var ctx = new DataModelContext())
     {
         this.ViewBag.IdLink = id;
         //
         var statsExample = ctx.StatsExamples.Include("Orders").Include("StatsType").Include("Orders.Logs").SingleOrDefault(e => e.IdLink == id && !e.Deleted);
         if(statsExample == null)
             return this.RedirectToAction("NotFoundExample");
         this.ViewData["StatsTypeName"] = statsExample.StatsType.Name;
         var typeConfig = ((TransactionTypesConfigSection)ConfigurationManager.GetSection("TransactionTypesConfig")).Types.Cast<TypeElementConfig>().ToList().Single(tc => tc.Id == statsExample.StatsType.TypeId);
         this.ViewBag.Symbol = typeConfig.Id;
         this.ViewBag.Spread = Settings.Default.Spread;
         this.ViewBag.SpreadTickValue = typeConfig.SpreadTickValue;
         this.ViewBag.DecimalDigits = GetDecimalDigits(typeConfig.SpreadTickValue);
         this.ViewBag.ExampleId = statsExample.Id;
         this.ViewBag.ExampleIsValid = statsExample.IsValid;
         //
         var models = statsExample.Orders.OrderBy(o => o.Index).Select(o => (TransactionModel)o).ToList();
         var transactionsCount = ctx.GetTransactionsCount();
         if(transactionsCount > models.Count)
         {
             for(var idx = models.Count; idx < transactionsCount; idx++)
             {
                 models.Add(new TransactionModel
                 {
                     StatsExampleId = statsExample.Id,
                     Index = idx,
                     Active = idx == 0 || (models[idx - 1].BuyPrice.HasValue && models[idx - 1].SellPrice.HasValue),
                     BuyEnabled = idx == 0 || (models[idx - 1].BuyPrice.HasValue && models[idx - 1].SellPrice.HasValue),
                     SellEnabled = idx == 0 || (models[idx - 1].BuyPrice.HasValue && models[idx - 1].SellPrice.HasValue),
                     ExampleIsValid = statsExample.IsValid
                 });
             }
         }
         //
         return this.View(models);
     }
 }
コード例 #10
0
ファイル: AdminController.cs プロジェクト: y-a-r/BuySellStats
 public ActionResult ReadStatsTypes([DataSourceRequest] DataSourceRequest request)
 {
     using(var ctx = new DataModelContext())
     {
         var allTypes = GetAllTypesConfig();
         this.ViewData["TransactionTypes"] = allTypes;
         //
         return this.Json(ctx.StatsTypes.ToList().Select(t => new StatsTypeModel
         {
             Id = t.Id,
             Name = t.Name,
             TypeConfig = allTypes.Single(tc => tc.Id == t.TypeId)
         }).ToDataSourceResult(request));
     }
 }
コード例 #11
0
ファイル: AdminController.cs プロジェクト: y-a-r/BuySellStats
 public ActionResult StatsExamples()
 {
     using(var ctx = new DataModelContext())
     {
         //
         return this.View(ctx.StatsTypes.ToList());
     }
 }
コード例 #12
0
ファイル: HomeController.cs プロジェクト: y-a-r/BuySellStats
 public JsonResult SetTakeProfit(long id, int idx, string takeProfit)
 {
     using(var client = new OrderServiceClient())
     {
         using(var ctx = new DataModelContext())
         {
             var numberFormat = new NumberFormatInfo {NumberDecimalSeparator = ".", NumberGroupSeparator = ","};
             var takeProfitValue = string.IsNullOrEmpty(takeProfit) ? (double?)null : double.Parse(takeProfit, numberFormat);
             var stopLossValue = ctx.Orders.Single(o => o.StatsExampleId == id && o.Index == idx).StopLoss;
             var response = client.ChangeOrder(new ChangeOrderRequest
             {
                 ExampleId = id,
                 Index = idx,
                 TakeProfit = takeProfitValue,
                 StopLoss = stopLossValue
             });
             if(!string.IsNullOrEmpty(response.Error))
             {
                 LogManager.GetCurrentClassLogger().Error(response.Error);
                 //
                 return this.Json(new {Response = SetOrderErrors.Other});
             }
             //
             return this.Json(new {Response = response.SetOrderErrors});
         }
     }
 }
コード例 #13
0
ファイル: AdminController.cs プロジェクト: y-a-r/BuySellStats
 public ActionResult ReadStatsExamples(long typeId, [DataSourceRequest] DataSourceRequest request)
 {
     using(var ctx = new DataModelContext())
     {
         return this.Json(ctx.StatsExamples.Include("Orders").Where(e => e.StatsTypeId == typeId && !e.Deleted).ToList().Select(e => new StatsExampleModel
         {
             Id = e.Id,
             Name = e.Name,
     // ReSharper disable once PossibleNullReferenceException
             IdLink = string.Format("{0}://{1}{2}", this.Request.Url.Scheme, this.Request.Url.Authority, this.Url.Content(string.Format("~/Home/Index?id={0}", e.IdLink))),
             PipsTotal = e.Orders.Sum(o => o.Pips)
         }).ToList().ToDataSourceResult(request));
     }
 }
コード例 #14
0
ファイル: HomeController.cs プロジェクト: y-a-r/BuySellStats
 public JsonResult GetValidTime(long id, long requestTimeValue)
 {
     LogManager.GetCurrentClassLogger().Info("GetValidTime. exampleId: {0}, requestTimeValue: {1}", id, requestTimeValue);
     try
     {
         using(var ctx = new DataModelContext())
         {
             var timeSpan = ctx.StatsExamples.Find(id).Timestamp.Add(Settings.Default.ExampleValidPeriod) - DateTime.Now;
             //
             return this.Json(new
             {
                 TimeSpan = timeSpan.TotalMilliseconds,
                 RequestTimeValue = requestTimeValue
             }, JsonRequestBehavior.AllowGet);
         }
     } catch(Exception ex)
     {
         LogManager.GetCurrentClassLogger().Error(ex);
         throw;
     }
 }
コード例 #15
0
ファイル: AdminController.cs プロジェクト: y-a-r/BuySellStats
 public ActionResult DeleteStatsExample([DataSourceRequest] DataSourceRequest request, StatsExampleModel model)
 {
     try
     {
         if(model != null)
         {
             using(var ctx = new DataModelContext())
             {
                 var example = ctx.StatsExamples.Include("StatsType").Include("Orders").Single(e => e.Id == model.Id);
                 example.Deleted = true;
                 var lastOrder = example.Orders.OrderBy(o => o.Index).LastOrDefault();
                 if(lastOrder != null && !lastOrder.ClosePrice.HasValue)
                 {
                     using(var client = new OrderServiceClient())
                     {
                         var response = client.GetPrice(new GetPriceDataContractRequest {SymbolId = example.StatsType.TypeId});
                         if(!string.IsNullOrEmpty(response.Error))
                         {
                             LogManager.GetCurrentClassLogger().Error(response.Error);
                         }
                         var price = response.Price;
                         if(price.HasValue)
                         {
                             var typeConfig = ((TransactionTypesConfigSection)ConfigurationManager.GetSection("TransactionTypesConfig")).Types.Cast<TypeElementConfig>().ToList().Single(tc => tc.Id == example.StatsType.TypeId);
                             lastOrder.ClosePrice = lastOrder.OrderType == OrderTypes.Buy ?
                                 Math.Round(price.Value - Settings.Default.Spread * typeConfig.SpreadTickValue, HomeController.GetDecimalDigits(typeConfig.SpreadTickValue))
                                 : Math.Round(price.Value + Settings.Default.Spread * typeConfig.SpreadTickValue, HomeController.GetDecimalDigits(typeConfig.SpreadTickValue));
                             lastOrder.Pips = Convert.ToInt32(Math.Round((lastOrder.OrderType == OrderTypes.Buy ? (lastOrder.ClosePrice.Value - lastOrder.OpenPrice) : (lastOrder.OpenPrice - lastOrder.ClosePrice.Value)) / typeConfig.SpreadTickValue, 0));
                             // Log
                             var log = OrderLog.CreateLog(lastOrder, OrderLogTypes.Close);
                             ctx.OrderLogs.Add(log);
                         }
                     }
                 }
                 //
                 ctx.SaveChanges();
             }
         }
     } catch(Exception ex)
     {
         LogManager.GetCurrentClassLogger().Error(ex);
     }
     //
     return this.Json(new[] {model}.ToDataSourceResult(request, this.ModelState));
 }
コード例 #16
0
ファイル: OrderManager.cs プロジェクト: y-a-r/BuySellStats
 public static void Start()
 {
     lock(_openOrders)
     {
         using(var ctx = new DataModelContext())
         {
             ctx.StatsExamples.Include("StatsType").Include("Orders")
                 .Where(e => !e.Deleted).ToList().Where(e => e.IsValid).ToList()
                 .ForEach(e =>
                 {
                     var lastOrder = e.Orders.OrderBy(o => o.Index).LastOrDefault();
                     if(lastOrder != null && !lastOrder.ClosePrice.HasValue)
                     {
                         _openOrders.Add(new OpenOrder
                         {
                             SymbolId = e.StatsType.TypeId,
                             Order = lastOrder
                         });
                     }
                 });
         }
         //
         PricesProvider.PriceChanged += PricesProvider_PriceChanged;
     }
 }
コード例 #17
0
ファイル: OrderManager.cs プロジェクト: y-a-r/BuySellStats
 public static SetOrderResponse CreateOrder(long exampleId, OrderTypes orderType, double? takeProfit, double? stopLoss)
 {
     using(var ctx = new DataModelContext())
     {
         var example = ctx.StatsExamples.Include("StatsType").Include("Orders").Single(e => e.Id == exampleId);
         // Check if example is not valid
         if(!example.IsValid)
         {
             return new SetOrderResponse {Error = SetOrderErrors.Other};
         }
         //
         var index = example.Orders.Count;
         if(index >= ctx.GetTransactionsCount())
             return new SetOrderResponse {Error = SetOrderErrors.Other};
         //
         var price = PricesProvider.GetPrice(example.StatsType.TypeId);
         if(!price.HasValue)
             return new SetOrderResponse {Error = SetOrderErrors.PriceError};
         //
         var buyPrice = PricesProvider.GetBuyPrice(price.Value, example.StatsType.TypeId);
         var sellPrice = PricesProvider.GetSellPrice(price.Value, example.StatsType.TypeId);
         if(orderType == OrderTypes.Buy)
         {
             var error = SetOrderErrors.None;
             // Check take profit value
             if(takeProfit.HasValue && takeProfit.Value <= sellPrice)
                 error |= SetOrderErrors.WrongTakeProfitValue;
             // Check Stop loss value
             if(stopLoss.HasValue && stopLoss.Value >= sellPrice)
                 error |= SetOrderErrors.WrongStopLossValue;
             //
             if(error != SetOrderErrors.None)
                 return new SetOrderResponse {Error = error};
             // Create order
             var order = new Order
             {
                 OpenPrice = buyPrice,
                 Index = index,
                 OrderType = orderType,
                 StatsExampleId = exampleId,
                 TakeProfit = takeProfit,
                 StopLoss = stopLoss
             };
             ctx.Orders.Add(order);
             // log
             var log = OrderLog.CreateLog(order, OrderLogTypes.Open);
             ctx.OrderLogs.Add(log);
             //
             ctx.SaveChanges();
             //
             lock(_openOrders)
             {
                 _openOrders.Add(new OpenOrder
                 {
                     SymbolId = example.StatsType.TypeId,
                     Order = order
                 });
             }
             //
             LogManager.GetCurrentClassLogger().Debug("Order created [0]", order.Id);
             //
             return new SetOrderResponse {Order = order, Error = SetOrderErrors.None};
         } else
         {
             var error = SetOrderErrors.None;
             // Check take profit value
             if(takeProfit.HasValue && takeProfit.Value >= buyPrice)
                 error |= SetOrderErrors.WrongTakeProfitValue;
             // Check Stop loss value
             if(stopLoss.HasValue && stopLoss.Value <= buyPrice)
                 error |= SetOrderErrors.WrongStopLossValue;
             //
             if(error != SetOrderErrors.None)
                 return new SetOrderResponse {Error = error};
             // Create order
             var order = new Order
             {
                 OpenPrice = sellPrice,
                 Index = index,
                 OrderType = orderType,
                 StatsExampleId = exampleId,
                 TakeProfit = takeProfit,
                 StopLoss = stopLoss
             };
             ctx.Orders.Add(order);
             // log
             var log = OrderLog.CreateLog(order, OrderLogTypes.Open);
             ctx.OrderLogs.Add(log);
             //
             ctx.SaveChanges();
             //
             lock(_openOrders)
             {
                 _openOrders.Add(new OpenOrder
                 {
                     SymbolId = example.StatsType.TypeId,
                     Order = order
                 });
             }
             //
             LogManager.GetCurrentClassLogger().Debug("Order created [0]", order.Id);
             //
             return new SetOrderResponse {Order = order, Error = SetOrderErrors.None};
         }
     }
 }
コード例 #18
0
ファイル: OrderManager.cs プロジェクト: y-a-r/BuySellStats
 public static SetOrderResponse CloseOrder(long exampleId, int index)
 {
     using(var ctx = new DataModelContext())
     {
         var example = ctx.StatsExamples.Include("StatsType").Include("Orders").Single(e => e.Id == exampleId);
         // Check if example is not valid
         if(!example.IsValid)
         {
             return new SetOrderResponse {Error = SetOrderErrors.Other};
         }
         //
         var order = example.Orders.SingleOrDefault(o => o.Index == index);
         if(order == null)
             return new SetOrderResponse {Error = SetOrderErrors.Other};
         // Check if order was closed already
         if(order.ClosePrice.HasValue)
         {
             LogManager.GetCurrentClassLogger().Warn("Close order process for order [{0}] but order was closed already.", order.Id);
             return new SetOrderResponse {Error = SetOrderErrors.Other};
         }
         //
         var price = PricesProvider.GetPrice(example.StatsType.TypeId);
         if(!price.HasValue)
             return new SetOrderResponse {Error = SetOrderErrors.PriceError};
         //
         lock(_openOrders)
         {
             if(order.OrderType == OrderTypes.Buy)
             {
                 var sellPrice = PricesProvider.GetSellPrice(price.Value, example.StatsType.TypeId);
                 order.ClosePrice = sellPrice;
                 order.Pips = PricesProvider.CalculatePips(example.StatsType.TypeId, order.OpenPrice, sellPrice);
                 // log
                 var log = OrderLog.CreateLog(order, OrderLogTypes.Close);
                 ctx.OrderLogs.Add(log);
             } else
             {
                 var buyPrice = PricesProvider.GetBuyPrice(price.Value, example.StatsType.TypeId);
                 order.ClosePrice = buyPrice;
                 order.Pips = PricesProvider.CalculatePips(example.StatsType.TypeId, buyPrice, order.OpenPrice);
                 // log
                 var log = OrderLog.CreateLog(order, OrderLogTypes.Close);
                 ctx.OrderLogs.Add(log);
             }
             //
             ctx.SaveChanges();
             _openOrders.Remove(_openOrders.Single(o => o.Order.Id == order.Id));
             //
             LogManager.GetCurrentClassLogger().Debug("Order closed [{0}]", order.Id);
             //
             return new SetOrderResponse {Order = order};
         }
     }
 }
コード例 #19
0
ファイル: OrderManager.cs プロジェクト: y-a-r/BuySellStats
 public static SetOrderResponse ChangeOrder(long exampleId, int index, double? takeProfit, double? stopLoss)
 {
     using(var ctx = new DataModelContext())
     {
         var example = ctx.StatsExamples.Include("StatsType").Include("Orders").Single(e => e.Id == exampleId);
         // Check if example is not valid
         if(!example.IsValid)
         {
             return new SetOrderResponse {Error = SetOrderErrors.Other};
         }
         //
         var order = example.Orders.SingleOrDefault(o => o.Index == index);
         if(order == null)
             return new SetOrderResponse {Error = SetOrderErrors.Other};
         //
         var price = PricesProvider.GetPrice(example.StatsType.TypeId);
         if(!price.HasValue)
             return new SetOrderResponse {Error = SetOrderErrors.PriceError};
         //
         if(order.TakeProfit == takeProfit && order.StopLoss == stopLoss)
         {
             LogManager.GetCurrentClassLogger().Debug("Nothing to change in order [{0}]", order.Id);
             //
             return new SetOrderResponse {Order = order};
         }
         //
         var buyPrice = PricesProvider.GetBuyPrice(price.Value, example.StatsType.TypeId);
         var sellPrice = PricesProvider.GetSellPrice(price.Value, example.StatsType.TypeId);
         //
         lock(_openOrders)
         {
             var error = SetOrderErrors.None;
             // Check take-profit
             if(order.TakeProfit != takeProfit)
             {
                 if(!takeProfit.HasValue)
                 {
                     order.TakeProfit = null;
                     // log
                     var log = OrderLog.CreateLog(order, OrderLogTypes.SetTakeProfit);
                     ctx.OrderLogs.Add(log);
                 } else if(order.OrderType == OrderTypes.Buy && takeProfit.Value <= sellPrice)
                     error |= SetOrderErrors.WrongTakeProfitValue;
                 else if(order.OrderType == OrderTypes.Sell && takeProfit.Value >= buyPrice)
                     error |= SetOrderErrors.WrongTakeProfitValue;
                 else
                 {
                     order.TakeProfit = takeProfit;
                     // log
                     var log = OrderLog.CreateLog(order, OrderLogTypes.SetTakeProfit);
                     ctx.OrderLogs.Add(log);
                 }
             }
             // Check stop-loss
             if(order.StopLoss != stopLoss)
             {
                 if(!stopLoss.HasValue)
                 {
                     order.StopLoss = null;
                     // log
                     var log = OrderLog.CreateLog(order, OrderLogTypes.SetStopLoss);
                     ctx.OrderLogs.Add(log);
                 } else if(order.OrderType == OrderTypes.Buy && stopLoss.Value >= sellPrice)
                     error |= SetOrderErrors.WrongStopLossValue;
                 else if(order.OrderType == OrderTypes.Sell && stopLoss.Value <= buyPrice)
                     error |= SetOrderErrors.WrongStopLossValue;
                 else
                 {
                     order.StopLoss = stopLoss;
                     // log
                     var log = OrderLog.CreateLog(order, OrderLogTypes.SetStopLoss);
                     ctx.OrderLogs.Add(log);
                 }
             }
             //
             if(error == SetOrderErrors.None)
             {
                 ctx.SaveChanges();
                 _openOrders.Single(o => o.Order.StatsExampleId == exampleId && o.Order.Index == index).Order = order;
                 //
                 LogManager.GetCurrentClassLogger().Debug("Order changed [{0}]", order.Id);
                 //
                 return new SetOrderResponse {Order = order};
             }
             LogManager.GetCurrentClassLogger().Debug("Order [{0}] was not changed. Error: {1}", order.Id, error);
             //
             return new SetOrderResponse {Error = error};
         }
     }
 }
コード例 #20
0
ファイル: HomeController.cs プロジェクト: y-a-r/BuySellStats
 public PartialViewResult GetTransaction(long id, int idx)
 {
     using(var ctx = new DataModelContext())
     {
         var statsExample = ctx.StatsExamples.Include("Orders").Include("StatsType").Include("Orders.Logs").Single(e => e.Id == id && !e.Deleted);
         var orders = statsExample.Orders.OrderBy(o => o.Index).ToList();
         var order = orders.SingleOrDefault(o => o.Index == idx);
         //
         return this.PartialView("_Transaction", order != null ? (TransactionModel)order : new TransactionModel
         {
             StatsExampleId = id,
             Index = idx,
             Active = idx == 0 || orders[idx - 1].ClosePrice.HasValue,
             BuyEnabled = idx == 0 || orders[idx - 1].ClosePrice.HasValue,
             SellEnabled = idx == 0 || orders[idx - 1].ClosePrice.HasValue,
             ExampleIsValid = statsExample.IsValid
         });
     }
 }