Coder Social home page Coder Social logo

invest-bot's Introduction

Trading bot based on Tinkoff Invest Python gRPC client API

Project Status

The project status is an example of trading bot and isn't ready for any production using. The provided trade strategy is just an example and have negative profit by the end.

Description

Here is trading bot for MOEX Exchange with ability to send information about trading to a telegram chat. The bot is using Tinkoff Invest Python gRPC client api.

Features

  • Trading RUB stocks via Тинькофф Инвестиции on MOEX Exchange
  • Ability to use personal trade strategy for every stock
  • Trade information sends to a telegram chat (orders details, trade day summary etc.)

Note: trade strategy is represented in code is just example and not a trade or invest recommendation.

Before Start

Dependencies

$ pip install tinkoff-investments
$ pip install -U aiogram

Brokerage account

Open brokerage account Тинькофф Инвестиции and top up your account:

  1. "Margin trading" must be enabled

Do not forget to take TOKEN for API trading.

Telegram (optional)

Register your bot via @BotFather.

Create a chat and get chat_id.

PS. Please use Google to find detailed instruction how to get chat_id.

Required configuration (minimal)

  1. Open settings.ini file
  2. Specify token for trade API in TOKEN (section INVEST_API)
  3. (Optinal) Specify token for a telegram bot in TELEGRAM_BOT_TOKEN (section BLOG)
  4. (Optinal) Specify id of a telegram chat in TELEGRAM_CHAT_ID (section BLOG)

Run

Recommendation is to use python 3.10 (bot has been tested on 3.10 version include real trading).

Run main.py

Configuration

Configuration can be specified via settings.ini file.

Section INVEST_API

Token and app name for Тинькофф Инвестиции api.

Section BLOG

  • status - telegram working mode:
    • 0 - disabled
    • 1 - enabled
  • token and chat id for telegram api

Section TRADING_ACCOUNT

Minimal amount of rub on account for start trading.

Section TRADING_SETTINGS

Settings for time management. Bot trades only in main trade session. Bot ignore pre\post market etc.

Section Strategies

Settings for trade strategies.

Section STRATEGY_ticker_name:

  • STRATEGY_NAME - name of algorithm
  • TICKER - ticker name (human-friendly name for telegram messages)
  • FIGI - figi of stock. Required for API
  • MAX_LOTS_PER_ORDER - Maximum count of lots per order

Section STRATEGY_ticker_name_SETTINGS:

Detailed settings for strategy. Strategy class reads and parses settings manually.

Note: Only one strategy for one stock in configuration.

Trading on stocks exchange

Before start:

  • Token verification
  • Appropriate account selects automatically by token
  • By trading schedule, bot selects time to start trading (start main trading session)

Main session:

  • Bot checks:
    • stock status for every stock (list of strategies from configuration)
    • minimum amount of rub on account
  • Starts gRPC stream for data from API
  • Strategies analyse candles and return signals if needed
  • Bot opens orders by signals from strategies
  • If stop or take price levels are confirmed, bot closes orders

Trading schedule:

  • Bot awaits start and end of main trading session
  • Bot works every trade day
  • Restart doesn't require for trading. Only in emergency situations.

How to add a new strategy

  • Write a new class with trade logic
  • The new class must have IStrategy as super class
  • Give a name for the new class
  • Extend StrategyFactory class by the name and return the new class by the name
  • Specify new settings in settings.ini file. Put the new class name in STRATEGY_NAME
  • Test the new class on historical candles

Telegram messages

Information about:

  • Trading day summary at start and list of stocks
  • Open and close orders, take profit and stop loss price levels
  • Trading day summary in the end of day

Telegram messages are optional and can be disabled without any effect on trading.

Logging

All logs are written in logs/robot.log. Any kind of settings can be changed in main.py code

Project change log

Here

Disclaimer

The author is not responsible for any errors or omissions, or for the trade results obtained from the use of this bot.

invest-bot's People

Contributors

eidiamond avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

invest-bot's Issues

Margin trading

the bot does not trade with leverage, if for example the bot trades with 5x leverage, 1x, then why set up a minimum liquid portfolio? I set the maximum number of lots with the condition of margin trading, but he buys less, maybe
Screenshot_2023-09-27-12-16-11-774_ru tinkoff investing
Screenshot_2023-09-27-12-16-46-632_com google chromeremotedesktop
Screenshot_2023-09-27-12-17-20-549_ru tinkoff investing
I’m doing something wrong?

Нужна помощь со стратегией

Здраствуйте, я к сожалению еще не знаю python на достаточно хорошем уровне и поэтому прошу помощи. У меня есть стратегия из другого бота - IntervalStrategy (https://github.com/qwertyo1/tinkoff-trading-bot). Если кому не сложно, можете помочь с тем чтобы изменить код так что бы это заработало. Могу дать на чай рублей 300. Заранее спасибо за ответ. Мой тг @liddel_off

market_data_stream_service - ERROR

Во время работы бота происходят ошибки. Что сделать что бы их не было?
Windows 10 Pro 22H2 19045.3448
Python 3.11.5
tinkoff-investments 0.2.0b60
aiogram 3.0.0
Интернет подключен через WiFi адаптер

Errors occur while the bot is running. What can be done to prevent them from happening?
Windows 10 Pro 22H2 19045.3448
Python 3.11.5
tinkoff-investments 0.2.0b60
aiogram 3.0.0
Internet connected via WiFi adapter

https://www.speedtest.net/result/15325988382.png

Будет ли это работать?

Я добавил досрочное закрытие позиции и открытие новой если появляется противоположный сигнал и профит больше 0.
trader.txt

Trading error: AioRequestError

Я дописываю этого бота под свои нужды. Оставил подписку на минутные свечи для работы стоплосса, соответственно, класс MarketDataStream я не трогал, но при получении новой свечи стратегия скачивает ещё 3 набора исторических данных. Вроде бы ошибка связана с этим, с превышением лимита запросов в минуту, но 1) как посчитать запросы я пока не понимаю 2) ошибка происходит на следующий день или через день, примерно в 10:15. Т.е. примерно 15 минут бот работает нормально.

trader - ERROR - trade_day: 85 - Trading error: AioRequestError(<StatusCode.UNKNOWN: (2, 'unknown')>, 'Stream removed', Metadata(tracking_id='c2b97145c0fe9d1d71e3d1b332d95654', ratelimit_limit='600, 600;w=60', ratelimit_remaining=598, ratelimit_reset=56, message=None))

P.S. Комменты в коде на английском это странно.

Контакт для связи

Добрый день!

Меня зовут Юрий, из Тиньков public invest API.

Мы сейчас пишем ряд статей на хабр про торговых роботов, и в статье про пайтон, хотели бы указать Вас как автора одного из наиболее качественных роботов, и ваш репозиторий как пример торгового робота. Как вы на это смотрите?
Не могли бы вы оставить email или телеграмм для связи?

Не работает телеграмм

Не работает отправка сообщений в телеграмм. Я пробовал писать /start до и во время работы. Я пересоздавал токен, я пересоздавал бота. Chat_id я получил из @getidsbot. В логах нет ошибок.

Вопрос

MAX_LOTS_PER_ORDER
Что делает эта настройка?
я сначала думал что это кол во лотов за ордер ( а максимальное колличество рассчитывается исходя из баланса), но моя теория не подтвердилась. я выставил 1 вместо 3, и после сигнала 2й лот не докупился. можете реализовать логику работы при которой можно выбрать максимальное колличество лотов и колличество лотов покупаемых при сигнале. например, максимум лотов 5, а за раз 1 , поступает 3 сигнала long, и покупается по одному лоту 3 раза. это бы очень сильно улучшило работу различных стратегий ( из за того что был бы меньше минус, появилось бы возможность усреднения, и тд)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.