- Notifications
You must be signed in to change notification settings - Fork32
MOEX API AlgoPack integration with Backtrader. На данных с биржи MOEX теперь можно создавать полноценные торговые стратегии. Проводить Backtesting и делать Live торговлю через брокеров Алор, Финам и тех, у кого есть торговый терминал Quik.
License
WISEPLAT/backtrader_moexalgo
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Интеграция MOEX API AlgoPack сBacktrader.Этот код был написан для ХакатонаGO ALGO организатором которого выступает биржаMOEX.
С помощью этой интеграции вы можете делать:
- Тестирование вашей стратегии на исторических данных с биржиMOEX +Backtrader
- Запускать торговые системы для автоматической торговли на биржеMOEX +Backtrader
- Для Live торговли вам необходимо установить дополнительные бесплатные библиотеки, например:
- брокер Финам:MOEX +Backtrader +FinamPy // Live торговля
- брокер Алор:MOEX +Backtrader +AlorPy // Live торговля
- для ЛЮБОГО брокера, у которого есть терминал Quik:MOEX +Backtrader +QuikPy // Live торговля
- Для Live торговли вам необходимо установить дополнительные бесплатные библиотеки, например:
- Загружать live, исторические данные и Super Candles с биржиMOEX
- Создавать и тестировать свои торговые стратегии пользуясь возможностями библиотекиBacktrader
- Много полезной документации о том, как делать стратегии естьздесь.
Для подключения к API мы используем библиотекуmoexalgo.
Обучающее видео по работе с этой библиотекой можно посмотретьна YouTube ина RuTube
- Самый простой способ:
pip install backtrader_moexalgo
или
git clone https://github.com/WISEPLAT/backtrader_moexalgo
или
pip install git+https://github.com/WISEPLAT/backtrader_moexalgo.git
- Пожалуйста, используйте backtrader из моего репозитория (так как вы можете размещать в нем свои коммиты). Установите его:
pip install git+https://github.com/WISEPLAT/backtrader.git
-- Могу ли я использовать ваш интерфейс для moexalgo с оригинальным backtrader?
-- Да, вы можете использовать оригинальный backtrader, так как автор оригинального backtrader одобрил все мои изменения.
Вот ссылка:mementum/backtrader#472
- У нас есть некоторые зависимости, вам нужно их установить:
pip install numpy pandas backtrader moexalgo requests websockets matplotlib
Чтобы было легче разобраться как всё работает, сделано множество примеров в папкахDataExamplesMoexAlgo_ru иStrategyExamplesMoexAlgo_ru.
Внимание! Для получения Super Candles - необходима авторизация на сайте Московской биржи.1. Активируйте эту строку:store = MoexAlgoStore(login=ConfigMOEX.Login, password=ConfigMOEX.Password)# Хранилище AlgoPack + авторизация на Московской Бирже2. Заполните ваши учетные данные в файле Config.pyclass Config: Login ='<Адрес электронной почты>'# Адрес электронной почты, указанный при регистрации на сайте moex.com Password ='<Пароль>'# Пароль от учетной записи на сайте moex.com
В папкеDataExamplesMoexAlgo_ru находится код примеров по работе с биржевыми данными через API интерфейсMOEX.
- 01 - Symbol.py - торговая стратегия для получения исторических и "живых" данных одного тикера по одному таймфрейму
- Реализована возможность получения Super Candles, свечей с расширенным набором параметров
- 02 - Symbol data to DF.py - экспорт в csv файл исторических данных одного тикера по одному таймфрейму
- 03 - Symbols.py - торговая стратегия для нескольких тикеров по одному таймфрейму
- 04 - Rollover.py - запуск торговой стратегии на склейке данных из файла с историческими данными и последней загруженной истории с брокера
- 05 - Timeframes.py - торговая стратегия для одного тикера по разным таймфреймам
- Strategy.py - Пример торговой стратегии, которая только выводит данные по тикеру/тикерам OHLCV
В папкеStrategyExamplesMoexAlgo_ru находится код примеров стратегий.
01 - Live Trade - broker Alor.py - Пример торговой стратегии в live режиме для тикера SBER - брокер Алор.
- Пример выставления заявок на биржу через брокера Алор и их снятие.
- Пожалуйста, имейте в виду! Это live режим - если на рынке произойдет значительное изменение цены в сторону понижения более чем на 0.5% - ордер может быть выполнен....
- Не забудьте после теста снять с биржи выставленные заявки!
- Пример выставления заявок на биржу через брокера Алор и их снятие.
01 - Live Trade - broker Finam.py - Пример торговой стратегии в live режиме для тикера SBER - брокер Финам.
- Пример выставления заявок на биржу через брокера Финам и их снятие.
- Пожалуйста, имейте в виду! Это live режим - если на рынке произойдет значительное изменение цены в сторону понижения более чем на 0.5% - ордер может быть выполнен....
- Не забудьте после теста снять с биржи выставленные заявки!
- Пример выставления заявок на биржу через брокера Финам и их снятие.
01 - Live Trade - brokers with Quik.py - Пример торговой стратегии в live режиме для тикера SBER - любые брокеры с терминалом Quik.
- Пример выставления заявок на биржу через брокеров с терминалом Quik и их снятие.
- Пожалуйста, имейте в виду! Это live режим - если на рынке произойдет значительное изменение цены в сторону понижения более чем на 0.5% - ордер может быть выполнен....
- Не забудьте после теста снять с биржи выставленные заявки!
- Пример выставления заявок на биржу через брокеров с терминалом Quik и их снятие.
02 - Offline Backtest.py - Пример торговой стратегии для теста на истории - не live режим - для двух тикеров SBER и LKOH.
- В стратегии показано как применять индикаторы (SMA, RSI) к нескольким тикерам одновременно.
- Не live режим - для тестирования стратегий без отправки заявок на биржу!
- В стратегии показано как применять индикаторы (SMA, RSI) к нескольким тикерам одновременно.
03 - Offline Backtest MultiPortfolio.py - Пример торговой стратегии для теста на истории - не live режим - для множества тикеров, которые можно передавать в стратегию списком (SBER, LKOH, AFLT, GMKN).
- В стратегии показано как применять индикаторы (SMA, RSI) к нескольким тикерам одновременно.
- Не live режим - для тестирования стратегий без отправки заявок на биржу!
- В стратегии показано как применять индикаторы (SMA, RSI) к нескольким тикерам одновременно.
04 - Offline Backtest Indicators.py - Пример торговой стратегии для теста на истории с использованием индикаторов SMA и RSI - не live режим - для двух тикеров SBER и LKOH.
- В стратегии показано как применять индикаторы (SMA, RSI) к нескольким тикерам одновременно.
- генерит 177% дохода на момент записи видео ))
- Не live режим - для тестирования стратегий без отправки заявок на биржу!
- В стратегии показано как применять индикаторы (SMA, RSI) к нескольким тикерам одновременно.
- backtrader: очень простая и классная библиотека!
- Команде разработчиков MOEXmoexalgo: Для создания оболочки MOEX API, сокращающей большую часть работы.
- Игорю Чечету: за классные бесплатные библиотеки для live торговли реализующие подключения к брокерам
Исправление ошибок, доработка и развитие библиотеки осуществляется автором и сообществом!
Пушьте ваши коммиты!
Библиотека backtrader_moexalgo позволяющая делать интеграцию Backtrader и MOEX API - этоПрограмма созданная исключительно для удобства работы.При использованииПрограммы Пользователь обязан соблюдать положения действующего законодательства Российской Федерации или своей страны.ИспользованиеПрограммы предлагается по принципу «Как есть» («AS IS»). Никаких гарантий, как устных, так и письменных не прилагается и не предусматривается.Автор и сообщество не дает гарантии, что все ошибкиПрограммы были устранены, соответственно автор и сообщество не несет никакой ответственности запоследствия использованияПрограммы, включая, но, не ограничиваясь любым ущербом оборудованию, компьютерам, мобильным устройствам,программному обеспечению Пользователя вызванным или связанным с использованиемПрограммы, а также за любые финансовые потери,понесенные Пользователем в результате использованияПрограммы.Никто не ответственен за потерю данных, убытки, ущерб, включаю случайный или косвенный, упущенную выгоду, потерю доходов или любые другие потери,связанные с использованиемПрограммы.
Программа распространяется на условиях лицензииMIT.
Пожалуйста, поставьте Звезду 🌟 этому коду
Please, put a Star 🌟 for this code
==========================================================================
MOEX API integration withBacktrader.This code was written forGO ALGO Hackathon, organized by theMOEX exchange.
With this integration you can do:
- Backtesting your strategy on historical data from the exchangeMOEX +Backtrader // Backtesting
- Launch trading systems for automatic trading on the exchangeMOEX +Backtrader // Live trading
- For Live trading you need install free additional libraries, like these:
- broker Finam:MOEX +Backtrader +FinamPy // Live trading
- broker Alor:MOEX +Backtrader +AlorPy // Live trading
- ANY broker with the use of Quik terminal:MOEX +Backtrader +QuikPy // Live trading
- For Live trading you need install free additional libraries, like these:
- Download live, historical data and Super Candles for tickers from the exchangeMOEX
- Create and test your trading strategies using the library's featuresBacktrader
- There is a lot of useful documentation on how to make strategies(see here).
For API connection we are using librarymoexalgo.
A tutorial video with this library can be viewedon YouTube andon RuTube
- The simplest way:
pip install backtrader_moexalgo
or
git clone https://github.com/WISEPLAT/backtrader_moexalgo
or
pip install git+https://github.com/WISEPLAT/backtrader_moexalgo.git
- Please use backtrader from my repository (as your can push your commits in it). Install it:
pip install git+https://github.com/WISEPLAT/backtrader.git
-- Can I use your interface for moexalgo with original backtrader?
-- Yes, you can use original backtrader, as the author of original backtrader had approved all my changes.
Here is the link:mementum/backtrader#472
- We have some dependencies, you need to install them:
pip install numpy pandas backtrader moexalgo requests websockets matplotlib
To make it easier to figure out how everything works, many examples have been made in the foldersDataExamplesMoexAlgo andStrategyExamplesMoexAlgo.
Attention! To receive Super Candles, you need to login to the Moscow Exchange website.1. Activate this line:store = MoexAlgoStore(login=ConfigMOEX.Login, password=ConfigMOEX.Password)# Storage AlgoPack + authorization on the Moscow Stock Exchange2. Fillin your credentialsin the file Config.pyclass Config: Login ='<Email address>'# The email address provided during registration on the site moex.com Password ='<Password>'# The password for the account on the site moex.com
TheDataExamplesMoexAlgo folder contains the code of examples for working with exchange data via theMOEX API.
- 01 - Symbol.py - trading strategy for obtaining historical and "live" data of one ticker for one timeframe
- The possibility of obtaining Super Candles, candles with an extended set of parameters is implemented
- 02 - Symbol data to DF.py - export to csv file of historical data of one ticker for one timeframe
- 03 - Symbols.py - trading strategy for multiple tickers on the same timeframe
- 04 - Rollover.py - launch of a trading strategy based on gluing data from a file with historical data and the last downloaded history from the broker
- 05 - Timeframes.py - trading strategy is running on different timeframes.
- Strategy.py - An example of a trading strategy that only outputs data of the OHLCV for ticker/tickers
TheStrategyExamplesMoexAlgo folder contains the code of sample strategies.
01 - Live Trade - broker Alor.py - An example of a live trading strategy for SBER ticker - broker Alor.
- Example of placing and cancel orders on the exchange with the use of broker Alor.
- Please be aware! This is Live order - if market has a big change down in value of price more than 0.5% - the order will be completed....
- Do not forget to cancel the submitted orders from the exchange after the test!
- Example of placing and cancel orders on the exchange with the use of broker Alor.
01 - Live Trade - broker Finam.py - An example of a live trading strategy for SBER ticker - broker Finam.
- Example of placing and cancel orders on the exchange with the use of broker Finam.
- Please be aware! This is Live order - if market has a big change down in value of price more than 0.5% - the order will be completed....
- Do not forget to cancel the submitted orders from the exchange after the test!
- Example of placing and cancel orders on the exchange with the use of broker Finam.
01 - Live Trade - broker brokers with Quik.py - An example of a live trading strategy for SBER ticker - any brokers with terminal Quik.
- Example of placing and cancel orders on the exchange with the use of broker with terminal Quik.
- Please be aware! This is Live order - if market has a big change down in value of price more than 0.5% - the order will be completed....
- Do not forget to cancel the submitted orders from the exchange after the test!
- Example of placing and cancel orders on the exchange with the use of broker with terminal Quik.
02 - Offline Backtest.py - An example of a trading strategy on a historical data - not live mode - for two SBER and LKOH tickers.
- The strategy shows how to apply indicators (SMA, RSI) to several tickers at the same time.
- Not a live mode - for testing strategies without sending orders to the exchange!
- The strategy shows how to apply indicators (SMA, RSI) to several tickers at the same time.
03 - Offline Backtest MultiPortfolio.py - An example of a trading strategy on a historical data - not live mode - for a set of tickers that can be transferred to the strategy in a list (SBER, LKOH, AFLT, GMKN).
- The strategy shows how to apply indicators (SMA, RSI) to several tickers at the same time.
- Not a live mode - for testing strategies without sending orders to the exchange!
- The strategy shows how to apply indicators (SMA, RSI) to several tickers at the same time.
04 - Offline Backtest Indicators.py - An example of a trading strategy for a history test using SMA and RSI indicators - not live mode - for two SBER and LKOH tickers.
- The strategy shows how to apply indicators (SMA, RSI) to several tickers at the same time.
- generates 177% of revenue at the time of video recording))
- Non-live mode - for testing strategies without sending orders to the exchange!
- The strategy shows how to apply indicators (SMA, RSI) to several tickers at the same time.
- backtrader: Very simple and cool library!
- Team of MOEXmoexalgo: For creating MOEX API wrapper, shortening a lot of work.
- Igor Chechet: for free cool libraries for live trading by connection to brokers
Error correction, revision and development of the library is carried out by the author and the community!
Push your commits!
The backtrader_moexalgo library, which allows you to integrate Backtrader and MOEX API, is theProgram created solely for the convenience of work.When using theProgram, the User is obliged to comply with the provisions of the current legislation of his country.Using theProgram are offered on an "AS IS" basis. No guarantees, either oral or written, are attached and are not provided.The author and the community does not guarantee that all errors of theProgram have been eliminated, respectively, the author and the community do not bear any responsibility forthe consequences of using theProgram, including, but not limited to, any damage to equipment, computers, mobile devices,User software caused by or related to the use of theProgram, as well as for any financial lossesincurred by the User as a result of using theProgram.No one is responsible for data loss, losses, damages, including accidental or indirect, lost profits, loss of revenue or any other lossesrelated to the use of theProgram.
TheProgram is distributed under the terms of theMIT license.
About
MOEX API AlgoPack integration with Backtrader. На данных с биржи MOEX теперь можно создавать полноценные торговые стратегии. Проводить Backtesting и делать Live торговлю через брокеров Алор, Финам и тех, у кого есть торговый терминал Quik.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.