### Install Jesse Python Package Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/getting-started-api.md Install the core Jesse framework using pip. This is the first step to begin using Jesse for algorithmic trading. ```bash pip install jesse ``` -------------------------------- ### Install Jesse Live Trading Extension Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/getting-started-api.md Install the jesse-livetrade package to enable live trading features. This is required if you plan to execute trades in a live environment. ```bash pip install jesse-livetrade ``` -------------------------------- ### Start Jesse Backend Server Source: https://github.com/jesse-ai/jesse/blob/master/AGENTS.md Commands to stop any running Jesse processes and start the API server from the bot directory. Logs are redirected to a file, and the server runs in the background. ```bash # Stop any running process pkill -f "jesse run" # Start Jesse from bot directory (not jesse/) cd /Users/salehmir/codes/jesse/dev-jesse/bot /Users/salehmir/miniconda3/envs/jesse3.12/bin/jesse run > /tmp/jesse-output.log 2>&1 & # Server runs at http://localhost:9001 # Check logs tail -f /tmp/jesse-output.log ``` -------------------------------- ### on_open_position Example Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/strategy.md Example of how to set stop loss and take profit within the `on_open_position` hook, which is required for spot trading and recommended for futures. ```APIDOC ## on_open_position Example Example — set stop/take in `on_open_position` (required for spot, recommended for futures), checking position type first: ```python def on_open_position(self, order) -> None: if self.is_long: self.stop_loss = self.position.qty, self.price - ta.atr(self.candles) * 2 self.take_profit = self.position.qty, self.price + ta.atr(self.candles) * 4 elif self.is_short: self.stop_loss = self.position.qty, self.price + ta.atr(self.candles) * 2 self.take_profit = self.position.qty, self.price - ta.atr(self.candles) * 4 ``` ``` -------------------------------- ### Configure Exchange Settings Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/getting-started-api.md Set up exchange-specific configurations including fees, type, starting balance, and futures leverage options. ```python from jesse.config import config config['env']['exchanges']['Binance Spot'] = { 'fee': 0.001, # 0.1% fee 'type': 'spot', # 'spot' or 'futures' 'balance': 10_000, # Starting balance } config['env']['exchanges']['Binance Perpetual Futures'] = { 'fee': 0.0002, 'type': 'futures', 'balance': 10_000, 'futures_leverage': 10, 'futures_leverage_mode': 'cross' # or 'isolated' } ``` -------------------------------- ### Position Usage Example Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/models.md An example demonstrating how to access and utilize the Position model within a trading strategy. ```APIDOC ## Position Usage Example An example demonstrating how to access and utilize the Position model within a trading strategy. ```python from jesse.models import Position # Access position from strategy position = self.position if position.is_long: print(f"Long {position.qty} at ${position.entry_price}") print(f"PnL: ${position.pnl} ({position.roi:.2f}%)") if position.is_short: print(f"Liquidation price: ${position.liquidation_price}") ``` ``` -------------------------------- ### Multi-Strategy Routing Configuration Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/modes-and-routing.md Provides an example of configuring multiple strategies to run on the same or different symbols and timeframes within the `routes.py` file. ```python routes = [ # Strategy 1: Trend-following on BTC 4h Route( exchange='Binance Spot', symbol='BTC-USDT', timeframe='4h', strategy_name='TrendFollower' ), # Strategy 2: Mean-reversion on ETH 1h Route( exchange='Binance Spot', symbol='ETH-USDT', timeframe='1h', strategy_name='MeanReversion' ), # Strategy 1 on different symbol Route( exchange='Binance Spot', symbol='ETH-USDT', timeframe='4h', strategy_name='TrendFollower' ), ] ``` -------------------------------- ### Configure Exchange Settings (Spot) Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/configuration.md Set per-exchange parameters including trading fee, type, starting balance, and leverage for spot trading. ```python config['env']['exchanges']['Binance Spot'] = { 'fee': 0.001, # Trading fee (0.1%) 'type': 'spot', # 'spot' or 'futures' 'balance': 10_000, # Starting balance (quote asset) 'futures_leverage': 1, # Leverage (futures only) 'futures_leverage_mode': 'cross' # 'cross' or 'isolated' } ``` -------------------------------- ### Run Optimization Session Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/optimization.md Starts an optimization session and polls for results. The server returns a 'started' status, and you should repeatedly check the session status until it reaches a terminal state. ```python run_optimization(session_id="") ``` -------------------------------- ### Scaling In/Out with Multiple Price Levels Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/strategy.md Shows how to place orders at multiple price levels by passing a list of (quantity, price) tuples. This example is for a long entry. ```python def go_long(self): # average_entry_price will be 110 self.buy = [ (1, 100), (1, 120), ] ``` -------------------------------- ### Usage Example: RSI Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/indicators-api.md Demonstrates how to get the current RSI value or a historical series, and how to use it within a strategy's logic. ```python import jesse.indicators as ta # Get current RSI value only rsi_value = ta.rsi(candles) # Returns float # Get historical RSI for all candles rsi_series = ta.rsi(candles, sequential=True) # Returns array # Use in strategy def should_long(self) -> bool: rsi = ta.rsi(self.candles) return 30 < rsi < 70 ``` -------------------------------- ### Backtest Mode via CLI Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/modes-and-routing.md Simulate strategy performance on historical data using the command-line interface. Specify strategy name, start date, and end date. ```bash jesse backtest "Strategy Name" --start-date 2024-01-01 --end-date 2024-12-31 ``` -------------------------------- ### Backtest Strategy Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/getting-started-api.md Simulate strategy performance on historical data. Specify start and end dates for the backtest period. ```bash jesse backtest MyStrategy --start-date 2024-01-01 --end-date 2024-12-31 ``` -------------------------------- ### Log Strategy Information and Actions Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/strategy.md Use self.log() to output messages during backtesting. This example logs the current PnL percentage and triggers liquidation if it exceeds 2%. ```python def update_position(self): self.log(f'Current PnL %: {self.position.pnl_percentage}') if self.position.pnl_percentage > 2: self.log('Liquidating position') self.liquidate() ``` -------------------------------- ### Multi-Strategy Setup in Jesse Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/README.md Configures multiple trading strategies to run independently by defining routes in `jesse/routes.py`. Each route specifies the exchange, symbol, timeframe, and strategy name. ```python # jesse/routes.py from jesse.models import Route routes = [ Route('Binance Spot', 'BTC-USDT', '4h', 'TrendFollower'), Route('Binance Spot', 'ETH-USDT', '1h', 'MeanReversion'), Route('Binance Futures', 'BTC-USDT', '1h', 'ScalperBot'), ] # Each strategy trades independently # Broadcast events between them if needed ``` -------------------------------- ### Jesse CLI Execution Modes Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/README.md Provides examples of common Jesse command-line interface commands for various execution modes, including backtesting, paper trading, live trading, optimization, Monte Carlo simulation, and benchmarking. ```bash # Backtest on historical data jesse backtest MyStrategy --start-date 2024-01-01 --end-date 2024-12-31 # Paper trade (simulated with real-time data) jesse livetrade MyStrategy --paper # Live trade (real money) jesse livetrade MyStrategy # Optimize hyperparameters jesse optimize MyStrategy --start-date 2024-01-01 --end-date 2024-12-31 # Stress-test with Monte Carlo jesse mc MyStrategy # Benchmark multiple runs jesse benchmark MyStrategy ``` -------------------------------- ### Run Backtest with Jesse CLI Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/getting-started-api.md Execute a backtest for a specified strategy using the Jesse command-line interface. Provide the strategy name, start date, and end date for the backtest period. ```bash jesse backtest GoldenCross --start-date 2024-01-01 --end-date 2024-12-31 ``` -------------------------------- ### Get Specific Configuration Sections Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/configuration.md Retrieves specific configuration sections for backtesting, live trading, or optimization. Use these to access targeted settings. ```python backtest_config = get_backtest_config() live_config = get_live_config() optimization_config = get_optimization_config() ``` -------------------------------- ### start_profit_at Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/broker-and-orders.md Submit a stop order to start or increase a position. Used for averaging in or scaling entries based on price levels. This method is specifically for trigger-based entries. ```APIDOC ## start_profit_at ### Description Submit a stop order to start/increase a position. Used for averaging in or scaling entries based on price levels. ### Method Signature ```python def start_profit_at(self, side: str, qty: float, price: float) -> Order | None: ``` ### Parameters #### Path Parameters - **side** (str) - Required - 'buy' or 'sell' - **qty** (float) - Required - Quantity - **price** (float) - Required - Trigger price ### Validation - For BUY: price must be higher than current_price (buying on strength) - For SELL: price must be lower than current_price (shorting on weakness) ### Returns - `Order` or `None` ### Raises - `InvalidStrategy` if qty == 0 - `OrderNotAllowed` if price direction invalid - `ValueError` if price < 0 ``` -------------------------------- ### Retrieve and Display Backtest Session Results Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/models.md Example of how to fetch a BacktestSession by its ID and print key performance metrics like Sharpe Ratio, Max Drawdown, and Win Rate. ```python from jesse.models import BacktestSession # Get session results session = BacktestSession.get_by_id('123e4567-e89b-12d3-a456-426614174000') print(f"Sharpe Ratio: {session.sharpe_ratio:.2f}") print(f"Max Drawdown: {session.max_drawdown:.2f}%") print(f"Win Rate: {session.win_rate:.2f}%") ``` -------------------------------- ### run_optimization(session_id) Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/optimization.md Starts an optimization session that has been previously drafted or prepared. This function initiates the optimization process and returns an initial status. ```APIDOC ## run_optimization(session_id) Fire-and-poll. Returns `{ "status": "started", ... }` when the server accepts. Then keep checking `get_optimization_session` until a terminal status. See "Checking for results" below. ``` -------------------------------- ### Reset Jesse Configuration to Initial State Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/configuration.md Use this function to revert all configuration changes and restore the initial state. This is useful for troubleshooting or starting fresh. ```python from jesse.config import reset_config reset_config() # Reverts all changes ``` -------------------------------- ### Configure Trading Routes Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/getting-started-api.md Define the trading routes for your strategies, specifying the exchange, symbol, timeframe, and the strategy to be used. This example sets up a route for the GoldenCross strategy on Binance Spot for BTC-USDT. ```python # jesse/routes.py from jesse.models import Route routes = [ Route( exchange='Binance Spot', symbol='BTC-USDT', timeframe='1h', strategy_name='GoldenCross' ) ] ``` -------------------------------- ### Create a New Jesse Strategy Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/strategy.md Use the `create_strategy` tool to generate a new strategy with the given name and code. This is the starting point for defining custom trading logic. ```python strategy_code = ''' from jesse.strategies import Strategy import jesse.indicators as ta from jesse import utils class MyStrategy(Strategy): def should_long(self) -> bool: # Entry condition for long positions return False def should_short(self) -> bool: # Entry condition for short positions return False def go_long(self): # Place long entry order qty = utils.size_to_qty(self.available_margin * 0.1, self.price, fee_rate=self.fee_rate) self.buy = qty, self.price def go_short(self): # Place short entry order qty = utils.size_to_qty(self.available_margin * 0.1, self.price, fee_rate=self.fee_rate) self.sell = qty, self.price def should_cancel_entry(self) -> bool: # Cancel pending entry orders return False def update_position(self): # Manage open positions and implement exit logic pass ''' result = create_strategy("MyStrategy", strategy_code) ``` -------------------------------- ### Implement Bollinger Bands Indicator Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/indicator.md Example of implementing Bollinger Bands, returning a namedtuple with upperband, middleband, and lowerband. Use to identify price proximity to bands. ```python # From get_indicator_details("bollinger_bands"): # signature: (candles, period=20, devup=2.0, devdn=2.0) -> BollingerBands(upperband, middleband, lowerband) bb = ta.bollinger_bands(self.candles) # Returns: BollingerBands(upperband=..., middleband=..., lowerband=...) price = self.close if price <= bb.lowerband: # Price touched lower band return True ``` -------------------------------- ### Position Sizing: Dynamic Sizing with Capital Percentage Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/backtest_management.md Use dynamic position sizing based on available capital and risk percentage for more robust trading. This example calculates quantity based on 5% of balance. ```python # WRONG - Fixed quantity regardless of capital def go_long(self): self.buy = 100, self.close # Always buys 100 units ``` ```python # CORRECT - Size based on capital percentage def go_long(self): risk_amount = self.balance * 0.05 # 5% of balance qty = utils.size_to_qty(risk_amount, self.close, fee_rate=self.fee_rate) self.buy = qty, self.close ``` -------------------------------- ### Multi-Timeframe Strategy Example Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/getting-started-api.md Implements a multi-timeframe strategy that uses RSI on the main timeframe and a 50-period EMA on a daily timeframe to determine long entry conditions. Higher timeframe data is accessed via the `store`. ```python class MultiTimeframe(Strategy): def should_long(self) -> bool: # Main timeframe rsi_1h = ta.rsi(self.candles) # Higher timeframe (via store) from jesse.store import store daily_candles = store.candles.get( self.exchange, self.symbol, '1D' ) trend_1d = ta.ema(daily_candles, 50)[-1] return rsi_1h < 40 and self.price > trend_1d ``` -------------------------------- ### Querying and Filtering Orders Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/models.md Demonstrates how to query the Order model using its ORM-like interface. Examples show how to filter orders by exchange and status, and how to retrieve orders associated with a specific trade. ```python from jesse.models import Order from jesse.enums import order_statuses # Query executed orders executed = Order.select().where( (Order.exchange == 'Binance Spot') & (Order.status == order_statuses.EXECUTED) ).order_by(Order.executed_at.desc()) # Find orders for a trade trade_orders = Order.select().where(Order.trade_id == '123e4567-e89b-12d3-a456-426614174000') # Check partial fills for order in trade_orders: if order.is_partially_filled: print(f"Remaining qty: {order.remaining_qty}") ``` -------------------------------- ### Optimize Mode via CLI Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/modes-and-routing.md Perform hyperparameter tuning for a strategy using the command-line interface. Specify strategy name, start date, and end date. Results include the best DNA for live trading. ```bash jesse optimize "Strategy Name" --start-date 2024-01-01 --end-date 2024-12-31 ``` -------------------------------- ### Run Monte Carlo Simulation Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/monte_carlo.md Initiates a Monte Carlo simulation. Returns a started status and session ID. Continuously check `get_monte_carlo_session` for updates until a terminal status is reached. ```python run_monte_carlo(session_id) ``` -------------------------------- ### Complete Strategy Example Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/indicators-api.md A full strategy implementation demonstrating the use of multiple indicators like RSI, ADX, and EMA for trend following and momentum confirmation. Includes logic for entering long and short positions, and setting take profit and stop loss levels. ```python import jesse.indicators as ta class TrendFollower(Strategy): def should_long(self) -> bool: # Multiple indicators rsi = ta.rsi(self.candles, period=14) adx = ta.adx(self.candles, period=14) ema_fast = ta.ema(self.candles, period=9) ema_slow = ta.ema(self.candles, period=21) # Trend + momentum confirmation trending = adx > 25 strong_momentum = 40 < rsi < 70 price_above_slow = self.price > ema_slow[-1] ema_aligned = ema_fast[-1] > ema_slow[-1] return trending and strong_momentum and price_above_slow and ema_aligned def should_short(self) -> bool: rsi = ta.rsi(self.candles) adx = ta.adx(self.candles) return adx > 25 and rsi < 40 def go_long(self): atr = ta.atr(self.candles) qty = utils.size_to_qty(self.balance * 0.05, self.price) self.buy = qty, self.price - 5 self.take_profit = qty, self.price * 1.15 self.stop_loss = qty, self.price - (2 * atr) ``` -------------------------------- ### Update Backtest Draft - Field Updates Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/backtest_management.md Updates specific fields within an existing backtest draft's state. This example shows how to modify the start date and debug mode settings by copying the current state and applying the new values. ```python session_response = get_backtest_session("550e8400-e29b-41d4-a716-446655440000") session = session_response.data.session current_state = session.state.state merged_state = current_state.copy() merged_state.form.start_date = "2024-06-01" merged_state.form.debug_mode = true update_backtest_draft("550e8400-e29b-41d4-a716-446655440000", merged_state) ``` -------------------------------- ### Mean Reversion Strategy Example Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/getting-started-api.md Implements a mean-reversion strategy using Relative Strength Index (RSI) and Bollinger Bands. Enters long positions when RSI is below 30 and the price is below the lower band, with take-profit at the SMA and stop-loss at 5% below entry. ```python class MeanReversion(Strategy): def should_long(self) -> bool: rsi = ta.rsi(self.candles) bb = ta.bollinger_bands(self.candles) return rsi < 30 and self.price < bb[2] # Below lower band def go_long(self): qty = utils.size_to_qty(self.balance * 0.05, self.price) bb = ta.bollinger_bands(self.candles) self.buy = qty, self.price self.take_profit = qty, bb[1][-1] # SMA self.stop_loss = qty, self.price * 0.95 ``` -------------------------------- ### Live Paper Trading with Jesse Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/README.md Sets up exchange API keys, creates a live session, and runs paper trading for a specified strategy. Monitoring is done via the dashboard. ```bash # 1. Set up exchange API keys in dashboard # 2. Create live session # 3. Run paper trading jesse livetrade MyStrategy --paper # 4. Monitor in dashboard # Open http://localhost:9000 ``` -------------------------------- ### Handle InvalidDateRange Exception Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/exceptions-and-errors.md Raised when the start date is after the end date in a backtest command. Ensure the start date precedes or is the same as the end date. ```bash jesse backtest MyStrategy --start-date 2024-12-31 --end-date 2024-01-01 # CORRECT jesse backtest MyStrategy --start-date 2024-01-01 --end-date 2024-12-31 ``` -------------------------------- ### Configuration and Mode Checks in Python Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/README.md Shows how to access configuration values and check the current execution mode (backtesting, live trading, optimization) using jesse.helpers. ```python import jesse.helpers as jh # Get configuration value = jh.get_config('env.exchanges.Binance Spot.fee') # Check mode if jh.is_backtesting(): print("In backtest mode") elif jh.is_livetrading(): print("In live trading mode") elif jh.is_optimizing(): print("In optimization mode") ``` -------------------------------- ### Trend Following Strategy Example Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/getting-started-api.md Implements a trend-following strategy using Exponential Moving Averages (EMA) and Average Directional Index (ADX). Sets buy orders with stop-loss and take-profit based on Average True Range (ATR). ```python class TrendFollower(Strategy): def should_long(self) -> bool: fast = ta.ema(self.candles, 9) slow = ta.ema(self.candles, 21) adx = ta.adx(self.candles) return fast[-1] > slow[-1] and adx > 25 def go_long(self): qty = utils.size_to_qty(self.balance * 0.05, self.price) atr = ta.atr(self.candles) self.buy = qty, self.price self.stop_loss = qty, self.price - 2*atr[-1] self.take_profit = qty, self.price + 3*atr[-1] ``` -------------------------------- ### Define a Trading Strategy in Python Source: https://github.com/jesse-ai/jesse/blob/master/README.md Example of defining a simple trading strategy using Python with Jesse. This strategy goes long when the EMA 8 crosses above the EMA 21 and sets entry price, quantity, take profit, and stop loss. ```python class GoldenCross(Strategy): def should_long(self): # go long when the EMA 8 is above the EMA 21 short_ema = ta.ema(self.candles, 8) long_ema = ta.ema(self.candles, 21) return short_ema > long_ema def go_long(self): entry_price = self.price - 10 # limit buy order at $10 below the current price qty = utils.size_to_qty(self.balance*0.05, entry_price) # spend only 5% of my total capital self.buy = qty, entry_price # submit entry order self.take_profit = qty, entry_price*1.2 # take profit at 20% above the entry price self.stop_loss = qty, entry_price*0.9 # stop loss at 10% below the entry price ``` -------------------------------- ### Backtest a Strategy with Jesse Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/README.md Steps to create a strategy, download historical candle data, and backtest it using the Jesse CLI. Requires defining a strategy file and using import-candles and backtest commands. ```bash # 1. Create strategy file # jesse/strategies/MyStrategy/__init__.py # 2. Download candle data jesse import-candles --exchange "Binance Spot" \ --symbol BTC-USDT --timeframe 1h \ --start-date 2024-01-01 --end-date 2024-12-31 # 3. Backtest jesse backtest MyStrategy --start-date 2024-01-01 --end-date 2024-12-31 # 4. Review results in dashboard # Open http://localhost:9000 ``` -------------------------------- ### Set Application Configuration Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/configuration.md Use `set_config()` to apply runtime configuration. This includes settings for warm-up candles, exchange details, logging, and live trading options. ```python from jesse.config import set_config conf = { 'warm_up_candles': 240, 'exchanges': { 'Binance Spot': { 'type': 'spot', 'fee': 0.001, 'balance': 10000 } }, 'logging': { 'strategy_execution': True, 'order_execution': True, # ... other logging settings }, # Live mode only: 'notifications': {...}, 'persistency': True, 'generate_candles_from_1m': False } set_config(conf) ``` -------------------------------- ### Start Profit Order Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/broker-and-orders.md Submit a stop order to start or increase a position. Used for averaging in or scaling entries based on price levels. Validation rules apply for BUY and SELL sides. ```python def start_profit_at(self, side: str, qty: float, price: float) -> Order | None: """ Submit a stop order to start/increase a position. Used for averaging in or scaling entries based on price levels. """ ``` -------------------------------- ### Anchor Timeframe Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/helpers-and-utilities.md Get the anchor (higher) timeframe for a given timeframe. Useful for multi-timeframe analysis. ```APIDOC ## anchor_timeframe ### Description Get the anchor (higher) timeframe for a given timeframe. ### Parameters #### Path Parameters - **timeframe** (str) - Required - Input timeframe ### Returns - **str** - Higher timeframe ``` -------------------------------- ### Standard Jesse Optimization Workflow Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/optimization.md This Python code demonstrates the complete workflow for running an optimization session in Jesse. It includes staging the optimization parameters, initiating the run, polling for completion, and processing the results based on the session status. ```python # 1. Stage the optimization (train then test, contiguous windows) draft = create_optimization_draft( exchange="Binance Perpetual Futures", routes='[{"exchange":"Binance Perpetual Futures","strategy":"MyStrategy","symbol":"BTC-USDT","timeframe":"4h"}]', training_start_date="2023-01-01", training_finish_date="2024-06-01", testing_start_date="2024-06-01", testing_finish_date="2024-12-01", objective_function="sharpe", trials=100, hypothesis="MyStrategy's EMA periods generalize out-of-sample.", ) sid = draft["session_id"] # 2. Fire it run_optimization(sid) # 3. Keep checking until terminal (optimization is slow — widen the interval) while True: s = get_optimization_session(sid) status = s["data"]["session"]["status"] if status in ("finished", "stopped", "terminated"): break time.sleep(20) # 4. Pick the candidate that generalizes best (smallest train->test drop) session = s["data"]["session"] if status == "finished": cands = session["best_candidates"] # report rank #1 plus train-vs-test for the top few; flag overfit candidates elif status == "stopped": # read session["exception"] / get_optimization_logs(sid); if missing candles, # import_candles() for both windows (~2 months before each start) then rerun_optimization(sid) ... ``` -------------------------------- ### Update Position with Reduce Order Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/broker-and-orders.md Example of using reduce_position_at to update a take-profit level for a long position. ```python def update_position(self): if self.is_long: # Update take-profit new_tp_price = self.price * 1.25 self.broker.reduce_position_at( qty=self.position.qty, price=new_tp_price, current_price=self.price ) ``` -------------------------------- ### Get Average Entry Price Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/strategy-framework.md Provides the average price at which the current position was entered. This is a read-only property. ```python @property def entry_price(self) -> float: """Average entry price of position""" ``` -------------------------------- ### Import Candles Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/candle.md Use this function to import historical candle data from exchanges. Specify the exchange, symbol, and start date. ```python result = import_candles( exchange="Binance Spot", symbol="BTC-USDT", start_date="2024-01-01" ) ``` -------------------------------- ### Run Jesse Tests Source: https://github.com/jesse-ai/jesse/blob/master/AGENTS.md Execute the test suite for the Jesse project. Ensure you are in the 'cd-jesse' directory before running. ```bash cd-jesse && pytest ``` -------------------------------- ### Configure Notifications (Live Trading) Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/configuration.md Set up event notifications for live trading, including which events trigger notifications and how to configure channels like Telegram, Slack, or Discord. ```python config['env']['notifications'] = { 'events': { 'updated_position': True, # Notify on position changes 'trade_closed': True, # Notify on trade exit 'error': True # Notify on errors }, 'channels': { 'telegram': { 'enabled': True, 'token': '...', 'chat_id': '...' }, 'slack': { 'enabled': True, 'webhook_url': '...' }, 'discord': { 'enabled': True, 'webhook_url': '...' } } } ``` -------------------------------- ### Implement RSI Indicator Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/indicator.md Example of implementing the RSI indicator, which returns a single float value between 0 and 100. Use this for oversold/overbought conditions. ```python # From get_indicator_details("rsi"): # signature: (candles, period=14, source_type="close", sequential=False) -> float rsi_value = ta.rsi(self.candles, period=14) # Returns: float between 0-100 if rsi_value < 30: # Oversold condition return True ``` -------------------------------- ### Run a Full Monte Carlo Simulation Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/monte_carlo.md This snippet demonstrates the complete workflow for a Monte Carlo simulation. It includes staging the simulation with specific parameters, running it, polling for completion, and analyzing the results, particularly the Sharpe ratio, to determine if the strategy is overfit. ```python draft = create_monte_carlo_draft( exchange="Binance Perpetual Futures", routes='[{"exchange":"Binance Perpetual Futures","strategy":"MyStrategy","symbol":"BTC-USDT","timeframe":"4h"}]', start_date="2023-01-01", finish_date="2024-01-01", hypothesis="MyStrategy is robust across resampled BTC price paths.", ) sid = draft["session_id"] # 2. Fire it run_monte_carlo(sid) # 3. Poll until done while True: s = get_monte_carlo_session(sid) status = s["data"]["session"]["status"] if status in ("finished", "stopped", "terminated"): break time.sleep(5) # 4. Inspect summary metrics session = s["data"]["session"] if status == "finished": candles = session["candles_session"] by_metric = {m["metric"]: m for m in candles["summary_metrics"]} sharpe = by_metric.get("sharpe_ratio", {}) orig, med, best5, worst5 = ( sharpe.get("original"), sharpe.get("median"), sharpe.get("best_5"), sharpe.get("worst_5"), ) # Overfit verdict from the original-vs-MC comparison if orig > best5: verdict = "OVERFIT — original beat 95% of MC scenarios" elif orig > med: verdict = "borderline — above median MC but inside the plausible range" elif orig < med: verdict = "fantastic — original is conservative vs MC distribution" else: verdict = "good — original is representative of typical MC outcomes" update_monte_carlo_notes( sid, description=( f"Sharpe — original={orig:.2f} median={med:.2f} " f"best_5={best5:.2f} worst_5={worst5:.2f}. {verdict}." ), ) elif status in ("stopped", "terminated"): logs = get_monte_carlo_logs(sid) # surface logs["logs"] to the user ``` -------------------------------- ### Watch GitHub Actions Workflow Source: https://github.com/jesse-ai/jesse/blob/master/AGENTS.md Monitor the progress of the GitHub Actions workflow after pushing a tag. This command requires the GitHub CLI to be installed. ```bash gh run watch --repo jesse-ai/jesse ``` -------------------------------- ### Order Submission in Python Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/README.md Demonstrates various methods for submitting orders, including using strategy properties for automatic submission and direct broker calls for manual execution. Supports single and multiple partial orders. ```python # Via strategy properties (auto-submitted) self.buy = (qty, price) # Entry order self.take_profit = (qty, price) # Exit order self.stop_loss = (qty, price) # Exit order # Multiple partial orders self.buy = [(qty1, p1), (qty2, p2)] # Via broker (manual) self.broker.buy_at_market(qty) self.broker.buy_at(qty, price) self.broker.reduce_position_at(qty, price, current_price) ``` -------------------------------- ### Get Optimization Logs Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/optimization.md Fetches the log file content for an optimization session. Useful for diagnosing errors when a session is stopped or to monitor progress. ```python get_optimization_logs(session_id="") ``` -------------------------------- ### Benchmark Strategy Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/getting-started-api.md Run multiple backtests in batch to benchmark strategy performance. ```bash jesse benchmark MyStrategy ``` -------------------------------- ### Get Leverage Multiplier Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/strategy-framework.md Returns the current leverage multiplier applied to the position. This will be 1 for spot trading and greater than 1 for futures trading. ```python @property def leverage(self) -> float: """Leverage multiplier (1 for spot, >1 for futures)""" ``` -------------------------------- ### Get Anchor Timeframe with `utils.anchor_timeframe` Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/helpers-and-utilities.md The `utils.anchor_timeframe` function returns the higher, or 'anchor', timeframe for a given input timeframe. This is useful for multi-timeframe analysis. ```python from jesse import utils upper = utils.anchor_timeframe('15m') # upper = '2h' upper = utils.anchor_timeframe('1h') # upper = '4h' ``` -------------------------------- ### Jesse API Documentation Overview Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt This section outlines the various documentation files generated for the Jesse framework, covering different aspects of its API and functionality. Each file provides detailed technical reference information. ```APIDOC ## Jesse API Documentation Files This is a list of the generated documentation files for the Jesse cryptocurrency trading framework (v2.4.0), organized by domain. ### Framework - **README.md**: Master index, module organization, common workflows, and troubleshooting. - **strategy-framework.md**: Strategy class API reference, lifecycle methods, order submission, position management, chart visualization, and ML features. - **models.md**: Documentation for Candle, Order, Position, ClosedTrade, BacktestSession, and OptimizationSession models, including field definitions and usage examples. - **enums-and-types.md**: Definitions for order statuses, sides, trade types, timeframes, exchanges, colors, and order types. ### Operations - **broker-and-orders.md**: API for broker order submission, including market, limit, and stop order types, order cancellation, status tracking, and position reduction methods. - **modes-and-routing.md**: Documentation for backtest, livetrade, papertrade, optimization, and Monte Carlo modes, including route configuration and multi-strategy setup. ### Analysis - **indicators-api.md**: Reference for 300+ technical indicators, including momentum, trend, volatility, volume, and cycle indicators, with strategy examples. - **helpers-and-utilities.md**: Documentation for over 40 helper functions for price/quantity conversion, risk management, cross detection, and statistical functions. ### Config - **configuration.md**: Details on environment configuration, exchange settings, logging, optimization parameters, and mode-specific configurations. - **exceptions-and-errors.md**: Reference for 30+ custom exception types related to strategy, order, data access, exchange, balance, and configuration, along with error handling best practices. ### Overview - **getting-started-api.md**: Quick start guide, core concepts, complete API reference, data access patterns, and common trading patterns. ### Code Examples and Quality All documentation files include complete function signatures, parameter tables, return types, error conditions, realistic usage examples, common patterns, and best practices. The documentation is tested on the actual Jesse codebase and ensures high quality with no marketing copy or tutorials, focusing purely on technical reference. ``` -------------------------------- ### Access Hyperparameter Values Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/strategy.md Access the optimized hyperparameter values within your strategy using `self.hp['parameter_name']`. This example shows how to use the 'sma_period' hyperparameter. ```python @property def sma(self): return ta.sma(self.candles, self.hp['sma_period']) ``` -------------------------------- ### Read Complete Configuration Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/configuration.md Retrieves the entire Jesse configuration object. Use this to inspect all current settings. ```python config = get_config() # Returns full configuration object ``` -------------------------------- ### Querying and Creating Candle Data Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/models.md Demonstrates how to query existing candle data based on specific criteria and how to create new candle records. Ensure the Candle model is imported. ```python from jesse.models import Candle # Query candles candles = Candle.select().where( (Candle.exchange == 'Binance Spot') & (Candle.symbol == 'BTC-USDT') & (Candle.timeframe == '1h') ).order_by(Candle.timestamp.asc()) # Create new candle candle = Candle.create( timestamp=1234567890000, open=100.0, close=105.0, high=106.0, low=99.0, volume=1000.0, exchange='Binance Spot', symbol='BTC-USDT', timeframe='1h' ) ``` -------------------------------- ### Implement MACD Indicator Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/indicator.md Example of implementing the MACD indicator, which returns a namedtuple containing macd, signal, and hist values. Use for crossover and trend analysis. ```python # From get_indicator_details("macd"): # signature: (candles, fast_period=12, slow_period=26, signal_period=9) -> MACD(macd, signal, hist) macd_result = ta.macd(self.candles) # Returns: MACD(macd=..., signal=..., hist=...) if macd_result.hist > 0 and macd_result.macd > macd_result.signal: # Bullish MACD crossover return True ``` -------------------------------- ### Get Monte Carlo Equity Curves Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/monte_carlo.md Fetches the per-scenario Portfolio equity curves. This is useful for computing custom statistics across scenarios or visualizing dispersion. ```json { "status": "success", "trades": { "original": {...}, "scenarios": [{...}, ...] }, "candles": { "original": {...}, "scenarios": [{...}, ...] } } ``` -------------------------------- ### Risk Management Utilities in Python Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/README.md Illustrates the use of jesse.utils for risk management, including converting between size and quantity, and calculating order quantities based on capital and risk tolerance. ```python import jesse.utils as utils # Size to quantity conversion qty = utils.size_to_qty(position_size=100, entry_price=50) # qty = 2 # Quantity to size conversion size = utils.qty_to_size(qty=2, price=50) # size = 100 # Risk-based sizing qty = utils.risk_to_qty( capital=10000, risk_per_capital=1.0, # Risk 1% entry_price=100, stop_loss_price=95 ) # Estimate risk risk = utils.estimate_risk(entry_price=100, stop_price=95) # risk = 5 ``` -------------------------------- ### ML Prediction for Regression Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/strategy-framework.md Use `ml_predict` to get a scalar prediction from a trained regression model. This method loads the model once and is idempotent. Ensure `ml_features()` is overridden. ```python def should_long(self) -> bool: prediction = self.ml_predict() return prediction > 0 # Predict positive return ``` -------------------------------- ### Workflow for Iterative Backtesting with New Sessions Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/backtest_management.md This workflow demonstrates creating new backtest sessions for each iteration of strategy development. It shows how to initialize drafts, run backtests, and then retrieve and compare session results. ```python # Iteration 1: Create new session with initial strategy draft1 = create_backtest_draft(routes='[{"exchange": "Binance Spot", "strategy": "MyStrategy", "symbol": "BTC-USDT", "timeframe": "4h"}]') run_backtest(draft1.backtest_id, config) # Iteration 2: Create NEW session with modified strategy draft2 = create_backtest_draft(routes='[{"exchange": "Binance Spot", "strategy": "MyStrategy", "symbol": "BTC-USDT", "timeframe": "4h"}]') run_backtest(draft2.backtest_id, config) # Compare results across sessions session1_response = get_backtest_session(draft1.backtest_id) session2_response = get_backtest_session(draft2.backtest_id) session1_results = session1_response.data.session session2_results = session2_response.data.session ``` -------------------------------- ### Get Active Entry Orders Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/strategy-framework.md Returns a list of all active entry orders that have been placed but not yet filled or canceled. Each item in the list represents an order object. ```python @property def entry_orders(self) -> list: """Active entry orders""" ``` -------------------------------- ### Access Candle Data in Strategy Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/getting-started-api.md Access all candles or specific price/volume data within a strategy. Also shows how to query candles from the database. ```python # In strategy candles = self.candles # All candles: shape (n, 6) close = candles[:, 2] # Close prices high = candles[:, 3] # High prices volume = candles[:, 5] # Volumes ``` ```python # Database queries from jesse.models import Candle candles = Candle.select().where( (Candle.exchange == 'Binance Spot') & (Candle.symbol == 'BTC-USDT') & (Candle.timeframe == '1h') ).order_by(Candle.timestamp.asc()) ``` -------------------------------- ### Get Optimization Session Details Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/optimization.md Fetches the full details of a specific optimization session, including its status, progress, and best candidates. This is the primary tool for polling results. ```json { "data": { "session": { "id": "", "status": "running", "completed_trials": 120, "total_trials": 400, "best_candidates": [ { "rank": "#1", "trial": "Trial 18", "params": {"fast_period": 12, "slow_period": 35}, "fitness": 0.48, "dna": "...", "training_metrics": {"sharpe_ratio": 2.13, "total": 38, ...}, "testing_metrics": {"sharpe_ratio": 1.72, "total": 17, ...}, "objective_metric": "2.13 / 1.72" } ], "objective_curve": [...], "exception": null, "traceback": null } }, "error": null, "message": "Optimization session retrieved successfully" } ``` -------------------------------- ### List All Available Indicators Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/indicator.md Use the `list_indicators` tool to discover all available indicators and their count. This is the first step to avoid errors from guessing indicator names. ```python # Use the list_indicators tool to discover all available indicators result = list_indicators() # Returns: {"status": "success", "count": 177, "indicators": ["sma", "ema", "rsi", ...]} ``` -------------------------------- ### Handle Sequential Indicator Data Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/indicator.md Demonstrates how to use `sequential=True` for indicators to get a numpy array of all values, allowing access to current and previous values for trend analysis. ```python # Most indicators support sequential=True for full series rsi_series = ta.rsi(self.candles, period=14, sequential=True) # Returns: numpy array of all RSI values # Access current value current_rsi = rsi_series[-1] # Access previous values for trend analysis prev_rsi = rsi_series[-2] ``` -------------------------------- ### Get Active Exit Orders Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/strategy-framework.md Returns a list of all active stop-loss and take-profit orders that are currently placed and not yet filled or canceled. Each item represents an order object. ```python @property def active_exit_orders(self) -> list: """Active stop-loss and take-profit orders""" ``` -------------------------------- ### Smart Order Types in Jesse Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/strategy.md Demonstrates how Jesse infers order types (market, limit, stop) based on the order price relative to the current price. Use for long entry orders. ```python # market order (price == current price) self.buy = qty, self.price # limit order (buy below current price) self.buy = qty, self.price - 10 # stop order (buy above current price) self.buy = qty, self.price + 10 ``` -------------------------------- ### run_significance_test Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/significance_test.md Initiates a significance test session. This is a fire-and-poll operation that returns immediately with a status of 'started'. You should then poll the `get_significance_test_session` endpoint periodically until the status changes to 'finished', 'stopped', or 'terminated'. ```APIDOC ## run_significance_test(session_id) ### Description Fire-and-poll. Returns `{ "status": "started", "session_id": ... }` immediately when the server accepts (HTTP 202). Then poll `get_significance_test_session` every few seconds until `status == "finished"` (or `stopped` / `terminated`). ### Parameters - `session_id` (string) - Required ``` -------------------------------- ### Live Trading Configuration Schema Source: https://github.com/jesse-ai/jesse/blob/master/jesse/mcp/resources/configuration.md Details the structure for live trading configuration, including warmup candles and exchange settings. ```json { "live": { "warm_up_candles": 240, "exchanges": { // Exchange configurations for live trading } } } ``` -------------------------------- ### Optimization Mode Configuration Source: https://github.com/jesse-ai/jesse/blob/master/_autodocs/configuration.md Configuration for optimization mode, specifying warm-up candles, objective function, and trial parameters. ```python { 'warm_up_candles': 240, 'objective_function': 'sharpe', 'trials': 200, 'best_candidates_count': 20 } ```