Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/ invest-robot-contest_tinkoffSDK-master/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,
8
MarginalTradeIsNotActive,
9
)
10
from tinkoff.invest.strategies.base.strategy_settings_base import StrategySettings
11
from tinkoff.invest.utils import quotation_to_decimal
12
13
logger = logging.getLogger(__name__)
14
15
16
class AccountManager:
17
def __init__(self, services: Services, 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 quotation_to_decimal(Quotation(units=balance.units, nano=balance.nano)), quotation_to_decimal(Quotation(units=shares.units, nano=balance.nano))
29
30
def ensure_marginal_trade(self) -> None:
31
account_id = self._strategy_settings.account_id
32
try:
33
response = self._services.users.get_margin_attributes(account_id=account_id)
34
except Exception as e:
35
raise MarginalTradeIsNotActive() from e
36
value = quotation_to_decimal(response.funds_sufficiency_level)
37
if value <= 1:
38
raise InsufficientMarginalTradeFunds()
39
logger.info("Marginal trade is active")
40
41