### Setup Example Notebooks Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/docs/visual-studio-code-docker-dev-container-for-jupyter-notebooks.md This script sets up example notebooks within the development environment by cloning them from the Trading Strategy documentation repository. ```shell scripts/set-up-examples.sh ``` -------------------------------- ### Setup Charting and Output Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum-2.ipynb Configures the notebook environment for charting and output. Prints the number of positions and trades made during the backtest. ```python from tradeexecutor.utils.notebook import setup_charting_and_output # Set notebook output mode setup_charting_and_output() print(f"Positions taken: {len(list(state.portfolio.get_all_positions()))}") print(f"Trades made: {len(list(state.portfolio.get_all_trades()))}") ``` -------------------------------- ### Install with QSTrader Dependency Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/docs/testing.md Installs the project dependencies using poetry, including the optional QSTrader dependency. ```shell poetry install --a ``` -------------------------------- ### Setup Trading Strategy Client and Charting Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/rsi-momentum/v18-new-style-backtest-btc-eth.ipynb Initializes the Trading Strategy client for Jupyter notebooks and configures charting output for static rendering. This is essential for visualizing backtest results. ```python from tradeexecutor.utils.notebook import setup_charting_and_output from tradingstrategy.client import Client client = Client.create_jupyter_client() # Render for Github web viewer from tradeexecutor.utils.notebook import setup_charting_and_output, OutputMode setup_charting_and_output(OutputMode.static, image_format="png", width=1500, height=1000) # etup_charting_and_output(width=1500, height=1000) ``` -------------------------------- ### Install Trade Executor with QSTrader, Web Server, and Execution Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/docs/install.md Clones the trade-executor repository, initializes submodules, and installs all specified features using Poetry. This is the recommended installation for full functionality. ```shell git clone git@github.com:tradingstrategy-ai/trade-executor.git cd trade-executor git submodule update --init --recursive poetry install -E qstrader -E web-server -E execution ``` -------------------------------- ### Setup Charting and Output Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/rsi-momentum/eth-btc-usdc/v39-defi-strategy-review.ipynb Initializes the charting and output environment for the notebook, setting image format and dimensions. This is crucial for rendering visualizations correctly. ```python from tradeexecutor.utils.notebook import setup_charting_and_output from tradingstrategy.client import Client client = Client.create_jupyter_client() # Render for Github web viewer from tradeexecutor.utils.notebook import setup_charting_and_output, OutputMode setup_charting_and_output(OutputMode.static, image_format="png", width=1500, height=1000) # setup_charting_and_output(width=1500, height=1000) ``` -------------------------------- ### Setup Charting and Output Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/rsi-momentum/eth-btc-usdc/v41-defi-strategy-clock-shift-review.ipynb Initializes the charting and output environment for the notebook, setting image format and dimensions. This is crucial for rendering visualizations correctly. ```python from tradeexecutor.utils.notebook import setup_charting_and_output from tradingstrategy.client import Client client = Client.create_jupyter_client() # Render for Github web viewer from tradeexecutor.utils.notebook import setup_charting_and_output, OutputMode setup_charting_and_output(OutputMode.static, image_format="png", width=1500, height=1000) # setup_charting_and_output(width=1500, height=1000) ``` -------------------------------- ### Install Trade Executor (Basic) Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/docs/install.md Installs the trade-executor project with default dependencies. Use this command if you do not require specific features like QSTrader, web-server, or execution. ```shell poetry install ``` -------------------------------- ### Setup Python Environment with Poetry Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/docs/running.md Sets up the Python environment for the trade executor using Poetry. It specifies the Python version, activates the virtual environment, and installs dependencies. ```shell cd trade-executor poetry env use `which python3.9` poetry shell poetry install ``` -------------------------------- ### Set up Charting and Output Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum.ipynb Configures the notebook environment for charting and output. It prints the number of positions and trades made during the backtest. ```python from tradeexecutor.utils.notebook import setup_charting_and_output # Set notebook output mode setup_charting_and_output() print(f"Positions taken: {len(list(state.portfolio.get_all_positions()))}") print(f"Trades made: {len(list(state.portfolio.get_all_trades()))}") ``` -------------------------------- ### Environment Variable Setup for Testing Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/docs/testing.md Sets up essential environment variables required for running tests, including the Trading Strategy API Key and JSON RPC endpoints for blockchain data. ```shell export TRADING_STRATEGY_API_KEY="" export BNB_CHAIN_JSON_RPC="https://bsc-dataseed.binance.org/" ``` -------------------------------- ### Set up Market Data Client Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/defi-bluechip-momentum.ipynb Initializes the market data client using an API key. This client is essential for fetching data feeds required for backtesting. ```python from tradingstrategy.client import Client client = Client.create_jupyter_client() ``` -------------------------------- ### Strategy Parameter Setup Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/defi-bluechip-momentum.ipynb Configures various parameters for the momentum-based portfolio construction strategy, including backtesting period, strategy type, trade routing, cycle duration, asset allocation, risk management thresholds, and initial deposit. ```python import datetime import pandas as pd from tradingstrategy.chain import ChainId from tradingstrategy.timebucket import TimeBucket from tradeexecutor.strategy.cycle import CycleDuration from tradeexecutor.strategy.strategy_module import StrategyType, TradeRouting, ReserveCurrency # Tell what trade execution engine version this strategy needs to use trading_strategy_engine_version = "0.1" # What kind of strategy we are running. # This tells we are going to use trading_strategy_type = StrategyType.managed_positions # How our trades are routed. # PancakeSwap basic routing supports two way trades with BUSD # and three way trades with BUSD-BNB hop. trade_routing = TradeRouting.ignore # Set cycle to 7 days and look back the momentum of the previous candle trading_strategy_cycle = CycleDuration.cycle_7d momentum_lookback_period = datetime.timedelta(days=7) # Hold top 3 coins for every cycle max_assets_in_portfolio = 4 # Leave 20% cash buffer value_allocated_to_positions = 0.80 # Set 33% stop loss over mid price stop_loss = 0.66 # Set 5% take profit over mid price take_profit = 1.05 # The weekly price must be up 2.5% for us to take a long position minimum_mometum_threshold = 0.025 # Don't bother with trades that would move position # less than 300 USD minimum_rebalance_trade_threshold = 300 # Use hourly candles to trigger the stop loss stop_loss_data_granularity = TimeBucket.h1 # Strategy keeps its cash in USDC reserve_currency = ReserveCurrency.usdc # The duration of the backtesting period start_at = datetime.datetime(2020, 11, 1) end_at = datetime.datetime(2023, 1, 31) # Start with 10,000 USD initial_deposit = 10_000 ``` -------------------------------- ### Run Grid Search Command Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum-grid.ipynb Executes the grid search notebook using IPython. This command initiates the backtesting process with parameter optimization. ```shell ipython notebooks/spot-and-short-momentum-grid.ipynb ``` -------------------------------- ### Create Jupyter Client Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/live-strategy-analysis/examine-multipair-breakout.ipynb Initializes a client specifically for use within a Jupyter Notebook environment. This is the first step to interact with the trade executor services. ```python from tradingstrategy.client import Client client = Client.create_jupyter_client() ``` -------------------------------- ### Load Strategy Module Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum.ipynb Loads a specified strategy module from the default strategies path. It retrieves the trading strategy engine version from the loaded module. ```python import datetime from tradeexecutor.utils.default_strategies import get_default_strategies_path from tradeexecutor.strategy.strategy_module import read_strategy_module strategies_folder = get_default_strategies_path() strategy_path = strategies_folder / "spot-and-short-momentum.py" strategy_mod = read_strategy_module(strategy_path) print(f"Backtesting for strategy {strategy_path}, engine version {strategy_mod.trading_strategy_engine_version}") ``` -------------------------------- ### Set Up Market Data Client Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum-grid-2.ipynb Initializes a market data client for accessing trading data. This client is essential for fetching real-time or historical market information required for backtesting and analysis. It depends on the tradeexecutor.client module. ```python from tradingstrategy.client import Client client = Client.create_jupyter_client() ``` -------------------------------- ### Start Trade Executor (Subsequent Runs) Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/docs/running.md Starts the trade executor for subsequent runs after the initial setup and first trade attempt. This command is used for ongoing operation. ```shell bootstraps/pancake_8h_momentum.sh start ``` -------------------------------- ### Set Up Market Data Client Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum-grid-3.ipynb Initializes a market data client for use in a Jupyter environment. This client is used to fetch market data required for backtesting and analysis. ```python from tradingstrategy.client import Client client = Client.create_jupyter_client() ``` -------------------------------- ### Set up Market Data Client Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum.ipynb Initializes the Trading Strategy market data client for Jupyter notebooks. Requires an API key for accessing market data. ```python from tradingstrategy.client import Client client = Client.create_jupyter_client() ``` -------------------------------- ### Set Up Market Data Client Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/breakout-bollinger-bands-old/bb-short-eth-polygon.ipynb This code snippet shows how to initialize the Trading Strategy market data client. It uses `Client.create_jupyter_client()` which is suitable for environments like Jupyter notebooks. The client is responsible for managing data feeds required for backtesting. ```python from tradingstrategy.client import Client client = Client.create_jupyter_client() ``` -------------------------------- ### Visualize Strategy Benchmark Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/defi-bluechip-momentum.ipynb Visualizes the performance of a trading strategy against a buy-and-hold benchmark for ETH/USDC. It requires the universe, state, start and end times, and uses the `visualise_benchmark` function. The output is a Plotly figure. ```python from tradeexecutor.visual.benchmark import visualise_benchmark eth_usd = universe.get_pair_by_human_description((ChainId.ethereum, "uniswap-v2", "WETH", "USDC")) eth_candles = universe.universe.candles.get_candles_by_pair(eth_usd.internal_id) eth_price = eth_candles["close"] fig = visualise_benchmark( state.name, portfolio_statistics=state.stats.portfolio, all_cash=state.portfolio.get_initial_deposit(), buy_and_hold_asset_name="ETH", buy_and_hold_price_series=eth_price, start_at=start_at, end_at=end_at ) fig.show() ``` -------------------------------- ### Run Backtest Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum-2.ipynb Sets up and runs the backtest using the provided strategy path and market data client. It outputs the state, strategy universe, and debug dump. ```python from tradeexecutor.backtest.backtest_runner import setup_backtest, run_backtest setup = setup_backtest( strategy_path, ) state, strategy_universe, debug_dump = run_backtest(setup, client) trade_count = len(list(state.portfolio.get_all_trades())) print(f"Backtesting completed, backtested strategy made {trade_count} trades") ``` -------------------------------- ### Setup Charting and Logging Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/tradeexecutor/backtest/dataset_report_template.ipynb Initializes charting and output settings for notebooks, and configures logging. It imports necessary libraries like traceback and pickle for data handling. ```python # # Setting up # from tradeexecutor.utils.notebook import setup_charting_and_output, OutputMode, set_notebook_logging import traceback import pickle saved_dataset = pickle.load(open(parameters["dataset_file"], "rb")) strategy_universe = pickle.load(open(parameters["universe_file"], "rb")) setup_charting_and_output(OutputMode.static, image_format="png", width=1500, height=1000) ``` -------------------------------- ### Load Trading Universe Data Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/breakout-bollinger-bands-old/bb-short-eth-polygon.ipynb This code loads the necessary data to create a trading universe for backtesting. It specifies the end time, the client, and configures `UniverseOptions` to include a look-back period by adjusting the start time. The `create_single_pair_trading_universe` function is called to fetch and process the data, and the number of loaded candles is printed. ```python from datetime import timedelta from tradeexecutor.strategy.execution_context import ExecutionMode, notebook_execution_context from tradeexecutor.strategy.universe_model import UniverseOptions universe = create_single_pair_trading_universe( END_AT, client, notebook_execution_context, UniverseOptions( # TODO: quick hack to get enough data for look back period start_at=START_AT - timedelta(days=90), end_at=END_AT, ) ) print(f"We loaded {universe.universe.candles.get_candle_count():,} candles.") ``` -------------------------------- ### Install Python Package with Pyodide Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/scripts/pyodide/index.html This snippet shows how to load Pyodide, install the 'micropip' package, and then use 'micropip' to install a Python wheel file from a specified URL. It includes an option to continue installation even if errors occur. ```javascript async function main() { let pyodide = await loadPyodide(); await pyodide.loadPackage("micropip"); const micropip = pyodide.pyimport("micropip"); await micropip.install.callKwargs( 'http://localhost:9000/trade_executor-0.3-py3-none-any.whl', {keep_going: true} ); console.log("Package installed successfully."); } main(); ``` -------------------------------- ### Initialize Market Data Client Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum-2.ipynb Initializes the Trading Strategy market data client for use in Jupyter notebooks. Requires an API key for registration. ```python from tradingstrategy.client import Client client = Client.create_jupyter_client() ``` -------------------------------- ### Prepare Grid Combinations Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum-grid-2.ipynb Prepares combinations of parameters for grid search. It takes a dictionary of parameters with lists of values and generates all possible combinations, storing them in a specified folder. Options for clearing cached results are available. Dependencies include pathlib and tradeexecutor.backtest.grid_search. ```python from pathlib import Path from tradeexecutor.backtest.grid_search import perform_grid_search, prepare_grid_combinations # This is the path where we keep the result files around storage_folder = Path(f"/tmp/{strategy_path.stem}-grid-search") parameters = { "cycle_duration_days": [6, 7, 8], "momentum_lookback": [6, 7, 8], "take_profit": [1.06, 1.07], "negative_take_profit": [1.06, 1.07], "positive_mometum_threshold": [0.0001, 0.025], "negative_mometum_threshold": [-0.06], } combinations = prepare_grid_combinations(parameters, storage_folder, clear_cached_results=True) ``` -------------------------------- ### Run Backtest Inline Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/breakout-bollinger-bands-old/bb-short-eth-polygon.ipynb This code executes a backtest using the `run_backtest_inline` function. It takes parameters such as the backtest name, start and end times, the market data client, cycle duration, the strategy's trade decision function (`decide_trades`), the trading universe, initial deposit, reserve currency, and trade routing. After execution, it prints the total number of trades made during the backtest. ```python from tradeexecutor.backtest.backtest_runner import run_backtest_inline state, universe, debug_dump = run_backtest_inline( name="BB short example", start_at=START_AT, end_at=END_AT, client=client, cycle_duration=TRADING_STRATEGY_CYCLE, decide_trades=decide_trades, universe=universe, initial_deposit=INITIAL_DEPOSIT, reserve_currency=RESERVE_CURRENCY, trade_routing=TRADE_ROUTING, engine_version="0.3", ) trade_count = len(list(state.portfolio.get_all_trades())) print(f"Backtesting completed, backtested strategy made {trade_count} trades") ``` -------------------------------- ### Initialize Market Data Client Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum-grid.ipynb Creates an instance of the Client for accessing market data, specifically tailored for a Jupyter environment. This client is essential for fetching data required for backtesting. ```python from tradingstrategy.client import Client client = Client.create_jupyter_client() ``` -------------------------------- ### Install Trade Executor with Legacy QSTrader Support Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/docs/install.md Installs the trade-executor project with legacy QSTrader support, web server, and execution features. This command is suitable for environments requiring older QSTrader compatibility or for remote development servers. ```shell poetry install -E qstrader -E web-server -E execution ``` -------------------------------- ### Install Trade Executor from GitHub URL with Pip Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/README.md This command demonstrates installing the trade-executor package directly from its GitHub master branch using pip, with specified extras. ```shell pip install -e "git+https://github.com/tradingstrategy-ai/trade-executor.git@master#egg=trade-executor[web-server,execution,qstrader,quantstats]" ``` -------------------------------- ### Install Trade Executor from GitHub with Poetry Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/README.md This shell command demonstrates how to clone the trade-executor repository from GitHub, update submodules, and install all dependencies including extras using Poetry. ```shell git clone git@github.com:tradingstrategy-ai/trade-executor.git cd trade-executor git submodule update --init --recursive # Extra dependencies # - execution: infrastructure to run live strategies # - web-server: support webhook server of live strategy executors # - qstrader: still needed to run legacy unit tests poetry install --all-extras ``` -------------------------------- ### Run Backtest Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum.ipynb Sets up and runs the backtest using the provided strategy path and market data client. It outputs the backtest state, strategy universe, and debug information. The engine downloads necessary datasets, which can be large. ```python from tradeexecutor.backtest.backtest_runner import setup_backtest, run_backtest setup = setup_backtest( strategy_path, ) state, strategy_universe, debug_dump = run_backtest(setup, client) trade_count = len(list(state.portfolio.get_all_trades())) print(f"Backtesting completed, backtested strategy made {trade_count} trades") ``` -------------------------------- ### Install Trade Executor with Pip Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/README.md This command shows how to install the trade-executor package in editable mode using pip, including specific extras for web server, execution, qstrader, and quantstats. ```shell pip install -e ".[web-server,execution,qstrader,quantstats]" ``` -------------------------------- ### Close Position Example Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/breakout-bollinger-bands-old/bb-short-eth-polygon.ipynb This snippet illustrates the logic for closing an open position. The strategy closes the position when the closing price falls below the 20-day moving average. It prints the current price and moving average before calling the position manager to close all open positions. ```python if price_close < moving_average.iloc[-1]: print(price_close, moving_average.iloc[-1]) new_trades = position_manager.close_all() trades.extend(new_trades) ``` -------------------------------- ### Load Strategy Module Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum-grid-2.ipynb Loads a Python trading strategy module dynamically from a specified path. It uses importlib to handle module loading and makes the strategy available for execution. Dependencies include datetime, importlib, sys, and tradeexecutor utilities. ```python import datetime import importlib.util import sys from tradeexecutor.utils.default_strategies import get_default_strategies_path strategies_folder = get_default_strategies_path() strategy_path = strategies_folder / "spot-and-short-momentum-grid.py" # See https://stackoverflow.com/a/67692/315168 spec = importlib.util.spec_from_file_location("strategy_mod", strategy_path) python_mod = importlib.util.module_from_spec(spec) sys.modules["strategy_mod"] = python_mod spec.loader.exec_module(python_mod) print(f"Backtesting for strategy {strategy_path}, engine version {python_mod.trading_strategy_engine_version}") ``` -------------------------------- ### Progress Bar Example with tqdm Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/progress-bar-tests/tqdl.ipynb Demonstrates the usage of the `tqdm` library to display a progress bar for a loop. It initializes a progress bar with a total of 10 steps and updates it in each iteration, with a 1-second delay. ```python import time from tqdm import tqdm with tqdm(total=10) as progress_bar: for i in range(10): progress_bar.update() time.sleep(1) ``` -------------------------------- ### Trading Pairs and Market Data Setup Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/rsi-portfolio/v01-initial-skeleton.ipynb Configures the universe of trading pairs and loads historical market data for backtesting. It specifies the use of Binance CEX data to ensure a longer history is available for analysis. The setup includes defining the traded pairs and the time buckets for candle data and stop-loss signals. ```python import datetime from tradingstrategy.timebucket import TimeBucket from tradingstrategy.chain import ChainId from tradeexecutor.utils.binance import create_binance_universe # Randomly picked well-known token set with some survivorship bias traded_pair_ids = [ (ChainId.centralised_exchange, "binance", "ETH", "USDT"), (ChainId.centralised_exchange, "binance", "MATIC", "USDT"), (ChainId.centralised_exchange, "binance", "BTC", "USDT"), (ChainId.centralised_exchange, "binance", "SOL", "USDT"), (ChainId.centralised_exchange, "binance", "ADA", "USDT"), (ChainId.centralised_exchange, "binance", "XRP", "USDT"), (ChainId.centralised_exchange, "binance", "XTZ", "USDT"), (ChainId.centralised_exchange, "binance", "AVAX", "USDT"), (ChainId.centralised_exchange, "binance", "DOT", "USDT"), (ChainId.centralised_exchange, "binance", "CAKE", "USDT"), # (ChainId.centralised_exchange, "binance", "AEVO", "USDT"), (ChainId.centralised_exchange, "binance", "BNB", "USDT"), ] strategy_universe = create_binance_universe( [f"{desc[2]}{desc[3]}" for desc in traded_pair_ids], candle_time_bucket=TimeBucket.d1, stop_loss_time_bucket=TimeBucket.h1, start_at=datetime.datetime(2018, 1, 1), end_at=datetime.datetime(2024, 3, 10), include_lending=False ) ``` -------------------------------- ### Run Basic Tests Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/docs/testing.md Executes all tests using the pytest framework. ```shell pytest ``` -------------------------------- ### Initialize Trading Universe and Backtest Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/bitcoin/arbitrum-btc-usd-sls-binance-data-1h.ipynb Sets up the trading environment, loads data, and runs a backtest with specified parameters. It configures the client, execution context, and universe options before initiating the backtest. ```python from tradeexecutor.client import Client from tradeexecutor.execution.execution_context import ExecutionContext from tradeexecutor.execution.execution_mode import ExecutionMode from tradeexecutor.portfolio.portfolio import Portfolio from tradeexecutor.strategy.strategy import Strategy from tradeexecutor.universe.universe_options import UniverseOptions from tradeexecutor.utils.constants import CycleDuration, ReserveCurrency, TradeRouting import datetime import os import logging # Configuration cycle_duration = CycleDuration.cycle_1h initial_deposit = 10_000 reserve_currency = ReserveCurrency.usdc trade_routing = TradeRouting.uniswap_v3_usdc_poly # Load trading universe with DEX data client = Client.create_jupyter_client() universe = create_trading_universe( datetime.datetime.utcnow(), client, ExecutionContext(mode=ExecutionMode.backtesting), universe_options=UniverseOptions(), ) print(os.getcwd()) # Change strategy backtesting period start_at = datetime.datetime(2018, 1, 1) end_at = datetime.datetime(2018, 3, 1) # Placeholder for decide_trades function (must be defined elsewhere) def decide_trades(portfolio: Portfolio, strategy: Strategy): pass # Placeholder for create_trading_universe function (must be defined elsewhere) def create_trading_universe(timestamp, client, execution_context, universe_options): # This is a mock implementation. Replace with actual universe creation. class MockUniverse: def __init__(self): self.assets = [] return MockUniverse() # Placeholder for run_backtest_inline function (must be defined elsewhere) def run_backtest_inline(name, start_at, end_at, client, cycle_duration, decide_trades, universe, initial_deposit, reserve_currency, trade_routing, log_level): # This is a mock implementation. Replace with actual backtest execution. class MockState: def __init__(self): self.portfolio = MockPortfolio() def write_json_file(self, path): print(f"Writing state to {path}") class MockPortfolio: def get_all_trades(self): return [] return MockState(), None, None ``` -------------------------------- ### Open Short Position Example Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/breakout-bollinger-bands-old/bb-short-eth-polygon.ipynb This code snippet demonstrates the logic for opening a short position based on technical indicators. It checks if the latest candle's high wick is above the upper Bollinger Band and the closing price is below it, combined with a low RSI value. If conditions are met, it calculates the trade amount and opens a short position using the position manager. ```python if candles["high"].iloc[-1] > bb_upper.iloc[-1] and price_close < bb_upper.iloc[-1] and current_rsi < RSI_THRESHOLD: amount = cash * POSITION_SIZE new_trades = position_manager.open_short(pair, amount, leverage=2, stop_loss_pct=STOP_LOSS_PCT, take_profit_pct=TAKE_PROFIT_PCT) trades.extend(new_trades) ``` -------------------------------- ### Trading Strategy Configuration Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/breakout-bollinger-bands-old/bb-short-eth-polygon.ipynb Sets up essential parameters for the trading strategy, including engine version, strategy type, trade routing, cycle duration, reserve currency, time buckets, trading pairs, lending reserves, position sizing, initial deposit, and stop-loss time buckets. ```python import datetime import pandas as pd from tradingstrategy.chain import ChainId from tradingstrategy.timebucket import TimeBucket from tradingstrategy.lending import LendingProtocolType from tradeexecutor.strategy.cycle import CycleDuration from tradeexecutor.strategy.strategy_module import StrategyType, TradeRouting, ReserveCurrency # Tell what trade execution engine version this strategy needs to use # NOTE: this setting has currently no effect TRADING_STRATEGY_TYPE_ENGINE_VERSION = "0.1" # What kind of strategy we are running. # This tells we are going to use # NOTE: this setting has currently no effect TRADING_STRATEGY_TYPE = StrategyType.managed_positions # How our trades are routed. TRADE_ROUTING = TradeRouting.uniswap_v3_usdc_poly # How often the strategy performs the decide_trades cycle. # We do it for every 4h. TRADING_STRATEGY_CYCLE = CycleDuration.cycle_1d # Strategy keeps its cash in USDC RESERVE_CURRENCY = ReserveCurrency.usdc # Time bucket for our candles CANDLE_TIME_BUCKET = TimeBucket.d1 # Which trading pair we are backtesting on TRADING_PAIR = (ChainId.polygon, "uniswap-v3", "WETH", "USDC", 0.0005) # Which lending reserves we are using for supplying/borrowing assets LENDING_RESERVES = [ (ChainId.polygon, LendingProtocolType.aave_v3, "WETH"), (ChainId.polygon, LendingProtocolType.aave_v3, "USDC.e"), ] # How much % of the cash to put on a single trade POSITION_SIZE = 0.50 # Start with this amount of USD INITIAL_DEPOSIT = 5_000 # Candle time granularity we use to trigger stop loss checks STOP_LOSS_TIME_BUCKET = TimeBucket.m15 ``` -------------------------------- ### Execution Completion Signal Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/breakout-bollinger-bands-old/bb-short-eth-polygon.ipynb Prints a simple message to indicate that the script or notebook execution has completed successfully. ```python print("All ok") ``` -------------------------------- ### Execution Completion Signal Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/defi-bluechip-momentum.ipynb Prints a confirmation message to the console indicating that the notebook execution has completed successfully. ```python print("All ok") ``` -------------------------------- ### Signal Successful Execution Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum.ipynb Prints a confirmation message to indicate that the notebook execution has completed successfully. ```python print("All ok") ``` -------------------------------- ### Signal Successful Execution Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/spot-and-short-momentum-2.ipynb Prints a confirmation message to indicate that the notebook execution has completed successfully. ```python print("All ok") ``` -------------------------------- ### Create Trading Universe Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/momentum/defi-bluechip-momentum.ipynb Sets up the trading universe for backtesting by defining a list of trading pairs, downloading candle data, and performing sanity checks on pair definitions and volumes. It utilizes the market data client and execution context to load and filter data. ```python from tradingstrategy.client import Client from tradeexecutor.strategy.trading_strategy_universe import TradingStrategyUniverse from tradeexecutor.strategy.trading_strategy_universe import load_partial_data from tradeexecutor.strategy.execution_context import ExecutionContext from tradeexecutor.strategy.execution_context import ExecutionMode from tradeexecutor.strategy.universe_model import UniverseOptions # List of trading pairs that we consider "DeFi blueschips" for this strategy # For token ordering, wrappign see https://tradingstrategy.ai/docs/programming/market-data/trading-pairs.html pairs = ( (ChainId.ethereum, "uniswap-v2", "WETH", "USDC"), # ETH (ChainId.ethereum, "sushi", "AAVE", "WETH"), # AAVE (ChainId.ethereum, "uniswap-v2", "UNI", "WETH"), # UNI (ChainId.ethereum, "uniswap-v2", "CRV", "WETH"), # Curve (ChainId.ethereum, "sushi", "SUSHI", "WETH"), # Sushi (ChainId.bsc, "pancakeswap-v2", "WBNB", "BUSD"), # BNB (ChainId.bsc, "pancakeswap-v2", "Cake", "BUSD"), # Cake (ChainId.polygon, "quickswap", "WMATIC", "USDC"), # Matic (ChainId.avalanche, "trader-joe", "WAVAX", "USDC"), # Avax (ChainId.avalanche, "trader-joe", "JOE", "WAVAX"), # TraderJoe ) def create_trading_universe( ts: datetime.datetime, client: Client, execution_context: ExecutionContext, universe_options: UniverseOptions, ) -> TradingStrategyUniverse: assert not execution_context.mode.is_live_trading(), \ f"Only strategy backtesting supported, got {execution_context.mode}" # Load data for our trading pair whitelist dataset = load_partial_data( client=client, time_bucket=trading_strategy_cycle.to_timebucket(), pairs=pairs, execution_context=execution_context, universe_options=universe_options, liquidity=False, stop_loss_time_bucket=stop_loss_data_granularity, start_at=start_at, end_at=end_at, ) # Filter down the dataset to the pairs we specified universe = TradingStrategyUniverse.create_multichain_universe_by_pair_descriptions( dataset, pairs, reserve_token_symbol="USDC" # Pick any USDC - does not matter as we do not route ) return universe universe = create_trading_universe( datetime.datetime.utcnow(), client, ExecutionContext(mode=ExecutionMode.backtesting), UniverseOptions(), ) for pair in universe.universe.pairs.iterate_pairs(): all_time_volume = pair.buy_volume_all_time print(f"Trading pair {pair.base_token_symbol} ({pair.base_token_address}) - {pair.quote_token_symbol} ({pair.quote_token_address}) - all time volume {all_time_volume:,0f} USD") ``` -------------------------------- ### Run Backtest and Get State Source: https://github.com/tradingstrategy-ai/trade-executor/blob/master/notebooks/bitcoin/arbitrum-btc-usd-sls-binance-data-1h.ipynb Executes the backtesting process with the configured parameters and returns the resulting state, debug information, and a debug dump. ```python state, _, debug_dump = run_backtest_inline( name="SLS", start_at=start_at, end_at=end_at, client=client, cycle_duration=cycle_duration, decide_trades=decide_trades, universe=universe, initial_deposit=initial_deposit, reserve_currency=reserve_currency, trade_routing=trade_routing, log_level=logging.WARNING, ) # state.write_json_file(Path("arbitrum-btc-usd-sls-binance-data-1h.json")) ```