Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/ invest-robot-contest_tinkoffSDK-master/my_account_manager.py
5925 views
1
import logging
2
from decimal import Decimal
3
4
from tinkoff.invest import Quotation
5
from tinkoff.invest.services import Services
6
from tinkoff.invest.strategies.base.errors import (
7
InsufficientMarginalTradeFunds, MarginalTradeIsNotActive)
8
from tinkoff.invest.strategies.base.strategy_settings_base import \
9
StrategySettings
10
from tinkoff.invest.utils import quotation_to_decimal
11
12
logger = logging.getLogger(__name__)
13
14
15
class AccountManager:
16
def __init__(self, services: Services,
17
strategy_settings: StrategySettings):
18
self._services = services
19
self._strategy_settings = strategy_settings
20
21
def get_current_balance(self) -> Decimal:
22
account_id = self._strategy_settings.account_id
23
portfolio_response = self._services.operations.get_portfolio(
24
account_id=account_id
25
)
26
balance = portfolio_response.total_amount_currencies
27
shares = portfolio_response.total_amount_shares
28
return (
29
quotation_to_decimal(Quotation(units=balance.units, nano=balance.nano)),
30
quotation_to_decimal(Quotation(units=shares.units, nano=balance.nano))
31
)
32
33
def ensure_marginal_trade(self) -> None:
34
account_id = self._strategy_settings.account_id
35
try:
36
response = self._services.users.get_margin_attributes(account_id=account_id)
37
except Exception as e:
38
raise MarginalTradeIsNotActive() from e
39
value = quotation_to_decimal(response.funds_sufficiency_level)
40
if value <= 1:
41
raise InsufficientMarginalTradeFunds()
42
logger.info("Marginal trade is active")
43
44