RAPTOR v18.4: Исправлена отчетность, активированы выходные
This commit is contained in:
13
invest-python-master/examples/README.md
Normal file
13
invest-python-master/examples/README.md
Normal file
@@ -0,0 +1,13 @@
|
||||
Cначала нужно добавить токен в переменную окружения.
|
||||
|
||||
<!-- termynal -->
|
||||
|
||||
```console
|
||||
$ export INVEST_TOKEN=YOUR_TOKEN
|
||||
```
|
||||
|
||||
А потом можно запускать примеры
|
||||
|
||||
```console
|
||||
$ python examples/client.py
|
||||
```
|
||||
0
invest-python-master/examples/__init__.py
Normal file
0
invest-python-master/examples/__init__.py
Normal file
25
invest-python-master/examples/all_candles.py
Normal file
25
invest-python-master/examples/all_candles.py
Normal file
@@ -0,0 +1,25 @@
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
from t_tech.invest import CandleInterval, Client
|
||||
from t_tech.invest.schemas import CandleSource
|
||||
from t_tech.invest.utils import now
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
for candle in client.get_all_candles(
|
||||
instrument_id="BBG004730N88",
|
||||
from_=now() - timedelta(days=365),
|
||||
interval=CandleInterval.CANDLE_INTERVAL_HOUR,
|
||||
candle_source_type=CandleSource.CANDLE_SOURCE_UNSPECIFIED,
|
||||
):
|
||||
print(candle)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
24
invest-python-master/examples/async_all_candles.py
Normal file
24
invest-python-master/examples/async_all_candles.py
Normal file
@@ -0,0 +1,24 @@
|
||||
import asyncio
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
from t_tech.invest import AsyncClient, CandleInterval
|
||||
from t_tech.invest.schemas import CandleSource
|
||||
from t_tech.invest.utils import now
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
async for candle in client.get_all_candles(
|
||||
instrument_id="BBG004730N88",
|
||||
from_=now() - timedelta(days=365),
|
||||
interval=CandleInterval.CANDLE_INTERVAL_HOUR,
|
||||
candle_source_type=CandleSource.CANDLE_SOURCE_EXCHANGE,
|
||||
):
|
||||
print(candle)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
15
invest-python-master/examples/async_client.py
Normal file
15
invest-python-master/examples/async_client.py
Normal file
@@ -0,0 +1,15 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
print(await client.users.get_accounts())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,25 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient, CandleInterval
|
||||
from t_tech.invest.utils import now
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
candles = await client.market_data.get_candles(
|
||||
instrument_id="BBG004730N88",
|
||||
to=now(),
|
||||
limit=3,
|
||||
interval=CandleInterval.CANDLE_INTERVAL_HOUR,
|
||||
)
|
||||
for candle in candles.candles:
|
||||
print(candle)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
38
invest-python-master/examples/async_get_insider_deals.py
Normal file
38
invest-python-master/examples/async_get_insider_deals.py
Normal file
@@ -0,0 +1,38 @@
|
||||
"""Example - How to get list of insider deals.
|
||||
Request data in loop with batches of 10 records.
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import GetInsiderDealsRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
deals = []
|
||||
|
||||
next_cursor = None
|
||||
while True:
|
||||
response = await client.instruments.get_insider_deals(
|
||||
request=GetInsiderDealsRequest(
|
||||
instrument_id="BBG004730N88", limit=10, next_cursor=next_cursor
|
||||
)
|
||||
)
|
||||
deals.extend(response.insider_deals)
|
||||
if not next_cursor:
|
||||
break
|
||||
next_cursor = response.next_cursor
|
||||
print("Insider deals:")
|
||||
for deal in deals:
|
||||
print(deal)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
20
invest-python-master/examples/async_get_last_prices.py
Normal file
20
invest-python-master/examples/async_get_last_prices.py
Normal file
@@ -0,0 +1,20 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient, InstrumentStatus
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
print(
|
||||
await client.market_data.get_last_prices(
|
||||
figi=["BBG004730ZJ9"],
|
||||
instrument_status=InstrumentStatus.INSTRUMENT_STATUS_ALL,
|
||||
)
|
||||
) # pylint:disable=line-too-long
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
28
invest-python-master/examples/async_get_market_values.py
Normal file
28
invest-python-master/examples/async_get_market_values.py
Normal file
@@ -0,0 +1,28 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import GetMarketValuesRequest, MarketValueType
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
market_values = await client.market_data.get_market_values(
|
||||
request=GetMarketValuesRequest(
|
||||
instrument_id=["BBG004730N88", "64c0da45-4c90-41d4-b053-0c66c7a8ddcd"],
|
||||
values=[
|
||||
MarketValueType.INSTRUMENT_VALUE_LAST_PRICE,
|
||||
MarketValueType.INSTRUMENT_VALUE_CLOSE_PRICE,
|
||||
],
|
||||
)
|
||||
)
|
||||
for instrument in market_values.instruments:
|
||||
print(instrument.instrument_uid)
|
||||
for value in instrument.values:
|
||||
print(value)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
39
invest-python-master/examples/async_get_orders.py
Normal file
39
invest-python-master/examples/async_get_orders.py
Normal file
@@ -0,0 +1,39 @@
|
||||
"""Example - How to get list of orders for 1 last hour (maximum requesting period)."""
|
||||
import asyncio
|
||||
import datetime
|
||||
import logging
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import OrderExecutionReportStatus
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
response = await client.users.get_accounts()
|
||||
account, *_ = response.accounts
|
||||
account_id = account.id
|
||||
|
||||
now = datetime.datetime.now()
|
||||
orders = await client.orders.get_orders(
|
||||
account_id=account_id,
|
||||
from_=now - datetime.timedelta(hours=1),
|
||||
to=now,
|
||||
# filter only executed or partially executed orders
|
||||
execution_status=[
|
||||
OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_FILL,
|
||||
OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_PARTIALLYFILL,
|
||||
],
|
||||
)
|
||||
print("Orders list:")
|
||||
for order in orders.orders:
|
||||
print(order)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
22
invest-python-master/examples/async_get_risk_rates.py
Normal file
22
invest-python-master/examples/async_get_risk_rates.py
Normal file
@@ -0,0 +1,22 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import RiskRatesRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
request = RiskRatesRequest()
|
||||
request.instrument_id = ["BBG001M2SC01", "BBG004730N88"]
|
||||
r = await client.instruments.get_risk_rates(request=request)
|
||||
for i in r.instrument_risk_rates:
|
||||
print(i.instrument_uid)
|
||||
print(i.short_risk_rate)
|
||||
print(i.long_risk_rate)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
22
invest-python-master/examples/async_get_sandbox_max_lots.py
Normal file
22
invest-python-master/examples/async_get_sandbox_max_lots.py
Normal file
@@ -0,0 +1,22 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import GetMaxLotsRequest
|
||||
from t_tech.invest.sandbox.async_client import AsyncSandboxClient
|
||||
from t_tech.invest.sandbox.client import SandboxClient
|
||||
|
||||
TOKEN = os.environ["INVEST_SANDBOX_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncSandboxClient(TOKEN) as client:
|
||||
account_id = (await client.users.get_accounts()).accounts[0].id
|
||||
request = GetMaxLotsRequest(
|
||||
account_id=account_id,
|
||||
instrument_id="BBG004730N88",
|
||||
)
|
||||
print(await client.sandbox.get_sandbox_max_lots(request=request))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
26
invest-python-master/examples/async_get_signals.py
Normal file
26
invest-python-master/examples/async_get_signals.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""Example - How to get Signals"""
|
||||
import asyncio
|
||||
import datetime
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import GetSignalsRequest, SignalState
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
request = GetSignalsRequest()
|
||||
request.instrument_uid = "e6123145-9665-43e0-8413-cd61b8aa9b13" # Сбербанк
|
||||
request.active = SignalState.SIGNAL_STATE_ALL # все сигналы
|
||||
request.from_ = datetime.datetime.now() - datetime.timedelta(
|
||||
weeks=4
|
||||
) # сигналы, созданные не больше чем 4 недели назад
|
||||
r = await client.signals.get_signals(request=request)
|
||||
for signal in r.signals:
|
||||
print(signal)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
19
invest-python-master/examples/async_get_strategies.py
Normal file
19
invest-python-master/examples/async_get_strategies.py
Normal file
@@ -0,0 +1,19 @@
|
||||
"""Example - How to get all strategies"""
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import GetStrategiesRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
r = await client.signals.get_strategies(request=GetStrategiesRequest())
|
||||
for strategy in r.strategies:
|
||||
print(strategy)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
41
invest-python-master/examples/async_get_tech_analysis.py
Normal file
41
invest-python-master/examples/async_get_tech_analysis.py
Normal file
@@ -0,0 +1,41 @@
|
||||
import asyncio
|
||||
import os
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import (
|
||||
Deviation,
|
||||
GetTechAnalysisRequest,
|
||||
IndicatorInterval,
|
||||
IndicatorType,
|
||||
Smoothing,
|
||||
TypeOfPrice,
|
||||
)
|
||||
from t_tech.invest.utils import decimal_to_quotation, now
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
request = GetTechAnalysisRequest(
|
||||
indicator_type=IndicatorType.INDICATOR_TYPE_RSI,
|
||||
instrument_uid="6542a064-6633-44ba-902f-710c97507522",
|
||||
from_=now() - timedelta(days=7),
|
||||
to=now(),
|
||||
interval=IndicatorInterval.INDICATOR_INTERVAL_4_HOUR,
|
||||
type_of_price=TypeOfPrice.TYPE_OF_PRICE_AVG,
|
||||
length=42,
|
||||
deviation=Deviation(
|
||||
deviation_multiplier=decimal_to_quotation(Decimal(1.0)),
|
||||
),
|
||||
smoothing=Smoothing(fast_length=13, slow_length=7, signal_smoothing=3),
|
||||
)
|
||||
response = await client.market_data.get_tech_analysis(request=request)
|
||||
for indicator in response.technical_indicators:
|
||||
print(indicator.signal)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
18
invest-python-master/examples/async_get_trading_statuses.py
Normal file
18
invest-python-master/examples/async_get_trading_statuses.py
Normal file
@@ -0,0 +1,18 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(token) as client:
|
||||
statuses = await client.market_data.get_trading_statuses(
|
||||
instrument_ids=["BBG004730N88"]
|
||||
)
|
||||
print(statuses)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
19
invest-python-master/examples/async_indicatives.py
Normal file
19
invest-python-master/examples/async_indicatives.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import IndicativesRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
request = IndicativesRequest()
|
||||
indicatives = await client.instruments.indicatives(request=request)
|
||||
for instrument in indicatives.instruments:
|
||||
print(instrument.name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
55
invest-python-master/examples/async_instrument_favorites.py
Normal file
55
invest-python-master/examples/async_instrument_favorites.py
Normal file
@@ -0,0 +1,55 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import (
|
||||
CreateFavoriteGroupRequest,
|
||||
DeleteFavoriteGroupRequest,
|
||||
EditFavoritesActionType as At,
|
||||
EditFavoritesRequestInstrument,
|
||||
GetFavoriteGroupsRequest,
|
||||
)
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
r = await client.instruments.get_favorites()
|
||||
|
||||
print("Список избранных инструментов:")
|
||||
for i in r.favorite_instruments:
|
||||
print(f"{i.ticker} - {i.name}")
|
||||
|
||||
request = CreateFavoriteGroupRequest()
|
||||
request.group_name = "My test favorite group"
|
||||
request.group_color = "aa0000" # red color
|
||||
r = await client.instruments.create_favorite_group(request=request)
|
||||
group_id = r.group_id
|
||||
print(f"Создана новая группа избранного с ИД: {group_id}")
|
||||
|
||||
await client.instruments.edit_favorites(
|
||||
instruments=[EditFavoritesRequestInstrument(instrument_id="BBG001M2SC01")],
|
||||
action_type=At.EDIT_FAVORITES_ACTION_TYPE_ADD,
|
||||
group_id=group_id,
|
||||
)
|
||||
|
||||
request = GetFavoriteGroupsRequest()
|
||||
request.instrument_id = ["BBG001M2SC01"]
|
||||
r = await client.instruments.get_favorite_groups(request=request)
|
||||
print(f"Список групп избранного:")
|
||||
for i in r.groups:
|
||||
print(
|
||||
f"{i.group_id} - {i.group_name}. Количество элементов: {i.size}. "
|
||||
f"Содержит выбранный инструмент {request.instrument_id[0]}: "
|
||||
f"{i.contains_instrument} "
|
||||
)
|
||||
|
||||
request = DeleteFavoriteGroupRequest()
|
||||
request.group_id = group_id
|
||||
await client.instruments.delete_favorite_group(request=request)
|
||||
print(f"Удалена группа избранного с ИД: {group_id}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
27
invest-python-master/examples/async_operations_stream.py
Normal file
27
invest-python-master/examples/async_operations_stream.py
Normal file
@@ -0,0 +1,27 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import OperationsStreamRequest, PingDelaySettings
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
accounts = await client.users.get_accounts()
|
||||
accounts = [i.id for i in accounts.accounts]
|
||||
print(f"Subscribe for operations on accounts: {accounts}")
|
||||
async for operation in client.operations_stream.operations_stream(
|
||||
OperationsStreamRequest(
|
||||
accounts=accounts,
|
||||
ping_settings=PingDelaySettings(
|
||||
ping_delay_ms=10_000,
|
||||
),
|
||||
)
|
||||
):
|
||||
print(operation)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
19
invest-python-master/examples/async_order_state_stream.py
Normal file
19
invest-python-master/examples/async_order_state_stream.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import OrderStateStreamRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
request = OrderStateStreamRequest()
|
||||
stream = client.orders_stream.order_state_stream(request=request)
|
||||
async for order_state in stream:
|
||||
print(order_state)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
28
invest-python-master/examples/async_post_order_async.py
Normal file
28
invest-python-master/examples/async_post_order_async.py
Normal file
@@ -0,0 +1,28 @@
|
||||
import asyncio
|
||||
import os
|
||||
from uuid import uuid4
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import OrderDirection, OrderType, PostOrderAsyncRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
accounts = await client.users.get_accounts()
|
||||
account_id = accounts.accounts[0].id
|
||||
request = PostOrderAsyncRequest(
|
||||
order_type=OrderType.ORDER_TYPE_MARKET,
|
||||
direction=OrderDirection.ORDER_DIRECTION_BUY,
|
||||
instrument_id="BBG004730ZJ9",
|
||||
quantity=1,
|
||||
account_id=account_id,
|
||||
order_id=str(uuid4()),
|
||||
)
|
||||
response = await client.orders.post_order_async(request=request)
|
||||
print(response)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
29
invest-python-master/examples/async_retrying_client.py
Normal file
29
invest-python-master/examples/async_retrying_client.py
Normal file
@@ -0,0 +1,29 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
from t_tech.invest import CandleInterval
|
||||
from t_tech.invest.retrying.aio.client import AsyncRetryingClient
|
||||
from t_tech.invest.retrying.settings import RetryClientSettings
|
||||
from t_tech.invest.utils import now
|
||||
|
||||
logging.basicConfig(format="%(asctime)s %(levelname)s:%(message)s", level=logging.DEBUG)
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
retry_settings = RetryClientSettings(use_retry=True, max_retry_attempt=2)
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncRetryingClient(TOKEN, settings=retry_settings) as client:
|
||||
async for candle in client.get_all_candles(
|
||||
figi="BBG000B9XRY4",
|
||||
from_=now() - timedelta(days=301),
|
||||
interval=CandleInterval.CANDLE_INTERVAL_1_MIN,
|
||||
):
|
||||
print(candle)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
41
invest-python-master/examples/async_stream_client.py
Normal file
41
invest-python-master/examples/async_stream_client.py
Normal file
@@ -0,0 +1,41 @@
|
||||
import asyncio
|
||||
import os
|
||||
from typing import AsyncIterable
|
||||
|
||||
from t_tech.invest import (
|
||||
AsyncClient,
|
||||
CandleInstrument,
|
||||
MarketDataRequest,
|
||||
SubscribeCandlesRequest,
|
||||
SubscriptionAction,
|
||||
SubscriptionInterval,
|
||||
)
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async def request_iterator():
|
||||
yield MarketDataRequest(
|
||||
subscribe_candles_request=SubscribeCandlesRequest(
|
||||
subscription_action=SubscriptionAction.SUBSCRIPTION_ACTION_SUBSCRIBE,
|
||||
instruments=[
|
||||
CandleInstrument(
|
||||
figi="BBG004730N88",
|
||||
interval=SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE,
|
||||
)
|
||||
],
|
||||
)
|
||||
)
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
async for marketdata in client.market_data_stream.market_data_stream(
|
||||
request_iterator()
|
||||
):
|
||||
print(marketdata)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
23
invest-python-master/examples/cancel_orders.py
Normal file
23
invest-python-master/examples/cancel_orders.py
Normal file
@@ -0,0 +1,23 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
response = client.users.get_accounts()
|
||||
account, *_ = response.accounts
|
||||
account_id = account.id
|
||||
logger.info("Orders: %s", client.orders.get_orders(account_id=account_id))
|
||||
client.cancel_all_orders(account_id=account.id)
|
||||
logger.info("Orders: %s", client.orders.get_orders(account_id=account_id))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
14
invest-python-master/examples/client.py
Normal file
14
invest-python-master/examples/client.py
Normal file
@@ -0,0 +1,14 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
print(client.users.get_accounts())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
32
invest-python-master/examples/download_all_candles.py
Normal file
32
invest-python-master/examples/download_all_candles.py
Normal file
@@ -0,0 +1,32 @@
|
||||
import logging
|
||||
import os
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from t_tech.invest import CandleInterval, Client
|
||||
from t_tech.invest.caching.market_data_cache.cache import MarketDataCache
|
||||
from t_tech.invest.caching.market_data_cache.cache_settings import (
|
||||
MarketDataCacheSettings,
|
||||
)
|
||||
from t_tech.invest.utils import now
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.DEBUG)
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
settings = MarketDataCacheSettings(base_cache_dir=Path("market_data_cache"))
|
||||
market_data_cache = MarketDataCache(settings=settings, services=client)
|
||||
for candle in market_data_cache.get_all_candles(
|
||||
figi="BBG004730N88",
|
||||
from_=now() - timedelta(days=1),
|
||||
interval=CandleInterval.CANDLE_INTERVAL_HOUR,
|
||||
):
|
||||
print(candle.time, candle.is_complete)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
46
invest-python-master/examples/easy_async_stream_client.py
Normal file
46
invest-python-master/examples/easy_async_stream_client.py
Normal file
@@ -0,0 +1,46 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import (
|
||||
AsyncClient,
|
||||
CandleInstrument,
|
||||
InfoInstrument,
|
||||
MarketDataResponse,
|
||||
SubscriptionInterval,
|
||||
TradeInstrument,
|
||||
)
|
||||
from t_tech.invest.async_services import AsyncMarketDataStreamManager
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
market_data_stream: AsyncMarketDataStreamManager = (
|
||||
client.create_market_data_stream()
|
||||
)
|
||||
market_data_stream.candles.waiting_close().subscribe(
|
||||
[
|
||||
CandleInstrument(
|
||||
figi="BBG004730N88",
|
||||
interval=SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE,
|
||||
)
|
||||
]
|
||||
)
|
||||
market_data_stream.trades.subscribe(
|
||||
[
|
||||
TradeInstrument(
|
||||
figi="BBG004730N88",
|
||||
)
|
||||
]
|
||||
)
|
||||
async for marketdata in market_data_stream:
|
||||
marketdata: MarketDataResponse = marketdata
|
||||
print(marketdata)
|
||||
market_data_stream.info.subscribe([InfoInstrument(figi="BBG004730N88")])
|
||||
if marketdata.subscribe_info_response:
|
||||
market_data_stream.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
28
invest-python-master/examples/easy_stream_client.py
Normal file
28
invest-python-master/examples/easy_stream_client.py
Normal file
@@ -0,0 +1,28 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import CandleInstrument, Client, InfoInstrument, SubscriptionInterval
|
||||
from t_tech.invest.services import MarketDataStreamManager
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
market_data_stream: MarketDataStreamManager = client.create_market_data_stream()
|
||||
market_data_stream.candles.waiting_close().subscribe(
|
||||
[
|
||||
CandleInstrument(
|
||||
figi="BBG004730N88",
|
||||
interval=SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE,
|
||||
)
|
||||
]
|
||||
)
|
||||
for marketdata in market_data_stream:
|
||||
print(marketdata)
|
||||
market_data_stream.info.subscribe([InfoInstrument(figi="BBG004730N88")])
|
||||
if marketdata.subscribe_info_response:
|
||||
market_data_stream.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
29
invest-python-master/examples/get_active_orders.py
Normal file
29
invest-python-master/examples/get_active_orders.py
Normal file
@@ -0,0 +1,29 @@
|
||||
"""Example - How to get list of active orders."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
response = client.users.get_accounts()
|
||||
account, *_ = response.accounts
|
||||
account_id = account.id
|
||||
|
||||
orders = client.orders.get_orders(
|
||||
account_id=account_id,
|
||||
)
|
||||
print("Active orders:")
|
||||
for order in orders.orders:
|
||||
print(order)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
23
invest-python-master/examples/get_candles_with_limit.py
Normal file
23
invest-python-master/examples/get_candles_with_limit.py
Normal file
@@ -0,0 +1,23 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import CandleInterval, Client
|
||||
from t_tech.invest.utils import now
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
for candle in client.market_data.get_candles(
|
||||
instrument_id="BBG004730N88",
|
||||
to=now(),
|
||||
limit=24,
|
||||
interval=CandleInterval.CANDLE_INTERVAL_HOUR,
|
||||
).candles:
|
||||
print(candle)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
19
invest-python-master/examples/get_last_prices.py
Normal file
19
invest-python-master/examples/get_last_prices.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client, InstrumentStatus
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
print(
|
||||
client.market_data.get_last_prices(
|
||||
figi=["BBG004730ZJ9"],
|
||||
instrument_status=InstrumentStatus.INSTRUMENT_STATUS_BASE,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
20
invest-python-master/examples/get_last_trades.py
Normal file
20
invest-python-master/examples/get_last_trades.py
Normal file
@@ -0,0 +1,20 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import TradeSourceType
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
print(
|
||||
client.market_data.get_last_trades(
|
||||
instrument_id="BBG004730ZJ9",
|
||||
trade_source=TradeSourceType.TRADE_SOURCE_EXCHANGE,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
27
invest-python-master/examples/get_market_values.py
Normal file
27
invest-python-master/examples/get_market_values.py
Normal file
@@ -0,0 +1,27 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import GetMarketValuesRequest, MarketValueType
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
for values in client.market_data.get_market_values(
|
||||
request=GetMarketValuesRequest(
|
||||
instrument_id=["BBG004730N88"],
|
||||
values=[
|
||||
MarketValueType.INSTRUMENT_VALUE_LAST_PRICE,
|
||||
MarketValueType.INSTRUMENT_VALUE_CLOSE_PRICE,
|
||||
],
|
||||
)
|
||||
).instruments:
|
||||
for value in values.values:
|
||||
print(value)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
28
invest-python-master/examples/get_operations_by_cursor.py
Normal file
28
invest-python-master/examples/get_operations_by_cursor.py
Normal file
@@ -0,0 +1,28 @@
|
||||
import os
|
||||
from pprint import pprint
|
||||
|
||||
from t_tech.invest import Client, GetOperationsByCursorRequest
|
||||
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
with Client(token) as client:
|
||||
accounts = client.users.get_accounts()
|
||||
account_id = accounts.accounts[0].id
|
||||
|
||||
def get_request(cursor=""):
|
||||
return GetOperationsByCursorRequest(
|
||||
account_id=account_id,
|
||||
instrument_id="BBG004730N88",
|
||||
cursor=cursor,
|
||||
limit=1,
|
||||
)
|
||||
|
||||
operations = client.operations.get_operations_by_cursor(get_request())
|
||||
print(operations)
|
||||
depth = 10
|
||||
while operations.has_next and depth > 0:
|
||||
request = get_request(cursor=operations.next_cursor)
|
||||
operations = client.operations.get_operations_by_cursor(request)
|
||||
pprint(operations)
|
||||
depth -= 1
|
||||
38
invest-python-master/examples/get_orders.py
Normal file
38
invest-python-master/examples/get_orders.py
Normal file
@@ -0,0 +1,38 @@
|
||||
"""Example - How to get list of orders for 1 last hour (maximum requesting period)."""
|
||||
import datetime
|
||||
import logging
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import OrderExecutionReportStatus
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
response = client.users.get_accounts()
|
||||
account, *_ = response.accounts
|
||||
account_id = account.id
|
||||
|
||||
now = datetime.datetime.now()
|
||||
orders = client.orders.get_orders(
|
||||
account_id=account_id,
|
||||
from_=now - datetime.timedelta(hours=1),
|
||||
to=now,
|
||||
# filter only executed or partially executed orders
|
||||
execution_status=[
|
||||
OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_FILL,
|
||||
OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_PARTIALLYFILL,
|
||||
],
|
||||
)
|
||||
print("Orders list:")
|
||||
for order in orders.orders:
|
||||
print(order)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
21
invest-python-master/examples/get_risk_rates.py
Normal file
21
invest-python-master/examples/get_risk_rates.py
Normal file
@@ -0,0 +1,21 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import RiskRatesRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
request = RiskRatesRequest()
|
||||
request.instrument_id = ["BBG001M2SC01", "BBG004730N88"]
|
||||
r = client.instruments.get_risk_rates(request=request)
|
||||
for i in r.instrument_risk_rates:
|
||||
print(i.instrument_uid)
|
||||
print(i.short_risk_rate)
|
||||
print(i.long_risk_rate)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
20
invest-python-master/examples/get_sandbox_max_lots.py
Normal file
20
invest-python-master/examples/get_sandbox_max_lots.py
Normal file
@@ -0,0 +1,20 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import GetMaxLotsRequest
|
||||
from t_tech.invest.sandbox.client import SandboxClient
|
||||
|
||||
TOKEN = os.environ["INVEST_SANDBOX_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with SandboxClient(TOKEN) as client:
|
||||
account_id = client.users.get_accounts().accounts[0].id
|
||||
request = GetMaxLotsRequest(
|
||||
account_id=account_id,
|
||||
instrument_id="BBG004730N88",
|
||||
)
|
||||
print(client.sandbox.get_sandbox_max_lots(request=request))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
22
invest-python-master/examples/get_signals.py
Normal file
22
invest-python-master/examples/get_signals.py
Normal file
@@ -0,0 +1,22 @@
|
||||
"""Example - How to get Signals with filtering"""
|
||||
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import GetSignalsRequest, SignalState
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
request = GetSignalsRequest()
|
||||
request.instrument_uid = "e6123145-9665-43e0-8413-cd61b8aa9b13" # Сбербанк
|
||||
request.active = SignalState.SIGNAL_STATE_ACTIVE # только активные сигналы
|
||||
r = client.signals.get_signals(request=request)
|
||||
for signal in r.signals:
|
||||
print(signal)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
19
invest-python-master/examples/get_strategies.py
Normal file
19
invest-python-master/examples/get_strategies.py
Normal file
@@ -0,0 +1,19 @@
|
||||
"""Example - How to get Strategies"""
|
||||
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import GetStrategiesRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
r = client.signals.get_strategies(request=GetStrategiesRequest())
|
||||
for strategy in r.strategies:
|
||||
print(strategy)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
40
invest-python-master/examples/get_tech_analysis.py
Normal file
40
invest-python-master/examples/get_tech_analysis.py
Normal file
@@ -0,0 +1,40 @@
|
||||
import os
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import (
|
||||
Deviation,
|
||||
GetTechAnalysisRequest,
|
||||
IndicatorInterval,
|
||||
IndicatorType,
|
||||
Smoothing,
|
||||
TypeOfPrice,
|
||||
)
|
||||
from t_tech.invest.utils import decimal_to_quotation, now
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
request = GetTechAnalysisRequest(
|
||||
indicator_type=IndicatorType.INDICATOR_TYPE_RSI,
|
||||
instrument_uid="6542a064-6633-44ba-902f-710c97507522",
|
||||
from_=now() - timedelta(days=7),
|
||||
to=now(),
|
||||
interval=IndicatorInterval.INDICATOR_INTERVAL_4_HOUR,
|
||||
type_of_price=TypeOfPrice.TYPE_OF_PRICE_AVG,
|
||||
length=42,
|
||||
deviation=Deviation(
|
||||
deviation_multiplier=decimal_to_quotation(Decimal(1.0)),
|
||||
),
|
||||
smoothing=Smoothing(fast_length=13, slow_length=7, signal_smoothing=3),
|
||||
)
|
||||
response = client.market_data.get_tech_analysis(request=request)
|
||||
for indicator in response.technical_indicators:
|
||||
print(indicator.signal)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
10
invest-python-master/examples/get_trading_statuses.py
Normal file
10
invest-python-master/examples/get_trading_statuses.py
Normal file
@@ -0,0 +1,10 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
with Client(token) as client:
|
||||
statuses = client.market_data.get_trading_statuses(instrument_ids=["BBG004730N88"])
|
||||
print(statuses)
|
||||
44
invest-python-master/examples/instrument_cache.py
Normal file
44
invest-python-master/examples/instrument_cache.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import logging
|
||||
import os
|
||||
from pprint import pprint
|
||||
|
||||
from t_tech.invest import Client, InstrumentIdType
|
||||
from t_tech.invest.caching.instruments_cache.instruments_cache import InstrumentsCache
|
||||
from t_tech.invest.caching.instruments_cache.settings import InstrumentsCacheSettings
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
inst = client.instruments.etfs().instruments[-1]
|
||||
pprint(inst)
|
||||
|
||||
from_server = client.instruments.etf_by(
|
||||
id_type=InstrumentIdType.INSTRUMENT_ID_TYPE_UID,
|
||||
class_code=inst.class_code,
|
||||
id=inst.uid,
|
||||
)
|
||||
pprint(from_server)
|
||||
|
||||
settings = InstrumentsCacheSettings()
|
||||
instruments_cache = InstrumentsCache(
|
||||
settings=settings, instruments_service=client.instruments
|
||||
)
|
||||
|
||||
from_cache = instruments_cache.etf_by(
|
||||
id_type=InstrumentIdType.INSTRUMENT_ID_TYPE_UID,
|
||||
class_code=inst.class_code,
|
||||
id=inst.uid,
|
||||
)
|
||||
pprint(from_cache)
|
||||
|
||||
if str(from_server) != str(from_cache):
|
||||
raise Exception("cache miss")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,28 @@
|
||||
import asyncio
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import GetAssetReportsRequest
|
||||
from t_tech.invest.utils import now
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
instruments = await client.instruments.find_instrument(
|
||||
query="Тинькофф Квадратные метры"
|
||||
)
|
||||
instrument = instruments.instruments[0]
|
||||
print(instrument.name)
|
||||
request = GetAssetReportsRequest(
|
||||
instrument_id=instrument.uid,
|
||||
from_=now() - timedelta(days=7),
|
||||
to=now(),
|
||||
)
|
||||
print(await client.instruments.get_asset_reports(request=request))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,24 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import AssetsRequest, InstrumentStatus, InstrumentType
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
r = await client.instruments.get_assets(
|
||||
request=AssetsRequest(
|
||||
instrument_type=InstrumentType.INSTRUMENT_TYPE_SHARE,
|
||||
instrument_status=InstrumentStatus.INSTRUMENT_STATUS_BASE,
|
||||
) # pylint:disable=line-too-long
|
||||
)
|
||||
print("BASE SHARE ASSETS")
|
||||
for bond in r.assets:
|
||||
print(bond)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,27 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient, InstrumentType
|
||||
from t_tech.invest.schemas import EventType, GetBondEventsRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
bond = (
|
||||
await client.instruments.find_instrument(
|
||||
query="Тинькофф Банк выпуск 1",
|
||||
instrument_kind=InstrumentType.INSTRUMENT_TYPE_BOND,
|
||||
)
|
||||
).instruments[0]
|
||||
|
||||
request = GetBondEventsRequest(
|
||||
instrument_id=bond.uid,
|
||||
type=EventType.EVENT_TYPE_CALL,
|
||||
)
|
||||
print(await client.instruments.get_bond_events(request=request))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
20
invest-python-master/examples/instruments/async_get_bonds.py
Normal file
20
invest-python-master/examples/instruments/async_get_bonds.py
Normal file
@@ -0,0 +1,20 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import InstrumentExchangeType
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
bonds = await client.instruments.bonds(
|
||||
instrument_exchange=InstrumentExchangeType.INSTRUMENT_EXCHANGE_UNSPECIFIED,
|
||||
)
|
||||
for bond in bonds.instruments:
|
||||
print(bond)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,22 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import GetConsensusForecastsRequest, Page
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
request = GetConsensusForecastsRequest(
|
||||
paging=Page(page_number=0, limit=2),
|
||||
)
|
||||
response = await client.instruments.get_consensus_forecasts(request=request)
|
||||
print(response.page)
|
||||
for forecast in response.items:
|
||||
print(forecast.uid, forecast.consensus.name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,23 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import GetForecastRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
async def main():
|
||||
async with AsyncClient(TOKEN) as client:
|
||||
instrument = (
|
||||
await client.instruments.find_instrument(
|
||||
query="Сбер Банк - привилегированные акции"
|
||||
)
|
||||
).instruments[0]
|
||||
request = GetForecastRequest(instrument_id=instrument.uid)
|
||||
response = await client.instruments.get_forecast_by(request=request)
|
||||
print(instrument.name, response.consensus.recommendation.name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,22 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import InstrumentsRequest, InstrumentStatus
|
||||
|
||||
|
||||
async def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
with AsyncClient(token) as client:
|
||||
r = await client.instruments.structured_notes(
|
||||
request=InstrumentsRequest(
|
||||
instrument_status=InstrumentStatus.INSTRUMENT_STATUS_ALL
|
||||
)
|
||||
)
|
||||
for note in r.instruments:
|
||||
print(note)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,21 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
from t_tech.invest.schemas import InstrumentIdType, InstrumentRequest
|
||||
|
||||
|
||||
async def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
with AsyncClient(token) as client:
|
||||
r = await client.instruments.structured_note_by(
|
||||
request=InstrumentRequest(
|
||||
id_type=InstrumentIdType.INSTRUMENT_ID_TYPE_FIGI, id="BBG012S2DCJ8"
|
||||
)
|
||||
)
|
||||
print(r.instrument)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,18 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import GetAssetFundamentalsRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
request = GetAssetFundamentalsRequest(
|
||||
assets=["40d89385-a03a-4659-bf4e-d3ecba011782"],
|
||||
)
|
||||
print(client.instruments.get_asset_fundamentals(request=request))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,27 @@
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import GetAssetReportsRequest
|
||||
from t_tech.invest.utils import now
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
instruments = client.instruments.find_instrument(
|
||||
query="Тинькофф Квадратные метры"
|
||||
)
|
||||
instrument = instruments.instruments[0]
|
||||
print(instrument.name)
|
||||
request = GetAssetReportsRequest(
|
||||
instrument_id=instrument.uid,
|
||||
from_=now() - timedelta(days=7),
|
||||
to=now(),
|
||||
)
|
||||
print(client.instruments.get_asset_reports(request=request))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
28
invest-python-master/examples/instruments/get_assets.py
Normal file
28
invest-python-master/examples/instruments/get_assets.py
Normal file
@@ -0,0 +1,28 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import AssetsRequest, InstrumentStatus, InstrumentType
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
r = client.instruments.get_assets(
|
||||
request=AssetsRequest(instrument_type=InstrumentType.INSTRUMENT_TYPE_BOND)
|
||||
)
|
||||
print("BONDS")
|
||||
for bond in r.assets:
|
||||
print(bond)
|
||||
r = client.instruments.get_assets(
|
||||
request=AssetsRequest(
|
||||
instrument_status=InstrumentStatus.INSTRUMENT_STATUS_BASE
|
||||
)
|
||||
)
|
||||
print("BASE ASSETS")
|
||||
for bond in r.assets:
|
||||
print(bond)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
24
invest-python-master/examples/instruments/get_bond_events.py
Normal file
24
invest-python-master/examples/instruments/get_bond_events.py
Normal file
@@ -0,0 +1,24 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import EventType, GetBondEventsRequest, InstrumentType
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
bond = client.instruments.find_instrument(
|
||||
query="Тинькофф Банк выпуск 1",
|
||||
instrument_kind=InstrumentType.INSTRUMENT_TYPE_BOND,
|
||||
).instruments[0]
|
||||
|
||||
request = GetBondEventsRequest(
|
||||
instrument_id=bond.uid,
|
||||
type=EventType.EVENT_TYPE_CALL,
|
||||
)
|
||||
print(client.instruments.get_bond_events(request=request))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
19
invest-python-master/examples/instruments/get_bonds.py
Normal file
19
invest-python-master/examples/instruments/get_bonds.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import InstrumentExchangeType
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
r = client.instruments.bonds(
|
||||
instrument_exchange=InstrumentExchangeType.INSTRUMENT_EXCHANGE_UNSPECIFIED
|
||||
)
|
||||
for bond in r.instruments:
|
||||
print(bond)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
18
invest-python-master/examples/instruments/get_brands.py
Normal file
18
invest-python-master/examples/instruments/get_brands.py
Normal file
@@ -0,0 +1,18 @@
|
||||
"""Example - How to get Brands"""
|
||||
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
r = client.instruments.get_brands()
|
||||
for brand in r.brands:
|
||||
print(brand)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,28 @@
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import (
|
||||
GetAssetReportsRequest,
|
||||
GetConsensusForecastsRequest,
|
||||
InstrumentIdType,
|
||||
Page,
|
||||
)
|
||||
from t_tech.invest.utils import now
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
request = GetConsensusForecastsRequest(
|
||||
paging=Page(page_number=0, limit=2),
|
||||
)
|
||||
response = client.instruments.get_consensus_forecasts(request=request)
|
||||
print(response.page)
|
||||
for forecast in response.items:
|
||||
print(forecast.uid, forecast.consensus.name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
20
invest-python-master/examples/instruments/get_dfa_by.py
Normal file
20
invest-python-master/examples/instruments/get_dfa_by.py
Normal file
@@ -0,0 +1,20 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client, InstrumentIdType, InstrumentRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
dfa = client.instruments.dfa_by(
|
||||
request=InstrumentRequest(
|
||||
id_type=InstrumentIdType.INSTRUMENT_ID_TYPE_POSITION_UID,
|
||||
id="ce604b33-70c7-4609-9f42-075dbd9fe278",
|
||||
)
|
||||
)
|
||||
print(dfa)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
16
invest-python-master/examples/instruments/get_dfas.py
Normal file
16
invest-python-master/examples/instruments/get_dfas.py
Normal file
@@ -0,0 +1,16 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
r = client.instruments.dfas()
|
||||
for dfa in r.instruments:
|
||||
print(dfa)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
28
invest-python-master/examples/instruments/get_forecast_by.py
Normal file
28
invest-python-master/examples/instruments/get_forecast_by.py
Normal file
@@ -0,0 +1,28 @@
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import (
|
||||
GetAssetReportsRequest,
|
||||
GetConsensusForecastsRequest,
|
||||
GetForecastRequest,
|
||||
InstrumentIdType,
|
||||
Page,
|
||||
)
|
||||
from t_tech.invest.utils import now
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
instrument = client.instruments.find_instrument(
|
||||
query="Сбер Банк - привилегированные акции"
|
||||
).instruments[0]
|
||||
request = GetForecastRequest(instrument_id=instrument.uid)
|
||||
response = client.instruments.get_forecast_by(request=request)
|
||||
print(instrument.name, response.consensus.recommendation.name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Example - How to get list of insider deals.
|
||||
Request data in loop with batches of 10 records.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import GetInsiderDealsRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
deals = []
|
||||
|
||||
next_cursor = None
|
||||
while True:
|
||||
response = client.instruments.get_insider_deals(
|
||||
request=GetInsiderDealsRequest(
|
||||
instrument_id="BBG004730N88", limit=10, next_cursor=next_cursor
|
||||
)
|
||||
)
|
||||
deals.extend(response.insider_deals)
|
||||
next_cursor = response.next_cursor
|
||||
if not next_cursor:
|
||||
break
|
||||
print("Insider deals:")
|
||||
for deal in deals:
|
||||
print(deal)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
18
invest-python-master/examples/instruments/indicatives.py
Normal file
18
invest-python-master/examples/instruments/indicatives.py
Normal file
@@ -0,0 +1,18 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import IndicativesRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
request = IndicativesRequest()
|
||||
indicatives = client.instruments.indicatives(request=request)
|
||||
for instrument in indicatives.instruments:
|
||||
print(instrument.name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,54 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import (
|
||||
CreateFavoriteGroupRequest,
|
||||
DeleteFavoriteGroupRequest,
|
||||
EditFavoritesActionType as At,
|
||||
EditFavoritesRequestInstrument,
|
||||
GetFavoriteGroupsRequest,
|
||||
)
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
r = client.instruments.get_favorites()
|
||||
|
||||
print("Список избранных инструментов:")
|
||||
for i in r.favorite_instruments:
|
||||
print(f"{i.uid} - {i.name}")
|
||||
|
||||
request = CreateFavoriteGroupRequest()
|
||||
request.group_name = "My test favorite group"
|
||||
request.group_color = "aa0000" # red color
|
||||
r = client.instruments.create_favorite_group(request=request)
|
||||
group_id = r.group_id
|
||||
print(f"Создана новая группа избранного с ИД: {group_id}")
|
||||
|
||||
client.instruments.edit_favorites(
|
||||
instruments=[EditFavoritesRequestInstrument(instrument_id="BBG001M2SC01")],
|
||||
action_type=At.EDIT_FAVORITES_ACTION_TYPE_ADD,
|
||||
group_id=group_id,
|
||||
)
|
||||
|
||||
request = GetFavoriteGroupsRequest()
|
||||
request.instrument_id = ["BBG001M2SC01"]
|
||||
r = client.instruments.get_favorite_groups(request=request)
|
||||
print(f"Список групп избранного:")
|
||||
for i in r.groups:
|
||||
print(
|
||||
f"{i.group_id} - {i.group_name}. Количество элементов: {i.size}. "
|
||||
f"Содержит выбранный инструмент {request.instrument_id[0]}: "
|
||||
f"{i.contains_instrument} "
|
||||
)
|
||||
|
||||
request = DeleteFavoriteGroupRequest()
|
||||
request.group_id = group_id
|
||||
client.instruments.delete_favorite_group(request=request)
|
||||
print(f"Удалена группа избранного с ИД: {group_id}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,19 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client, InstrumentIdType
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
r = client.instruments.get_instrument_by(
|
||||
id_type=InstrumentIdType.INSTRUMENT_ID_TYPE_TICKER,
|
||||
id="LKOH",
|
||||
class_code="TQBR",
|
||||
)
|
||||
print(r.instrument)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
16
invest-python-master/examples/instruments/instruments.py
Normal file
16
invest-python-master/examples/instruments/instruments.py
Normal file
@@ -0,0 +1,16 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
r = client.instruments.find_instrument(query="BBG001M2SC01")
|
||||
for i in r.instruments:
|
||||
print(i)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
16
invest-python-master/examples/instruments/options.py
Normal file
16
invest-python-master/examples/instruments/options.py
Normal file
@@ -0,0 +1,16 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
r = client.instruments.options()
|
||||
for instrument in r.instruments:
|
||||
print(instrument)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,21 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import InstrumentsRequest, InstrumentStatus
|
||||
|
||||
|
||||
def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
with Client(token) as client:
|
||||
r = client.instruments.structured_notes(
|
||||
request=InstrumentsRequest(
|
||||
instrument_status=InstrumentStatus.INSTRUMENT_STATUS_ALL
|
||||
)
|
||||
)
|
||||
for note in r.instruments:
|
||||
print(note)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,21 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import InstrumentIdType, InstrumentRequest
|
||||
|
||||
|
||||
def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
with Client(token) as client:
|
||||
r = client.instruments.structured_note_by(
|
||||
request=InstrumentRequest(
|
||||
id_type=InstrumentIdType.INSTRUMENT_ID_TYPE_UID,
|
||||
id="1d7dfabb-9e82-4de4-8add-8475db83d2bd",
|
||||
)
|
||||
)
|
||||
print(r.instrument)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
23
invest-python-master/examples/logger.py
Normal file
23
invest-python-master/examples/logger.py
Normal file
@@ -0,0 +1,23 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client, RequestError
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
logging.basicConfig(format="%(asctime)s %(levelname)s:%(message)s", level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
_ = client.users.get_accounts().accounts
|
||||
try:
|
||||
client.users.get_margin_attributes(account_id="123")
|
||||
except RequestError as err:
|
||||
tracking_id = err.metadata.tracking_id if err.metadata else ""
|
||||
logger.error("Error tracking_id=%s code=%s", tracking_id, str(err.code))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
137
invest-python-master/examples/market_order_stop_order.py
Normal file
137
invest-python-master/examples/market_order_stop_order.py
Normal file
@@ -0,0 +1,137 @@
|
||||
"""
|
||||
Алгоритм:
|
||||
|
||||
выставляем рыночный ордер по дешевой бумаге
|
||||
если он не исполнен - возвращаем ошибку (код и message)
|
||||
если он исполнен и вернулся его идентификатор,
|
||||
то выставляем тейкпрофит на цену +5% к цене покупки
|
||||
и стоплосс на -2% к цене покупки.
|
||||
Контур выбираем: песочница или боевой.
|
||||
|
||||
Примеры дешевых акций:
|
||||
BBG001M2SC01 84.120000000р
|
||||
BBG000K3STR7 134.900000000р
|
||||
BBG00F9XX7H4 142.000000000р
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
from t_tech.invest import (
|
||||
Client,
|
||||
OrderDirection,
|
||||
OrderExecutionReportStatus,
|
||||
OrderType,
|
||||
PostOrderResponse,
|
||||
StopOrderDirection,
|
||||
StopOrderExpirationType,
|
||||
StopOrderType,
|
||||
)
|
||||
from t_tech.invest.services import Services
|
||||
from t_tech.invest.utils import decimal_to_quotation, money_to_decimal, now
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
QUANTITY = 1
|
||||
INSTRUMENT_ID = "BBG001M2SC01"
|
||||
TAKE_PROFIT_PERCENTAGE = 0.05
|
||||
STOP_LOSS_PERCENTAGE = -0.02
|
||||
MIN_PRICE_STEP = 0.02
|
||||
STOP_ORDER_EXPIRE_DURATION = timedelta(hours=1)
|
||||
EXPIRATION_TYPE = StopOrderExpirationType.STOP_ORDER_EXPIRATION_TYPE_GOOD_TILL_DATE
|
||||
|
||||
|
||||
def main():
|
||||
logger.info("Using Real market")
|
||||
with Client(TOKEN) as client:
|
||||
response = client.users.get_accounts()
|
||||
account, *_ = response.accounts
|
||||
account_id = account.id
|
||||
|
||||
order_id = str(uuid.uuid4())
|
||||
|
||||
logger.info(
|
||||
"Placing order for %s security of %s, with order_id=%s",
|
||||
QUANTITY,
|
||||
INSTRUMENT_ID,
|
||||
order_id,
|
||||
)
|
||||
post_order_response: PostOrderResponse = client.orders.post_order(
|
||||
quantity=QUANTITY,
|
||||
direction=OrderDirection.ORDER_DIRECTION_BUY,
|
||||
account_id=account_id,
|
||||
order_type=OrderType.ORDER_TYPE_MARKET,
|
||||
order_id=order_id,
|
||||
instrument_id=INSTRUMENT_ID,
|
||||
)
|
||||
|
||||
status = post_order_response.execution_report_status
|
||||
if status == OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_FILL:
|
||||
logger.info("Order was fulfilled, posting stop orders.")
|
||||
|
||||
post_stop_orders(
|
||||
client=client,
|
||||
account_id=account_id,
|
||||
post_order_response=post_order_response,
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
'Order was not fulfilled: (%s) "%s"',
|
||||
post_order_response.execution_report_status,
|
||||
post_order_response.message,
|
||||
)
|
||||
logger.info("Cancelling all orders.")
|
||||
client.cancel_all_orders(account_id=account_id)
|
||||
|
||||
|
||||
def post_stop_orders(
|
||||
client: Services, account_id: str, post_order_response: PostOrderResponse
|
||||
):
|
||||
executed_order_price = money_to_decimal(post_order_response.executed_order_price)
|
||||
take_profit_price = executed_order_price * Decimal((1 + TAKE_PROFIT_PERCENTAGE))
|
||||
take_profit_price -= take_profit_price % Decimal(MIN_PRICE_STEP)
|
||||
take_profit_response = client.stop_orders.post_stop_order(
|
||||
quantity=QUANTITY,
|
||||
price=decimal_to_quotation(take_profit_price),
|
||||
stop_price=decimal_to_quotation(take_profit_price),
|
||||
direction=StopOrderDirection.STOP_ORDER_DIRECTION_SELL,
|
||||
account_id=account_id,
|
||||
stop_order_type=StopOrderType.STOP_ORDER_TYPE_TAKE_PROFIT,
|
||||
instrument_id=INSTRUMENT_ID,
|
||||
expire_date=now() + STOP_ORDER_EXPIRE_DURATION,
|
||||
expiration_type=EXPIRATION_TYPE,
|
||||
order_id=str(uuid.uuid4()),
|
||||
)
|
||||
logger.info(
|
||||
"Take profit order was placed stop_order_id=%s. Price: %s",
|
||||
take_profit_response.stop_order_id,
|
||||
take_profit_price,
|
||||
)
|
||||
stop_loss_price = executed_order_price * Decimal((1 + STOP_LOSS_PERCENTAGE))
|
||||
stop_loss_price -= stop_loss_price % Decimal(MIN_PRICE_STEP)
|
||||
take_profit_response = client.stop_orders.post_stop_order(
|
||||
quantity=QUANTITY,
|
||||
stop_price=decimal_to_quotation(stop_loss_price),
|
||||
direction=StopOrderDirection.STOP_ORDER_DIRECTION_SELL,
|
||||
account_id=account_id,
|
||||
stop_order_type=StopOrderType.STOP_ORDER_TYPE_STOP_LOSS,
|
||||
instrument_id=INSTRUMENT_ID,
|
||||
expire_date=now() + STOP_ORDER_EXPIRE_DURATION,
|
||||
expiration_type=EXPIRATION_TYPE,
|
||||
order_id=str(uuid.uuid4()),
|
||||
)
|
||||
logger.info(
|
||||
"Stop loss order was placed stop_order_id=%s. Price: %s",
|
||||
take_profit_response.stop_order_id,
|
||||
stop_loss_price,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
36
invest-python-master/examples/max_lots.py
Normal file
36
invest-python-master/examples/max_lots.py
Normal file
@@ -0,0 +1,36 @@
|
||||
"""Example - How to get available limits."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client, GetMaxLotsRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
INSTRUMENT_ID = "TCS00A105GE2"
|
||||
|
||||
|
||||
def main():
|
||||
logger.info("Getting Max Lots")
|
||||
with Client(TOKEN) as client:
|
||||
response = client.users.get_accounts()
|
||||
account, *_ = response.accounts
|
||||
account_id = account.id
|
||||
|
||||
logger.info(
|
||||
"Calculating available order amount for instrument=%s and market price",
|
||||
INSTRUMENT_ID,
|
||||
)
|
||||
get_max_lots = client.orders.get_max_lots(
|
||||
GetMaxLotsRequest(account_id=account_id, instrument_id=INSTRUMENT_ID)
|
||||
)
|
||||
|
||||
print(get_max_lots)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
15
invest-python-master/examples/open_sandbox_account.py
Normal file
15
invest-python-master/examples/open_sandbox_account.py
Normal file
@@ -0,0 +1,15 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest.sandbox.client import SandboxClient
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with SandboxClient(TOKEN) as client:
|
||||
print(client.sandbox.open_sandbox_account(name="tcs"))
|
||||
print(client.users.get_accounts())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
26
invest-python-master/examples/operations_stream.py
Normal file
26
invest-python-master/examples/operations_stream.py
Normal file
@@ -0,0 +1,26 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import OperationsStreamRequest, PingDelaySettings
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
accounts = client.users.get_accounts().accounts
|
||||
accounts = [i.id for i in accounts]
|
||||
print(f"Subscribe for operations on accounts: {accounts}")
|
||||
for operation in client.operations_stream.operations_stream(
|
||||
OperationsStreamRequest(
|
||||
accounts=accounts,
|
||||
ping_settings=PingDelaySettings(
|
||||
ping_delay_ms=5000,
|
||||
),
|
||||
)
|
||||
):
|
||||
print(operation)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
48
invest-python-master/examples/order_price.py
Normal file
48
invest-python-master/examples/order_price.py
Normal file
@@ -0,0 +1,48 @@
|
||||
"""Example - How to get order price."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
from decimal import Decimal
|
||||
|
||||
from t_tech.invest import Client, GetOrderPriceRequest, OrderDirection
|
||||
from t_tech.invest.utils import decimal_to_quotation
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
INSTRUMENT_ID = "TCS00A105GE2"
|
||||
QUANTITY = 1
|
||||
PRICE = 230.1
|
||||
|
||||
|
||||
def main():
|
||||
logger.info("Getting Max Lots")
|
||||
with Client(TOKEN) as client:
|
||||
response = client.users.get_accounts()
|
||||
account, *_ = response.accounts
|
||||
account_id = account.id
|
||||
|
||||
logger.info(
|
||||
"Get pre-trade order commission and price for instrument=%s, quantity=%s and price=%s",
|
||||
INSTRUMENT_ID,
|
||||
QUANTITY,
|
||||
PRICE,
|
||||
)
|
||||
get_order_price = client.orders.get_order_price(
|
||||
GetOrderPriceRequest(
|
||||
account_id=account_id,
|
||||
instrument_id=INSTRUMENT_ID,
|
||||
quantity=QUANTITY,
|
||||
direction=OrderDirection.ORDER_DIRECTION_BUY,
|
||||
price=decimal_to_quotation(Decimal(PRICE)),
|
||||
)
|
||||
)
|
||||
|
||||
print(get_order_price)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
19
invest-python-master/examples/order_state_stream.py
Normal file
19
invest-python-master/examples/order_state_stream.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.schemas import OrderStateStreamRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
request = OrderStateStreamRequest()
|
||||
request.ping_delay_millis = 10000
|
||||
stream = client.orders_stream.order_state_stream(request=request)
|
||||
for order_state in stream:
|
||||
print(order_state)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
18
invest-python-master/examples/porfolio_stream_client.py
Normal file
18
invest-python-master/examples/porfolio_stream_client.py
Normal file
@@ -0,0 +1,18 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
accounts = client.users.get_accounts()
|
||||
for portfolio in client.operations_stream.portfolio_stream(
|
||||
accounts=[acc.id for acc in accounts.accounts], ping_delay_ms=60_000
|
||||
):
|
||||
print(portfolio)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
19
invest-python-master/examples/positions_stream.py
Normal file
19
invest-python-master/examples/positions_stream.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
response = client.users.get_accounts()
|
||||
accounts = [account.id for account in response.accounts]
|
||||
for response in client.operations_stream.positions_stream(
|
||||
accounts=accounts, with_initial_positions=True
|
||||
): # noqa:E501 # pylint:disable=line-too-long
|
||||
print(response)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
36
invest-python-master/examples/post_order.py
Normal file
36
invest-python-master/examples/post_order.py
Normal file
@@ -0,0 +1,36 @@
|
||||
"""Example - How to Post order"""
|
||||
|
||||
import os
|
||||
from uuid import uuid4
|
||||
|
||||
from t_tech.invest import Client, OrderDirection, OrderType
|
||||
from t_tech.invest.sandbox.client import SandboxClient
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
"""
|
||||
Примеры дешевых акций:
|
||||
BBG001M2SC01 84.120000000р
|
||||
BBG000K3STR7 134.900000000р
|
||||
BBG00F9XX7H4 142.000000000р
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
accounts = client.users.get_accounts()
|
||||
account_id = accounts.accounts[0].id
|
||||
|
||||
response = client.orders.post_order(
|
||||
order_type=OrderType.ORDER_TYPE_MARKET,
|
||||
direction=OrderDirection.ORDER_DIRECTION_BUY,
|
||||
instrument_id="BBG004730ZJ9",
|
||||
quantity=1,
|
||||
account_id=account_id,
|
||||
order_id=str(uuid4()),
|
||||
)
|
||||
print(response)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
30
invest-python-master/examples/post_order_async.py
Normal file
30
invest-python-master/examples/post_order_async.py
Normal file
@@ -0,0 +1,30 @@
|
||||
"""Example - How to get Post Order"""
|
||||
|
||||
import os
|
||||
from uuid import uuid4
|
||||
|
||||
from t_tech.invest import Client, OrderDirection, OrderType
|
||||
from t_tech.invest.schemas import PostOrderAsyncRequest
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
accounts = client.users.get_accounts()
|
||||
account_id = accounts.accounts[0].id
|
||||
|
||||
request = PostOrderAsyncRequest(
|
||||
order_type=OrderType.ORDER_TYPE_MARKET,
|
||||
direction=OrderDirection.ORDER_DIRECTION_BUY,
|
||||
instrument_id="BBG004730ZJ9",
|
||||
quantity=1,
|
||||
account_id=account_id,
|
||||
order_id=str(uuid4()),
|
||||
)
|
||||
response = client.orders.post_order_async(request=request)
|
||||
print(response)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
22
invest-python-master/examples/retrying_client.py
Normal file
22
invest-python-master/examples/retrying_client.py
Normal file
@@ -0,0 +1,22 @@
|
||||
import logging
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
from t_tech.invest import CandleInterval
|
||||
from t_tech.invest.retrying.settings import RetryClientSettings
|
||||
from t_tech.invest.retrying.sync.client import RetryingClient
|
||||
from t_tech.invest.utils import now
|
||||
|
||||
logging.basicConfig(format="%(asctime)s %(levelname)s:%(message)s", level=logging.DEBUG)
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
retry_settings = RetryClientSettings(use_retry=True, max_retry_attempt=2)
|
||||
|
||||
with RetryingClient(TOKEN, settings=retry_settings) as client:
|
||||
for candle in client.get_all_candles(
|
||||
figi="BBG000B9XRY4",
|
||||
from_=now() - timedelta(days=301),
|
||||
interval=CandleInterval.CANDLE_INTERVAL_1_MIN,
|
||||
):
|
||||
print(candle)
|
||||
@@ -0,0 +1,40 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from _decimal import Decimal
|
||||
|
||||
from t_tech.invest import utils
|
||||
from t_tech.invest.sandbox.async_client import AsyncSandboxClient
|
||||
from t_tech.invest.schemas import (
|
||||
GetOrderPriceRequest,
|
||||
GetOrderPriceResponse,
|
||||
OrderDirection,
|
||||
)
|
||||
|
||||
|
||||
async def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
async with AsyncSandboxClient(token) as client:
|
||||
accounts = await client.users.get_accounts()
|
||||
account_id = accounts.accounts[0].id
|
||||
response = await get_async_order_price(client, account_id, 105)
|
||||
print(utils.money_to_decimal(response.total_order_amount))
|
||||
|
||||
|
||||
async def get_async_order_price(
|
||||
sandbox_service, account_id, price
|
||||
) -> GetOrderPriceResponse:
|
||||
return await sandbox_service.sandbox.get_sandbox_order_price(
|
||||
request=GetOrderPriceRequest(
|
||||
account_id=account_id,
|
||||
instrument_id="BBG004730ZJ9",
|
||||
direction=OrderDirection.ORDER_DIRECTION_BUY,
|
||||
quantity=1,
|
||||
price=utils.decimal_to_quotation(Decimal(price)),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,41 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest.sandbox.client import SandboxClient
|
||||
from t_tech.invest.schemas import (
|
||||
CancelStopOrderRequest,
|
||||
CancelStopOrderResponse,
|
||||
GetStopOrdersRequest,
|
||||
StopOrderStatusOption,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
with SandboxClient(token) as client:
|
||||
accounts = client.users.get_accounts()
|
||||
account_id = accounts.accounts[0].id
|
||||
stop_orders = client.sandbox.get_sandbox_stop_orders(
|
||||
request=GetStopOrdersRequest(
|
||||
account_id=account_id,
|
||||
status=StopOrderStatusOption.STOP_ORDER_STATUS_ACTIVE,
|
||||
)
|
||||
)
|
||||
stop_order_id = stop_orders.stop_orders[0].stop_order_id
|
||||
response = cancel_stop_order(client, account_id, stop_order_id)
|
||||
print(f"Отменена отложенная заявка id={stop_order_id}: {response}")
|
||||
|
||||
|
||||
def cancel_stop_order(
|
||||
sandbox_service, account_id, stop_order_id
|
||||
) -> CancelStopOrderResponse:
|
||||
return sandbox_service.sandbox.cancel_sandbox_stop_order(
|
||||
request=CancelStopOrderRequest(
|
||||
account_id=account_id,
|
||||
stop_order_id=stop_order_id,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,39 @@
|
||||
import os
|
||||
|
||||
from _decimal import Decimal
|
||||
|
||||
from t_tech.invest import utils
|
||||
from t_tech.invest.sandbox.client import SandboxClient
|
||||
from t_tech.invest.schemas import (
|
||||
GetOrderPriceRequest,
|
||||
GetOrderPriceResponse,
|
||||
OrderDirection,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
with SandboxClient(token) as client:
|
||||
accounts = client.users.get_accounts()
|
||||
account_id = accounts.accounts[0].id
|
||||
response = get_order_price(client, account_id, "BBG004730ZJ9", 105)
|
||||
print(utils.money_to_decimal(response.total_order_amount))
|
||||
|
||||
|
||||
def get_order_price(
|
||||
sandbox_service, account_id, instrument_id, price
|
||||
) -> GetOrderPriceResponse:
|
||||
return sandbox_service.sandbox.get_sandbox_order_price(
|
||||
request=GetOrderPriceRequest(
|
||||
account_id=account_id,
|
||||
instrument_id=instrument_id,
|
||||
direction=OrderDirection.ORDER_DIRECTION_BUY,
|
||||
quantity=1,
|
||||
price=utils.decimal_to_quotation(Decimal(price)),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,36 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest.sandbox.client import SandboxClient
|
||||
from t_tech.invest.schemas import (
|
||||
GetStopOrdersRequest,
|
||||
GetStopOrdersResponse,
|
||||
StopOrderStatusOption,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
with SandboxClient(token) as client:
|
||||
accounts = client.users.get_accounts()
|
||||
account_id = accounts.accounts[0].id
|
||||
response = get_stop_orders(
|
||||
client, account_id, StopOrderStatusOption.STOP_ORDER_STATUS_ACTIVE
|
||||
)
|
||||
if len(response.stop_orders) > 0:
|
||||
print(response.stop_orders)
|
||||
else:
|
||||
print("Активных отложенных заявок не найдено")
|
||||
|
||||
|
||||
def get_stop_orders(sandbox_service, account_id, status) -> GetStopOrdersResponse:
|
||||
return sandbox_service.sandbox.get_sandbox_stop_orders(
|
||||
request=GetStopOrdersRequest(
|
||||
account_id=account_id,
|
||||
status=status,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,58 @@
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from _decimal import Decimal
|
||||
|
||||
from t_tech.invest import (
|
||||
PostStopOrderRequest,
|
||||
PostStopOrderRequestTrailingData,
|
||||
PostStopOrderResponse,
|
||||
StopOrderExpirationType,
|
||||
StopOrderType,
|
||||
)
|
||||
from t_tech.invest.sandbox.client import SandboxClient
|
||||
from t_tech.invest.schemas import Quotation, StopOrderDirection, TrailingValueType
|
||||
from t_tech.invest.utils import decimal_to_quotation
|
||||
|
||||
|
||||
def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
with SandboxClient(token) as client:
|
||||
accounts = client.users.get_accounts()
|
||||
account_id = accounts.accounts[0].id
|
||||
response = post_stop_order(
|
||||
client,
|
||||
account_id,
|
||||
"BBG004730ZJ9",
|
||||
stop_order_direction=StopOrderDirection.STOP_ORDER_DIRECTION_BUY,
|
||||
quantity=1,
|
||||
price=Quotation(units=10, nano=0),
|
||||
)
|
||||
print(response)
|
||||
|
||||
|
||||
def post_stop_order(
|
||||
sandbox_service, account_id, instrument_id, stop_order_direction, quantity, price
|
||||
) -> PostStopOrderResponse:
|
||||
return sandbox_service.sandbox.post_sandbox_stop_order(
|
||||
request=PostStopOrderRequest(
|
||||
account_id=account_id,
|
||||
instrument_id=instrument_id,
|
||||
direction=stop_order_direction,
|
||||
quantity=quantity,
|
||||
price=price,
|
||||
order_id=str(uuid.uuid4()),
|
||||
expiration_type=StopOrderExpirationType.STOP_ORDER_EXPIRATION_TYPE_GOOD_TILL_CANCEL,
|
||||
stop_price=price,
|
||||
stop_order_type=StopOrderType.STOP_ORDER_TYPE_TAKE_PROFIT,
|
||||
trailing_data=PostStopOrderRequestTrailingData(
|
||||
indent_type=TrailingValueType.TRAILING_VALUE_RELATIVE,
|
||||
indent=decimal_to_quotation(Decimal(1)),
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
14
invest-python-master/examples/sandbox_client.py
Normal file
14
invest-python-master/examples/sandbox_client.py
Normal file
@@ -0,0 +1,14 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest.sandbox.client import SandboxClient
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with SandboxClient(TOKEN) as client:
|
||||
print(client.users.get_info())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
84
invest-python-master/examples/strategies/moving_average.py
Normal file
84
invest-python-master/examples/strategies/moving_average.py
Normal file
@@ -0,0 +1,84 @@
|
||||
import logging
|
||||
import os
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
from matplotlib import pyplot as plt
|
||||
|
||||
from t_tech.invest import CandleInterval, Client
|
||||
from t_tech.invest.strategies.base.account_manager import AccountManager
|
||||
from t_tech.invest.strategies.moving_average.plotter import MovingAverageStrategyPlotter
|
||||
from t_tech.invest.strategies.moving_average.signal_executor import (
|
||||
MovingAverageSignalExecutor,
|
||||
)
|
||||
from t_tech.invest.strategies.moving_average.strategy import MovingAverageStrategy
|
||||
from t_tech.invest.strategies.moving_average.strategy_settings import (
|
||||
MovingAverageStrategySettings,
|
||||
)
|
||||
from t_tech.invest.strategies.moving_average.strategy_state import (
|
||||
MovingAverageStrategyState,
|
||||
)
|
||||
from t_tech.invest.strategies.moving_average.supervisor import (
|
||||
MovingAverageStrategySupervisor,
|
||||
)
|
||||
from t_tech.invest.strategies.moving_average.trader import MovingAverageStrategyTrader
|
||||
|
||||
logging.basicConfig(format="%(asctime)s %(levelname)s:%(message)s", level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
FIGI = os.environ["INVEST_FIGI"]
|
||||
ACCOUNT_ID = os.environ["INVEST_ACCOUNT_ID"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as services:
|
||||
settings = MovingAverageStrategySettings(
|
||||
share_id=FIGI,
|
||||
account_id=ACCOUNT_ID,
|
||||
max_transaction_price=Decimal(10000),
|
||||
candle_interval=CandleInterval.CANDLE_INTERVAL_1_MIN,
|
||||
long_period=timedelta(minutes=100),
|
||||
short_period=timedelta(minutes=20),
|
||||
std_period=timedelta(minutes=30),
|
||||
)
|
||||
|
||||
account_manager = AccountManager(services=services, strategy_settings=settings)
|
||||
state = MovingAverageStrategyState()
|
||||
strategy = MovingAverageStrategy(
|
||||
settings=settings,
|
||||
account_manager=account_manager,
|
||||
state=state,
|
||||
)
|
||||
signal_executor = MovingAverageSignalExecutor(
|
||||
services=services,
|
||||
state=state,
|
||||
settings=settings,
|
||||
)
|
||||
supervisor = MovingAverageStrategySupervisor()
|
||||
trader = MovingAverageStrategyTrader(
|
||||
strategy=strategy,
|
||||
settings=settings,
|
||||
services=services,
|
||||
state=state,
|
||||
signal_executor=signal_executor,
|
||||
account_manager=account_manager,
|
||||
supervisor=supervisor,
|
||||
)
|
||||
plotter = MovingAverageStrategyPlotter(settings=settings)
|
||||
|
||||
initial_balance = account_manager.get_current_balance()
|
||||
|
||||
for i in range(5):
|
||||
logger.info("Trade %s", i)
|
||||
trader.trade()
|
||||
|
||||
current_balance = account_manager.get_current_balance()
|
||||
|
||||
logger.info("Initial balance %s", initial_balance)
|
||||
logger.info("Current balance %s", current_balance)
|
||||
|
||||
events = supervisor.get_events()
|
||||
plotter.plot(events)
|
||||
plt.show()
|
||||
1546
invest-python-master/examples/strategies/param-search.ipynb
Normal file
1546
invest-python-master/examples/strategies/param-search.ipynb
Normal file
File diff suppressed because one or more lines are too long
254
invest-python-master/examples/strategies/real-time-render.ipynb
Normal file
254
invest-python-master/examples/strategies/real-time-render.ipynb
Normal file
File diff suppressed because one or more lines are too long
43
invest-python-master/examples/stream_client.py
Normal file
43
invest-python-master/examples/stream_client.py
Normal file
@@ -0,0 +1,43 @@
|
||||
import os
|
||||
import time
|
||||
|
||||
from t_tech.invest import (
|
||||
CandleInstrument,
|
||||
Client,
|
||||
MarketDataRequest,
|
||||
SubscribeCandlesRequest,
|
||||
SubscriptionAction,
|
||||
SubscriptionInterval,
|
||||
)
|
||||
from t_tech.invest.schemas import CandleSource
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
def request_iterator():
|
||||
yield MarketDataRequest(
|
||||
subscribe_candles_request=SubscribeCandlesRequest(
|
||||
waiting_close=True,
|
||||
subscription_action=SubscriptionAction.SUBSCRIPTION_ACTION_SUBSCRIBE,
|
||||
candle_source_type=CandleSource.CANDLE_SOURCE_EXCHANGE,
|
||||
instruments=[
|
||||
CandleInstrument(
|
||||
figi="BBG004730N88",
|
||||
interval=SubscriptionInterval.SUBSCRIPTION_INTERVAL_ONE_MINUTE,
|
||||
)
|
||||
],
|
||||
)
|
||||
)
|
||||
while True:
|
||||
time.sleep(1)
|
||||
|
||||
with Client(TOKEN) as client:
|
||||
for marketdata in client.market_data_stream.market_data_stream(
|
||||
request_iterator()
|
||||
):
|
||||
print(marketdata)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
78
invest-python-master/examples/trailing_stop.py
Normal file
78
invest-python-master/examples/trailing_stop.py
Normal file
@@ -0,0 +1,78 @@
|
||||
"""Example - Trailing Stop Take Profit order.
|
||||
spread=0.5 relative value
|
||||
indent=0.5 absolute value
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from decimal import Decimal
|
||||
|
||||
from t_tech.invest import (
|
||||
Client,
|
||||
ExchangeOrderType,
|
||||
GetStopOrdersRequest,
|
||||
PostStopOrderRequest,
|
||||
PostStopOrderRequestTrailingData,
|
||||
StopOrderDirection,
|
||||
StopOrderExpirationType,
|
||||
StopOrderTrailingData,
|
||||
StopOrderType,
|
||||
TakeProfitType,
|
||||
)
|
||||
from t_tech.invest.schemas import TrailingValueType
|
||||
from t_tech.invest.utils import decimal_to_quotation
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
INSTRUMENT_ID = "TCS00A105GE2"
|
||||
QUANTITY = 1
|
||||
PRICE = 230.500000000
|
||||
STOPPRICE = 230
|
||||
INDENT = 0.5
|
||||
SPREAD = 0.5
|
||||
|
||||
|
||||
def main():
|
||||
logger.info("Getting Max Lots")
|
||||
with Client(TOKEN) as client:
|
||||
response = client.users.get_accounts()
|
||||
account, *_ = response.accounts
|
||||
account_id = account.id
|
||||
|
||||
logger.info(
|
||||
"Post take profit stop order for instrument=%s and trailing parameters: indent=%s, spread=%s, price=%s ",
|
||||
INSTRUMENT_ID,
|
||||
INDENT,
|
||||
SPREAD,
|
||||
STOPPRICE,
|
||||
)
|
||||
|
||||
post_stop_order = client.stop_orders.post_stop_order(
|
||||
quantity=QUANTITY,
|
||||
price=decimal_to_quotation(Decimal(PRICE)),
|
||||
stop_price=decimal_to_quotation(Decimal(STOPPRICE)),
|
||||
direction=StopOrderDirection.STOP_ORDER_DIRECTION_SELL,
|
||||
account_id=account_id,
|
||||
stop_order_type=StopOrderType.STOP_ORDER_TYPE_TAKE_PROFIT,
|
||||
instrument_id=INSTRUMENT_ID,
|
||||
expiration_type=StopOrderExpirationType.STOP_ORDER_EXPIRATION_TYPE_GOOD_TILL_CANCEL,
|
||||
exchange_order_type=ExchangeOrderType.EXCHANGE_ORDER_TYPE_LIMIT,
|
||||
take_profit_type=TakeProfitType.TAKE_PROFIT_TYPE_TRAILING,
|
||||
trailing_data=StopOrderTrailingData(
|
||||
indent=decimal_to_quotation(Decimal(INDENT)),
|
||||
indent_type=TrailingValueType.TRAILING_VALUE_ABSOLUTE,
|
||||
spread=decimal_to_quotation(Decimal(SPREAD)),
|
||||
spread_type=TrailingValueType.TRAILING_VALUE_RELATIVE,
|
||||
),
|
||||
)
|
||||
|
||||
print(post_stop_order)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,41 @@
|
||||
import asyncio
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from _decimal import Decimal
|
||||
|
||||
from t_tech.invest import AccountType, AsyncClient
|
||||
from t_tech.invest.schemas import CurrencyTransferRequest
|
||||
from t_tech.invest.utils import decimal_to_money
|
||||
|
||||
|
||||
async def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
async with AsyncClient(token) as client:
|
||||
accounts = [
|
||||
i
|
||||
for i in (await client.users.get_accounts()).accounts
|
||||
if i.type == AccountType.ACCOUNT_TYPE_TINKOFF
|
||||
]
|
||||
|
||||
if len(accounts) < 2:
|
||||
print("Недостаточно счетов для демонстрации")
|
||||
return
|
||||
|
||||
from_account_id = accounts[0].id
|
||||
to_account_id = accounts[1].id
|
||||
|
||||
await client.users.currency_transfer(
|
||||
CurrencyTransferRequest(
|
||||
from_account_id=from_account_id,
|
||||
to_account_id=to_account_id,
|
||||
amount=decimal_to_money(Decimal(1), "rub"),
|
||||
transaction_id=str(uuid.uuid4()),
|
||||
)
|
||||
)
|
||||
print("Перевод выполнен")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,16 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from t_tech.invest import AsyncClient
|
||||
|
||||
|
||||
async def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
async with AsyncClient(token) as client:
|
||||
response = await client.users.get_bank_accounts()
|
||||
print(response)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
41
invest-python-master/examples/users/async_pay_in.py
Normal file
41
invest-python-master/examples/users/async_pay_in.py
Normal file
@@ -0,0 +1,41 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from _decimal import Decimal
|
||||
|
||||
from t_tech.invest import AccountType, AsyncClient
|
||||
from t_tech.invest.schemas import PayInRequest
|
||||
from t_tech.invest.utils import decimal_to_money
|
||||
|
||||
|
||||
async def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
async with AsyncClient(token) as client:
|
||||
accounts = [
|
||||
i
|
||||
for i in (await client.users.get_accounts()).accounts
|
||||
if i.type == AccountType.ACCOUNT_TYPE_TINKOFF
|
||||
]
|
||||
|
||||
bank_accounts = await client.users.get_bank_accounts()
|
||||
|
||||
if len(accounts) < 1 or len(bank_accounts.bank_accounts) < 1:
|
||||
print("Недостаточно счетов для демонстрации")
|
||||
return
|
||||
|
||||
from_account_id = bank_accounts.bank_accounts[0].id
|
||||
to_account_id = accounts[0].id
|
||||
|
||||
await client.users.pay_in(
|
||||
PayInRequest(
|
||||
from_account_id=from_account_id,
|
||||
to_account_id=to_account_id,
|
||||
amount=decimal_to_money(Decimal(1), "rub"),
|
||||
)
|
||||
)
|
||||
print("Пополнение выполнено")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
40
invest-python-master/examples/users/currency_transfer.py
Normal file
40
invest-python-master/examples/users/currency_transfer.py
Normal file
@@ -0,0 +1,40 @@
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from _decimal import Decimal
|
||||
|
||||
from t_tech.invest import AccountType, Client
|
||||
from t_tech.invest.schemas import CurrencyTransferRequest
|
||||
from t_tech.invest.utils import decimal_to_money
|
||||
|
||||
|
||||
def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
with Client(token) as client:
|
||||
accounts = [
|
||||
i
|
||||
for i in client.users.get_accounts().accounts
|
||||
if i.type == AccountType.ACCOUNT_TYPE_TINKOFF
|
||||
]
|
||||
|
||||
if len(accounts) < 2:
|
||||
print("Недостаточно счетов для демонстрации")
|
||||
return
|
||||
|
||||
from_account_id = accounts[0].id
|
||||
to_account_id = accounts[1].id
|
||||
|
||||
client.users.currency_transfer(
|
||||
CurrencyTransferRequest(
|
||||
from_account_id=from_account_id,
|
||||
to_account_id=to_account_id,
|
||||
amount=decimal_to_money(Decimal(1), "rub"),
|
||||
transaction_id=str(uuid.uuid4()),
|
||||
)
|
||||
)
|
||||
print("Перевод выполнен")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
15
invest-python-master/examples/users/get_bank_accounts.py
Normal file
15
invest-python-master/examples/users/get_bank_accounts.py
Normal file
@@ -0,0 +1,15 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
|
||||
|
||||
def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
with Client(token) as client:
|
||||
response = client.users.get_bank_accounts()
|
||||
print(response)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
15
invest-python-master/examples/users/get_user_info.py
Normal file
15
invest-python-master/examples/users/get_user_info.py
Normal file
@@ -0,0 +1,15 @@
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
|
||||
def main():
|
||||
with Client(TOKEN) as client:
|
||||
response = client.users.get_info()
|
||||
print(response)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
40
invest-python-master/examples/users/pay_in.py
Normal file
40
invest-python-master/examples/users/pay_in.py
Normal file
@@ -0,0 +1,40 @@
|
||||
import os
|
||||
|
||||
from _decimal import Decimal
|
||||
|
||||
from t_tech.invest import AccountType, Client
|
||||
from t_tech.invest.schemas import PayInRequest
|
||||
from t_tech.invest.utils import decimal_to_money
|
||||
|
||||
|
||||
def main():
|
||||
token = os.environ["INVEST_TOKEN"]
|
||||
|
||||
with Client(token) as client:
|
||||
accounts = [
|
||||
i
|
||||
for i in client.users.get_accounts().accounts
|
||||
if i.type == AccountType.ACCOUNT_TYPE_TINKOFF
|
||||
]
|
||||
|
||||
bank_accounts = client.users.get_bank_accounts().bank_accounts
|
||||
|
||||
if len(accounts) < 1 or len(bank_accounts) < 1:
|
||||
print("Недостаточно счетов для демонстрации")
|
||||
return
|
||||
|
||||
from_account_id = bank_accounts[0].id
|
||||
to_account_id = accounts[0].id
|
||||
|
||||
client.users.pay_in(
|
||||
PayInRequest(
|
||||
from_account_id=from_account_id,
|
||||
to_account_id=to_account_id,
|
||||
amount=decimal_to_money(Decimal(1), "rub"),
|
||||
)
|
||||
)
|
||||
print("Пополнение выполнено")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Example - How to cancel all stop orders."""
|
||||
import logging
|
||||
import os
|
||||
|
||||
from t_tech.invest import Client
|
||||
from t_tech.invest.exceptions import InvestError
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
logging.basicConfig(format="%(asctime)s %(levelname)s:%(message)s", level=logging.DEBUG)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def main():
|
||||
"""Example - How to cancel all stop orders."""
|
||||
with Client(TOKEN) as client:
|
||||
response = client.users.get_accounts()
|
||||
account, *_ = response.accounts
|
||||
account_id = account.id
|
||||
|
||||
try:
|
||||
stop_orders_response = client.stop_orders.get_stop_orders(
|
||||
account_id=account_id
|
||||
)
|
||||
logger.info("Stop Orders: %s", stop_orders_response)
|
||||
for stop_order in stop_orders_response.stop_orders:
|
||||
client.stop_orders.cancel_stop_order(
|
||||
account_id=account_id, stop_order_id=stop_order.stop_order_id
|
||||
)
|
||||
logger.info("Stop Order: %s was canceled.", stop_order.stop_order_id)
|
||||
logger.info(
|
||||
"Orders: %s", client.stop_orders.get_stop_orders(account_id=account_id)
|
||||
)
|
||||
except InvestError as error:
|
||||
logger.error("Failed to cancel all orders. Error: %s", error)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Example - How to create takeprofit buy order."""
|
||||
import logging
|
||||
import os
|
||||
from decimal import Decimal
|
||||
|
||||
from t_tech.invest import (
|
||||
Client,
|
||||
InstrumentIdType,
|
||||
StopOrderDirection,
|
||||
StopOrderExpirationType,
|
||||
StopOrderType,
|
||||
)
|
||||
from t_tech.invest.exceptions import InvestError
|
||||
from t_tech.invest.utils import decimal_to_quotation, quotation_to_decimal
|
||||
|
||||
TOKEN = os.environ["INVEST_TOKEN"]
|
||||
|
||||
logging.basicConfig(format="%(asctime)s %(levelname)s:%(message)s", level=logging.DEBUG)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def main():
|
||||
"""Example - How to create takeprofit buy order."""
|
||||
with Client(TOKEN) as client:
|
||||
response = client.users.get_accounts()
|
||||
account, *_ = response.accounts
|
||||
account_id = account.id
|
||||
logger.info("Orders: %s", client.orders.get_orders(account_id=account_id))
|
||||
|
||||
figi = "BBG004730ZJ9" # BBG004730ZJ9 - VTBR / BBG004730N88 - SBER
|
||||
|
||||
# getting the last price for instrument
|
||||
last_price = (
|
||||
client.market_data.get_last_prices(figi=[figi]).last_prices[0].price
|
||||
)
|
||||
last_price = quotation_to_decimal(last_price)
|
||||
print(f"figi, last price = {last_price}")
|
||||
|
||||
# setting the percentage by which the takeprofit stop order
|
||||
# should be set below the last price
|
||||
percent_down = 5
|
||||
|
||||
# calculation of the price for takeprofit stop order
|
||||
calculated_price = last_price - last_price * Decimal(percent_down / 100)
|
||||
print(f"calculated_price = {calculated_price}")
|
||||
|
||||
# getting the min price increment and the number of digits after point
|
||||
min_price_increment = client.instruments.get_instrument_by(
|
||||
id_type=InstrumentIdType.INSTRUMENT_ID_TYPE_FIGI, id=figi
|
||||
).instrument.min_price_increment
|
||||
number_digits_after_point = 9 - len(str(min_price_increment.nano)) + 1
|
||||
min_price_increment = quotation_to_decimal(min_price_increment)
|
||||
print(
|
||||
f"min_price_increment = {min_price_increment}, "
|
||||
f"number_digits_after_point={number_digits_after_point}"
|
||||
)
|
||||
|
||||
# calculation of the price for instrument which is
|
||||
# divisible to min price increment
|
||||
calculated_price = (
|
||||
round(calculated_price / min_price_increment) * min_price_increment
|
||||
)
|
||||
print(
|
||||
f"let's send stop order at price = "
|
||||
f"{calculated_price:.{number_digits_after_point}f} divisible to "
|
||||
f"min price increment {min_price_increment}"
|
||||
)
|
||||
|
||||
# creating takeprofit buy order
|
||||
stop_order_type = StopOrderType.STOP_ORDER_TYPE_TAKE_PROFIT
|
||||
direction = StopOrderDirection.STOP_ORDER_DIRECTION_BUY
|
||||
exp_type = StopOrderExpirationType.STOP_ORDER_EXPIRATION_TYPE_GOOD_TILL_CANCEL
|
||||
try:
|
||||
response = client.stop_orders.post_stop_order(
|
||||
figi=figi,
|
||||
quantity=1,
|
||||
price=decimal_to_quotation(Decimal(calculated_price)),
|
||||
stop_price=decimal_to_quotation(Decimal(calculated_price)),
|
||||
direction=direction,
|
||||
account_id=account_id,
|
||||
expiration_type=exp_type,
|
||||
stop_order_type=stop_order_type,
|
||||
expire_date=None,
|
||||
)
|
||||
print(response)
|
||||
print("stop_order_id=", response.stop_order_id)
|
||||
except InvestError as error:
|
||||
logger.error("Posting trade takeprofit order failed. Exception: %s", error)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user