Exemplo n.º 1
0
        public async Task <long> Save(FarmAccount entity)
        {
            _context.Entry(entity).State = entity.Id > 0 ? EntityState.Modified : EntityState.Added;
            await _context.SaveChangesAsync();

            return(entity.Id);
        }
Exemplo n.º 2
0
        private List <MarketOrder> GetAccountHistoryOrders(FarmAccount account)
        {
            var context = account.GetContext();

            byte[] buffer;
            context.GetHistoryOrdersCompressed(account.AccountId, startDate, out buffer);
            if (buffer == null || buffer.Length == 0)
            {
                return(null);
            }

            try
            {
                using (var reader = new SerializationReader(buffer))
                {
                    var array = reader.ReadObjectArray(typeof(MarketOrder));
                    if (array != null && array.Length > 0)
                    {
                        return(array.Cast <MarketOrder>().ToList());
                    }
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("GetHistoryOrdersUncompressed() - serialization error", ex);
                return(null);
            }
        }
Exemplo n.º 3
0
        public async Task <long> Delete(long id)
        {
            FarmAccount farmAccount = await GetById(id);

            _context.FarmAccounts.Remove(farmAccount);
            await _context.SaveChangesAsync();

            return(id);
        }
Exemplo n.º 4
0
        /// <summary>
        /// добавление нового аккаунта
        /// </summary>
        private static void AddNewAccount(FarmAccountArg e)
        {
            CheckValidationSubmitData(e, "Add");

            var newAccount = new FarmAccount
            {
                AccountId    = e.AccountId,
                TradeEnabled = e.TradeEnabled,
                UserLogin    = e.Login,
                UserPassword = e.Password
            };

            RobotFarm.Instance.Accounts.Add(newAccount);
        }
Exemplo n.º 5
0
        private List <MarketOrder> GetAccountOpenedOrders(FarmAccount account)
        {
            var context = account.GetContext();

            try
            {
                List <MarketOrder> orderList;
                context.GetMarketOrders(account.AccountId, out orderList);
                return(orderList);
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в GetMarketOrders()", ex);
            }
            return(null);
        }
Exemplo n.º 6
0
        private AccountTrades MakeAccountTradesRecord(FarmAccount account)
        {
            var record = new AccountTrades
            {
                AccountTitle = "#" + account.AccountId + " / " + account.UserLogin
            };

            var context = account.GetContext();

            if (context == null)
            {
                return new AccountTrades
                       {
                           ErrorMessage = "контекст не создан"
                       }
            }
            ;

            var ordersClosed = GetAccountHistoryOrders(account) ?? new List <MarketOrder>();

            record.ClosedTrades = ordersClosed.Count;
            var errors = new List <string>();

            var quotes = QuoteStorage.Instance.ReceiveAllData();

            record.ClosedVolumeDepo = DalSpot.Instance.CalculateExposure(ordersClosed,
                                                                         quotes, context.AccountInfo.Currency, errors);

            var ordersOpened = GetAccountOpenedOrders(account);

            record.OpenedTrades = ordersOpened.Count;
            record.Exposure     = DalSpot.Instance.CalculateExposure(ordersOpened,
                                                                     quotes, context.AccountInfo.Currency, errors);
            record.OpenProfit = (decimal)DalSpot.Instance.CalculateOpenedPositionsCurrentResult(ordersOpened,
                                                                                                quotes, context.AccountInfo.Currency);
            var lastClosedEnter = ordersClosed.Count > 0 ? ordersClosed.Max(o => o.TimeEnter) : DateTime.MinValue;
            var lastOpenEnter   = ordersOpened.Count > 0 ? ordersOpened.Max(o => o.TimeEnter) : DateTime.MinValue;
            var maxEnterTime    = lastClosedEnter > lastOpenEnter ? lastClosedEnter : lastOpenEnter;

            record.LastOpen = maxEnterTime == DateTime.MinValue ? (DateTime?)null : maxEnterTime;

            return(record);
        }
Exemplo n.º 7
0
        private List<MarketOrder> GetAccountHistoryOrders(FarmAccount account)
        {
            var context = account.GetContext();
            byte[] buffer;
            context.GetHistoryOrdersCompressed(account.AccountId, startDate, out buffer);
            if (buffer == null || buffer.Length == 0)
                return null;

            try
            {
                using (var reader = new SerializationReader(buffer))
                {
                    var array = reader.ReadObjectArray(typeof(MarketOrder));
                    if (array != null && array.Length > 0)
                        return array.Cast<MarketOrder>().ToList();
                    return null;
                }
            }
            catch (Exception ex)
            {
                Logger.Error("GetHistoryOrdersUncompressed() - serialization error", ex);
                return null;
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Обработчик асинхронных действий пользователя с помощью объекта XMLHttpRequest и ответа клиенту в виде простого текста
        /// </summary>
        /// <returns>Выполнено ли какое либо асинхронное действие</returns>
        private static bool AccountAjaxAction(HttpListenerContext context)
        {
            switch (context.Request.QueryString["actionAccount"])
            {
            case "check":
                try
                {
                    var message = FarmAccount.CheckCredentials(new FarmAccountArg
                    {
                        AccountId = context.Request.QueryString["col0"].ToIntSafe() ?? -1,
                        // ReSharper disable AssignNullToNotNullAttribute
                        Login    = Encoding.UTF8.GetString(HttpUtility.UrlDecodeToBytes(context.Request.QueryString["col1"], Encoding.Default)),
                        Password = Encoding.UTF8.GetString(HttpUtility.UrlDecodeToBytes(context.Request.QueryString["col2"], Encoding.Default)),
                        // ReSharper restore AssignNullToNotNullAttribute
                        TradeEnabled = context.Request.QueryString.AllKeys.Contains("col3") && context.Request.QueryString["col3"] == "true"
                    });
                    WriteTextResponse(context, string.Format("Результат : \"{0}\"", message));
                    return(true);
                }
                catch (ArgumentException ex)
                {
                    Logger.Error("Ошибка проверки счёта", ex);
                    WriteTextResponse(context, ex.Message);
                    return(true);
                }
                catch (Exception ex)
                {
                    Logger.Error("Ошибка проверки счёта", ex);
                    WriteTextResponse(context, ex.Message);
                    return(true);
                }

            case "edit":
                try
                {
                    var currentAccountId = context.Request.QueryString["currentAccountId"].ToIntSafe() ?? -1;

                    EditAccount(new FarmAccountArg
                    {
                        CurrentAccountId = currentAccountId,
                        AccountId        = context.Request.QueryString["col0"].ToIntSafe() ?? -1,
                        // ReSharper disable AssignNullToNotNullAttribute
                        Login    = Encoding.UTF8.GetString(HttpUtility.UrlDecodeToBytes(context.Request.QueryString["col1"], Encoding.Default)),
                        Password = Encoding.UTF8.GetString(HttpUtility.UrlDecodeToBytes(context.Request.QueryString["col2"], Encoding.Default)),
                        // ReSharper restore AssignNullToNotNullAttribute
                        TradeEnabled = context.Request.QueryString.AllKeys.Contains("col3") && context.Request.QueryString["col3"] == "true"
                    });

                    WriteTextResponse(context, string.Format("Результат : аккаунт \"{0}\" изменён", currentAccountId));
                    return(true);
                }
                catch (ArgumentException ex)
                {
                    Logger.Error("Ошибка обновления счёта", ex);
                    WriteTextResponse(context, ex.Message);
                    return(true);
                }
                catch (Exception ex)
                {
                    Logger.Error("Ошибка обновления счёта", ex);
                    WriteTextResponse(context, ex.Message);
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 9
0
 private List<MarketOrder> GetAccountOpenedOrders(FarmAccount account)
 {
     var context = account.GetContext();
     try
     {
         List<MarketOrder> orderList;
         context.GetMarketOrders(account.AccountId, out orderList);
         return orderList;
     }
     catch (Exception ex)
     {
         Logger.Error("Ошибка в GetMarketOrders()", ex);
     }
     return null;
 }
Exemplo n.º 10
0
        private AccountTrades MakeAccountTradesRecord(FarmAccount account)
        {
            var record = new AccountTrades
            {
                AccountTitle = "#" + account.AccountId + " / " + account.UserLogin
            };

            var context = account.GetContext();
            if (context == null)
                return new AccountTrades
                {
                    ErrorMessage = "контекст не создан"
                };

            var ordersClosed = GetAccountHistoryOrders(account) ?? new List<MarketOrder>();
            record.ClosedTrades = ordersClosed.Count;
            var errors = new List<string>();

            var quotes = QuoteStorage.Instance.ReceiveAllData();
            record.ClosedVolumeDepo = DalSpot.Instance.CalculateExposure(ordersClosed,
                quotes, context.AccountInfo.Currency, errors);

            var ordersOpened = GetAccountOpenedOrders(account);
            record.OpenedTrades = ordersOpened.Count;
            record.Exposure = DalSpot.Instance.CalculateExposure(ordersOpened,
                quotes, context.AccountInfo.Currency, errors);
            record.OpenProfit = (decimal) DalSpot.Instance.CalculateOpenedPositionsCurrentResult(ordersOpened,
                quotes, context.AccountInfo.Currency);
            var lastClosedEnter = ordersClosed.Count > 0 ? ordersClosed.Max(o => o.TimeEnter) : DateTime.MinValue;
            var lastOpenEnter = ordersOpened.Count > 0 ? ordersOpened.Max(o => o.TimeEnter) : DateTime.MinValue;
            var maxEnterTime = lastClosedEnter > lastOpenEnter ? lastClosedEnter : lastOpenEnter;
            record.LastOpen = maxEnterTime == DateTime.MinValue ? (DateTime?) null : maxEnterTime;

            return record;
        }