Skip to content

Latest commit

 

History

History
 
 

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

README.md

Anomaly Volumes Detector

Документация на русском

TKSBrokerAPI-Logo

Technologies · Knowledge · Science

task gift

Acknowledgements

Description

Anomaly Volumes Detector is a simple Telegram bot, based on the TKSBrokerAPI platform, for detecting anomaly volumes in Buyers and Sellers orders.

The bot monitors the volumes of Buyers and Sellers in the orders book (DOM), looks for anomalies in the number series of volumes and notifies in Telegram. The notification contains: the current price and prices with anomaly volumes.

The following screenshot illustrates the Depth of Market with the volumes of offers of buyers and sellers, which a trader can visually take as anomalies:

AnomalyVolumes-example

Concept

Main steps:

  • The script enters the market on schedule, e.g. crontab format: timeToWork: "*/2 10-21 * * 1-5" (at every 2nd minute past every hour from 10 through 22 (including) on every day-of-week from Monday through Friday). See also another examples.

  • In a parallel (multiprocessing) conveyor mode, it requests data on the state of the order book for the specified instruments and with the specified depth of the order book (depth <= 50).

  • For each order book, it searches for all current anomalies in the volumes of Sellers and Buyers (filtering by Hampel method along the entire length of the current DOM).

  • If the list of anomalies is not empty, then script generates a human-readable message, for example:

    Anomalous volumes detected
    of Sellers and Buyers:
      - [YNDX] [Shares] [Yandex]
      - Date and time:
        2023-01-29 14:51:54 UTC
      - Is in portfolio: No
    
    - Current price/volume/value
      - Buy (1st seller price):
        [0] 1928.1/5/9640.5 rub
      - Sell (1st buyer price):
        [0] 1916.4/3/5749.2 rub
    
    - Anomaly, price/volume/value
      - in sellers volumes: 
        [5] 1929.1/6/11574.6 rub
        [14] 1930.9/6/11585.4 rub
      - in buyers volumes: 
        [0] 1916.4/3/5749.2 rub
        [1] 1916.2/6/11497.2 rub
    
    Generated by ⚙️ TKSBrokerAPI
    
  • Connect to the specified TG-bot by token and send a notification through it.

    AnomalyVolumesDetector-example

Bot launch

All parameters are configured in two configuration files: config.yaml and secrets.yaml, which must be present next to the script TKSAVDetector.py.

The script works with python >= 3.9, and dependencies from requirements.txt must also be installed. Steps to start on a new server:

git clone https://github.com/Tim55667757/TKSBrokerAPI.git
cd TKSBrokerAPI
git branch
git checkout -f develop
git pull
cd ./docs/examples/AnomalyVolumesDetector
python3 -m pip install -r requirements.txt
python3 TKSAVDetector.py config.yaml secrets.yaml

If you're using default names config.yaml and secrets.yaml, then they can be omitted in python3 TKSAVDetector.py command.

Auth

All critical secrets must store locally in secrets.yaml file. You can define there some parameters:

  • userToken — place here the Tinkoff Investment API token (t.*****) or stay it empty and use TKS_API_TOKEN environment variable;
  • userAccount — place here the accountId of Tinkoff Investment broker account or stay it empty and use TKS_ACCOUNT_ID environment variable;
  • botToken — place here TG bot token (******:***) or stay it empty and use TKS_BOT_TOKEN environment variable;
  • chatId — Telegram Chat ID with authorized user for sending messages.

How to create the Tinkoff Investment API token see here. After creating token, store it to userToken variable in secrets.yaml or in TKS_API_TOKEN environment variable.

You can find accountId number using the TKSBrokerAPI platform with command: tksbrokerapi --accounts and then store it to userAccount variable in secrets.yaml or in TKS_ACCOUNT_ID environment variable.

How to create new Telegram bot and receive token see here. After creating bot, store its token to botToken variable in secrets.yaml or in TKS_BOT_TOKEN environment variable. See also, Telegram auth and some examples.

How you can find Chat ID for chatId variable:

Methods

  • The ConfigDecorator() method is a wrapper (decorator) for loading configuration files and secrets, controlling the start time of iterations on a schedule, for a single run or in infinite mode, as well as for parameterizing the Trade Manager.

    • Decorator ConfigDecorator():
      • loads settings from configuration files,
      • checks the number of CPU available for parallelization,
      • checks if it's working time (according to crontab settings),
      • launches the Trade Manager once or in infinite mode.
  • The TradeManager() method is a manager for initializing, launching and managing parallel pipelines, which will analyze the state of the order book for a specific set of tickers.

    • Manager TradeManager():
      • initializes the reporter (an instance of the TinkoffBrokerServer() class for generating reports),
      • updates the cache for instruments once and gets the user's portfolio so that they are not updated on each pipeline once again,
      • starts iteration over all tickers, splits them into sets,
      • each set sends to its own pipeline for parallelization.
  • The TradeScenario() class contains methods for implementing the trading scenario logic. It has two important methods: Run() and Steps().

    • Run() is a runner of trade steps for all given instruments tickers.
    • Steps() is a section for implementing the steps of the trading scenario for one current instrument.

🚀 Good luck for you in trade automation! And profit!

gift


Детектор аномальных объёмов

See doc in English

TKSBrokerAPI-Logo

Technologies · Knowledge · Science

task gift

Благодарности

Описание

Детектор аномальных объёмов — это простой Телеграм бот для анализа объёмов спроса и предложения покупателей и продавцов.

Бот следит за объёмами покупателей и продавцов в биржевом стакане, ищет аномалии в числовом ряду объёмов и оповещает о них в Телеграм. Оповещение содержит: текущую цену инструмента и цены с аномальными объёмами.

Следующий скриншот иллюстрирует стакан цен с объёмами предложений продавцов и покупателей, которые трейдер визуально может принять за аномалии:

AnomalyVolumes-example

Концепция

Основные шаги:

  • Скрипт выходит на рынок по расписанию, например, в формате crontab: timeToWork: "*/2 10-21 * * 1-5" (c 10:00 утра до 22:00 вечера (включительно) в будние дни, каждые 2 минуты). Можете посмотреть другие примеры.

  • В параллельном (мультипроцессном) конвейерном режиме скрипт запрашивает данные по состоянию биржевого стакана по указанным инструментам и с указанной глубиной стакана (depth <= 50).

  • Для каждого стакана скрипт ищет все текущие аномалии в объёмах продавцов и покупателей (фильтрация методом Хампеля по всей длине текущего стакана).

  • Если список аномалий по инструменту получился не пустой, то скрипт формирует оповещение, например, такого вида:

    Обнаружены аномальные объёмы
    продавцов и покупателей:
      - [YNDX] [Shares] [Yandex]
      - Время обнаружения:
        2023-01-29 14:49:31 UTC
      - Есть в портфеле: Нет
    
    - Текущая цена/объём/стоимость
      - Купить:
        [0] 1927.6/4/7710.4 руб
      - Продать:
        [0] 1915.9/4/7663.6 руб
    
    - Аномалии
      - в объёмах продавцов: 
        [0] 1927.6/4/7710.4 руб
        [3] 1928.2/6/11569.2 руб
      - в объёмах покупателей: 
        [0] 1915.9/4/7663.6 руб
        [1] 1915.7/6/11494.2 руб
    
    Сгенерировано ⚙️ TKSBrokerAPI
    
  • Скрипт подключается к указанному ТГ-боту по токену и отправляет через него оповещение.

    AnomalyVolumesDetector-example

Запуск бота

Все параметры настраиваются в двух конфигурационных файлах: config.yaml и secrets.yaml, которые должны присутствовать рядом со скриптом TKSAVDetector.py.

Скрипт работает с python >= 3.9, а также должны быть установлены зависимости из requirements.txt. Шаги для запуска на новом сервере:

git clone https://github.com/Tim55667757/TKSBrokerAPI.git
cd TKSBrokerAPI
git branch
git checkout -f develop
git pull
cd ./docs/examples/AnomalyVolumesDetector
python3 -m pip install -r requirements.txt
python3 TKSAVDetector.py config.yaml secrets.yaml

Если используются дефолтные файлы конфигурации config.yaml и secrets.yaml, то в команде python3 TKSAVDetector.py их можно не указывать.

Авторизация

Все критичные секреты должны храниться локально в файле secrets.yaml. Вы можете определить там некоторые параметры:

  • userToken — укажите здесь свой API-токен от Тинькофф Инвестиции (t.*****) или оставьте пустую строку и используйте переменную окружения TKS_API_TOKEN;
  • userAccount — укажите здесь свой accountId, это счёт пользователя в Тинькофф Инвестиции, или оставьте пустую строку и используйте переменную окружения TKS_ACCOUNT_ID;
  • botToken — укажите здесь токен от вашего Телеграм-бота (******:***) или оставьте пустую строку и используйте переменную окружения TKS_BOT_TOKEN;
  • chatId — укажите здесь ID номер Телеграм-чата, где вы авторизовали бота для отправки сообщений.

Как создать API-токен в Тинькофф Инвестиции, смотрите по ссылке. После создания токена, сохраните его в переменной userTokensecrets.yaml) или в переменной окружения TKS_API_TOKEN.

Вы можете найти номер своего аккаунта accountId используя команду платформы TKSBrokerAPI: tksbrokerapi --accounts. После этого сохраните его в переменной userAccountsecrets.yaml) или в переменной окружения TKS_ACCOUNT_ID.

Как создать нового Телеграм-бота и получить токен для него, смотрите по ссылке. После создания бота сохраните его токен в переменной botTokensecrets.yaml) или в переменной окружения TKS_BOT_TOKEN. Смотрите также примеры, как авторизоваться в Телеграм для отправки сообщений.

Как вы можете найти ID чата с ботом для переменной chatId:

  • когда бот будет создан, вы узнаете и сохраните его токен;
  • подключитесь к боту и авторизуйте его в Telegram командой /start, чтобы он мог отправлять вам сообщения;
  • отправьте любое сообщение боту;
  • подставьте свой токен и перейдите в браузере по ссылке вида: https://api.telegram.org/bot<положите_сюда_свой_токен>/getUpdates
  • в тексте ответа от сервера Телеграм найдите ваше сообщение и рядом с ним будет параметр id, который является искомым значением для переменной chatId.

Основные методы

  • Метод ConfigDecorator() — это обёртка (декоратор) для загрузки файлов конфигурации и секретов, управления временем запуска итераций по расписанию, для однократного запуска или в бесконечном режиме, а также для параметризации менеджера.

    • Декоратор ConfigDecorator():
      • загружает настройки из файлов конфигурации,
      • проверяет количество доступных для распараллеливания запросов CPU,
      • проверяет рабочее ли сейчас время (согласно настройкам crontab),
      • однократно или в бесконечном режиме запускает менеджер.
  • Метод TradeManager() — это менеджер для инициализации, запуска и управления параллельными конвейерами, на которых будет исполняться анализ состояния стакана для конкретного набора тикеров.

    • Менеджер TradeManager():
      • инициализирует репортер (экземпляр класса TinkoffBrokerServer() для генерации отчётов),
      • однократно обновляет кеш по инструментам и получает портфель пользователя, чтобы они не обновлялись на каждом конвейере лишний раз,
      • запускает итерацию по всем тикерам, разбивает их на наборы,
      • каждый набор отправляет на свой конвейер для параллелизации.
  • Класс TradeScenario() содержит методы для реализации логики торгового сценария. Он содержит два основных метода: Run() и Steps().

    • Run() — это метод для запуска сценария итеративно по всем указанным тикерам инструментов.
    • Steps() — это раздел с описанием, реализацией и запуском отдельных шагов торгового сценария для одного указанного инструмента.

🚀 Успехов вам в автоматизации биржевой торговли! И профита!

gift