Exemplo n.º 1
0
 public Pattern(PatternConfig settings, ILogger _logger, string engineName = "Generic")
 {
     logger   = _logger;
     Symbol   = settings.Symbol;
     Interval = settings.Interval;
     Name     = settings.Name;
     Engine   = new TradeEngine(logger, engineName);
 }
Exemplo n.º 2
0
 public PatternRunner(ILogger logger, DataRepository repository)
 {
     _logger           = logger;
     PatternRepository = InitializePatternRepository();
     CoinPairDict      = new Dictionary <string, CoinPair>();
     KlineRepository   = repository;
     Trade             = new TradeEngine(_logger);
 }
Exemplo n.º 3
0
        //
        //
        //
        //
        // ****************************************
        // ****     Setup Initialize()         ****
        // ****************************************
        /// <summary>
        /// The Strategy has been created, and now we add its engines.
        /// When we call Engine.SetupInitialize() the engine can make NO assumptions
        /// about the Strategy, except that it and its StrategyHub exists.
        /// Other Engines may or may not exist.
        /// What is allowed is that Engines can spawn other Engines and add them
        /// to the *end* of the Strategy.m_Engines[] list freely.
        /// </summary>
        public void SetupInitialize(IEngineHub myHub)
        {
            StrategyHub = (StrategyHub)myHub;                           // store ptr to new parent hub.

            // First initialize each of my engines.
            int id = 0;

            while (id < m_Engines.Count)                                // Loop using while so that Engines can ADD new engines to end of list.
            {                                                           // Adding new engines spontaneously is allowed here only.
                Engine engine = m_Engines[id];
                engine.SetupInitialize(StrategyHub, this, id);          // Tell Engine his new Hub, and owner, and his new id#.

                // Keep track of important engine ptrs we need.
                if (engine is PricingEngine)                            // using simple "if"s allows one engine to play multiple roles.
                {
                    PricingEngines.Add((PricingEngine)engine);          //m_PricingEngine = (StrategyEngines.PricingEngine)engine;
                }
                if (engine is TradeEngine)
                {
                    m_OrderEngine = (TradeEngine)engine;
                }
                if (engine is ZGraphEngine)
                {
                    m_GraphEngine = (ZGraphEngine)engine;
                }
                if (engine is FauxQuote)
                {
                    m_QuoteEngine = (FauxQuote)engine;
                }
                id++;
            }//next engine id

            // Create missing basic engines
            if (m_OrderEngine == null)
            {
                m_OrderEngine = new TradeEngine();
                TryAddEngine(m_OrderEngine, myHub);
                m_OrderEngine.SetupInitialize(StrategyHub, this, -1);// Tell Engine his new Hub, and owner, and his new id# (which is already set in TryAddEngine()).
            }
            if (m_GraphEngine == null)
            {
                m_GraphEngine = new ZGraphEngine();
                TryAddEngine(m_GraphEngine, myHub);
                m_GraphEngine.SetupInitialize(StrategyHub, this, -1);
            }
            if (m_QuoteEngine == null)
            {
                QuoteEngine quoteEngine = new QuoteEngine();
                m_QuoteEngine = quoteEngine;
                TryAddEngine(quoteEngine, myHub);
                quoteEngine.SetupInitialize(StrategyHub, this, -1);
            }

            // Exit
            m_IsInitializeComplete = true;                               // Must be last line in this method.
        }//SetupInitialize()
Exemplo n.º 4
0
        public LeechPlatform(TickSource tickSrc, IInstrumBL instrumBL, IInsStoreBL insStoreBL, TradeEngine engine, 
            TradeEngineData data, SeriesData seriesData, ILogger logger)
        {
            _tickSource = tickSrc;
            _instrumBL = instrumBL;
            _insStoreBL = insStoreBL;
            _engine = engine;
            _data = data;
            _seriesData = seriesData;
            _logger = logger;

            _barRows = new List<BarRow>();
            _tickSource.OnTick += _tickSource_OnTick;
            _insID_onTicks = new Dictionary<int, List<OnTickDelegate>>();
            _insID_pm = new Dictionary<int, IPosManager>();
        }
Exemplo n.º 5
0
        /// <summary>
        /// Инициализация объекта Тестовый прогон
        /// </summary>
        /// <param name="tickSourceID">Источник тиковых данных</param>
        /// <param name="testConfigID">Тестовая конфигурация</param>
        /// <param name="accountID">Торговый счет, если не указан, то создается новый, иначе берется указанный, в нем очищаются все данные и он заполняется новыми данными</param>
        /// <param name="progress">Индикатор прогресса</param>
        /// <returns>true-успешно, false-ошибка</returns>
        public async Task <bool> Initialize(int tickSourceID, int testConfigID, int?accountID, BgTaskProgress progress = null)
        {
            _tickSource = _tickSourceBL.GetTickSourceByID(tickSourceID);
            var testConfig = _testConfigBL.GetTestConfig(testConfigID);

            if (_tickSource == null || testConfig == null)
            {
                return(false);
            }

            if (accountID != null)
            {
                var account = _accountBL.GetAccountByID(accountID.Value);
                if (account == null)
                {
                    throw new ApplicationException("Указанный счет не найден.");
                }
                if (account.AccountType != AccountTypes.Test)
                {
                    throw new ApplicationException("Указанный счет не может использоваться для тестирования.");
                }
            }

            _progress                  = progress;
            _data                      = new TradeEngineData(_accountDA);
            _engine                    = new TradeEngine(_data, _instrumBL, (ITimeProvider)_tickSource);
            _seriesData                = new SeriesData(_accountDA);
            _tickSource.OnTick        += _tickSource_OnTick;
            _tickSource.OnStateChange += _tickSource_OnStateChange;

            if (accountID != null)
            {
                _accountBL.DeleteTestAccountData(accountID.Value, false);
                _data.LoadData(accountID.Value);
                _seriesData.LoadData(accountID.Value);
            }

            var acc = _data.GetAccount();

            acc.AccountType   = AccountTypes.Test;
            acc.CommPerc      = testConfig.CommPerc;
            acc.IsShortEnable = testConfig.IsShortEnable;
            acc.Name          = testConfig.Name + " - " + _tickSource.Name;
            acc.Code          = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss");
            var cash = _data.GetCash();

            cash.Initial = cash.Current = testConfig.InitialSumma;

            var botConfigs = testConfig.GetBotConfigs();

            foreach (var conf in botConfigs)
            {
                try
                {
                    string asmPath = "";
                    if (Path.IsPathRooted(conf.Assembly))
                    {
                        asmPath = conf.Assembly;
                    }
                    else
                    {
                        string botsPath = _config.GetBotsPath();
                        asmPath = Path.Combine(botsPath, conf.Assembly);
                    }

                    var asm = Assembly.LoadFrom(asmPath);
                    if (asm == null)
                    {
                        throw new ApplicationException("Сборка не загружена: " + asmPath);
                    }

                    var type = asm.GetType(conf.Class);
                    if (type == null)
                    {
                        throw new ApplicationException("Тип не найден: " + conf.Class);
                    }

                    var  platform = new LeechPlatform(_tickSource, _instrumBL, _insStoreBL, _engine, _data, _seriesData, _logger);
                    IBot bot      = null;
                    try
                    {
                        bot = Activator.CreateInstance(type, platform) as IBot;
                    }
                    catch (Exception ex)
                    {
                        throw new ApplicationException("Ошибка при создании бота: " + conf.Key, ex);
                    }
                    if (bot == null)
                    {
                        throw new ApplicationException("Бот не создан: " + conf.Key);
                    }

                    var loader    = new BotParamsLoader();
                    var botParams = loader.Load(asmPath, conf.Class);
                    if (loader.Exception != null)
                    {
                        throw new ApplicationException("Ошибка при загрузке файла конфигурации бота: " + conf.Key, loader.Exception);
                    }

                    if (botParams == null)
                    {
                        botParams = loader.Load(conf.InitData);
                        if (loader.Exception != null)
                        {
                            throw new ApplicationException("Ошибка при загрузке данных инициализации бота: " + conf.Key, loader.Exception);
                        }
                    }
                    if (botParams == null)
                    {
                        botParams = new BotParams(null);
                    }

                    try
                    {
                        var botResult = await bot.Initialize(botParams);

                        if (botResult != null && !botResult.IsSuccess)
                        {
                            throw new ApplicationException("Ошибка при инициализации бота: " + botResult.Message);
                        }

                        _bot_platform.Add(bot, platform);
                    }
                    catch (Exception ex)
                    {
                        throw new ApplicationException("Ошибка при инициализации бота: " + conf.Key, ex);
                    }
                }
                catch (Exception ex)
                {
                    throw new ApplicationException("Ошибка при инициализации ботов.", ex);
                }
            }

            int count = await _tickSource.LoadDataAsync();

            return(count > 0);
        }