### Configuration Setup Source: https://context7.com/eidiamond/invest-bot/llms.txt Initialize bot configuration by loading parameters and strategies from a settings file. ```APIDOC ## Configuration Setup ### Description Initialize bot configuration with trading parameters and strategies by loading from a settings file. ### Method N/A (Python class initialization) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from configuration.configuration import ProgramConfiguration # Load configuration from settings.ini file config = ProgramConfiguration("settings.ini") # Access configuration sections tinkoff_token = config.tinkoff_token tinkoff_app_name = config.tinkoff_app_name blog_settings = config.blog_settings account_settings = config.account_settings trading_settings = config.trading_settings trade_strategies = config.trade_strategy_settings ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Start blog worker and send notification messages in Python Source: https://context7.com/eidiamond/invest-bot/llms.txt This function demonstrates starting a background blog worker task and sending various trading-related messages using the Blogger utility. It covers messages for the start of the trading day, opening and closing positions, and summaries of trading activity. Dependencies include asyncio, Decimal, and custom modules like blog_worker, blogger, Signal, and TradeOrder. ```python import asyncio from decimal import Decimal # Assume these are defined elsewhere class BlogWorker: async def worker(self): pass class Blogger: def start_trading_message(self, strategies, amount): pass def open_position_message(self, trade_order): pass def close_position_message(self, trade_order): pass def summary_message(self): pass def trading_depo_summary_message(self, rub_before_trade_day, current_rub_on_depo): pass def final_message(self): pass class Signal: def __init__(self, figi, signal_type, take_profit_level, stop_loss_level): pass class TradeOrder: def __init__(self, signal, open_order_id, close_order_id): pass class SignalType: LONG = "LONG" # Placeholder instances worker = BlogWorker() blogger = Blogger() async def run_notifications(): # Start blog worker worker_task = asyncio.create_task(worker.worker()) # Send trading day start message today_strategies = {} # dict[figi, IStrategy] blogger.start_trading_message(today_strategies, Decimal("50000.00")) # Send position opened message signal = Signal( figi="BBG004730N88", signal_type=SignalType.LONG, take_profit_level=Decimal("250.50"), stop_loss_level=Decimal("245.00") ) trade_order = TradeOrder( signal=signal, open_order_id="order_123", close_order_id=None ) blogger.open_position_message(trade_order) # Send position closed message blogger.close_position_message(trade_order) # Send trading day summary blogger.summary_message() blogger.trading_depo_summary_message( rub_before_trade_day=Decimal("50000.00"), current_rub_on_depo=Decimal("50500.00") ) blogger.final_message() await worker_task # Run the notification system # asyncio.run(run_notifications()) ``` -------------------------------- ### Install Tinkoff Invest Python gRPC Client Source: https://github.com/eidiamond/invest-bot/blob/main/README.md Installs the Tinkoff Invest Python gRPC client library using pip. This library is essential for interacting with the Tinkoff Investments API. ```shell pip install tinkoff-investments ``` -------------------------------- ### Initialize and Run Trading Bot Service (Python) Source: https://context7.com/eidiamond/invest-bot/llms.txt This Python snippet initializes and runs the main trading bot service. It sets up all necessary services from the invest API, configures account and trading settings, loads strategies, and starts both the blog worker and the trade service concurrently. Dependencies include asyncio, various services from trading and invest_api modules, configuration settings, strategy factory, and blogger components. ```python import asyncio from trading.trade_service import TradeService from invest_api.services.accounts_service import AccountService from invest_api.services.client_service import ClientService from invest_api.services.instruments_service import InstrumentService from invest_api.services.market_data_service import MarketDataService from invest_api.services.operations_service import OperationService from invest_api.services.orders_service import OrderService from invest_api.services.market_data_stream_service import MarketDataStreamService from blog.blogger import Blogger from blog.blog_worker import BlogWorker from configuration.settings import AccountSettings, TradingSettings, BlogSettings from trade_system.strategies.strategy_factory import StrategyFactory async def run_trading_bot(): # Initialize all services token = "your_tinkoff_api_token" app_name = "EIDiamond.invest-bot" account_service = AccountService(token, app_name) client_service = ClientService(token, app_name) instrument_service = InstrumentService(token, app_name) operation_service = OperationService(token, app_name) order_service = OrderService(token, app_name) stream_service = MarketDataStreamService(token, app_name) market_data_service = MarketDataService(token, app_name) # Configure settings account_settings = AccountSettings( min_liquid_portfolio=9000, min_rub_on_account=5000 ) trading_settings = TradingSettings( delay_start_after_open=10, stop_trade_before_close=600, stop_signals_before_close=60 ) blog_settings = BlogSettings( blog_status=True, bot_token="telegram_bot_token", chat_id="telegram_chat_id" ) # Load strategies from configuration strategy_configs = [] # Load from settings.ini strategies = [StrategyFactory.new_factory(s.name, s) for s in strategy_configs] # Create message queue for Telegram messages_queue = asyncio.Queue() # Initialize blogger and blog worker blogger = Blogger(blog_settings, strategy_configs, messages_queue) blog_worker = BlogWorker(blog_settings, messages_queue) # Initialize trade service trade_service = TradeService( account_service=account_service, client_service=client_service, instrument_service=instrument_service, operation_service=operation_service, order_service=order_service, stream_service=stream_service, market_data_service=market_data_service, blogger=blogger, account_settings=account_settings, trading_settings=trading_settings, strategies=strategies ) # Run both workers concurrently blog_task = asyncio.create_task(blog_worker.worker()) trade_task = asyncio.create_task(trade_service.worker()) await asyncio.gather(blog_task, trade_task) # Run the bot asyncio.run(run_trading_bot()) ``` -------------------------------- ### Install aiogram for Telegram Bot Integration Source: https://github.com/eidiamond/invest-bot/blob/main/README.md Installs the aiogram library, a modern and asynchronous Telegram Bot API framework for Python. This is used for sending trading information to a Telegram chat. ```shell pip install -U aiogram ``` -------------------------------- ### Get Trading Status and Price with Python Source: https://context7.com/eidiamond/invest-bot/llms.txt This snippet demonstrates how to use the MarketDataService from the invest_api to check if a stock is ready for trading and retrieve its last price. It requires the tinkoff.invest library and handles the conversion of quotation types to decimal. The output indicates whether the stock is tradable and its current last price. ```python from invest_api.services.market_data_service import MarketDataService from tinkoff.invest.utils import quotation_to_decimal # Initialize market data service market_data_service = MarketDataService( token="your_tinkoff_api_token", app_name="EIDiamond.invest-bot" ) # Check if stock is ready for trading figi = "BBG004730N88" # SBER is_ready = market_data_service.is_stock_ready_for_trading(figi) if is_ready: print(f"Stock {figi} is ready for trading") # This means: # - Limit orders are allowed # - Market orders are allowed # - API trading is allowed # - Trading status is NORMAL_TRADING # Get last price last_price = market_data_service.get_last_price(figi) if last_price: price_decimal = quotation_to_decimal(last_price) print(f"Last price for {figi}: {price_decimal}") else: print(f"Stock {figi} is not available for trading") ``` -------------------------------- ### Account Service - Verify Token and Get Trading Account Source: https://context7.com/eidiamond/invest-bot/llms.txt Verify the Tinkoff API token and retrieve a trading account that meets specified criteria. ```APIDOC ## Account Service ### Description Verify API token and retrieve trading account with required permissions and settings. ### Method N/A (Python class initialization and method calls) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python from invest_api.services.accounts_service import AccountService from configuration.settings import AccountSettings # Initialize account service account_service = AccountService( token="your_tinkoff_api_token", app_name="EIDiamond.invest-bot" ) # Verify token is valid if account_service.verify_token(): print("Token verified successfully") # Get trading account ID with required settings account_settings = AccountSettings( min_liquid_portfolio=9000, min_rub_on_account=5000 ) account_id = account_service.trading_account_id(account_settings) if account_id: print(f"Trading account found: {account_id}") else: print("No suitable account found for trading") else: print("Token verification failed") ``` ### Response #### Success Response (200) - **account_id** (string) - The ID of the trading account if found and suitable. #### Response Example ```json { "account_id": "your_account_id" } ``` #### Error Response - **Error Message** (string) - Description of the error (e.g., token verification failed, no suitable account found). #### Error Example ``` Token verification failed ``` ``` -------------------------------- ### Account Service: Verify Token and Get Trading Account (Python) Source: https://context7.com/eidiamond/invest-bot/llms.txt Initializes the AccountService to verify the Tinkoff API token and retrieve a suitable trading account. It checks for full access rights, common account type, open status, minimum liquid portfolio, and green margin status based on provided AccountSettings. ```python from invest_api.services.accounts_service import AccountService from configuration.settings import AccountSettings # Initialize account service account_service = AccountService( token="your_tinkoff_api_token", app_name="EIDiamond.invest-bot" ) # Verify token is valid if account_service.verify_token(): print("Token verified successfully") # Get trading account ID with required settings account_settings = AccountSettings( min_liquid_portfolio=9000, min_rub_on_account=5000 ) account_id = account_service.trading_account_id(account_settings) if account_id: print(f"Trading account found: {account_id}") # Account has: # - Full access rights # - Common account type (not IIS) # - Open status # - Liquid portfolio >= min_liquid_portfolio # - Green margin status (liquid > starting_margin) else: print("No suitable account found for trading") else: print("Token verification failed") ``` -------------------------------- ### Configure Logging and Initialize Services in Python Source: https://context7.com/eidiamond/invest-bot/llms.txt Configures logging with file rotation and initializes various services for the trading bot. It loads program configuration, verifies the Tinkoff token, and sets up trading and blog-related services. Dependencies include the 'logging' module, 'ProgramConfiguration', and several 'Service' classes. ```python import logging from logging.handlers import RotatingFileHandler import sys import asyncio # Assuming ProgramConfiguration, AccountService, ClientService, InstrumentService, OperationService, OrderService, MarketDataStreamService, MarketDataService, StrategyFactory, BlogWorker, Blogger, TradeService are defined elsewhere # from config import ProgramConfiguration # from services import AccountService, ClientService, InstrumentService, OperationService, OrderService, MarketDataStreamService, MarketDataService # from strategy import StrategyFactory # from blog import BlogWorker, Blogger # from trade import TradeService logging.basicConfig( level=logging.DEBUG, format="%(asctime)s - %(module)s - %(levelname)s - %(funcName)s: %(lineno)d - %(message)s", handlers=[RotatingFileHandler('logs/robot.log', maxBytes=100000000, backupCount=10, encoding='utf-8')], encoding="utf-8" ) logger = logging.getLogger(__name__) async def start_trading_bot(): try: # Load configuration config = ProgramConfiguration("settings.ini") logger.info("Configuration loaded") # Initialize services account_service = AccountService(config.tinkoff_token, config.tinkoff_app_name) client_service = ClientService(config.tinkoff_token, config.tinkoff_app_name) instrument_service = InstrumentService(config.tinkoff_token, config.tinkoff_app_name) operation_service = OperationService(config.tinkoff_token, config.tinkoff_app_name) order_service = OrderService(config.tinkoff_token, config.tinkoff_app_name) stream_service = MarketDataStreamService(config.tinkoff_token, config.tinkoff_app_name) market_data_service = MarketDataService(config.tinkoff_token, config.tinkoff_app_name) # Verify token if not account_service.verify_token(): logger.critical("Token verification failed") return # Initialize strategies trade_strategies = [ StrategyFactory.new_factory(s.name, s) for s in config.trade_strategy_settings ] # Setup Telegram messaging messages_queue = asyncio.Queue() blog_worker = BlogWorker(config.blog_settings, messages_queue) blogger = Blogger(config.blog_settings, config.trade_strategy_settings, messages_queue) # Initialize trade service trade_service = TradeService( account_service=account_service, client_service=client_service, instrument_service=instrument_service, operation_service=operation_service, order_service=order_service, stream_service=stream_service, market_data_service=market_data_service, blogger=blogger, account_settings=config.account_settings, trading_settings=config.trading_settings, strategies=trade_strategies ) # Run both workers logger.info("Starting trading bot workers") blog_task = asyncio.create_task(blog_worker.worker()) trade_task = asyncio.create_task(trade_service.worker()) await asyncio.gather(blog_task, trade_task) except Exception as ex: logger.critical(f"Fatal error: {repr(ex)}") if __name__ == "__main__": # Windows asyncio compatibility if sys.version_info[0] == 3 and sys.version_info[1] >= 8 and sys.platform.startswith('win'): asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) logger.info("Trading bot starting") asyncio.run(start_trading_bot()) logger.info("Trading bot stopped") ``` -------------------------------- ### Initialize Bot Configuration (Python) Source: https://context7.com/eidiamond/invest-bot/llms.txt Loads bot trading parameters and strategies from an 'settings.ini' file using the ProgramConfiguration class. It provides access to various configuration sections like Tinkoff API credentials, blog settings, account limits, trading parameters, and strategy-specific settings. ```python from configuration.configuration import ProgramConfiguration # Load configuration from settings.ini file config = ProgramConfiguration("settings.ini") # Access configuration sections tinkoff_token = config.tinkoff_token tinkoff_app_name = config.tinkoff_app_name blog_settings = config.blog_settings account_settings = config.account_settings trading_settings = config.trading_settings trade_strategies = config.trade_strategy_settings # Example settings.ini structure: """ [INVEST_API] TOKEN=your_tinkoff_api_token APP_NAME=EIDiamond.invest-bot [BLOG] STATUS=1 TELEGRAM_BOT_TOKEN=your_telegram_bot_token TELEGRAM_CHAT_ID=your_chat_id [TRADING_ACCOUNT] MIN_LIQUID_PORTFOLIO=9000 MIN_RUB_ON_ACCOUNT=5000 [TRADING_SETTINGS] DELAY_START_AFTER_EXCHANGE_OPEN_SECONDS=10 STOP_TRADE_BEFORE_EXCHANGE_CLOSE_SECONDS=600 STOP_SIGNALS_BEFORE_EXCHANGE_CLOSE_MINUTES=60 [STRATEGY_SBER] STRATEGY_NAME=ChangeAndVolumeStrategy TICKER=SBER FIGI=BBG004730N88 MAX_LOTS_PER_ORDER=1 [STRATEGY_SBER_SETTINGS] SIGNAL_VOLUME=21000 SIGNAL_MIN_CANDLES=2 SIGNAL_MIN_TAIL=0.2 LONG_TAKE=1.01 LONG_STOP=0.985 SHORT_TAKE=0.99 SHORT_STOP=1.015 """ ``` -------------------------------- ### Initialize Invest Bot application services in Python Source: https://context7.com/eidiamond/invest-bot/llms.txt This code snippet shows the initialization of core services required for the Invest Bot application. It sets up logging, configuration, and various service clients for interacting with the Invest API. Dependencies include asyncio, logging, sys, and custom modules for configuration and API services. ```python import asyncio import logging import sys from logging.handlers import RotatingFileHandler from configuration.configuration import ProgramConfiguration from invest_api.services.accounts_service import AccountService from invest_api.services.client_service import ClientService from invest_api.services.instruments_service import InstrumentService from invest_api.services.market_data_service import MarketDataService from invest_api.services.operations_service import OperationService from invest_api.services.orders_service import OrderService from invest_api.services.market_data_stream_service import MarketDataStreamService from trade_system.strategies.strategy_factory import StrategyFactory from trading.trade_service import TradeService from blog.blog_worker import BlogWorker from blog.blogger import Blogger # Placeholder for configuration loading config = ProgramConfiguration() # Setup logging log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') log_handler = RotatingFileHandler('invest_bot.log', maxBytes=1024*1024, backupCount=3) log_handler.setFormatter(log_formatter) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.addHandler(log_handler) # Initialize services client_service = ClientService(config.invest_api_token, config.invest_api_url) accounts_service = AccountService(client_service) instruments_service = InstrumentService(client_service) market_data_service = MarketDataService(client_service) operations_service = OperationService(client_service) orders_service = OrderService(client_service) market_data_stream_service = MarketDataStreamService(client_service) strategy_factory = StrategyFactory() trade_service = TradeService(accounts_service, instruments_service, market_data_service, operations_service, orders_service, strategy_factory) blog_worker = BlogWorker(trade_service) blogger = Blogger(config.bot_name, config.telegram_chat_id, config.telegram_token) # Example of running the notification system (from previous snippet) # async def main(): # await run_notifications() # # if __name__ == "__main__": # asyncio.run(main()) ``` -------------------------------- ### Initialize Telegram Notification Worker (Python) Source: https://context7.com/eidiamond/invest-bot/llms.txt This Python snippet demonstrates the initialization of components for sending Telegram notifications. It sets up blog settings including the bot token and chat ID, configures strategy settings for ticker mapping, creates an asyncio message queue, and initializes both the Blogger and BlogWorker. These are essential for the Telegram notification integration within the trading bot. ```python import asyncio from blog.blogger import Blogger from blog.blog_worker import BlogWorker from configuration.settings import BlogSettings, StrategySettings from trade_system.signal import Signal, SignalType from trading.trade_results import TradeOrder from decimal import Decimal # Initialize blog settings blog_settings = BlogSettings( blog_status=True, # 1 = enabled, 0 = disabled bot_token="your_telegram_bot_token", chat_id="your_telegram_chat_id" ) # Strategy settings for ticker name mapping strategy_settings = [ StrategySettings( name="ChangeAndVolumeStrategy", figi="BBG004730N88", ticker="SBER", max_lots_per_order=1, settings={} ) ] # Create message queue messages_queue = asyncio.Queue() # Initialize blogger blogger = Blogger(blog_settings, strategy_settings, messages_queue) # Initialize blog worker for sending messages blog_worker = BlogWorker(blog_settings, messages_queue) ``` -------------------------------- ### Implement Custom Trading Strategy with Python Source: https://context7.com/eidiamond/invest-bot/llms.txt This code defines a `CustomStrategy` class that extends the `IStrategy` interface for custom trading logic. It parses strategy-specific settings like threshold, take profit, and stop loss from a `StrategySettings` object. The `analyze_candles` method analyzes historical candle data to generate trading signals (LONG, SHORT, CLOSE) based on predefined conditions, including price movements and risk management levels. It also shows how to register this strategy in a `StrategyFactory`. ```python from trade_system.strategies.base_strategy import IStrategy from trade_system.signal import Signal, SignalType from configuration.settings import StrategySettings from tinkoff.invest import HistoricCandle from tinkoff.invest.utils import quotation_to_decimal from typing import Optional from decimal import Decimal class CustomStrategy(IStrategy): """ Custom trading strategy implementation """ def __init__(self, settings: StrategySettings) -> None: self.__settings = settings # Parse custom settings from configuration self.__threshold = Decimal(settings.settings["THRESHOLD"]) self.__take_profit = Decimal(settings.settings["TAKE_PROFIT"]) self.__stop_loss = Decimal(settings.settings["STOP_LOSS"]) @property def settings(self) -> StrategySettings: return self.__settings def update_lot_count(self, lot: int) -> None: self.__settings.lot_size = lot def update_short_status(self, status: bool) -> None: self.__settings.short_enabled_flag = status def analyze_candles(self, candles: list[HistoricCandle]) -> Optional[Signal]: """ Analyze candles and return trading signal if conditions are met """ if not candles: return None last_candle = candles[-1] open_price = quotation_to_decimal(last_candle.open) close_price = quotation_to_decimal(last_candle.close) # Example logic: buy if price increased by threshold if close_price > open_price * (1 + self.__threshold): return Signal( figi=self.settings.figi, signal_type=SignalType.LONG, take_profit_level=close_price * self.__take_profit, stop_loss_level=close_price * self.__stop_loss ) return None # Register strategy in factory (in strategy_factory.py) from trade_system.strategies.strategy_factory import StrategyFactory class StrategyFactory: @staticmethod def new_factory(name: str, settings: StrategySettings): if name == "CustomStrategy": return CustomStrategy(settings) elif name == "ChangeAndVolumeStrategy": from trade_system.strategies.change_and_volume_strategy import ChangeAndVolumeStrategy return ChangeAndVolumeStrategy(settings) else: raise ValueError(f"Unknown strategy: {name}") # Configure in settings.ini: """ [STRATEGY_SBER] STRATEGY_NAME=CustomStrategy TICKER=SBER FIGI=BBG004730N88 MAX_LOTS_PER_ORDER=1 [STRATEGY_SBER_SETTINGS] THRESHOLD=0.01 TAKE_PROFIT=1.02 STOP_LOSS=0.98 """ ``` -------------------------------- ### Order Service - Market Orders Source: https://context7.com/eidiamond/invest-bot/llms.txt Execute market orders for buying and selling securities, and manage order states. ```APIDOC ## Order Service ### Description Execute market orders for buying and selling securities. Allows for posting market orders, retrieving order states, fetching all active orders, and cancelling orders. ### Method N/A (Python class initialization and method calls) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from invest_api.services.orders_service import OrderService from tinkoff.invest import OrderExecutionReportStatus # Initialize order service order_service = OrderService( token="your_tinkoff_api_token", app_name="EIDiamond.invest-bot" ) # Post market order to buy buy_order = order_service.post_market_order( account_id="your_account_id", figi="BBG004730N88", # SBER count_lots=1, is_buy=True ) if buy_order.execution_report_status == OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_FILL: print(f"Buy order executed: {buy_order.order_id}") # Get order state order_state = order_service.get_order_state( account_id="your_account_id", order_id=buy_order.order_id ) print(f"Lots executed: {order_state.lots_executed}") print(f"Average price: {order_state.average_position_price}") # Post market order to sell sell_order = order_service.post_market_order( account_id="your_account_id", figi="BBG004730N88", count_lots=1, is_buy=False ) # Get all active orders active_orders = order_service.get_orders(account_id="your_account_id") for order in active_orders: print(f"Order ID: {order.order_id}, Status: {order.execution_report_status}") # Cancel an order if needed order_service.cancel_order( account_id="your_account_id", order_id=buy_order.order_id ) ``` ### Response #### Success Response (200) - **post_market_order**: Returns an `OrderExecutionReport` object detailing the executed order. - **get_order_state**: Returns an `OrderState` object with the current status of the order. - **get_orders**: Returns a list of `OrderState` objects for all active orders. - **cancel_order**: Returns a `CancelOrderResult` indicating the success of the cancellation. #### Response Example ```json { "post_market_order": { "order_id": "1234567890", "execution_report_status": "EXECUTION_REPORT_STATUS_FILL", "lots_executed": 1, "initial_order_price": {"units": 100, "nano": 0}, "executed_order_price": {"units": 100, "nano": 0}, "average_position_price": {"units": 100, "nano": 0} }, "get_order_state": { "order_id": "1234567890", "execution_report_status": "EXECUTION_REPORT_STATUS_PARTIALLY_FILL", "lots_requested": 1, "lots_executed": 1, "average_position_price": {"units": 100, "nano": 0} }, "get_orders": [ { "order_id": "1234567890", "execution_report_status": "EXECUTION_REPORT_STATUS_NEW" } ], "cancel_order": { "order_id": "1234567890", "status": "CANCEL_STATUS_SUCCESS" } } ``` #### Error Response - **Error Message** (string) - Description of the error (e.g., invalid account ID, insufficient funds, order not found). #### Error Example ``` Invalid account ID provided. ``` ``` -------------------------------- ### Order Service: Execute Market Orders (Python) Source: https://context7.com/eidiamond/invest-bot/llms.txt Manages the execution of market orders for buying and selling securities using the OrderService. It allows posting market orders, retrieving order states, fetching all active orders, and cancelling specific orders. ```python from invest_api.services.orders_service import OrderService from tinkoff.invest import OrderExecutionReportStatus # Initialize order service order_service = OrderService( token="your_tinkoff_api_token", app_name="EIDiamond.invest-bot" ) # Post market order to buy buy_order = order_service.post_market_order( account_id="your_account_id", figi="BBG004730N88", # SBER count_lots=1, is_buy=True ) if buy_order.execution_report_status == OrderExecutionReportStatus.EXECUTION_REPORT_STATUS_FILL: print(f"Buy order executed: {buy_order.order_id}") # Get order state order_state = order_service.get_order_state( account_id="your_account_id", order_id=buy_order.order_id ) print(f"Lots executed: {order_state.lots_executed}") print(f"Average price: {order_state.average_position_price}") # Post market order to sell sell_order = order_service.post_market_order( account_id="your_account_id", figi="BBG004730N88", count_lots=1, is_buy=False ) # Get all active orders active_orders = order_service.get_orders(account_id="your_account_id") for order in active_orders: print(f"Order ID: {order.order_id}, Status: {order.execution_report_status}") # Cancel an order if needed order_service.cancel_order( account_id="your_account_id", order_id=buy_order.order_id ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.