Esempio n. 1
0
        //[SetUp]
        public void InitContext()
        {
            // подготовить тестовые котировки

            // подготовить тестовый контекст
            context = new RobotContextBacktest((tickers, end) => { });
        }
Esempio n. 2
0
        public StatInfoForm(RobotContextBacktest robotContext)
            : this()
        {
            this.robotContext = robotContext;
            var orderTags = robotContext.PosHistory.ToList();
            orderTags.AddRange(robotContext.Positions.ToList());
            AccountHistoryCtrl.historyGrid.DataBind(orderTags);

            SetupGrids();
            SetupCharts();
            BuildEquityCurve();
            CalculateStatistics();
            ShowLog();
        }
Esempio n. 3
0
        public void TestSetup()
        {
            TradeSharpDictionary.Initialize(MoqTradeSharpDictionary.Mock);
            context = TestRobotUtil.GetRobotContextBacktest(new DateTime(2013, 12, 25), new DateTime(2013, 12, 25).AddDays(30));

            bot = new VoidRobot();
            bot.Graphics.Add(new Cortege2<string, BarSettings>("EURUSD", new BarSettings
            {
                StartMinute = 0,
                Intervals = new List<int> { 30 }
            }));
            bot.Initialize(context, CurrentProtectedContext.Instance);

            ExecutablePath.InitializeFake(string.Empty);
            context.SubscribeRobot(bot);
            context.InitiateTest();

            // Инициализация дополнительных объектом, MOCK-и
            QuoteMaker.FillQuoteStorageWithDefaultValues();
        }
Esempio n. 4
0
        public void InitContext()
        {
            TradeSharpDictionary.Initialize(MoqTradeSharpDictionary.Mock);
            context = TestRobotUtil.GetRobotContextBacktest(new DateTime(2013, 9, 30), new DateTime(2014, 1, 30), currency : "IND");

            bot = new IchimokuRobot();
            bot.Graphics.Clear();
            bot.Graphics.Add(new Cortege2<string, BarSettings>("INDUSD", new BarSettings
            {
                StartMinute = 0,
                Intervals = new List<int> { 30 }
            }));
            bot.Initialize(context, CurrentProtectedContext.Instance);

            ExecutablePath.InitializeFake(string.Empty);
        }
Esempio n. 5
0
        private RobotContextBacktest MakeRobotContext(ACCOUNT accountData, List<BaseRobot> robots)
        {
            var timeFrom = testOnly
                ? accountData.TimeCreated
                : accountData.TimeCreated.AddMinutes(rand.Next(60*24*9));

            try
            {
                var context = new RobotContextBacktest((tickers, end) => { })
                {
                    TimeFrom = timeFrom
                };
                context.TimeFrom = timeFrom;
                context.TimeTo = endTime;

                context.AccountInfo = new Account
                {
                    Currency = accountData.Currency,
                    Group = accountData.AccountGroup,
                    Balance = accountData.Balance,
                    Equity = accountData.Balance,
                    ID = accountData.ID
                };
                foreach (var robot in robots)
                {
                    context.SubscribeRobot(robot);
                    robot.Initialize(context, CurrentProtectedContext.Instance);
                }

                context.InitiateTest();
                return context;
            }
            catch (Exception ex)
            {
                Logger.Error("Error in MakeRobotContext()", ex);
                throw;
            }
        }
Esempio n. 6
0
 private void InvertLossDeal(RobotContextBacktest context, MarketOrder lastClosedDeal)
 {
     if (rand.Next(100) >= reverseClosedDealProb)
         return;
     lastClosedDeal.ResultDepo = -lastClosedDeal.ResultDepo;
     lastClosedDeal.Side = -lastClosedDeal.Side;
     lastClosedDeal.ResultPoints = -lastClosedDeal.ResultPoints;
     var delta = lastClosedDeal.ResultDepo * 2;
     context.AccountInfo.Balance += (decimal) delta;
     context.AccountInfo.Equity += (decimal) delta;
 }
Esempio n. 7
0
        private void CheckDepositWithdraw(RobotContextBacktest context, List<BalanceChange> transfers, DateTime curTime)
        {
            const int minMinutesSinceLastTransfer = 60;

            var lastTrans = transfers[transfers.Count - 1];

            var minutesSinceLastTransfer = (curTime - lastTrans.ValueDate).TotalMinutes;
            if (minutesSinceLastTransfer < minMinutesSinceLastTransfer)
                return;

            // не выводить слишком часто
            if (rand.Next(withdrawProb) > 0)
                return;

            // не выводить вне рабочих часов
            if (curTime.Hour < 8 || curTime.Hour > 19)
                if (rand.Next(100) < 85)
                    return;

            // ввод / вывод
            var initBalance = transfers[0].Amount;
            var lessThanInit = context.AccountInfo.Equity < initBalance;
            var probWdth = lessThanInit ? probWithdrawWhenLoss : probWithdrawWhenProfit;
            var sign = rand.Next(100) < probWdth ? BalanceChangeType.Withdrawal : BalanceChangeType.Deposit;

            // объем
            var amount = Math.Ceiling(rand.Next(1, 90) * context.AccountInfo.Equity / 100);
            if (rand.Next(100) < 70)
            {
                var amount10 = (int)Math.Ceiling(amount / 10);
                amount = amount10 * 10;
            }
            var amountSigned = sign == BalanceChangeType.Deposit ? amount : -amount;

            var moneyLeft = context.AccountInfo.Equity + amountSigned;
            if (moneyLeft < 100)
            {
                return;
                sign = BalanceChangeType.Deposit;
                amountSigned = Math.Abs(amount);
            }

            // добавить в список
            transfers.Add(new BalanceChange
                {
                    AccountID = lastTrans.AccountID,
                    Amount = amount,
                    ChangeType = sign,
                    ValueDate = curTime
                });
            context.AccountInfo.Balance += amountSigned;
            context.AccountInfo.Equity += amountSigned;

            //Logger.InfoFormat("Счет #{0}, средства {1}: {2} {3} USD",
            //    lastTrans.AccountID, context.AccountInfo.Equity.ToStringUniformMoneyFormat(),
            //    sign, amount);
        }
Esempio n. 8
0
 private void AddAccountPerformanceRecord(RobotContextBacktest context)
 {
     try
     {
         performance.Add(new AccountPerformance
         {
             AccountId = context.AccountInfo.ID,
             DealsCount = context.PosHistory.Count + context.Positions.Count,
             SummaryResult = (decimal)context.PosHistory.Sum(p => p.ResultDepo)
                             + context.AccountInfo.Equity - context.AccountInfo.Balance,
             SummaryVolume = (long)context.PosHistory.Sum(p => p.VolumeInDepoCurrency)
         });
     }
     catch (Exception ex)
     {
         Logger.Error("Error in AddAccountPerformanceRecord()", ex);
     }
 }
Esempio n. 9
0
        private static void SaveTrackInDatabase(RobotContextBacktest context, int accountId, 
            List<BalanceChange> transfers,
            int transfersInDbCount)
        {
            try
            {
                Logger.InfoFormat("Сохранение изменений в БД для счета {0}", accountId);

                int nextPosId;
                using (var conn = DatabaseContext.Instance.Make())
                {
                    nextPosId = Math.Max(conn.POSITION.Max(p => p.ID), conn.POSITION_CLOSED.Max(p => p.ID)) + 1;
                }

                Logger.InfoFormat("Запись {0} позиций для счета {1}",
                    context.PosHistory.Count, accountId);

                // закрытые ордера
                var listPos = new List<POSITION_CLOSED>();
                foreach (var pos in context.PosHistory)
                {
                    var orderClosed = LinqToEntity.UndecorateClosedPosition(pos);
                    orderClosed.ID = ++nextPosId;
                    listPos.Add(orderClosed);
                }

                using (var conn = DatabaseContext.Instance.Make())
                {
                    conn.BulkInsert(listPos);
                    conn.SaveChanges();
                }

                // трансферы...
                var listTrans =
                    transfers.Skip(transfersInDbCount).Select(t =>
                        new BALANCE_CHANGE
                        {
                            AccountID = accountId,
                            Amount = t.Amount,
                            ChangeType = (int) t.ChangeType,
                            ValueDate = t.ValueDate,
                        }).ToList();
                // + трансферы по закрытым ордерам
                foreach (var pos in listPos)
                {
                    var transfer = new BALANCE_CHANGE
                    {
                        AccountID = accountId,
                        Amount = Math.Abs(pos.ResultDepo),
                        ChangeType = (int) (pos.ResultDepo >= 0
                            ? BalanceChangeType.Profit
                            : BalanceChangeType.Loss),
                        ValueDate = pos.TimeExit,
                        Position = pos.ID,
                    };
                    listTrans.Add(transfer);
                }

                using (var conn = DatabaseContext.Instance.Make())
                {
                    conn.BulkInsert(listTrans);
                    conn.SaveChanges();
                }

                // открытые сделки - как есть
                using (var conn = DatabaseContext.Instance.Make())
                {
                    foreach (var pos in context.Positions)
                    {
                        var orderOpened = LinqToEntity.UndecorateOpenedPosition(pos);
                        orderOpened.ID = ++nextPosId;
                        conn.POSITION.Add(orderOpened);
                    }

                    conn.SaveChanges();
                }
                Logger.InfoFormat("Сохранение успешно для счета {0}: {1} сделок сохранено",
                    accountId, context.PosHistory.Count + context.Positions.Count);
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка сохранения трека пользователя в БД", ex);
            }
        }