### Set Up Market Data Time Range Source: https://github.com/russianinvestments/invest-python/blob/main/examples/strategies/real-time-render.ipynb Establishes the historical market data time range for testing the strategy. It defines a `start_datetime` function and calculates `real_market_data_test_from`, `real_market_data_test_start`, and `real_market_data_test_end` based on this starting point. ```python def start_datetime() -> datetime: return datetime(year=2022, month=2, day=16, hour=17, tzinfo=timezone.utc) real_market_data_test_from = start_datetime() - timedelta(days=1) real_market_data_test_start = start_datetime() real_market_data_test_end = start_datetime() + timedelta(days=3) ``` -------------------------------- ### Import Tinkoff Invest Strategy Components Source: https://github.com/russianinvestments/invest-python/blob/main/examples/strategies/real-time-render.ipynb Imports necessary modules for implementing a moving average trading strategy, including client, settings, state, supervisor, and trader classes from `tinkoff.invest`. It also configures basic logging. ```python import logging from tinkoff.invest.mock_services import MockedSandboxClient from decimal import Decimal from tinkoff.invest.strategies.moving_average.strategy_settings import ( MovingAverageStrategySettings, ) from tinkoff.invest import CandleInterval, MoneyValue from tinkoff.invest.strategies.moving_average.signal_executor import ( MovingAverageSignalExecutor, ) from tinkoff.invest.strategies.moving_average.supervisor import ( MovingAverageStrategySupervisor, ) from tinkoff.invest.strategies.moving_average.strategy_state import ( MovingAverageStrategyState, ) from tinkoff.invest.strategies.moving_average.strategy import MovingAverageStrategy from tinkoff.invest.strategies.moving_average.trader import MovingAverageStrategyTrader from datetime import timedelta, datetime, timezone from tinkoff.invest.typedefs import ShareId, AccountId from tinkoff.invest.strategies.base.account_manager import AccountManager from tinkoff.invest.strategies.moving_average.plotter import ( MovingAverageStrategyPlotter, ) logging.basicConfig(format="%(asctime)s %(levelname)s:%(message)s", level=logging.INFO) logger = logging.getLogger(__name__) ``` -------------------------------- ### Execute Moving Average Trading Simulation Source: https://github.com/russianinvestments/invest-python/blob/main/examples/strategies/real-time-render.ipynb Initializes and runs a simulated trading session using the `MockedSandboxClient`. It sets up various strategy components, including the account manager, strategy state, supervisor, signal executor, and the main trader. The code then iterates through a series of simulated trades, logging progress and plotting events. ```python with MockedSandboxClient( token=token, balance=balance, ) as mocked_services: account_manager = AccountManager( services=mocked_services, strategy_settings=settings ) state = MovingAverageStrategyState() strategy = MovingAverageStrategy( settings=settings, account_manager=account_manager, state=state, ) supervisor = MovingAverageStrategySupervisor() signal_executor = MovingAverageSignalExecutor( services=mocked_services, state=state, settings=settings, ) moving_average_strategy_trader = MovingAverageStrategyTrader( strategy=strategy, settings=settings, services=mocked_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(50): logger.info("Trade %s", i) events = list(supervisor.get_events()) plotter.plot(events) try: moving_average_strategy_trader.trade() except Exception: pass ``` -------------------------------- ### Specify Initial Account Balance Source: https://github.com/russianinvestments/invest-python/blob/main/examples/strategies/real-time-render.ipynb Defines the initial monetary balance available in the trading account for the simulation. This balance is used by the `MockedSandboxClient` to simulate available funds for trades. ```python balance = MoneyValue(currency="rub", units=20050, nano=690000000) ``` -------------------------------- ### Configure API Token Placeholder Source: https://github.com/russianinvestments/invest-python/blob/main/examples/strategies/real-time-render.ipynb Defines a placeholder for the API token required for authentication with the Tinkoff Invest API. This token is crucial for accessing market data and executing trades in a real or mocked environment. ```python token = ``` -------------------------------- ### Verify and Log Final Balance Source: https://github.com/russianinvestments/invest-python/blob/main/examples/strategies/real-time-render.ipynb Asserts that the account balance has changed after the simulated trades, indicating activity. It then logs both the initial and the final current balance of the trading account for review and verification of the simulation's impact. ```python current_balance = account_manager.get_current_balance() assert initial_balance != current_balance logger.info("Initial balance %s", initial_balance) logger.info("Current balance %s", current_balance) ``` -------------------------------- ### Corrected Import Path for MarketDataCache Source: https://github.com/russianinvestments/invest-python/blob/main/BREAKING_CHANGES.md This snippet demonstrates the new, correct import path for the `MarketDataCache` class. As of version 0.2.0-beta60, `MarketDataCache` has been relocated to the `tinkoff.invest.caching.market_data_cache.cache` module. Developers should update their existing code to use this new path to avoid import errors. ```python from tinkoff.invest.caching.market_data_cache.cache import MarketDataCache ``` -------------------------------- ### Deprecated Import Path for MarketDataCache Source: https://github.com/russianinvestments/invest-python/blob/main/BREAKING_CHANGES.md This snippet shows the old import path for the `MarketDataCache` class, which is now deprecated and incorrect as of tinkoff/invest-python version 0.2.0-beta60. Using this import statement will lead to an `ImportError` because the class has been moved to a new module. This is provided for context regarding the breaking change. ```python from tinkoff.invest.services import MarketDataCache ``` -------------------------------- ### Define Moving Average Strategy Settings Source: https://github.com/russianinvestments/invest-python/blob/main/examples/strategies/real-time-render.ipynb Configures the core parameters for the moving average trading strategy. This includes the financial instrument ID (FIGI), account ID, maximum transaction price, candle interval, and the long, short, and standard deviation periods for the moving averages. ```python figi = ShareId("BBG0013HGFT4") account_id = AccountId("1337007228") 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=50), std_period=timedelta(minutes=30), ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.