tksbrokerapi.TKSBrokerAPI
Technologies · Knowledge · Science
TKSBrokerAPI is the trading platform for automation and simplifying the implementation of trading scenarios,
as well as working with Tinkoff Invest API server via the REST protocol. The TKSBrokerAPI Platform may be used in two ways:
from the console, it has a rich keys and commands, or you can use it as Python module with python import
.
TKSBrokerAPI allows you to automate routine trading operations and implement your trading scenarios, or just receive the necessary information from the broker. It is easy enough to integrate into various CI/CD automation systems.
See also:
- Open account for trading: https://tinkoff.ru/sl/AaX1Et1omnH
- TKSBrokerAPI Platform documentation: https://tim55667757.github.io/TKSBrokerAPI/docs/tksbrokerapi/TKSBrokerAPI.html
- CLI examples: https://github.com/Tim55667757/TKSBrokerAPI/blob/master/README_EN.md#Usage-examples
- Used constants are in the TKSEnums module: https://tim55667757.github.io/TKSBrokerAPI/docs/tksbrokerapi/TKSEnums.html
- About Tinkoff Invest API: https://tinkoff.github.io/investAPI/
- Tinkoff Invest API documentation: https://tinkoff.github.io/investAPI/swagger-ui/
- How to implement trading scenario in Python: https://github.com/Tim55667757/TKSBrokerAPI/blob/master/README_EN.md#Module-import
Using the TKSBrokerAPI Platform,
you can implement any trading scenario in Python. Many system used for making trading decisions about buying or selling
(technical analysis, neural networks, parsing reports or tracking other traders’ transactions), but you still need
to perform trading operations: place orders, open and close transactions. The TKSBrokerAPI
module will act as an
intermediary between the code with the trading logic and services infrastructure of the Tinkoff Investments broker,
as well as perform routine tasks on your behalf in brokerage account.
The scheme of trade scenario automation with TKSBrokerAPI is very simple:
- You come up with a brilliant trading algorithm.
- Write it down step by step in the form of some kind of plan or trading scenario.
- Automate scenario as a Python script using TKSBrokerAPI.
- TKSBrokerAPI takes care of all the work with the Tinkoff Investments broker infrastructure.
- Profit!
But where to get this "brilliant trading algorithm"? The TKSBrokerAPI Platform will also help you solve the problem of obtaining primary, "raw" data on trading instruments (shares, bonds, funds, futures and currencies) from the broker server, for their future analysis in any analytical tool convenient for you. To do this, the methods of the TKSBrokerAPI module provide the ability to extend and save data in classic formats: XLSX and CSV (for analysis in spreadsheet editors), Markdown (for readability), and Pandas DataFrame (for data scientists and stock analysts).
The "raw" data can be anything that can be obtained from the broker's server. After extends, this data can be used to build, for example, a consolidated payment calendar for bonds and calculate their coupon and current yields, or you can generate analytics about the status of the user's portfolio and the distribution of assets by types, companies, industries, currencies, and countries. In addition, you can download historical data on the prices of any instrument as OHLCV-candlesticks.
How data is extended and used in TKSBrokerAPI Platform:
- You request the data you need from the Tinkoff Investments broker server:
- in this module, almost all methods return "raw" data from the server in the form of a Python dictionary.
- Then they are processed and extended:
- with various statistics, parameters and some analytical reports.
- After that, the data is stored in a form suitable for further analysis:
- most of the methods return extended data in the form of a Python dictionary or Pandas DataFrame;
- if you launched the TKSBrokerAPI platform in the console, then the data will be saved in XLSX, CSV or Markdown formats.
- Next, you can load the data into analytical system and use various data analysis methods to find and highlight dependencies, correlations, make predictions and suggest hypothesis.
- Further, based on data analysis, you come up with the same "brilliant trading algorithm".
- Automate the trading scenario (according to the previous scheme).
- Profit!
Initialize RateLimiter with given method limits (requests per minute).
Parameters
- methodLimits: dict[str, int] with per-method RPM limits.
This class implements methods to work with Tinkoff broker server.
Examples to work with API: https://tinkoff.github.io/investAPI/swagger-ui/
About token
: https://tinkoff.github.io/investAPI/token/
Main class init.
Parameters
- token: Bearer token for Tinkoff Invest API. It can be set from environment variable
TKS_API_TOKEN
. - accountId: string with numeric user account ID in Tinkoff Broker. It can be found in broker's reports.
Also, this variable can be set from environment variable
TKS_ACCOUNT_ID
. - useCache: use default cache file with raw data to use instead of
iList
.True
by default. Cache is auto-update if new day has come. If you don't want to use cache and always updates raw data then setuseCache=False
. - defaultCache: path to default cache file.
dump.json
by default. - moreDebug: if
True
, enables detailed debug-level logging for API requests, data processing, history segmentation, and other internal stages. Useful for development and diagnostics.False
by default.
Enables more debug information in this class, such as net request and response headers in all methods. False
by default.
RateLimiter object to work with given method limits (requests per minute) from TKS_METHOD_LIMITS
.
Current TKSBrokerAPI Platform version: major.minor, but the build number define at the build-server only.
Latest version: https://pypi.org/project/tksbrokerapi/
Depth of Market (DOM) can be >= 1. Default: 1. It used with --price
key to showing DOM with current prices for givens ticker or FIGI.
See also: GetCurrentPrices()
.
Tinkoff REST API server for real trade operations. Default: https://invest-public-api.tinkoff.ru/rest
See also: API method https://tinkoff.github.io/investAPI/#tinkoff-invest-api_1 and SendAPIRequest()
.
How many times retry after first request if a 5xx server errors occurred. If set to 0, then only first main request will be sent without retries. This allows you to reduce the number of calls to the server API for all methods.
3 times of retries by default.
See also: SendAPIRequest()
.
Sleep time in seconds between retries, in all network requests 3 seconds by default.
See also: SendAPIRequest()
.
Headers which send in every request to broker server. Please, do not change it!
Default: {"Content-Type": "application/json", "accept": "application/json", "Authorization": "Bearer {your_token}", "x-app-name": "Tim55667757.TKSBrokerAPI"}
.
See also: SendAPIRequest()
.
If True
then TKSBrokerAPI generate also HTML reports from Markdown. False
by default.
See also: Mako Templates for Python (https://www.makotemplates.org/). Mako is a template library provides simple syntax and maximum performance.
Full path to the output file where history candles will be saved or updated. Default: None
, it mean that returns only Pandas DataFrame.
See also: History()
.
Full path to the html file where rendered candles chart stored. Default: index.html
.
See also: ShowHistoryChart()
.
Filename where full available to user instruments list will be saved. Default: instruments.md
.
See also: ShowInstrumentsInfo()
.
Filename with all found instruments searched by part of its ticker, FIGI or name. Default: search-results.md
.
See also: SearchInstruments()
.
Filename where prices of selected instruments will be saved. Default: prices.md
.
See also: GetListOfPrices()
.
Filename where prices of selected instruments will be saved. Default: prices.md
.
See also: ShowInstrumentsInfo()
, RequestBondCoupons()
and RequestTradingStatus()
.
Filename where wider Pandas DataFrame with more information about bonds: main info, current prices,
bonds payment calendar, some statistics will be stored. Default: ext-bonds.xlsx
.
See also: ExtendBondsData()
.
Filename where bonds payment calendar will be saved. Default: calendar.md
.
Pandas dataframe with only bonds payment calendar also will be stored to default file calendar.xlsx
.
See also: CreateBondsCalendar()
, ShowBondsCalendar()
, ShowInstrumentInfo()
, RequestBondCoupons()
and ExtendBondsData()
.
Filename where current portfolio, open trades and orders will be saved. Default: overview.md
.
See also: Overview()
, RequestPortfolio()
, RequestPositions()
, RequestPendingOrders()
and RequestStopOrders()
.
Filename where short digest of the portfolio status will be saved. Default: overview-digest.md
.
See also: Overview()
with parameter details="digest"
.
Filename where only open positions, without everything else will be saved. Default: overview-positions.md
.
See also: Overview()
with parameter details="positions"
.
Filename where open limits and stop orders will be saved. Default: overview-orders.md
.
See also: Overview()
with parameter details="orders"
.
Filename where only the analytics section and the distribution of the portfolio by various categories will be saved. Default: overview-analytics.md
.
See also: Overview()
with parameter details="analytics"
.
Filename where only the bonds calendar section will be saved. Default: overview-calendar.md
.
See also: Overview()
with parameter details="calendar"
.
Filename where history of deals and trade statistics will be saved. Default: deals.md
.
See also: Deals()
.
Filename where table of funds available for withdrawal will be saved. Default: limits.md
.
See also: OverviewLimits()
and RequestLimits()
.
Filename where all available user's data (accountId
s, common user information, margin status and tariff connections limit) will be saved. Default: user-info.md
.
See also: OverviewUserInfo()
, RequestAccounts()
, RequestUserInfo()
, RequestMarginStatus()
and RequestTariffLimits()
.
Filename where simple table with all available user accounts (accountId
s) will be saved. Default: accounts.md
.
See also: OverviewAccounts()
, RequestAccounts()
.
Filename where raw data about shares, currencies, bonds, etfs and futures will be stored. Default: dump.json
.
Pandas dataframe with raw instruments data also will be stored to default file dump.xlsx
.
See also: DumpInstruments()
and DumpInstrumentsAsXLSX()
.
Dictionary with raw data about shares, currencies, bonds, etfs and futures from broker server. Auto-updating and saving dump to the iListDumpFile
.
See also: Listing()
, DumpInstruments()
.
PriceGenerator object to work with candles data: load, render interact and non-interact charts and so on.
See also: LoadHistory()
, ShowHistoryChart()
and the PriceGenerator project: https://github.com/Tim55667757/PriceGenerator
Identification TKSBrokerAPI tag in log messages to simplify debugging when platform instances runs in parallel mode. Default: ""
(empty string).
String with ticker, e.g. GOOGL
. Tickers may be upper case only.
Use alias for USD000UTSTOM
simple as USD
, EUR_RUB__TOM
as EUR
etc.
More tickers aliases here: TKSEnums.TKS_TICKER_ALIASES
.
See also: SearchByTicker()
, SearchInstruments()
.
String with FIGI identifier. FIGIs are case-sensitive and must be used as provided.
Example: ticker GOOGL
has FIGI BBG009S39JX6
.
See also: SearchByFIGI()
, SearchInstruments()
.
Send GET or POST request to broker server and receive JSON object.
self.header: must be defining with dictionary of headers. self.body: if define then used as request body. None by default. self.timeout: global request timeout, 15 seconds by default.
Parameters
- url: url with REST request.
- reqType: send "GET" or "POST" request. "GET" by default.
- methodName: optional manual override for REST method name (used for throttling).
- _internalBody: DO NOT use this variable in your scripts! This is debug variable for internal used only.
Returns
response JSON (dictionary) from broker.
Gets JSON with raw data about shares, currencies, bonds, ETFs, and futures from broker server.
Returns
Dictionary with all available broker instruments: currencies, shares, bonds, ETFs, and futures.
Creates XLSX-formatted dump file with raw data of instruments to further used by data scientists or stock analytics.
See also: DumpInstruments()
, Listing()
.
Parameters
Receives and returns actual raw data about shares, currencies, bonds, etfs and futures from broker server
using Listing()
method. If iListDumpFile
string is not empty then also save information to this file.
See also: DumpInstrumentsAsXLSX()
, Listing()
.
Parameters
- forceUpdate: if
True
then at first updates data withListing()
method, otherwise just saves existiList
as JSON-file (default:dump.json
).
Returns
serialized JSON formatted
str
with full data of instruments, also saved to the--output
JSON-file.
Show information about one instrument defined by json data and prints it in Markdown format.
See also: SearchByTicker()
, SearchByFIGI()
, RequestBondCoupons()
, ExtendBondsData()
, ShowBondsCalendar()
and RequestTradingStatus()
.
Parameters
- iJSON: json data of instrument, example:
iJSON = self.iList["Shares"][self._ticker]
- show: if
True
then also printing information about instrument and its current price. - onlyFiles: if
True
then do not show Markdown table in the console, but only generates report files.
Returns
multilines text in Markdown format with information about one instrument.
Search and return raw broker's information about instrument by its ticker. Variable ticker
must be defined!
Parameters
- requestPrice: if
False
then do not request current price of instrument (because this is long operation). - show: if
False
then do not runShowInstrumentInfo()
method and do not print info to the console.
Returns
JSON formatted data with information about instrument.
Search and return raw broker's information about instrument by its FIGI. Variable figi
must be defined!
Parameters
- requestPrice: if
False
then do not request current price of instrument (it's long operation). - show: if
False
then do not runShowInstrumentInfo()
method and do not print info to the console.
Returns
JSON formatted data with information about instrument.
Get and show Depth of Market with current prices of the instrument as dictionary. Result example with depth
5:
{"buy": [{"price": 1243.8, "quantity": 193},
{"price": 1244.0, "quantity": 168},
{"price": 1244.8, "quantity": 5},
{"price": 1245.0, "quantity": 61},
{"price": 1245.4, "quantity": 60}],
"sell": [{"price": 1243.6, "quantity": 8},
{"price": 1242.6, "quantity": 10},
{"price": 1242.4, "quantity": 18},
{"price": 1242.2, "quantity": 50},
{"price": 1242.0, "quantity": 113}],
"limitUp": 1619.0, "limitDown": 903.4, "lastPrice": 1243.8, "closePrice": 1263.0}
, where parameters mean:
- buy: list of dicts with Sellers prices, see also: https://tinkoff.github.io/investAPI/marketdata/#order
- sell: list of dicts with Buyers prices,
- price: price of 1 instrument (to get the cost of the lot, you need to multiply it by the lot of size of the instrument),
- quantity: volume value by current price in lots,
- limitUp: current trade session limit price, maximum,
- limitDown: current trade session limit price, minimum,
- lastPrice: last deal price of the instrument,
- closePrice: previous trade session close price of the instrument.
See also: SearchByTicker()
and SearchByFIGI()
.
REST API for request: https://tinkoff.github.io/investAPI/swagger-ui/#/MarketDataService/MarketDataService_GetOrderBook
Response fields: https://tinkoff.github.io/investAPI/marketdata/#getorderbookresponse
Parameters
- show: if
True
then print DOM to log and console.
Returns
orders book dict with lists of current buy and sell prices:
{"buy": [{"price": x1, "quantity": y1, ...}], "sell": [....]}
. If an error occurred then returns an empty record:{"buy": [], "sell": [], "limitUp": None, "limitDown": None, "lastPrice": None, "closePrice": None}
.
This method get and show information about all available broker instruments for current user account.
If instrumentsFile
string is not empty then also save information to this file.
Parameters
- show: if
True
then print results to console, ifFalse
— print only to file. - onlyFiles: if
True
then do not show Markdown table in the console, but only generates report files.
Returns
multi-lines string with all available broker instruments.
This method search and show information about instruments by part of its ticker, FIGI or name.
If searchResultsFile
string is not empty then also save information to this file.
Parameters
- pattern: string with part of ticker, FIGI or instrument's name.
- show: if
True
then print results to console, ifFalse
— return list of result only. - onlyFiles: if
True
then do not show Markdown table in the console, but only generates report files.
Returns
list of dictionaries with all found instruments.
Creating list with unique instrument FIGIs from input list of tickers (priority) or FIGIs.
Parameters
- instruments: list of strings with tickers or FIGIs.
Returns
list with unique instrument FIGIs only.
This method get, maybe show and return prices of list of instruments. WARNING! This is potential long operation!
See limits: https://tinkoff.github.io/investAPI/limits/
If pricesFile
string is not empty then also save information to this file.
Parameters
- instruments: list of strings with tickers or FIGIs.
- show: if
True
then prints prices to console, ifFalse
— prints only to filepricesFile
. - onlyFiles: if
True
then do not show Markdown table in the console, but only generates report files.
Returns
list of instruments looks like
[{some ticker info, "currentPrice": {current prices}}, {...}, ...]
. One item is dict returned bySearchByTicker()
orSearchByFIGI()
methods.
Show table contains current prices of given instruments.
Parameters
- **iList: list of instruments looks like
[{some ticker info, "currentPrice"**: {current prices}}, {...}, ...]
. One item is dict returned bySearchByTicker(requestPrice=True)
or bySearchByFIGI(requestPrice=True)
methods. - show: if
True
then prints prices to console, ifFalse
— prints only to filepricesFile
. - onlyFiles: if
True
then do not show Markdown table in the console, but only generates report files.
Returns
multilines text in Markdown format as a table contains current prices.
Requesting trading status for the instrument defined by figi
variable.
Documentation: https://tinkoff.github.io/investAPI/marketdata/#gettradingstatusrequest
Returns
dictionary with trading status attributes. Response example:
{"figi": "TCS00A103X66", "tradingStatus": "SECURITY_TRADING_STATUS_NOT_AVAILABLE_FOR_TRADING", "limitOrderAvailableFlag": false, "marketOrderAvailableFlag": false, "apiTradeAvailableFlag": true}
Requesting actual user's portfolio for current accountId
.
REST API for user portfolio: https://tinkoff.github.io/investAPI/swagger-ui/#/OperationsService/OperationsService_GetPortfolio
Documentation: https://tinkoff.github.io/investAPI/operations/#portfoliorequest
Returns
dictionary with user's portfolio.
Requesting open positions by currencies and instruments for current accountId
.
REST API for open positions: https://tinkoff.github.io/investAPI/swagger-ui/#/OperationsService/OperationsService_GetPositions
Documentation: https://tinkoff.github.io/investAPI/operations/#positionsrequest
Returns
dictionary with open positions by instruments.
Requesting current actual pending limit orders for current accountId
.
REST API for pending (market) orders: https://tinkoff.github.io/investAPI/swagger-ui/#/OrdersService/OrdersService_GetOrders
Documentation: https://tinkoff.github.io/investAPI/orders/#getordersrequest
Returns
list of dictionaries with pending limit orders.
Requesting current actual stop orders for current accountId
.
REST API for opened stop-orders: https://tinkoff.github.io/investAPI/swagger-ui/#/StopOrdersService/StopOrdersService_GetStopOrders
Documentation: https://tinkoff.github.io/investAPI/stoporders/#getstopordersrequest
Returns
list of dictionaries with stop orders.
Get portfolio: all open positions, orders, some statistics for current accountId
.
If overviewFile
, overviewDigestFile
, overviewPositionsFile
, overviewOrdersFile
, overviewAnalyticsFile
and overviewBondsCalendarFile
are defined, then also save information to file.
WARNING! It is not recommended to run this method too many times in a loop! The server receives many requests about the state of the portfolio, and then, based on the received data, a large number of calculations and statistics are collected.
Parameters
- show: if
False
then only dictionary returns ifTrue
then shows more debug information. - details: how detailed should the information be?
full
— shows full available information about portfolio status (by default),positions
— shows only open positions,orders
— shows only sections of open limits and stop orders.digest
— shows a short digest of the portfolio status,analytics
— shows only the analytics section and the distribution of the portfolio by various categories,calendar
— shows only the bonds calendar section (if these are present in portfolio).
- onlyFiles: if
True
, then does not show the Markdown table in the console but only generates report files.
Returns
dictionary with a client's raw portfolio and some statistics.
Returns history operations between two given dates for current accountId
.
If reportFile
string is not empty then also save human-readable report.
Shows some statistical data of closed positions.
Parameters
- start: see docstring in
TradeRoutines.GetDatesAsString()
method. - end: see docstring in
TradeRoutines.GetDatesAsString()
method. - show: if
True
then also prints all records to the console. - showCancelled: if
False
then remove information about cancelled operations from the deals report. - onlyFiles: if
True
then do not show Markdown table in the console, but only generates report files.
Returns
original list of dictionaries with history of deals records from API ("operations" key): https://tinkoff.github.io/investAPI/swagger-ui/#/OperationsService/OperationsService_GetOperations and dictionary with custom stats: operations in different currencies, withdrawals, incomes etc.
This method returns last history candles of the current instrument defined by ticker
or figi
(FIGI id).
History returned between two given dates: start
and end
. Minimum requested date in the past is 1970-01-01
.
Warning! Broker server used ISO UTC time by default.
If historyFile
is not None
then method save history to file, otherwise return only Pandas DataFrame.
Also, historyFile
used to update history with onlyMissing
parameter.
See also: LoadHistory()
and ShowHistoryChart()
methods.
Parameters
- start: see docstring in
TradeRoutines.GetDatesAsString()
method. - end: see docstring in
TradeRoutines.GetDatesAsString()
method. - interval: this is a candle interval. Current available values are
"1min"
,"5min"
,"15min"
,"hour"
,"day"
. Default:"hour"
. - onlyMissing: if
True
then add only last missing candles, do not request all history length fromstart
. False by default. Warning! History appends only from last candle to current time with always update last candle! - csvSep: separator if csv-file is used,
,
by default. - show: if
True
then also prints Pandas DataFrame to the console.
Returns
Pandas DataFrame with prices history. Headers of columns are defined by default:
["date", "time", "open", "high", "low", "close", "volume"]
.
Load candles history from csv-file and return Pandas DataFrame object.
See also: History()
and ShowHistoryChart()
methods.
Parameters
- filePath: path to csv-file to open.
- show: if
True
then also prints Pandas DataFrame to the console.
Returns
Pandas DataFrame with prices history. Headers of columns are defined by default:
["date", "time", "open", "high", "low", "close", "volume"]
.
Render an HTML-file with interact or non-interact candlesticks chart. Candles may be path to the csv-file.
Self variable htmlHistoryFile
can be use as html-file name to save interaction or non-interaction chart.
Default: index.html
(both for interact and non-interact candlesticks chart).
See also: History()
and LoadHistory()
methods.
Parameters
- candles: string to csv-file with candles in OHLCV-model or like Pandas Dataframe object.
- interact: if True (default) then chain of candlesticks will render as interactive Bokeh chart. See examples: https://github.com/Tim55667757/PriceGenerator#overriding-parameters If False then chain of candlesticks will render as not interactive Google Candlestick chart. See examples: https://github.com/Tim55667757/PriceGenerator#statistics-and-chart-on-a-simple-template
- openInBrowser: if True then immediately open chart in default browser, otherwise only path to
html-file prints to console. False by default, to avoid issues with
permissions denied
to html-file.
Universal method to create market order and make deal at the current price for current accountId
. Returns JSON data with response.
If tp
or sl
> 0, then in additional will open stop-orders with "TP" and "SL" flags for stopType
parameter.
See also: Order()
docstring. More simple methods than Trade()
are Buy()
and Sell()
.
Parameters
- operation: string "Buy" or "Sell".
- lots: volume, integer count of lots >= 1.
- tp: float > 0, target price for stop-order with "TP" type. It used as take profit parameter
targetPrice
inself.Order()
. - sl: float > 0, target price for stop-order with "SL" type. It used as stop loss parameter
targetPrice
inself.Order()
. - expDate: string "Undefined" by default or local date in the future,
it is a string with format
%Y-%m-%d %H:%M:%S
.
Returns
JSON with response from broker server.
More simple method than Trade()
. Create Buy
market order and make deal at the current price. Returns JSON data with response.
If tp
or sl
> 0, then in additional will open stop-orders with "TP" and "SL" flags for stopType
parameter.
See also: Order()
and Trade()
docstrings.
Parameters
- lots: volume, integer count of lots >= 1.
- tp: float > 0, take profit price of stop-order.
- sl: float > 0, stop loss price of stop-order.
- expDate: it's a local date in the future.
String has a format like this:
%Y-%m-%d %H:%M:%S
.
Returns
JSON with response from broker server.
More simple method than Trade()
. Create Sell
market order and make deal at the current price. Returns JSON data with response.
If tp
or sl
> 0, then in additional will open stop-orders with "TP" and "SL" flags for stopType
parameter.
See also: Order()
and Trade()
docstrings.
Parameters
- lots: volume, integer count of lots >= 1.
- tp: float > 0, take profit price of stop-order.
- sl: float > 0, stop loss price of stop-order.
- expDate: it's a local date in the future.
String has a format like this:
%Y-%m-%d %H:%M:%S
.
Returns
JSON with response from broker server.
Close position of given instruments.
Parameters
- instruments: list of instruments defined by tickers or FIGIs that must be closed.
- portfolio: pre-received dictionary with open trades, returned by
Overview()
method. This avoids unnecessary downloading data from the server.
Close all positions of given instruments with defined type.
Parameters
- iType: type of the instruments that be closed, it must be one of supported types in
TKS_INSTRUMENTS
list. - portfolio: pre-received dictionary with open trades, returned by
Overview()
method. This avoids unnecessary downloading data from the server.
Universal method to create market or limit orders with all available parameters for current accountId
.
See more simple methods: BuyLimit()
, BuyStop()
, SellLimit()
, SellStop()
.
If orderType is "Limit" then create pending limit-order below current price if operation is "Buy" and above current price if operation is "Sell". A limit order has no expiration date, it lasts until the end of the trading day.
Warning! If you try to create limit-order above current price if "Buy" or below current price if "Sell" then broker immediately open market order as you can do simple --buy or --sell operations!
If orderType is "Stop" then creates stop-order with any direction "Buy" or "Sell". When current price will go up or down to target price value then broker opens a limit order. Stop-order is opened with unlimited expiration date by default, or you can define expiration date with expDate parameter.
Only one attempt without retries recommended for opens order, set self.retry = 0
. If network issue occurred you can create new request.
Parameters
- operation: string "Buy" or "Sell".
- orderType: string "Limit" or "Stop".
- lots: volume, integer count of lots >= 1.
- targetPrice: target price > 0. This is open trade price for limit order.
- limitPrice: limit price >= 0. This parameter only makes sense for stop-order. If limitPrice = 0, then it set as targetPrice. Broker will create limit-order with price equal to limitPrice, when current price goes to target price of stop-order.
- stopType: string "Limit" by default. This parameter only makes sense for stop-order. There are 3 stop-order types "SL", "TP", "Limit" for "Stop loss", "Take profit" and "Stop limit" types accordingly. Stop loss order always executed by market price.
- expDate: string "Undefined" by default or local date in the future.
String has a format like this:
%Y-%m-%d %H:%M:%S
. This date is converting to UTC format for server. This parameter only makes sense for stop-order. A limit order has no expiration date, it lasts until the end of the trading day.
Returns
JSON with response from broker server.
Create pending Buy
limit-order (below current price). You must specify only 2 parameters:
lots
and target price
to open buy limit-order. If you try to create buy limit-order above current price then
broker immediately open Buy
market order, such as if you do simple --buy
operation!
See also: Order()
docstring.
Parameters
- lots: volume, integer count of lots >= 1.
- targetPrice: target price > 0. This is open trade price for limit order.
Returns
JSON with response from broker server.
Create Buy
stop-order. You must specify at least 2 parameters: lots
target price
to open buy stop-order.
In additional you can specify 3 parameters for buy stop-order: limit price
>=0, stop type
= Limit|SL|TP,
expiration date
= Undefined|%%Y-%%m-%%d %%H:%%M:%%S
. When current price will go up or down to
target price value then broker opens a limit order. See also: Order()
docstring.
Parameters
- lots: volume, integer count of lots >= 1.
- targetPrice: target price > 0. This is trigger price for buy stop-order.
- limitPrice: limit price >= 0 (limitPrice = targetPrice if limitPrice is 0). Broker will create limit-order with price equal to limitPrice, when current price goes to target price of buy stop-order.
- stopType: string "Limit" by default. There are 3 stop-order types "SL", "TP", "Limit" for "Stop loss", "Take profit" and "Stop limit" types accordingly.
- expDate: string "Undefined" by default or local date in the future.
String has a format like this:
%Y-%m-%d %H:%M:%S
. This date is converting to UTC format for server.
Returns
JSON with response from broker server.
Create pending Sell
limit-order (above current price). You must specify only 2 parameters:
lots
and target price
to open sell limit-order. If you try to create sell limit-order below current price then
broker immediately open Sell
market order, such as if you do simple --sell
operation!
See also: Order()
docstring.
Parameters
- lots: volume, integer count of lots >= 1.
- targetPrice: target price > 0. This is open trade price for limit order.
Returns
JSON with response from broker server.
Create Sell
stop-order. You must specify at least 2 parameters: lots
target price
to open sell stop-order.
In addition, you can specify 3 parameters in sell stop-order: limit price
>=0, stop type
= Limit|SL|TP,
expiration date
= Undefined|%%Y-%%m-%%d %%H:%%M:%%S
. When current price will go up or down to
target price value then broker opens a limit order. See also: Order()
docstring.
Parameters
- lots: volume, integer count of lots >= 1.
- targetPrice: target price > 0. This is trigger price in sell stop-order.
- limitPrice: limit price >= 0 (limitPrice = targetPrice if limitPrice is 0). Broker will create limit-order with price equal to limitPrice, when current price goes to target price of sell stop-order.
- stopType: string "Limit" by default. There are 3 stop-order types "SL", "TP", "Limit" for "Stop loss", "Take profit" and "Stop limit" types accordingly.
- expDate: string "Undefined" by default or local date in the future.
String has a format like this:
%Y-%m-%d %H:%M:%S
. This date is converting to UTC format for server.
Returns
JSON with response from broker server.
Cancel order or list of orders by its orderId
or stopOrderId
for current accountId
.
Parameters
- orderIDs: list of integers with
orderId
orstopOrderId
. - allOrdersIDs: pre-received lists of all active pending limit orders. This avoids unnecessary downloading data from the server.
- allStopOrdersIDs: pre-received lists of all active stop orders.
Close all available (not blocked) opened trades and orders.
Also, you can select one or more keywords case-insensitive:
orders
, shares
, bonds
, etfs
and futures
from TKS_INSTRUMENTS
enum to specify trades type.
Currency positions you must close manually using buy or sell operations, CloseTrades()
or CloseAllTrades()
methods.
Close all available (not blocked) opened trades and orders for one instrument defined by its ticker.
This method searches opened trade and orders of instrument throw all portfolio and then use
CloseTrades()
and CloseOrders()
methods to close trade and cancel all orders for that instrument.
See also: IsInLimitOrders()
, GetLimitOrderIDs()
, IsInStopOrders()
, GetStopOrderIDs()
, CloseTrades()
and CloseOrders()
.
Parameters
- instrument: string with ticker.
Close all available (not blocked) opened trades and orders for one instrument defined by its FIGI id.
This method searches opened trade and orders of instrument throw all portfolio and then use
CloseTrades()
and CloseOrders()
methods to close trade and cancel all orders for that instrument.
See also: IsInLimitOrders()
, GetLimitOrderIDs()
, IsInStopOrders()
, GetStopOrderIDs()
, CloseTrades()
and CloseOrders()
.
Parameters
- instrument: string with FIGI id.
Parse input dictionary of strings with order parameters and return dictionary with parameters to open all orders.
Parameters
- operation: string "Buy" or "Sell".
- inputParameters: this is dict of strings that looks like this
{"lots": "L_int,...", "prices": "P_float,..."}
where "lots" key: one or more lot values (integer numbers) to open with every limit-order "prices" key: one or more prices to open limit-orders Counts of values in lots and prices lists must be equals!
Returns
list of dictionaries with all lots and prices to open orders that looks like this
[{"lot": lots_1, "price": price_1}, {...}, ...]
Checks if instrument is in the user's portfolio. Instrument must be defined by ticker
(highly priority) or figi
.
Parameters
- portfolio: dict with user's portfolio data. If
None
, then requests portfolio fromOverview()
method.
Returns
True
if portfolio contains open position with given instrument,False
otherwise.
Returns instrument from the user's portfolio if it presents there.
Instrument must be defined by ticker
(highly priority) or figi
.
Parameters
- portfolio: dict with user's portfolio data. If
None
, then requests portfolio fromOverview()
method.
Returns
dict with instrument if portfolio contains open position with this instrument,
None
otherwise.
Checks if instrument is in the limit orders list. Instrument must be defined by ticker
(highly priority) or figi
.
See also: CloseAllByTicker()
and CloseAllByFIGI()
.
Parameters
- portfolio: dict with user's portfolio data. If
None
, then requests portfolio fromOverview()
method.
Returns
True
if limit orders list contains some limit orders for the instrument,False
otherwise.
Returns list with all orderID
s of opened pending limit orders for the instrument.
Instrument must be defined by ticker
(highly priority) or figi
.
See also: CloseAllByTicker()
and CloseAllByFIGI()
.
Parameters
- portfolio: dict with user's portfolio data. If
None
, then requests portfolio fromOverview()
method.
Returns
list with
orderID
s of limit orders.
Checks if instrument is in the stop orders list. Instrument must be defined by ticker
(highly priority) or figi
.
See also: CloseAllByTicker()
and CloseAllByFIGI()
.
Parameters
- portfolio: dict with user's portfolio data. If
None
, then requests portfolio fromOverview()
method.
Returns
True
if stop orders list contains some stop orders for the instrument,False
otherwise.
Returns list with all orderID
s of opened stop orders for the instrument.
Instrument must be defined by ticker
(highly priority) or figi
.
See also: CloseAllByTicker()
and CloseAllByFIGI()
.
Parameters
- portfolio: dict with user's portfolio data. If
None
, then requests portfolio fromOverview()
method.
Returns
list with
orderID
s of stop orders.
Method for obtaining the available funds for withdrawal for current accountId
.
See also:
- REST API for limits: https://tinkoff.github.io/investAPI/swagger-ui/#/OperationsService/OperationsService_GetWithdrawLimits
OverviewLimits()
method
Returns
dict with raw data from server that contains free funds for withdrawal. Example of dict:
{"money": [{"currency": "rub", "units": "100", "nano": 290000000}, {...}], "blocked": [...], "blockedGuarantee": [...]}
. Heremoney
is an array of portfolio currency positions,blocked
is an array of blocked currency positions of the portfolio andblockedGuarantee
is locked money under collateral for futures.
Method for parsing and show table with available funds for withdrawal for current accountId
.
See also: RequestLimits()
.
Parameters
- show: if
False
then only dictionary returns, ifTrue
then also print withdrawal limits to log. - onlyFiles: if
True
then do not show Markdown table in the console, but only generates report files.
Returns
dict with raw parsed data from server and some calculated statistics about it.
Method for requesting all brokerage accounts (accountId
s) of current user detected by token
.
See also:
- REST API: https://tinkoff.github.io/investAPI/swagger-ui/#/UsersService/UsersService_GetAccounts
- What does account fields mean: https://tinkoff.github.io/investAPI/users/#account
OverviewUserInfo()
method
Returns
dict with raw data from server that contains accounts info. Example of dict:
{"accounts": [{"id": "20000xxxxx", "type": "ACCOUNT_TYPE_TINKOFF", "name": "TKSBrokerAPI account", "status": "ACCOUNT_STATUS_OPEN", "openedDate": "2018-05-23T00:00:00Z", "closedDate": "1970-01-01T00:00:00Z", "accessLevel": "ACCOUNT_ACCESS_LEVEL_FULL_ACCESS"}, ...]}
. IfclosedDate="1970-01-01T00:00:00Z"
it means that account is active now.
Method for requesting common user information.
See also:
- REST API: https://tinkoff.github.io/investAPI/swagger-ui/#/UsersService/UsersService_GetInfo
- What does user info fields mean: https://tinkoff.github.io/investAPI/users/#getinforequest
- What does
qualified_for_work_with
field mean: https://tinkoff.github.io/investAPI/faq_users/#qualified_for_work_with OverviewUserInfo()
method
Returns
dict with raw data from server that contains user's information. Example of dict:
{"premStatus": true, "qualStatus": false, "qualifiedForWorkWith": ["bond", "foreign_shares", "leverage", "russian_shares", "structured_income_bonds"], "tariff": "premium"}
.
Method for requesting margin calculation for defined account ID.
See also:
- REST API: https://tinkoff.github.io/investAPI/swagger-ui/#/UsersService/UsersService_GetMarginAttributes
- What does margin fields mean: https://tinkoff.github.io/investAPI/users/#getmarginattributesresponse
OverviewUserInfo()
method
Parameters
- accountId: string with numeric account ID. If
None
, then used class fieldaccountId
.
Returns
dict with raw data from server that contains margin calculation. If margin is disabled then returns empty dict. Example of responses: status code 400:
{"code": 3, "message": "account margin status is disabled", "description": "30051" }
, returns:{}
. status code 200:{"liquidPortfolio": {"currency": "rub", "units": "7175", "nano": 560000000}, "startingMargin": {"currency": "rub", "units": "6311", "nano": 840000000}, "minimalMargin": {"currency": "rub", "units": "3155", "nano": 920000000}, "fundsSufficiencyLevel": {"units": "1", "nano": 280000000}, "amountOfMissingFunds": {"currency": "rub", "units": "-863", "nano": -720000000}}
.
Method for requesting limits of current tariff (connections, API methods etc.) of current user detected by token
.
See also:
- REST API: https://tinkoff.github.io/investAPI/swagger-ui/#/UsersService/UsersService_GetUserTariff
- What does fields in tariff mean: https://tinkoff.github.io/investAPI/users/#getusertariffrequest
- Unary limit: https://tinkoff.github.io/investAPI/users/#unarylimit
- Stream limit: https://tinkoff.github.io/investAPI/users/#streamlimit
OverviewUserInfo()
method
Returns
dict with raw data from server that contains limits of current tariff. Example of dict:
{"unaryLimits": [{"limitPerMinute": 0, "methods": ["methods", "methods"]}, ...], "streamLimits": [{"streams": ["streams", "streams"], "limit": 6}, ...]}
.
Requesting bond payment calendar from official placement date to maturity date. If these dates are unknown
then requesting dates "from": "1970-01-01T00:00:00.000Z"
and "to": "2099-12-31T23:59:59.000Z"
.
All dates are in UTC timezone.
REST API: https://tinkoff.github.io/investAPI/swagger-ui/#/InstrumentsService/InstrumentsService_GetBondCoupons Documentation:
- request: https://tinkoff.github.io/investAPI/instruments/#getbondcouponsrequest
- response: https://tinkoff.github.io/investAPI/instruments/#coupon
See also: ExtendBondsData()
.
Parameters
- iJSON: raw json data of a bond from broker server, example
iJSON = self.iList["Bonds"][self._ticker]
If raw iJSON is not data of bond then server returns an error [400] with message:{"code": 3, "message": "instrument type is not bond", "description": "30048"}
.
Returns
dictionary with bond payment calendar. Response example
{"events": [{"figi": "TCS00A101YV8", "couponDate": "2023-07-26T00:00:00Z", "couponNumber": "12", "fixDate": "2023-07-25T00:00:00Z", "payOneBond": {"currency": "rub", "units": "7", "nano": 170000000}, "couponType": "COUPON_TYPE_CONSTANT", "couponStartDate": "2023-04-26T00:00:00Z", "couponEndDate": "2023-07-26T00:00:00Z", "couponPeriod": 91}, {...}, ...]}
Requests jsons with raw bonds data for every ticker or FIGI in instruments list and transform it to the wider Pandas DataFrame with more information about bonds: main info, current prices, bond payment calendar, coupon yields, current yields and some statistics etc.
WARNING! This is too long operation if a lot of bonds requested from broker server.
See also: ShowInstrumentInfo()
, CreateBondsCalendar()
, ShowBondsCalendar()
, RequestBondCoupons()
.
Parameters
- instruments: list of strings with tickers or FIGIs.
- xlsx: if True then also exports Pandas DataFrame to xlsx-file
bondsXLSXFile
, defaultext-bonds.xlsx
, for further used by data scientists or stock analytics.
Returns
wider Pandas DataFrame with more full and calculated data about bonds, than raw response from broker. In XLSX-file and Pandas DataFrame fields mean: - main info about bond: https://tinkoff.github.io/investAPI/instruments/#bond - info about coupon: https://tinkoff.github.io/investAPI/instruments/#coupon
Creates bond payments calendar as Pandas DataFrame, and also save it to the XLSX-file, calendar.xlsx
by default.
WARNING! This is too long operation if a lot of bonds requested from broker server.
See also: ShowBondsCalendar()
, ExtendBondsData()
.
Parameters
- extBonds: Pandas DataFrame object returns by
ExtendBondsData()
method and contains extended information about bonds: main info, current prices, bond payment calendar, coupon yields, current yields and some statistics etc. If this parameter isNone
then usedfigi
orticker
as bond name and then calculateExtendBondsData()
. - xlsx: if True then also exports Pandas DataFrame to file
calendarFile
+".xlsx"
,calendar.xlsx
by default, for further used by data scientists or stock analytics.
Returns
Pandas DataFrame with only bond payments calendar data. Fields mean: https://tinkoff.github.io/investAPI/instruments/#coupon
Show bond payments calendar as a table. One row in input bonds
dataframe contains one bond.
Also, creates Markdown file with calendar data, calendar.md
by default.
See also: ShowInstrumentInfo()
, RequestBondCoupons()
, CreateBondsCalendar()
and ExtendBondsData()
.
Parameters
- extBonds: Pandas DataFrame object returns by
ExtendBondsData()
method and contains extended information about bonds: main info, current prices, bond payment calendar, coupon yields, current yields and some statistics etc. If this parameter isNone
then usedfigi
orticker
as bond name and then calculateExtendBondsData()
. - show: if
True
then also printing bonds payment calendar to the console, otherwise save to filecalendarFile
only.False
by default. - onlyFiles: if
True
then do not show Markdown table in the console, but only generates report files.
Returns
multilines text in Markdown format with bonds payment calendar as a table.
Method for parsing and show simple table with all available user accounts.
See also: RequestAccounts()
and OverviewUserInfo()
methods.
Parameters
- show: if
False
then only dictionary with accounts data returns, ifTrue
then also print it to log. - onlyFiles: if
True
then do not show Markdown table in the console, but only generates report files.
Returns
dict with parsed accounts data received from
RequestAccounts()
method. Example of dict:view = {"rawAccounts": {rawAccounts from RequestAccounts() method...}, "stat": {"accountId string": {"type": "Tinkoff brokerage account", "name": "Test - 1", "status": "Opened and active account", "opened": "2018-05-23 00:00:00", "closed": "—", "access": "Full access" }, ...}}
Method for parsing and show all available user's data (accountId
s, common user information, margin status and tariff connections limit).
See also: OverviewAccounts()
, RequestAccounts()
, RequestUserInfo()
, RequestMarginStatus()
and RequestTariffLimits()
methods.
Parameters
- show: if
False
then only dictionary returns, ifTrue
then also print user's data to log. - onlyFiles: if
True
then do not show Markdown table in the console, but only generates report files.
Returns
dict with raw parsed data from server and some calculated statistics about it.
Periodically updates history for a list of tickers using cron expression and multithreading. This method blocks execution in an infinite loop. Can be used for --auto-update mode.
Required fields for history update must be passed via **kwargs and will be forwarded to self.History().
Example: HistoryAutoUpdater( tickersList=["GAZP", "SBER"], crontabExpr="*/2 10-18,19-23 * * 0-6", timeToSleep=300, interval="hour", onlyMissing=True, show=True, csvSep="," )
Parameters
- tickersList: List of ticker symbols to update.
- dateStart: This is
start
parameter fromTinkoffBrokerServer.History()
method. Default is-3
. See alsoTradeRoutines.GetDatesAsString()
method. - outputDir: Output directory where history files are stored. Default is
None
mean current workdir. - crontabExpr: Cron-style schedule string (evaluated by pycron). Default is
*/5 10-23 * * 1-5
. See example at https://crontab.guru/#/5_10-23__*_1-5 - waitAfterIteration: Delay in seconds after each iteration completed, default is
60
seconds. - waitNext: Technical pause (in seconds) between two crontab checks, default is
1
second. - kwargs: All additional keyword arguments are passed to the
History()
method of theTinkoffBrokerServer()
class, include token and accountId.
If the Main ()
function is imported as module, then this class used to convert arguments from **kwargs as object.
This function gets and parses command line keys.
Main function for work with TKSBrokerAPI Platform in the console.
See examples: