diff --git a/README.md b/README.md index 9446e0e..e2d1644 100644 --- a/README.md +++ b/README.md @@ -3018,6 +3018,27 @@ TKSBrokerAPI.py L:1922 INFO [2022-08-23 17:35:59,958] Statistics of clien +Как вы могли заметить, в примере выше фактически написан линейный скрипт, последовательно выполняющий торговый сценарий. Параметризация происходит в начале скрипта, далее идут множество торговых шагов-команд. То есть используется классическая императивная парадигма программирования. Из плюсов такого подхода, что логика торгового сценария описывается в скрипте подряд, шаг за шагом, и сразу видно, что и для чего выполняется. Если сценарий простой, можно окинуть взглядом его код целиком. Этот же плюс становится минусом, когда логика торгового сценария слишком сложная, с множеством ветвлений. В этом случае скрипт может превратиться в "портянку" трудно-читаемого кода. + +Если вы поклонник больше объектно-ориентированного подхода к программированию, тот же самый сценарий можно реализовать классами. При этом исчезнет предыдущий минус: логика отдельных шагов будет вынесена в методы класса, что упростит их отладку, а финальный сценарий торговых шагов можно будет описать короткими конструкциями вида `if ... else`. + +В этом случае лучше создать унаследованный от основного API-класса `TinkoffBrokerServer()` класс `TradeScenario(TinkoffBrokerServer)`. В качестве полей класса можно взять имена констант из первого примера, написать отдельные методы для каждого шага и логических проверок, и затем объединить вызов всех условий и торговых операций в методе `run()`. В основном блоке `if __name__ == "__main__:"` при запуске скрипта будет достаточно создать экземпляр класса-сценария и параметризовать его константами из первого примера, а затем вызвать метод `run()`. + +Пример первого торгового сценария, переписанный классами, можно посмотреть под спойлером ниже. Не забудьте при инициализации класса указать свой token и accountId (см. раздел ["Аутентификация"](#Аутентификация)). + +
+ Торговый сценарий для платформы TKSBrokerAPI (вариант с классом для торгового сценария) + +Скачать скрипт можно здесь: [./docs/examples/scenario1a.py](./docs/examples/scenario1a.py) + +```python + +``` + +
+ +Вывод скрипта в консоль будет полностью аналогичен, как в первом примере. + На этом всё, вопросы задавайте в разделе 👉 [**Issues**](https://github.com/Tim55667757/TKSBrokerAPI/issues/new) 👈, пожалуйста. diff --git a/README_EN.md b/README_EN.md index 9ac9bb4..7daa388 100644 --- a/README_EN.md +++ b/README_EN.md @@ -2783,7 +2783,7 @@ In this documentation, we do not want to focus on specific trading scenarios, bu To understand the example, just save and run the script under the spoiler below. Before doing this, don't forget to get a token and find out your accountId (see the section ["Auth"](#Auth)). Most of the code is commented in detail and links to the relevant API methods are given.
- Example of trading script in Python using TKSBrokerAPI + Example of trading script in Python using TKSBrokerAPI platform Download script here: [./docs/examples/scenario1.py](./docs/examples/scenario1.py) @@ -2995,6 +2995,27 @@ TKSBrokerAPI.py L:1922 INFO [2022-08-23 17:35:59,958] Statistics of clien
+As you can see, in the example above, a linear script is actually written that sequentially executes the trading script. Parameterization occurs at the beginning of the script, then there are many trading steps and commands. That is, the classical imperative programming paradigm is used. One of the advantages of this approach is that the logic of the trading scenario is described step by step, and you can see what is being done and why. If the trade logic is simple, you can take a look all code on one screen. The same plus becomes a minus when the logic of the trading scenario is too complicated, with many variances. In this case, the script can turn into a "footcloth" of hard-to-read code. + +If you're more of an object oriented programming fan, the same scenario can be implemented with classes. At the same time, the previous disadvantage will disappear: the logic of individual steps will be moved to class methods, which will simplify their debugging, and the final scenario of trading steps can be described with short constructions like `if ... else`. + +In this case, it is better to create a class `TradeScenario(TinkoffBrokerServer)` inherited from the main API class `TinkoffBrokerServer()`. As class fields, you can take the names of constants from the first example, write separate methods for each step and logical checks, and then combine the call of all conditions and trading operations in the `run()` method. In the main block `if __name__ == "__main__:"` when running the script, it will be enough to create an instance of the class and initialize it with constants from the first example, and then just call the `run()` method. + +Trading script from the first example, rewritten with classes, can be viewed under the spoiler below. Don't forget to set up your token and accountId when class initialization (see the section ["Auth"](#Auth)). + +
+ Trading script for the TKSBrokerAPI platform (version with a class for a trading scenario) + +Download script here: [./docs/examples/scenario1a.py](./docs/examples/scenario1a.py) + +```python + +``` + +
+ +Вывод скрипта в консоль будет полностью аналогичен, как в первом примере. + That's all, ask questions in the section 👉 [**Issues**](https://github.com/Tim55667757/TKSBrokerAPI/issues/new) 👈, please.