### Quickstart Mode with Strategy Source: https://context7.com/tdl321/hummingbot/llms.txt Commands for starting Hummingbot in headless mode with a specific strategy and configuration. Includes optional Gateway setup for DEX support. ```bash python bin/hummingbot_quickstart.py \ --config-file-name simple_pmm.py \ --script-conf simple_pmm.yml \ --config-password mypassword \ --headless # With Gateway for DEX support (uncomment gateway section in docker-compose.yml) docker compose up -d # Gateway runs on port 15888 ``` -------------------------------- ### VS Code launch.json for debugging Source: https://github.com/tdl321/hummingbot/blob/master/CURSOR_VSCODE_SETUP.md Sets up VS Code to launch and debug the main Hummingbot application directly from the IDE. ```json { "version": "0.2.0", "configurations": [ { "name": "Python: Hummingbot", "type": "debugpy", "request": "launch", "program": "${workspaceRoot}/bin/hummingbot.py", "console": "integratedTerminal" } ] } ``` -------------------------------- ### Configure .env for Hummingbot Source: https://github.com/tdl321/hummingbot/blob/master/CURSOR_VSCODE_SETUP.md Sets up environment variables for Python path and Conda environment to ensure Hummingbot modules are accessible. ```bash PYTHONPATH=${PYTHONPATH}:${PWD} CONDA_ENV=hummingbot ``` -------------------------------- ### Programmatic Initialization in Python Source: https://context7.com/tdl321/hummingbot/llms.txt Python code example for programmatically initializing and starting a Hummingbot instance with a specific strategy. Includes configuration loading, authentication, and strategy execution. ```python import asyncio from pathlib import Path from hummingbot.client.hummingbot_application import HummingbotApplication from hummingbot.client.config.config_helpers import ( load_client_config_map_from_file, ClientConfigAdapter ) from hummingbot.client.config.security import Security from hummingbot.core.utils.trading_pair_fetcher import TradingPairFetcher async def start_bot(): # Load configuration client_config = load_client_config_map_from_file() # Authenticate password = "mypassword" Security.login(Security.new_password_required(password)) await Security.wait_til_decryption_done() # Create application instance hb = HummingbotApplication.main_application( client_config_map=client_config, headless_mode=True ) # Start strategy await hb.trading_core.start_strategy( strategy_name="simple_pmm", strategy_config="simple_pmm.yml", strategy_file_name="simple_pmm" ) # Run await hb.run() # Execute asyncio.run(start_bot()) ``` -------------------------------- ### Docker Installation with Docker Compose Source: https://context7.com/tdl321/hummingbot/llms.txt Instructions for cloning the Hummingbot repository and launching it using Docker Compose. Includes commands for attaching to the running instance. ```bash git clone https://github.com/hummingbot/hummingbot.git cd hummingbot docker compose up -d docker attach hummingbot ``` -------------------------------- ### Start Hummingbot Application and MQTT via Python Source: https://context7.com/tdl321/hummingbot/llms.txt Initializes the main Hummingbot application in headless mode and manually starts the MQTT service. Requires the HummingbotApplication class and a client configuration map. Enables remote command publishing over MQTT. ```python hb = HummingbotApplication.main_application( client_config_map=config, headless_mode=True ) # MQTT is automatically started if mqtt_autostart=True # Or manually start hb.mqtt_start() ``` -------------------------------- ### Create symbolic link for Conda environment Source: https://github.com/tdl321/hummingbot/blob/master/CURSOR_VSCODE_SETUP.md Commands to create a symbolic link to address a known Conda environment detection issue in VS Code. ```bash mkdir -p ~/anaconda3/envs/hummingbot/envs ln -s ~/anaconda3/envs/hummingbot/ ~/anaconda3/envs/hummingbot/envs/hummingbot ``` -------------------------------- ### Install Hummingbot with Docker Source: https://github.com/tdl321/hummingbot/blob/master/README.md Instructions to clone the Hummingbot repository and launch the client using Docker Compose. Requires Docker and Docker Compose installed. ```bash # Clone the repository git clone https://github.com/hummingbot/hummingbot.git cd hummingbot # Launch Hummingbot docker compose up -d # Attach to the running instance docker attach hummingbot ``` -------------------------------- ### VS Code settings.json for pytest Source: https://github.com/tdl321/hummingbot/blob/master/CURSOR_VSCODE_SETUP.md Configures VS Code to use pytest for testing with specific arguments to ignore certain test directories and files. ```json { "python.testing.pytestEnabled": true, "python.testing.pytestArgs": [ "test", "--ignore=test/hummingbot/connector/derivative/dydx_v4_perpetual/", "--ignore=test/hummingbot/connector/derivative/injective_v2_perpetual/", "--ignore=test/hummingbot/connector/exchange/injective_v2/", "--ignore=test/hummingbot/remote_iface/", "--ignore=test/connector/utilities/oms_connector/", "--ignore=test/hummingbot/strategy/amm_arb/", "--ignore=test/hummingbot/client/command/test_create_command.py" ], "python.envFile": "${workspaceFolder}/.env", "python.terminal.activateEnvironment": true } ``` -------------------------------- ### Install Hummingbot + Gateway DEX Middleware Source: https://github.com/tdl321/hummingbot/blob/master/README.md Instructions to run Hummingbot with Gateway DEX middleware by modifying the docker-compose.yml file. Gateway enables interaction with decentralized exchanges. ```yaml # Clone the repository git clone https://github.com/hummingbot/hummingbot.git cd hummingbot # Uncomment the following lines in docker-compose.yml: gateway: restart: always container_name: gateway image: hummingbot/gateway:latest ports: - "15888:15888" volumes: - "./gateway-files/conf:/home/gateway/conf" - "./gateway-files/logs:/home/gateway/logs" - "./certs:/home/gateway/certs" environment: - GATEWAY_PASSPHRASE=admin - DEV=true ``` ```bash # Launch Hummingbot docker compose up -d # Attach to the running instance docker attach hummingbot ``` -------------------------------- ### Deploy Hummingbot Gateway with Docker Compose (Bash) Source: https://context7.com/tdl321/hummingbot/llms.txt Defines a Docker‑Compose service for the Hummingbot Gateway, mounting configuration, logs, and certificates. Adjusts environment variables for passphrase and development mode. Starts the in detached mode. ```bash # docker-compose.yml configuration services: gateway: restart: always container_name: gateway image: hummingbot/gateway:latest ports: - "15888:15888" volumes: - "./gateway-files/conf:/home/gateway/conf" - "./gateway-files/logs:/home/gateway/logs" - "./certs:/home/gateway/certs" environment: - GATEWAY_PASSPHRASE=your_passphrase - DEV=false # Use true for development/testing # Start with gateway docker compose up -d ``` -------------------------------- ### Setup DCA Executor for Dollar-Cost Averaging (Python) Source: https://context7.com/tdl321/hummingbot/llms.txt Defines a DCAExecutorConfig to place sequential market orders of fixed quote amounts when price moves by a threshold. Configured for Binance, ETH‑USDT pair, with a 24‑hour time limit and optional maker/taker mode. Enables automated dollar‑cost averaging. ```python from hummingbot.strategy_v2.executors.dca_executor.data_types import ( DCAExecutorConfig, DCAMode ) # DCA buy strategy dca_config = DCAExecutorConfig( timestamp=time.time(), connector_name="binance", trading_pair="ETH-USDT", side=TradeType.BUY, amounts_quote=[Decimal("100")] * 10, # 10 orders of $100 each prices=[], # Market orders mode=DCAMode.MAKER, # or DCAMode.TAKER time_limit=86400, # 24 hours activation_bounds=[Decimal("0.01")], # 1% activation threshold ) ``` -------------------------------- ### Production Trading Bot Strategy Logic Source: https://context7.com/tdl321/hummingbot/llms.txt Implements a production-ready trading bot strategy. It handles initialization, market setup, state tracking, risk management, and the main trading loop (`on_tick`) which includes safety checks and order management. ```python class ProductionBot(ScriptStrategyBase): """Production-ready trading bot with risk management""" markets: Dict[str, Set[str]] = {} @classmethod def init_markets(cls, config: ProductionBotConfig): cls.markets = {config.exchange: {config.trading_pair}} def __init__(self, connectors: Dict[str, ConnectorBase], config: ProductionBotConfig): super().__init__(connectors) self.config = config # State tracking self.last_refresh = 0 self.daily_pnl = Decimal("0") self.daily_start = None self.position_count = 0 self.active_order_ids = set() # Risk tracking self.total_filled_buy_amount = Decimal("0") self.total_filled_sell_amount = Decimal("0") self.realized_pnl = Decimal("0") self.logger().info( f"Initialized {self.__class__.__name__} with config: " f"{config.dict()}" ) def on_tick(self): """Main strategy loop with safety checks""" try: # Check circuit breakers if not self.safety_checks(): self.logger().warning("Safety checks failed, skipping tick") return # Reset daily PnL tracking self.check_daily_reset() # Manage orders if self.should_refresh_orders(): self.refresh_orders() except Exception as e: self.logger().error(f"Error in on_tick: {e}", exc_info=True) def safety_checks(self) -> bool: """Perform safety checks before trading""" # Check daily loss limit if self.daily_pnl < -self.config.max_daily_loss: self.logger().error( f"Daily loss limit exceeded: {self.daily_pnl:.4f}" ) return False # Check max positions if self.position_count >= self.config.max_positions: return False # Check connector health connector = self.connectors[self.config.exchange] if not connector.ready: return False # Check balance balance = connector.get_balance("USDT") if balance < self.config.position_size_quote: self.logger().warning(f"Insufficient balance: {balance}") return False return True def check_daily_reset(self): """Reset daily tracking at midnight""" import datetime now = datetime.datetime.now() if self.daily_start is None or now.date() > self.daily_start.date(): self.daily_start = now self.daily_pnl = Decimal("0") self.logger().info("Daily PnL reset") def should_refresh_orders(self) -> bool: """Check if orders should be refreshed""" return ( self.current_timestamp - self.last_refresh >= self.config.refresh_interval ) def refresh_orders(self): """Cancel old orders and place new ones""" self.cancel_all_orders() # Wait for cancellations self.active_order_ids.clear() # Create new proposal proposal = self.create_proposal() if proposal: adjusted = self.adjust_proposal_to_budget(proposal) self.place_orders(adjusted) self.last_refresh = self.current_timestamp def create_proposal(self) -> list[OrderCandidate]: """Create order proposals with spread""" connector = self.connectors[self.config.exchange] mid_price = connector.get_price_by_type( ``` -------------------------------- ### Create Custom Hummingbot Script Strategy in Python Source: https://context7.com/tdl321/hummingbot/llms.txt Defines a MyStrategyConfig using Pydantic and a MyStrategy class extending ScriptStrategyBase. It sets up market requirements, generates buy/sell order proposals based on spreads, and logs order fills. Requires Hummingbot core libraries and can be executed via the quickstart script. ```python from decimal import Decimal from typing import Dict, Set from pydantic import Field from hummingbot.strategy.script_strategy_base import ScriptStrategyBase from hummingbot.client.config.config_data_types import BaseClientModel from hummingbot.connector.connector_base import ConnectorBase from hummingbot.core.data_type.common import OrderType, TradeType, PriceType from hummingbot.core.data_type.order_candidate import OrderCandidate class MyStrategyConfig(BaseClientModel): """Strategy configuration using Pydantic""" script_file_name: str = "my_strategy.py" exchange: str = Field("binance_paper_trade") trading_pair: str = Field("ETH-USDT") order_amount: Decimal = Field(Decimal("0.01")) bid_spread: Decimal = Field(Decimal("0.002")) # 0.2% ask_spread: Decimal = Field(Decimal("0.002")) order_refresh_time: int = Field(15) # seconds class MyStrategy(ScriptStrategyBase):n """Simple market making strategy""" markets: Dict[str, Set[str]] = {} @classmethod def init_markets(cls, config: MyStrategyConfig): """Define required markets before initialization""" cls.markets = {config.exchange: {config.trading_pair}} def __init__(self, connectors: Dict[str, ConnectorBase], config: MyStrategyConfig): super().__init__(connectors) self.config = config self.create_timestamp = 0 def on_tick(self): """Called every second after connectors are ready""" # Refresh orders periodically if self.create_timestamp <= self.current_timestamp: self.cancel_all_orders() # Create new orders proposal = self.create_proposal() proposal_adjusted = self.adjust_proposal_to_budget(proposal) self.place_orders(proposal_adjusted) self.create_timestamp = (self.config.order_refresh_time + self.current_timestamp) def create_proposal(self) -> list[OrderCandidate]: """Generate order proposals""" connector = self.connectors[self.config.exchange] mid_price = connector.get_price_by_type( self.config.trading_pair, PriceType.MidPrice ) buy_price = mid_price * (1 - self.config.bid_spread) sell_price = mid_price * (1 + self.config.ask_spread) return [ OrderCandidate( trading_pair=self.config.trading_pair, is_maker=True, order_type=OrderType.LIMIT, order_side=TradeType.BUY, amount=self.config.order_amount, price=buy_price ), OrderCandidate( trading_pair=self.config.trading_pair, is_maker=True, order_type=OrderType.LIMIT, order_side=TradeType.SELL, amount=self.config.order_amount, price=sell_price ) ] def did_fill_order(self, event): """Callback when order is filled""" self.logger().info( f"Order filled: {event.trade_type.name} " f"{event.amount} {event.trading_pair} @ {event.price}" ) # Save as: scripts/my_strategy.py # Config: conf/scripts/my_strategy.yml # Run: python bin/hummingbot_quickstart.py -f my_strategy.py -c my_strategy.yml ``` -------------------------------- ### Manage Dynamic Exchange Connectors Source: https://context7.com/tdl321/hummingbot/llms.txt Demonstrates dynamic creation and management of both paper trading and live exchange connectors. Shows how to initialize trading core, create connectors with different configurations, set balances, access market data, and place orders directly through connectors. Requires API keys for live trading connectors. ```python from decimal import Decimal from hummingbot.core.trading_core import TradingCore from hummingbot.client.config.config_helpers import ( load_client_config_map_from_file, ClientConfigAdapter ) async def connector_management_example(): # Initialize trading core config = load_client_config_map_from_file() trading_core = TradingCore(config) # Start clock system await trading_core.start_clock() # Create paper trading connector (no API keys needed) binance_paper = await trading_core.create_connector( connector_name="binance_paper_trade", trading_pairs=["BTC-USDT", "ETH-USDT"], trading_required=True ) # Set paper trading balances binance_paper.set_balance("USDT", 10000) binance_paper.set_balance("BTC", 0.1) # Create live connector (requires API keys in conf/connectors/) kucoin_live = await trading_core.create_connector( connector_name="kucoin", trading_pairs=["SOL-USDT"], trading_required=True, api_keys={ "kucoin_api_key": "your_key", "kucoin_secret_key": "your_secret", "kucoin_passphrase": "your_passphrase" } ) # Access connector data btc_price = binance_paper.get_mid_price("BTC-USDT") order_book = binance_paper.get_order_book("BTC-USDT") usdt_balance = binance_paper.get_balance("USDT") # Place order directly through connector order_id = binance_paper.buy( trading_pair="BTC-USDT", amount=Decimal("0.01"), order_type=OrderType.LIMIT, price=btc_price * Decimal("0.98") ) # Get all active connectors all_connectors = trading_core.markets for name, connector in all_connectors.items(): print(f"Connector: {name}, Ready: {connector.ready}") # Remove connector trading_core.connector_manager.remove_connector("binance_paper_trade") # Stop clock when done await trading_core.stop_clock() # Run import asyncio asyncio.run(connector_management_example()) ``` -------------------------------- ### Client Configuration Management with Pydantic Source: https://context7.com/tdl321/hummingbot/llms.txt Illustrates how to manage Hummingbot client configuration using Pydantic models. It covers loading, modifying, and saving configuration, including settings for MQTT, paper trading, market data collection, and logging. It also shows how to define custom strategy configuration models. ```python from decimal import Decimal from typing import List, Dict from pydantic import Field from hummingbot.client.config.config_data_types import BaseClientModel, ClientConfigMap # Load existing configuration from hummingbot.client.config.config_helpers import ( load_client_config_map_from_file, save_to_yml ) # Load config config = load_client_config_map_from_file() # Access configuration sections mqtt_config = config.mqtt_bridge mqtt_config.mqtt_host = "mqtt.example.com" mqtt_config.mqtt_port = 1883 mqtt_config.mqtt_autostart = True # Paper trading configuration paper_trade_config = config.paper_trade paper_trade_config.paper_trade_exchanges = ["binance", "kucoin"] paper_trade_config.paper_trade_account_balance = { "USDT": Decimal("10000"), "BTC": Decimal("1.0"), "ETH": Decimal("10.0") } # Market data collection config.market_data_collection.market_data_collection_enabled = True config.market_data_collection.market_data_collection_interval = 60 # Rate limiting config.rate_limits_share_pct = Decimal("80") # Use 80% of rate limits # Logging config.log_level = "INFO" config.logger_override_whitelist = ["hummingbot.strategy"] # Save modified configuration save_to_yml("conf_client.yml", config) # Create custom configuration model class CustomStrategyConfig(BaseClientModel): """Custom strategy configuration""" exchange: str = Field("binance") trading_pair: str = Field("BTC-USDT") order_amount: Decimal = Field(Decimal("0.01")) refresh_interval: int = Field(30) risk_factor: Decimal = Field(Decimal("1.0"), ge=0.1, le=5.0) # Validation def validate_config(self): if self.order_amount <= 0: raise ValueError("Order amount must be positive") return True # Use in strategy config_data = { "exchange": "binance_paper_trade", "trading_pair": "ETH-USDT", "order_amount": "0.05", "refresh_interval": 15, "risk_factor": "1.5" } strategy_config = CustomStrategyConfig(**config_data) ``` -------------------------------- ### Implement DEX Trading Strategy Using Gateway Connectors (Python) Source: https://context7.com/tdl321/hummingbot/llms.txt Shows how to define a strategy class that utilizes Gateway DEX connectors to fetch prices and place market swaps. Includes configuration of connector, trading pair, wallet address, and order amount. on ScriptStrategyBase and OrderType from Hummingbot. ```python # Using Gateway connectors in strategy from decimal import Decimal from hummingbot.strategy.script_strategy_base import ScriptStrategyBase class DexStrategyConfig(BaseClientModel): script_file_name: str = "dex_strategy.py" connector: str = "uniswap_ethereum_mainnet" trading_pair: str = "WETH-USDC" wallet_address: str = "0x..." order_amount: Decimal = Decimal("0.1") class DexStrategy(ScriptStrategyBase): markets = {} @classmethod def init_markets(cls, config: DexStrategyConfig): cls.markets = {config.connector: {config.trading_pair}} def __init__(self, connectors, config: DexStrategyConfig): super().__init__(connectors) self.config = config def on_tick(self): # Get DEX price dex_connector = self.connectors[self.config.connector] price = dex_connector.get_mid_price(self.config.trading_pair) # Place swap through Gateway swap_order = self.buyn connector_name=self.config.connector, trading_pair=self.config.trading_pair, amount=self.config.order_amount, order_type=OrderType.MARKET ) ``` -------------------------------- ### Real-time Clock Execution with Hummingbot Strategy Source: https://context7.com/tdl321/hummingbot/llms.txt Demonstrates running a Hummingbot strategy using a real-time clock. It initializes the trading core, creates a connector, loads a strategy, and adds them to a 1-second tick clock for execution. ```python import asyncio import time from hummingbot.core.clock import Clock, ClockMode from hummingbot.core.trading_core import TradingCore async def realtime_clock_example(): """Run strategy with real-time clock""" # Initialize config = load_client_config_map_from_file() trading_core = TradingCore(config) # Create clock with 1-second ticks clock = Clock(ClockMode.REALTIME, tick_size=1.0) # Create connectors connector = await trading_core.create_connector( "binance_paper_trade", ["BTC-USDT"] ) # Load strategy strategy = await trading_core.start_strategy( "simple_pmm", "simple_pmm.yml" ) # Add to clock with clock: clock.add_iterator(connector) clock.add_iterator(strategy) # Run for 1 hour end_time = time.time() + 3600 await clock.run_til(end_time) # Clock automatically stops all iterators on exit asyncio.run(realtime_clock_example()) ``` -------------------------------- ### Backtesting Clock Execution with Hummingbot Strategy Source: https://context7.com/tdl321/hummingbot/llms.txt Shows how to run a Hummingbot strategy in backtesting mode. It defines a timeframe, creates a backtesting clock, adds components, runs the backtest synchronously, and prints the PnL results. ```python from hummingbot.core.clock import Clock, ClockMode from datetime import datetime def backtest_example(): """Run strategy in backtesting mode""" # Define timeframe start_time = datetime(2024, 1, 1).timestamp() end_time = datetime(2024, 1, 31).timestamp() # Create backtest clock (synchronous) clock = Clock( ClockMode.BACKTEST, tick_size=1.0, start_time=start_time, end_time=end_time ) # Add components clock.add_iterator(mock_connector) clock.add_iterator(strategy) # Run backtest (synchronous) with clock: clock.backtest() # Runs until end_time # Analyze results trades = strategy.trades_history pnl = strategy.calculate_pnl() print(f"Total PnL: {pnl}") backtest_example() ``` -------------------------------- ### Implement Direct Buy/Sell Trading Strategy Source: https://context7.com/tdl321/hummingbot/llms.txt Creates a manual trading strategy with direct buy and sell order placement capabilities. The strategy demonstrates limit and market order execution, order cancellation, and active order monitoring. Requires hummingbot strategy base classes and decimal module for precise calculations. ```python from decimal import Decimal from hummingbot.strategy.script_strategy_base import ScriptStrategyBase from hummingbot.core.data_type.common import OrderType, PositionAction class ManualTradingStrategy(ScriptStrategyBase): markets = {"binance": {"BTC-USDT"}} @classmethod def init_markets(cls, config): cls.markets = {config.exchange: {config.trading_pair}} def on_tick(self): """Place orders based on custom logic""" connector = self.connectors["binance"] # Get market data mid_price = connector.get_mid_price("BTC-USDT") balance = connector.get_balance("USDT") # Place limit buy order buy_order_id = self.buy( connector_name="binance", trading_pair="BTC-USDT", amount=Decimal("0.001"), order_type=OrderType.LIMIT, price=mid_price * Decimal("0.99") ) # Place market sell order sell_order_id = self.sell( connector_name="binance", trading_pair="BTC-USDT", amount=Decimal("0.001"), order_type=OrderType.MARKET ) # Cancel specific order self.cancel("binance", "BTC-USDT", buy_order_id) # Get active orders active_orders = self.get_active_orders("binance") for order in active_orders: self.logger().info( f"Active: {order.client_order_id} - " f"{order.trading_pair} {order.quantity}" ) # Event callbacks def did_create_buy_order(self, event): self.logger().info(f"Buy order created: {event.order_id}") def did_fill_order(self, event): self.logger().info( f"Filled {event.amount} at {event.price}, " f"Fee: {event.trade_fee}" ) def did_fail_order(self, event): self.logger().error(f"Order failed: {event.order_id}") ``` -------------------------------- ### Production Bot Configuration Model Source: https://context7.com/tdl321/hummingbot/llms.txt Defines the configuration structure for the production bot using Pydantic for validation. It includes settings for the exchange, trading pair, position sizing, risk management thresholds, strategy parameters, and circuit breakers. ```python import asyncio import logging from decimal import Decimal from pathlib import Path from typing import Dict, Set from pydantic import Field from hummingbot.strategy.script_strategy_base import ScriptStrategyBase from hummingbot.client.config.config_data_types import BaseClientModel from hummingbot.connector.connector_base import ConnectorBase from hummingbot.core.data_type.common import ( OrderType, TradeType, PriceType, OrderSide ) from hummingbot.core.data_type.order_candidate import OrderCandidate from hummingbot.core.event.events import ( OrderFilledEvent, BuyOrderCompletedEvent, SellOrderCompletedEvent ) class ProductionBotConfig(BaseClientModel): """Production configuration with validation""" script_file_name: str = "production_bot.py" # Exchange settings exchange: str = Field("binance") trading_pair: str = Field("BTC-USDT") # Position sizing position_size_quote: Decimal = Field(Decimal("1000")) max_positions: int = Field(3) # Risk management max_loss_per_trade: Decimal = Field(Decimal("0.01")) # 1% max_daily_loss: Decimal = Field(Decimal("0.05")) # 5% # Strategy parameters spread_bps: Decimal = Field(Decimal("20")) # 20 basis points refresh_interval: int = Field(60) # 60 seconds # Circuit breakers enable_kill_switch: bool = Field(True) max_order_age: int = Field(300) # 5 minutes ``` -------------------------------- ### Configure Position Executor with Triple Barrier in Hummingbot (Python) Source: https://context7.com/tdl321/hummingbot/llms.txt Creates a PositionExecutorConfig with a TripleBarrierConfig to manage stop‑loss, take‑profit, time limit, and trailing stop for a position. Utilizes Decimal for precise percentages and specifies leverage. Suitable for risk‑controlled automated trading on Binance perpetual. ```python from hummingbot.strategy_v2.executors.position_executor.data_types import ( PositionExecutorConfig, TripleBarrierConfig ) # Create position with stop-loss and take-profit triple_barrier = TripleBarrierConfig( stop_loss=Decimal("0.02"), # 2% stop loss take_profit=Decimal("0.05"), # 5% take profit time_limit=3600, # 1 hour time limit trailing_stop_activation_price=Decimal("0.03"), # Activate trailing at 3% trailing_stop_trailing_delta=Decimal("0.01") # Trail by 1% ) executor_config = PositionExecutorConfig( timestamp=time.time(), connector_name="binance_perpetual", trading_pair="BTC-USDT", side=TradeType.BUY, amount=Decimal("0.01"), triple_barrier_config=triple_barrier, leverage=10 ) ``` -------------------------------- ### Create Trend-Following V2 Controller in Python Source: https://context7.com/tdl321/hummingbot/llms.txt Defines a TrendFollowingConfig class for controller settings and a TrendFollowingController class that processes market data, detects price trends using moving averages, and generates executor actions. Dependencies include Hummingbot core modules and pydantic. Outputs include processed data and formatted status strings. ```python from decimal import Decimal from typing import List from pydantic import Field from hummingbot.strategy_v2.controllers.controller_base import ( ControllerBase, ControllerConfigBase ) from hummingbot.strategy_v2.models.executor_actions import ( CreateExecutorAction, StopExecutorAction ) from hummingbot.strategy_v2.executors.position_executor.data_types import ( PositionExecutorConfig, TripleBarrierConfig ) from hummingbot.core.data_type.common import ( TradeType, PriceType, PositionMode ) class TrendFollowingConfig(ControllerConfigBase): \"\"\"Configuration for trend following controller\"\"\" controller_name: str = \"trend_following\" connector_name: str = Field(\"binance_perpetual\") trading_pair: str = Field(\"ETH-USDT\") leverage: int = Field(10, ge=1, le=125) position_size_quote: Decimal = Field(Decimal(\"100\")) # Triple barrier parameters stop_loss: Decimal = Field(Decimal(\"0.02\")) # 2% take_profit: Decimal = Field(Decimal(\"0.05\")) # 5% time_limit: int = Field(3600) # 1 hour # Trend detection fast_ma_period: int = Field(20) slow_ma_period: int = Field(50) def update_markets(self, markets): \"\"\"Register required markets\"\"\" return markets.add_or_update( self.connector_name, self.trading_pair ) class TrendFollowingController(ControllerBase): \"\"\"Controller that follows price trends\"\"\" def __init__(self, config: TrendFollowingConfig, *args, **kwargs): super().__init__(config, *args, **kwargs) self.config = config async def update_processed_data(self): \"\"\"Analyze market data and detect trends\"\"\" # Get candles data candles = self.market_data_provider.get_candles_df( connector_name=self.config.connector_name.config.trading_pair, interval=\"1m\", max_records=100 ) # Calculate moving averages fast_ma = candles[\'close\'].rolling( window=self.config.fast_ma_period ).mean().iloc[-1] slow_ma = candles[\'close\'].rolling( window=self.config.slow_ma_period ).mean().iloc[-1] # Get current price current_price = self.market_data_provider.get_price_by_type( self.config.connector_name, self.config.trading_pair, PriceType.MidPrice ) # Detect trend trend = \"BULLISH\" if fast_ma > slow_ma else \"BEARISH\" # Count active executors active_executors = [ e for e in self.executors_info if e.is_active ] self.processed_data = { \"price\": current_price, \"fast_ma\": fast_ma, \"slow_ma\": slow_ma, \"trend\": trend, \"active_count\": len(active_executors) } def determine_executor_actions(self) -> List: \"\"\"Create or close positions based on trend\"\"\" actions = [] # Only one position at a time if self.processed_data[\"active_count"] > 0: return actions # Create position based on trend trend = selfed_data[\"trend\"] price = self.processed_data[\"price\"] if trend == \"BULLISH\": side = TradeType.BUY elif trend == \"BEARISH\": side = TradeType.SELL else: return actions # Calculate position parameters amount = self.config.position_size_quote / price # Create triple barrier config triple_barrier = TripleBarrierConfig( stop_loss=self.config.stop_loss, take_profit=self.config.take_profit, time_limit=self.config.time_limit ) # Create position executor config executor_config = PositionExecutorConfig( timestamp=self.market_data_provider.time(), connector_name=self.config.connector_name, trading_pair=self.config.trading_pair, side=side, amount=amount, triple_barrier_config=triple_barrier, leverage=self.config.leverage, position_mode=PositionMode.HEDGE ) # Create action actions.append( CreateExecutorAction( controller_id=self.config.id, executor_config=executor_config ) ) return actions def to_format_status(self) -> List[str]: \"\"\"Format status for display\"\"\" return [ f\"Trend: {self.processed_data.get(\'trend\', \"N/A\")}\", f\"Price: {self.processed_data.get(\'price\', 0):.2f}\", f\"Fast MA: {self.processed_data.get(\'fast_ma\', 0):.2f}\", f\"Slow MA: {self.processed_data.get(\'slow_ma\', 0):.2f}\", f\"Active Positions: {self.processed_data.get(\'active_count\', 0)}\" ] # Save as: controllers/trend_following.py ``` -------------------------------- ### Generate Buy and Sell Order Candidates in Hummingbot Python Strategy Source: https://context7.com/tdl321/hummingbot/llms.txt This method fetches the mid price for the configured trading pair and applies a spread (in basis points converted to decimal) to compute adjusted buy and sell prices. It then calculates order amounts based on the quote position size divided by the prices, returning a list of OrderCandidate objects for limit maker orders. Depends on Hummingbot's config (trading_pair, spread_bps, position_size_quote) and PriceType; inputs include current market data for mid price; outputs two candidates for BUY and SELL; limitations include assuming positive spreads and no slippage. ```python self.config.trading_pair, PriceType.MidPrice ) # Calculate spread in decimal spread = self.config.spread_bps / Decimal("10000") buy_price = mid_price * (1 - spread) sell_price = mid_price * (1 + spread) # Calculate amounts buy_amount = self.config.position_size_quote / buy_price sell_amount = self.config.position_size_quote / sell_price return [ OrderCandidate( trading_pair=self.config.trading_pair, is_maker=True, order_type=OrderType.LIMIT, order_side=TradeType.BUY, amount=buy_amount, price=buy_price ), OrderCandidate( trading_pair=self.config.trading_pair, is_maker=True, order_type=OrderType.LIMIT, order_side=TradeType.SELL, amount=sell_amount, price=sell_price ) ] ``` -------------------------------- ### MQTT Bridge Configuration for Remote Control Source: https://context7.com/tdl321/hummingbot/llms.txt Configures the MQTT bridge in Hummingbot for remote control and monitoring. This includes setting connection details like host, port, username, password, and enabling various features such as remote logging, notifications, commands, and market event streaming. ```python from hummingbot.client.hummingbot_application import HummingbotApplication from hummingbot.client.config.config_helpers import load_client_config_map_from_file # Configure MQTT config = load_client_config_map_from_file() config.mqtt_bridge.mqtt_host = "localhost" config.mqtt_bridge.mqtt_port = 1883 config.mqtt_bridge.mqtt_username = "hbot_user" config.mqtt_bridge.mqtt_password = "secure_password" config.mqtt_bridge.mqtt_namespace = "hbot" config.mqtt_bridge.mqtt_ssl = True # Enable MQTT features config.mqtt_bridge.mqtt_logger = True # Remote logging config.mqtt_bridge.mqtt_notifier = True # Notifications config.mqtt_bridge.mqtt_commands = True # Remote commands config.mqtt_bridge.mqtt_events = True # Market events config.mqtt_bridge.mqtt_autostart = True # Auto-start on launch ``` -------------------------------- ### Handle Order Creation Events in Hummingbot Python Strategy Source: https://context7.com/tdl321/hummingbot/llms.txt These methods respond to buy and sell order creation events by adding order IDs to an active set and logging details like ID, amount, and price. They rely on Hummingbot's event system and logger; inputs are BuyOrderCreatedEvent or SellOrderCreatedEvent; outputs update internal tracking and logs; no direct returns, suitable for real-time monitoring but lacks error handling for logging failures. ```python # Event handlers def did_create_buy_order(self, event): """Track buy order creation""" self.active_order_ids.add(event.order_id) self.logger().info( f"Buy order created: {event.order_id} - " f"{event.amount} @ {event.price}" ) def did_create_sell_order(self, event): """Track sell order creation""" self.active_order_ids.add(event.order_id) self.logger().info( f"Sell order created: {event.order_id} - " f"{event.amount} @ {event.price}" ) ``` -------------------------------- ### Handle Order Fill Events and PnL Calculation in Hummingbot Python Source: https://context7.com/tdl321/hummingbot/llms.txt This method processes OrderFilledEvent by updating total filled amounts and position count based on trade type, computes trade value and fees, estimates realized PnL for sells using average buy price (simplified), and accumulates daily/total PnL. Depends on internal trackers like total_filled_buy_amount and Decimal for precision; inputs: OrderFilledEvent; outputs: updated state and logged details; limitations: PnL estimation assumes FIFO-like averaging and ignores complex position management or multiple assets. ```python def did_fill_order(self, event: OrderFilledEvent): """Handle order fills and update PnL""" # Update position tracking if event.trade_type == TradeType.BUY: self.total_filled_buy_amount += event.amount self.position_count += 1 else: self.total_filled_sell_amount += event.amount self.position_count = max(0, self.position_count - 1) # Calculate realized PnL trade_value = event.amount * event.price fee_amount = event.trade_fee.flat_fees[0].amount if event.trade_fee.flat_fees else Decimal("0") if event.trade_type == TradeType.SELL: # Estimate PnL (simplified) avg_buy_price = (self.total_filled_buy_amount * event.price / max(self.total_filled_buy_amount, Decimal("1"))) pnl = (event.price - avg_buy_price) * event.amount - fee_amount self.realized_pnl += pnl self.daily_pnl += pnl self.logger().info( f"Order filled: {event.trade_type.name} {event.amount} " f"@ {event.price}, Fee: {fee_amount}, " f"Realized PnL: {self.realized_pnl:.4f}, " f"Daily PnL: {self.daily_pnl:.4f}" ) # Remove from active orders self.active_order_ids.discard(event.order_id) ``` -------------------------------- ### Strategy Stop and Cleanup Method in Hummingbot Python Source: https://context7.com/tdl321/hummingbot/llms.txt This async method triggers on strategy stop, logs the event, cancels all active orders, and outputs final statistics including total filled amounts, PnL, and open positions. Depends on internal cancel_all_orders and logger; no inputs beyond self; outputs logs for review; ensures graceful shutdown but assumes cancel_all_orders handles concurrency. ```python async def on_stop(self): """Cleanup on strategy stop""" self.logger().info("Stopping strategy") self.cancel_all_orders() # Log final statistics self.logger().info( f"Final Statistics:\n" f" Total Buy Amount: {self.total_filled_buy_amount}\n" f" Total Sell Amount: {self.total_filled_sell_amount}\n" f" Realized PnL: {self.realized_pnl:.4f}\n" f" Daily PnL: {self.daily_pnl:.4f}\n" f" Open Positions: {self.position_count}" ) ``` -------------------------------- ### Handle Order Failure and Cancellation Events in Hummingbot Python Source: https://context7.com/tdl321/hummingbot/llms.txt These methods manage OrderFailedEvent and OrderCancelledEvent by logging errors or info and removing order IDs from the active set. They use Hummingbot's logger and event objects; inputs: respective events; outputs: updated tracking and logs; simple cleanup without retries, suitable for monitoring but may need extension for automated recovery. ```python def did_fail_order(self, event): """Handle order failures""" self.logger().error( f"Order failed: {event.order_id} - {event.order_type}" ) self.active_order_ids.discard(event.order_id) def did_cancel_order(self, event): """Handle order cancellations""" self.active_order_ids.discard(event.order_id) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.