The Injective Trader uses a YAML configuration file to define behavior, components, and strategy parameters.The most important configuration sections to focus on are:
LogLevel
Network and MarketTickers in the Initializer under the Components section
Strategies section
Here’s a detailed breakdown of the configuration structure:
The Components section configures framework components:
Copy
Ask AI
Components: # Chain initialization and market setup Initializer: Network: mainnet # Network to connect to (mainnet or testnet) MarketTickers: # Market tickers to track (will be converted to IDs) - INJ/USDT PERP - ETH/USDT BotName: MyBot # Chain listening configuration ChainListener: ReconnectionDelay: 5 # Seconds to wait before reconnection attempts LargeGapThreshold: 50 # Sequence gap threshold for orderbook snapshot requests # Transaction broadcasting configuration MessageBroadcaster: ErrorCodesJson: config/error_codes.json # Error code lookup for tx validation GranteePool: # For authz transaction mode MaxPendingTxs: 5 # Maximum pending transactions per grantee ErrorThreshold: 3 # Consecutive errors before blocking a grantee BlockDuration: 300 # Seconds to block a grantee after errors RotationInterval: 1 # Seconds between grantee rotations RefreshInterval: 300 # Seconds between grant refresh checks Batch: # Transaction batching settings MaxBatchSize: 15 # Maximum messages per batch MinBatchSize: 3 # Minimum messages to trigger immediate send MaxGasLimit: 5000000 # Maximum gas per batch MaxBatchDelay: 0.5 # Maximum seconds to wait for batch completion
Note: Most users only need to take care of Network and include all the markets that they want to listen to in MarketTickers.
They won’t need to modify these advanced component settings. The default values work well for most use cases.
The Strategies section defines each trading strategy:
Copy
Ask AI
Strategies: SimpleStrategy: # Strategy identifier (your choice) # Required parameters Name: "SimpleStrategy" # Strategy name (used in logs) Class: "SimpleStrategy" # [REQUIRED] Python class name to instantiate MarketIds: # [REQUIRED] Markets to trade on - "0x9b9980167ecc3645ff1a5517886652d94a0825e54a77d2057cbbe3ebee015963" # INJ/USDT PERP AccountAddresses: # [REQUIRED] Accounts to use - "inj1youractualaccount..." # (Must match private key in env) TradingAccount: "inj1youractualaccount..." # [REQUIRED] Account for placing orders (Must match private key in env) # Optional parameters FeeRecipient: "inj1feerecipient..." # Address to receive trading fees (if applicable) CIDPrefix: "simple_strat" # Prefix for client order IDs SubaccountIds: ["0x123..."] # Specific subaccounts to use (otherwise all available) # Risk management configuration [Optional] # You don't have to include them if you don't have your specific risk model Risk: "BasicRiskModel" # Risk model to apply (if using risk management) RiskConfig: # Risk thresholds DrawdownWarning: 0.1 # 10% drawdown warning threshold DrawdownCritical: 0.2 # 20% drawdown critical threshold MarginWarning: 0.7 # 70% margin usage warning MarginCritical: 0.8 # 80% margin usage critical
Required Strategy Parameters:
Class: Must exactly match your Python class name
MarketIds: List of market IDs to trade on in this strategy (use hex format)
AccountAddresses: List of accounts to use for trading in this strategy
TradingAccount: Account used for order execution (must be in AccountAddresses) [See more details on Trading Mode Configuration ]
Recommended Parameters:
CIDPrefix: Prefix for client order IDs (helps identify your orders)
Name: Human-readable name for logs and monitoring
Custom Parameters:
You can add any custom parameters your strategy needs
All parameters under your strategy name will be available in self.config
Group related parameters under the Parameters section for clarity
Strategies: SimpleStrategy: # Other parameters... Granter: "inj1granteraccount..." # Account granting permission to execute trades Grantees: # Accounts that can execute trades on behalf of granter - "inj1grantee1..." - "inj1grantee2..."
Note: You must specify either TradingAccount for direct execution OR Granter and Grantees for authorization mode.
The framework enforces this requirement during initialization.
Strategies in the Injective Trader follow a consistent structure based on the Strategy base class. This section explains how to build effective strategies.
The on_initialize method is called once during framework startup, after markets and accounts are loaded.Purpose: Initialize strategy state and parameters Parameters:
accounts: Dictionary of account_address → Account objects
markets: Dictionary of market_id → Market objects
Returns: [Optional] StrategyResult with initial orders (if any)
Copy
Ask AI
def on_initialize(self, accounts, markets): # Now you have access to all market and account data # Example: Access market metadata for market_id in self.market_ids: market = markets[market_id] self.logger.info(f"Market {market_id} tick sizes: " f"price={market.min_price_tick}, " f"quantity={market.min_quantity_tick}") # Example: Initialize parameters that need market info self.avg_prices = { market_id: markets[market_id].orderbook.tob()[0] for market_id in self.market_ids if markets[market_id].orderbook.tob()[0] } # Example: Place initial orders if self.config.get("PlaceInitialOrders", False): result = StrategyResult() # Add initial orders... return result return None # No initial orders
This method is part of the strategy initialization sequence:
Framework loads markets and accounts required by this strategy
Your on_initialize method is called with loaded data
Any returned orders are immediately submitted
The strategy moves to running state
Tip: Use on_initialize for parameter initialization that requires market or account data, and to place any initial orders needed for your strategy.
For data structure information on Account and Market, see below.
The _execute_strategy method is a part of “Strategy Execution (execute) Method”. The base class execute method handles the complete execution flow:
Initialization check: Initializes the strategy if needed
State update: Updates the strategy’s account and market references
Data processing: Processes raw update data through the appropriate handler
Strategy execution: Calls your _execute_strategy method with processed data
Order enrichment: Adds default values to orders (fee recipient, client ID)
You rarely need to override this method. Instead, focus on implementing _execute_strategy where your custom trading logic goes:Purpose: Analyze market data and generate trading signals Parameters:
processed_data: Handler-processed data dictionary with relevant fields
Returns: StrategyResult with orders/cancellations or None
Copy
Ask AI
async def _execute_strategy(self, update_type, processed_data): # Only respond to orderbook updates if update_type != UpdateType.OnOrderbook: return None # Get market data market_id = processed_data["market_id"] market = self.markets[market_id] # Get current prices bid, ask = market.orderbook.tob() if not bid or not ask: self.logger.warning(f"Incomplete orderbook for {market_id}") return None # Implement your strategy logic spread = (ask - bid) / bid if spread < self.min_spread_threshold: self.logger.info(f"Spread too narrow: {spread:.2%}") return None # Get subaccount for orders subaccount_id = self.config.get("SubaccountIds", [""])[0] if not subaccount_id: return None # Check current position to avoid exceeding limits position = self.get_position(subaccount_id, market_id) current_size = Decimal("0") if position: current_size = position.get("quantity", Decimal("0")) # Determine order parameters result = StrategyResult() # Create a new order if current_size < self.max_position: buy_order = Order( market_id=market_id, subaccount_id=subaccount_id, order_side=Side.BUY, price=bid, quantity=self.order_size, market_type=market.market_type # Required field as of v0.5.1 ) result.orders.append(buy_order) self.logger.info(f"Creating BUY order at {bid}: {self.order_size}") # Cancel existing orders if needed for order_hash in self.active_orders: result.cancellations.append({ "market_id": market_id, "subaccount_id": subaccount_id, "order_hash": order_hash }) return result
In _execute_strategy you can:
Filter by update type to handle specific events
Access current market data and account state
Check existing positions before placing orders
Implement custom trading logic based on market conditions
Create new orders and cancel existing ones
Update position margins for derivative markets
Log strategy decisions for monitoring and debugging
The framework will handle the execution details like transaction creation, simulation, and broadcasting based on your returned StrategyResult.
The framework processes updates through specialized handlers before passing the data to your strategy. You can create custom handlers for more control over data processing.
- market_id: str - subaccount_id: str - account: Account object - trade: Order object representing the trade - order: Original Order object that was filled
UpdateType.OnDerivativeTrade
Derivative trade execution
- market_id: str - subaccount_id: str - account: Account object - trade: Order object representing the trade - order: Original Order object that was filled