### Start the Jesse application Source: https://docs.jesse.trade/docs/getting-started Launches the Jesse trading server locally. Requires the environment variables to be configured correctly in the .env file. ```sh jesse run ``` -------------------------------- ### Initialize a new Jesse project Source: https://docs.jesse.trade/docs/getting-started Clones the official Jesse project template and initializes the environment configuration file. This is the first step to setting up a new trading bot project. ```sh # change the name "my-bot" to whatever you want git clone https://github.com/jesse-ai/project-template my-bot # enter the directory cd my-bot # create a .env file by copying it from the template # edit this to match you enviroment cp .env.example .env ``` -------------------------------- ### Install or upgrade Jesse via pip Source: https://docs.jesse.trade/docs/getting-started Commands to install the Jesse framework or update an existing installation to the latest version using the Python package manager. ```bash pip install jesse # To upgrade: pip install -U jesse ``` -------------------------------- ### Install Redis Server on Ubuntu (WSL) Source: https://docs.jesse.trade/docs/getting-started/environment-setup A sequence of apt commands to update package lists, upgrade existing packages, and install the Redis server on an Ubuntu system within WSL. It also verifies the Redis installation. ```bash sudo apt-get update sudo apt-get upgrade sudo apt-get install redis-server redis-cli -v ``` -------------------------------- ### Install Cython using pip Source: https://docs.jesse.trade/docs/getting-started/environment-setup A simple pip command to install the Cython package, which is required for Jesse. This command should be run after setting up the Python environment. ```bash pip install cython ``` -------------------------------- ### Install Docker on Ubuntu Source: https://docs.jesse.trade/docs/getting-started/docker Uses the official Docker convenience script to install Docker and Docker Compose on Ubuntu-based systems. ```shell # install docker and docker compose curl -fsSL https://get.docker.com -o get-docker.sh && sudo sh get-docker.sh ``` -------------------------------- ### Complete Monte Carlo Simulation Example in Jesse.trade Source: https://docs.jesse.trade/docs/research/monte_carlo This comprehensive example demonstrates how to configure and run a full Monte Carlo simulation using Jesse.trade. It includes settings for trading routes, data routes, simulation parameters, strategy configuration, and the selection of a Monte Carlo candles pipeline (either GaussianNoiseCandlesPipeline or MovingBlockBootstrapCandlesPipeline). ```python from jesse.enums import exchanges import os import jesse.helpers as jh from jesse.research import get_candles from jesse.research.monte_carlo import ( monte_carlo_candles, monte_carlo_trades, print_monte_carlo_candles_summary, plot_monte_carlo_candles_chart, print_monte_carlo_trades_summary, plot_monte_carlo_trades_chart ) from jesse.research.monte_carlo.candle_pipelines import GaussianNoiseCandlesPipeline, MovingBlockBootstrapCandlesPipeline # ============================================================================= # CONFIGURATION - MODIFY ALL SETTINGS HERE # ============================================================================= # Trading Routes Configuration TRADING_ROUTES = [ {"exchange": exchanges.BINANCE_PERPETUAL_FUTURES, "symbol": "BTC-USDT", "timeframe": "5m", "strategy": "MyAwesomeStrategy"}, ] # Data Routes Configuration DATA_ROUTES = [ {"exchange": exchanges.BINANCE_PERPETUAL_FUTURES, "symbol": "BTC-USDT", "timeframe": "4h"}, ] # Simulation Configuration SIMULATION_CONFIG = { "num_scenarios": 40, # Back to normal "start_date": "2025-03-01", "end_date": "2025-09-01", "progress_bar": True, "benchmark": True, "fast_mode": True, } # Strategy Configuration STRATEGY_CONFIG = { "starting_balance": 10_000, "fee": 0.05 / 100, "type": "futures", "futures_leverage": 10, "futures_leverage_mode": "cross", "warm_up_candles": 210, } # Monte Carlo Candles Pipeline Configuration MONTE_CARLO_CANDLES_CONFIG = { # "pipeline_class": MovingBlockBootstrapCandlesPipeline, # "pipeline_kwargs": {"batch_size": 7 * 24 * 60}, # 1 week batches "pipeline_class": GaussianNoiseCandlesPipeline, "pipeline_kwargs": {"batch_size": 7 * 24 * 60, "close_sigma": 10.0, "high_sigma": 5.0, "low_sigma": 5.0}, # 1 week batches } ``` -------------------------------- ### Start Redis Server Source: https://docs.jesse.trade/docs/getting-started/environment-setup Command to start the Redis server. This command is typically run in the Ubuntu terminal within WSL and needs to be re-executed after each system reboot. ```bash redis-server ``` -------------------------------- ### Install Live Trade Plugin (Native Environment) Source: https://docs.jesse.trade/docs/livetrade This command installs the live trade plugin for native environments. It automatically detects your system's architecture, OS, Python version, and Jesse version to download the correct package. Ensure you have already set your LICENSE_API_TOKEN in the .env file. ```shell jesse install-live ``` -------------------------------- ### Install Miniconda for Windows Source: https://docs.jesse.trade/docs/getting-started/environment-setup Shell commands to download, install, and clean up the Miniconda installer on Windows using PowerShell. Miniconda is used for creating isolated Python environments. ```powershell curl https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe -o .\miniconda.exe start /wait "" .\miniconda.exe /S del .\miniconda.exe ``` -------------------------------- ### Strategy initialization and termination hooks Source: https://docs.jesse.trade/docs/strategies/entering-and-exiting Shows how to implement the class constructor and termination methods to handle setup tasks and final logging or cleanup. ```python def __init__(self): super().__init__() print('initiated the strategy class') ``` ```python def terminate(self): self.log('About to terminate execution...') ``` -------------------------------- ### Implement Simple ATR Stoploss and Take Profit (Python) Source: https://docs.jesse.trade/docs/strategies/example-strategies This example demonstrates how to set a simple stop-loss and take-profit order based on the Average True Range (ATR). It calculates the stop and take-profit levels by multiplying the ATR by a factor and then places a buy order with these levels. The ATR is calculated using 'ta.atr'. ```python import ta def go_long(self): take_profit = self.price + self.atr * 3 stop = self.price - self.atr * 2 qty = 10 self.buy = qty, self.price self.stop_loss = qty, stop self.take_profit = qty, take_profit @property def atr(self): return ta.atr(self.candles, period=22) ``` -------------------------------- ### Python Lazy Loading ML Model Example Source: https://docs.jesse.trade/docs/research/ml/deploying This Python example illustrates the concept of lazy loading for a machine learning model. The `load_ml_model()` method is called within an inference method, ensuring the model is loaded only when needed and is idempotent. ```python def _ml_confidence(self) -> float: self.load_ml_model() # no-op after the first bar ... ``` -------------------------------- ### Install JupyterLab Source: https://docs.jesse.trade/docs/research/jupyter Installs the JupyterLab environment, a web-based interactive development environment for notebooks, code, and data. This is a prerequisite for using Jupyter with Jesse. ```shell pip install jupyterlab ``` -------------------------------- ### Jesse Backtest Usage Example: Generating Candles and Strategy Source: https://docs.jesse.trade/docs/research/backtest This example demonstrates how to use the `backtest()` function by first generating fake candle data from price series, defining a simple trading strategy, preparing the necessary input parameters (config, routes, candles), and finally executing the backtest. It shows how to access the returned metrics, charts, and logs. ```python # imports import jesse.helpers as jh from jesse.strategies import Strategy from jesse import utils from jesse.research import backtest, candles_from_close_prices # generate fake candles prices01 = [10, 11, 12, 12, 11, 13, 14, 12, 11, 15] fake_candles01 = candles_from_close_prices(prices01) # strategy class ResearchStrategy(Strategy): def should_long(self): return True def should_short(self): return False def should_cancel_entry(self): return True def go_long(self): entry_price = self.price qty = utils.size_to_qty(self.balance * 0.5, entry_price) self.buy = qty, entry_price def go_short(self): pass # prepare inputs exchange_name = 'Fake Exchange' symbol = 'BTC-USDT' timeframe = '4h' config = { 'starting_balance': 10_000, 'fee': 0, 'type': 'futures', 'futures_leverage': 2, 'futures_leverage_mode': 'cross', 'exchange': exchange_name, 'warm_up_candles': 0 } routes = [ {'exchange': exchange_name, 'strategy': ResearchStrategy, 'symbol': symbol, 'timeframe': timeframe} ] extra_routes = [] candles = { jh.key(exchange_name, symbol): { 'exchange': exchange_name, 'symbol': symbol, 'candles': fake_candles01, }, } # execute backtest result = backtest( config, routes, extra_routes, candles, generate_charts=True ) # access the metrics dict: result['metrics'] # access the charts string (path of the generated file): result['charts'] # access the logs list: result['logs'] ``` -------------------------------- ### Start Jupyter Notebook/Lab Source: https://docs.jesse.trade/docs/research/jupyter Commands to launch either the classic Jupyter Notebook interface or the more advanced JupyterLab interface. Ensure you run these commands from the root of your Jesse project. ```shell # to start Jupyter Notebook jupyter notebook # to start Jupyter Lab jupyter-lab ``` -------------------------------- ### Binary Classification Strategy Example in Python Source: https://docs.jesse.trade/docs/research/ml/binary A Python strategy example for Jesse that implements binary classification. It includes feature gathering logic within `_record_features`, defines trading signals in `should_long` and `should_short`, and records the trade outcome label upon position closure. ```python import jesse.indicators as ta from jesse import utils from jesse.strategies import Strategy class MyStrategy(Strategy): ML_MODE = "gather" # "gather" | "deploy" def _record_features(self, side: str) -> None: if self.ML_MODE != "gather": return atr = ta.atr(self.candles) price = self.price self.record_features({ "side": 1 if side == "long" else -1, "rsi_centered": (ta.rsi(self.candles) - 50) / 50, "atr_pct": atr / price, "ema200_dist": (price - ta.ema(self.candles, 200)) / price, "keltner_pos": (price - ta.keltner(self.candles).lowerband) / (ta.keltner(self.candles).upperband - ta.keltner(self.candles).lowerband + 1e-9), }) def should_long(self) -> bool: signal = ( ta.rsi(self.candles) < 35 and self.price > ta.ema(self.candles, 200) ) if signal: self._record_features("long") return signal def should_short(self) -> bool: signal = ( ta.rsi(self.candles) > 65 and self.price < ta.ema(self.candles, 200) ) if signal: self._record_features("short") return signal def should_cancel_entry(self) -> bool: return True def go_long(self): entry = self.price stop = entry - ta.atr(self.candles) * 2.5 qty = utils.risk_to_qty( self.available_margin, 2, entry, stop, fee_rate=self.fee_rate ) self.buy = qty, entry def go_short(self): entry = self.price stop = entry + ta.atr(self.candles) * 2.5 qty = utils.risk_to_qty( self.available_margin, 2, entry, stop, fee_rate=self.fee_rate ) self.sell = qty, entry def on_close_position(self, order, closed_trade) -> None: if self.ML_MODE != "gather": return self.record_label("profitable", closed_trade.pnl > 0) # bool ``` -------------------------------- ### Recording Features for Model Training Source: https://docs.jesse.trade/docs/research/ml/deploying Example of recording features within a Jesse strategy. The keys used here will be sorted alphabetically by `train_model` to form the training matrix columns. Ensure the same order is maintained during inference. ```python self.record_features({ "rsi_centered": ..., "atr_pct": ..., "ema9_dist": ..., "supertrend_dist": ..., "adx_centered": ... }) ``` -------------------------------- ### Install Matplotlib for Visualization Source: https://docs.jesse.trade/docs/research/monte_carlo Some Monte Carlo analysis features in Jesse, such as plotting scenario distributions or equity curves, require the matplotlib library. ```bash pip install matplotlib ``` -------------------------------- ### Enable Windows Subsystem for Linux (WSL) Source: https://docs.jesse.trade/docs/getting-started/environment-setup PowerShell command to enable the 'Microsoft-Windows-Subsystem-Linux' optional feature. This is a prerequisite for installing Linux distributions on Windows. ```powershell Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux ``` -------------------------------- ### Place a Market Buy Order Source: https://docs.jesse.trade/docs/strategies/api This Python example shows how to place a market buy order for one share at the current price. The `self.buy` attribute is used to specify the quantity and price for the order. ```python def go_long(self): # buy 1 share at the current price (MARKET order) self.buy = 1, self.price ``` -------------------------------- ### Pine Script Example of Elliott Wave Oscillator Source: https://docs.jesse.trade/docs/indicators/custom-indicators This is the original Pine Script code for the Elliott Wave Oscillator from Tradingview, used as a reference for conversion. ```pine-script //@version=3 study("Elliott Wave Oscillator") s2=ema(close, 5) - ema(close, 34) c_color=s2 <= 0 ? red : lime plot(s2, color=c_color, style=histogram, linewidth=2) ``` -------------------------------- ### Import Jesse Indicators Module Source: https://docs.jesse.trade/docs/indicators This snippet shows how to import the necessary `indicators` module from the Jesse library to start using technical indicators. No external dependencies are required beyond the Jesse library itself. ```python import jesse.indicators as ta ``` -------------------------------- ### Calculate Position Size with Risk Management (Python) Source: https://docs.jesse.trade/docs/strategies/example-strategies This code snippet calculates the appropriate quantity for a trade using risk management principles. It first determines the quantity based on a desired risk percentage of the capital using 'utils.risk_to_qty' and then ensures the quantity does not exceed a maximum percentage of the capital using 'utils.size_to_qty'. This prevents excessive risk, especially with tight stop-losses. ```python import ta import utils def go_long(self): stop = self.bb.lowerband qty = self.position_size(self.price, stop) take_profit = self.bb.upperband self.buy = qty, self.price self.stop_loss = qty, stop self.take_profit = qty, take_profit @property def position_size(self, entry, stop): # risk 10% risk_qty = utils.risk_to_qty(self.balance, 10, entry, stop, fee_rate=self.fee_rate) # never risk more than 25% of the capital max_qty = utils.size_to_qty(0.25 * self.balance, entry, precision=6, fee_rate=self.fee_rate) qty = min(risk_qty, max_qty) return qty ``` -------------------------------- ### Implement Trailing Stoploss Based on ATR (Python) Source: https://docs.jesse.trade/docs/strategies/example-strategies This snippet shows how to implement a trailing stop-loss that adjusts based on the price movement and ATR. The stop-loss is updated only if the position is in profit, and it's set at a distance of 2 * ATR from the current price. This helps to lock in profits as the price moves favorably. ```python import ta def update_position(self): # update trailing_stop_loss only if in profit if self.position.pnl > 0: if self.is_long: self.stop_loss = self.position.qty, self.price - self.atr * 2 else: self.stop_loss = self.position.qty, self.price + self.atr * 2 @property def atr(self): return ta.atr(self.candles, period=22) ``` -------------------------------- ### Create and Configure PostgreSQL Database Source: https://docs.jesse.trade/docs/getting-started/environment-setup Commands to create a new database named 'jesse_db', a user 'jesse_user' with a password, grant privileges, and set the owner for PostgreSQL versions 15 and above. This ensures the database is ready for Jesse. ```sql CREATE DATABASE jesse_db; CREATE USER jesse_user WITH PASSWORD 'password'; GRANT ALL PRIVILEGES ON DATABASE jesse_db to jesse_user; ALTER DATABASE jesse_db OWNER TO jesse_user; ``` -------------------------------- ### Configure and Execute Jesse ML Backtest Source: https://docs.jesse.trade/docs/research/ml/regression Sets the strategy to deploy mode, prepares data routes and candle data, executes the backtest, and outputs key performance metrics. ```python import strategies.ML3 as ml3_module ml3_module.ML3.ML_MODE = "deploy" routes = [{"exchange": EXCHANGE_NAME, "strategy": "ML3", "symbol": SYMBOL, "timeframe": TIMEFRAME}] data_routes = [{"exchange": EXCHANGE_NAME, "symbol": r["symbol"], "timeframe": r["timeframe"]} for r in DATA_ROUTES] all_timeframes = [TIMEFRAME] + [r["timeframe"] for r in DATA_ROUTES] max_tf = jh.max_timeframe(all_timeframes) warmup_raw, trading_raw = get_candles(EXCHANGE_NAME, SYMBOL, max_tf, jh.date_to_timestamp(START_DATE), jh.date_to_timestamp(END_DATE), CONFIG["warm_up_candles"], caching=True, is_for_jesse=True) candles = {jh.key(EXCHANGE_NAME, SYMBOL): {"exchange": EXCHANGE_NAME, "symbol": SYMBOL, "candles": trading_raw}} warmup_candles = {jh.key(EXCHANGE_NAME, SYMBOL): {"exchange": EXCHANGE_NAME, "symbol": SYMBOL, "candles": warmup_raw}} result = backtest(config=CONFIG, routes=routes, data_routes=data_routes, candles=candles, warmup_candles=warmup_candles, fast_mode=True) m = result.get("metrics", {}) print(f"Trades : {m.get('total', 0)}") print(f"Net profit % : {m.get('net_profit_percentage', 0):.2f}%") print(f"Max drawdown : {m.get('max_drawdown', 0):.2f}%") print(f"Sharpe ratio : {m.get('sharpe_ratio', float('nan')):.3f}") print(f"Win rate : {m.get('win_rate', 0) * 100:.1f}%") print(f"Total fees : ${m.get('fee', 0):.2f}") ``` -------------------------------- ### Add PostgreSQL to Windows PATH Source: https://docs.jesse.trade/docs/getting-started/environment-setup Instructions for adding the PostgreSQL 'bin' directory to the system's PATH environment variable. This allows running PostgreSQL commands from any directory in the command prompt. ```text # Example path: C:\Program Files\PostgreSQL\12\bin ``` -------------------------------- ### Exit Position Using Exponential Moving Average (Python) Source: https://docs.jesse.trade/docs/strategies/example-strategies This example demonstrates exiting a long position when the price falls below an Exponential Moving Average (EMA). It uses 'ta.ema' to calculate the EMA and 'self.liquidate()' to close the position if the condition is met. This is a common strategy for exiting trades based on trend indicators. ```python import ta def update_position(self): if self.is_long and self.price <= self.exit_ema: self.liquidate() @property def exit_ema(self): return ta.ema(self.candles) ``` -------------------------------- ### Gather ML Data Configuration (Python) Source: https://docs.jesse.trade/docs/research/ml/meta-labeling This Python script configures the Jesse research environment to gather machine learning data. It defines strategy parameters, exchange details, symbol, timeframe, and date ranges. It also sets up the necessary configuration for backtesting and data collection, including balance, fees, and leverage. ```python # gather_meta.py (place next to your strategies/ folder) from pathlib import Path import jesse.helpers as jh from jesse.enums import exchanges from jesse.research import gather_ml_data, get_candles STRATEGY = "MyStrategy" EXCHANGE = exchanges.BINANCE_PERPETUAL_FUTURES SYMBOL = "BTC-USDT" TIMEFRAME = "15m" START = "2021-01-01" END = "2025-01-01" config = { "starting_balance": 10_000, "fee": 0.0007, "type": "futures", "futures_leverage": 10, "futures_leverage_mode": "cross", "exchange": EXCHANGE, "warm_up_candles": 210, } routes = [ {"exchange": EXCHANGE, "strategy": STRATEGY, "symbol": SYMBOL, "timeframe": TIMEFRAME} ] data_routes = [ {"exchange": EXCHANGE, "symbol": SYMBOL, "timeframe": "4h"} ] # Pass is_for_jesse=True so Jesse receives raw 1m candles and can internally # aggregate them to any timeframe required by routes or data_routes. # Use TIMEFRAME here so the warmup period is calculated correctly ``` -------------------------------- ### GET /vosc Source: https://docs.jesse.trade/docs/indicators/reference Calculates the Volume Oscillator (VOSC) to identify momentum in trading volume. ```APIDOC ## GET /vosc ### Description The Volume Oscillator (VOSC) measures the difference between two volume-based moving averages to identify bullish and bearish volume trends. ### Method GET ### Endpoint /vosc ### Parameters #### Query Parameters - **candles** (np.ndarray) - Required - Input price data - **short_period** (int) - Optional - Default: 2 - **long_period** (int) - Optional - Default: 5 - **sequential** (bool) - Optional - Default: False ### Response #### Success Response (200) - **result** (float | np.ndarray) - The calculated VOSC values. ``` -------------------------------- ### GET /vwap Source: https://docs.jesse.trade/docs/indicators/reference Calculates the Volume Weighted Average Price (VWAP) based on specified time anchors. ```APIDOC ## GET /vwap ### Description The Volume Weighted Average Price (VWAP) provides the average price of an asset weighted by trading volume over a specified time interval. ### Method GET ### Endpoint /vwap ### Parameters #### Query Parameters - **candles** (np.ndarray) - Required - Input price data - **source_type** (str) - Optional - Default: "hlc3" - **anchor** (str) - Optional - Default: "D" (Options: Y, M, W, D, h, m) - **sequential** (bool) - Optional - Default: False ### Response #### Success Response (200) - **result** (float | np.ndarray) - The calculated VWAP values. ``` -------------------------------- ### GET /vlma Source: https://docs.jesse.trade/docs/indicators/reference Calculates the Variable Length Moving Average (VLMA), which adjusts its period based on market volatility. ```APIDOC ## GET /vlma ### Description The Variable Length Moving Average (VLMA) is an adaptive moving average that changes its period length in response to market conditions, helping to capture shifts in price trends. ### Method GET ### Endpoint /vlma ### Parameters #### Query Parameters - **candles** (np.ndarray) - Required - Input price data - **min_period** (int) - Optional - Default: 5 - **max_period** (int) - Optional - Default: 50 - **matype** (int) - Optional - Default: 0 - **devtype** (int) - Optional - Default: 0 - **source_type** (str) - Optional - Default: "close" - **sequential** (bool) - Optional - Default: False ### Response #### Success Response (200) - **result** (float | np.ndarray) - The calculated VLMA values. ``` -------------------------------- ### Implementing Strategy Filters in Python Source: https://docs.jesse.trade/docs/strategies/filters Demonstrates how to define a filters method in a strategy class, create individual filter functions, and register them. Filters must be passed as method objects without parentheses to the list returned by the filters method. ```python def filters(self): return [] def filter_1(self): return abs(self.price - self.long_EMA) < abs(self.price - self.longer_EMA) def filters(self): return [ self.filter_1 ] ``` -------------------------------- ### Incorrect Filter Implementation Source: https://docs.jesse.trade/docs/strategies/filters An example of an incorrect implementation where the filter method is called instead of being passed as an object. ```python def filters(self): return [ self.filter_1() ] ``` -------------------------------- ### Complete ML Strategy Template for Jesse Source: https://docs.jesse.trade/docs/research/ml/deploying A comprehensive strategy template demonstrating the shared feature builder pattern. It handles both 'gather' mode for data collection and 'deploy' mode for live inference, including entry logic and feature recording. ```python import numpy as np import jesse.indicators as ta from jesse import utils from jesse.strategies import Strategy class MyStrategy(Strategy): ML_MODE = "deploy" ML_THRESHOLD = 0.62 def _build_features(self, side: int) -> dict: atr = ta.atr(self.candles) + 1e-9 price = self.price ema9 = ta.ema(self.candles, 9) + 1e-9 return { "adx_centered": (float(ta.adx(self.candles)) - 25) / 25, "atr_pct": atr / price, "ema9_dist": (price - ema9) / ema9, "rsi_centered": (float(ta.rsi(self.candles)) - 50) / 50, "side": float(side), "supertrend_dist": (price - ta.supertrend(self.candles).trend) / atr, } def _ml_confidence(self, side: int) -> float: self.load_ml_model() feats = self._build_features(side) keys = sorted(feats.keys()) X = np.array([[feats[k] for k in keys]]) return float(self._ml_model.predict_proba( self._ml_scaler.transform(X) )[0, 1]) def should_long(self) -> bool: if not self._primary_signal_long: return False if self.ML_MODE == "gather": self.record_features(self._build_features(1)) return True return self._ml_confidence(1) >= self.ML_THRESHOLD ``` -------------------------------- ### Check Probability Calibration with CalibratedClassifierCV Source: https://docs.jesse.trade/docs/research/ml/meta-labeling If the model is miscalibrated, confidence-based sizing can be detrimental. This snippet shows how to wrap an estimator in `CalibratedClassifierCV` to improve probability calibration. Ensure scikit-learn is installed. ```python from sklearn.calibration import CalibratedClassifierCV from sklearn.ensemble import RandomForestClassifier # Assume 'estimator' is your trained model (e.g., RandomForestClassifier) estimator = RandomForestClassifier() # ... train your estimator ... # Wrap the estimator with CalibratedClassifierCV calibrated_estimator = CalibratedClassifierCV( estimator, method='isotonic', # or 'sigmoid' cv=5 # number of cross-validation folds ) # Train the calibrated classifier on your data calibrated_estimator.fit(X_train, y_train) # Now use calibrated_estimator for predictions ``` -------------------------------- ### Calculate Price Difference Over Time with a Loop Source: https://docs.jesse.trade/docs/indicators/custom-indicators Illustrates how to calculate the difference between the current closing price and the closing price from 10 candles ago using a Python loop. It highlights the importance of initializing the result array with NaNs to handle cases where the calculation is not possible due to insufficient past data. Numba can be used to optimize this loop. ```python close = candles[:, 2] my_indicator_from_loop = np.full_like(close, np.nan) for i in range(10, len(close)): my_indicator_from_loop[i] = close[i] - close[i-10] ``` -------------------------------- ### Get Anchor Timeframe Source: https://docs.jesse.trade/docs/utils Returns the anchor timeframe for a given input. This is useful for building dynamic strategies that operate across multiple timeframes. ```python bigger_timeframe = anchor_timeframe('1h') # returns '4h' ``` -------------------------------- ### Convert Prices to Returns Source: https://docs.jesse.trade/docs/utils Transforms a series of asset prices into percentage returns. Note that the first index will result in NaN as it cannot be calculated. ```python prices_to_returns(price_series: np.ndarray) -> np.ndarray ``` -------------------------------- ### Multi-point trade entry and exit configuration Source: https://docs.jesse.trade/docs/strategies/entering-and-exiting Demonstrates how to use lists of tuples to define multiple take-profit or entry points within a strategy, allowing for scaling in or out of positions. ```python def go_long(): qty = 1 self.buy = qty, 100 self.stop_loss = qty, 80 # take-profit at two points self.take_profit = [ (qty/2, 120), (qty/2, 140) ] ``` ```python def go_long(): qty = 1 # open position at $120 and increase it at $140 self.buy = [ (qty/2, 120), (qty/2, 140) ] self.stop_loss = qty, 100 self.take_profit = qty, 160 ``` -------------------------------- ### Calculate Linear Regression Intercept in Python Source: https://docs.jesse.trade/docs/indicators/reference Computes the y-intercept of a linear regression line based on candle data. Useful for identifying the starting point of price trends over a specified period. ```python linearreg_intercept(candles: np.ndarray, period=14, source_type="close", sequential=False) -> Union[float, np.ndarray] ``` -------------------------------- ### Gather Trading and Warmup Candles with Jesse Source: https://docs.jesse.trade/docs/research/ml/meta-labeling Fetches historical candle data for a given exchange, symbol, and timeframe using the `get_candles` function. It supports caching and is designed for use with Jesse. The output is structured into `candles` and `warmup_candles` dictionaries. ```python from jesse.helpers import get_candles, date_to_timestamp # Assuming EXCHANGE, SYMBOL, TIMEFRAME, START, END, config, routes, data_routes are defined elsewhere warmup_raw, trading_raw = get_candles( EXCHANGE, SYMBOL, TIMEFRAME, date_to_timestamp(START), date_to_timestamp(END), config["warm_up_candles"], caching=True, is_for_jesse=True, ) candles = { jh.key(EXCHANGE, SYMBOL): { "exchange": EXCHANGE, "symbol": SYMBOL, "candles": trading_raw } } warmup_candles = { jh.key(EXCHANGE, SYMBOL): { "exchange": EXCHANGE, "symbol": SYMBOL, "candles": warmup_raw } } result = gather_ml_data( config=config, routes=routes, data_routes=data_routes, candles=candles, warmup_candles=warmup_candles, ) ``` -------------------------------- ### Use XGBClassifier for Gradient Boosting Source: https://docs.jesse.trade/docs/research/ml/meta-labeling As an alternative to standard Gradient Boosting, `XGBClassifier` from the XGBoost library provides a highly optimized and efficient implementation. This snippet shows how to import and instantiate it. Ensure the 'xgboost' library is installed. ```python import xgboost as xgb # Instantiate the XGBClassifier # Common parameters include n_estimators, max_depth, learning_rate, subsample, colsample_bytree xgb_classifier = xgb.XGBClassifier( objective='binary:logistic', n_estimators=100, max_depth=3, learning_rate=0.1, use_label_encoder=False, # Recommended to set to False to avoid warnings eval_metric='logloss' # Specify evaluation metric ) # Train the model xgb_classifier.fit(X_train, y_train) # Make predictions predictions = xgb_classifier.predict(X_test) ``` -------------------------------- ### Try HistGradientBoostingClassifier for Faster Training Source: https://docs.jesse.trade/docs/research/ml/meta-labeling When Gradient Boosting performance plateaus, `HistGradientBoostingClassifier` offers improved speed and better handling of large datasets. This example demonstrates its instantiation. Requires scikit-learn version 0.21 or later. ```python from sklearn.ensemble import HistGradientBoostingClassifier # Instantiate the HistGradientBoostingClassifier hist_gb_classifier = HistGradientBoostingClassifier( max_iter=100, learning_rate=0.1, # other parameters can be tuned ) # Train the model hist_gb_classifier.fit(X_train, y_train) # Make predictions predictions = hist_gb_classifier.predict(X_test) ``` -------------------------------- ### Implement Triple-Barrier Data Gathering Strategy in Jesse Source: https://docs.jesse.trade/docs/research/ml/meta-labeling A Python strategy class for the Jesse trading framework that implements a state machine for data collection. It monitors market flips and uses triple-barrier logic to record labels for machine learning, while providing a deploy mode for executing trades based on model confidence. ```python import datetime import jesse.indicators as ta import numpy as np from jesse import utils from jesse.strategies import Strategy class MyStrategy(Strategy): ML_MODE = "gather" # "gather" | "deploy" ML_THRESHOLD = 0.60 # used in deploy mode only vertical_barrier = 24 _obs_active = False _obs_start_index = 0 _obs_entry_price = None _obs_direction = 0 _obs_atr = None @property def atr(self): return ta.atr(self.candles) + 1e-9 @property def supertrend(self): return ta.supertrend(self.candles, sequential=True) def go_long(self): entry = self.price stop = entry - self.atr * 2.5 confidence = self._meta_confidence() risk_pct = 1.0 + (confidence - self.ML_THRESHOLD) / (1.0 - self.ML_THRESHOLD) qty = utils.risk_to_qty( self.available_margin, risk_pct, entry, stop, fee_rate=self.fee_rate ) self.buy = qty, entry def _gather_tick(self) -> None: if self._obs_active: bars_elapsed = self.index - self._obs_start_index price = self.price atr = self._obs_atr ``` -------------------------------- ### Dynamic position management with update_position Source: https://docs.jesse.trade/docs/strategies/entering-and-exiting Provides examples of using update_position to implement trailing stops, conditional liquidation, and position scaling based on real-time market data and indicators. ```python def update_position(self): qty = self.position.qty # set stop-loss price $10 away from the high/low of the current candle if self.is_long: self.take_profit = qty, self.high - 10 else: self.take_profit = qty, self.low + 10 ``` ```python def update_position(self): if self.is_long and ta.rsi(self.candles) == 100: self.liquidate() ``` ```python def update_position(self): if self.is_long: if self.position.pnl_percentage > 5 and ta.rsi(self.candles) < 30: # double the size of the already open position at current price (with a MARKET order) self.buy = self.position.qty, self.price ``` -------------------------------- ### Advanced Filter with Trade Properties Source: https://docs.jesse.trade/docs/strategies/filters An example of a filter that utilizes trade-specific properties like average entry price and take profit to validate a minimum PNL condition. ```python def minimum_pnl_filter(self): reward_per_qty = abs(self.average_take_profit - self.average_entry_price) pnl_percentage = (reward_per_qty / self.average_entry_price) * 100 return pnl_percentage > 1 ``` -------------------------------- ### Deploy Backtest Script for Jesse Trade Source: https://docs.jesse.trade/docs/research/ml/regression A Python script template for configuring and running a backtest within the Jesse framework. It defines exchange settings, symbol routes, and financial parameters for model evaluation. ```python # ml3_deploy_backtest.py import sys from pathlib import Path import jesse.helpers as jh from jesse.enums import exchanges from jesse.research import get_candles, backtest EXCHANGE_NAME = exchanges.BINANCE_PERPETUAL_FUTURES SYMBOL = "BTC-USDT" TIMEFRAME = "15m" START_DATE = "2024-06-01" END_DATE = "2025-01-01" DATA_ROUTES = [{"symbol": SYMBOL, "timeframe": "4h"}] CONFIG = { "starting_balance": 10_000, "fee": 0.0007, "type": "futures", "futures_leverage": 10, "futures_leverage_mode": "cross", "exchange": EXCHANGE_NAME, "warm_up_candles": 210, } sys.path.insert(0, str(Path(__file__).parent)) ``` -------------------------------- ### Monitor Strategy Execution Index Source: https://docs.jesse.trade/docs/strategies/api Provides a counter representing the current iteration of the strategy loop. It is useful for conditional logic based on the start of a backtest or periodic execution of expensive tasks. ```python # Execute only on the first candle def should_long(self): return self.index == 0 # Periodic execution (e.g., daily on 1m timeframe) def before(self): if self.index % 1440 == 0: do_slow_updates() ``` -------------------------------- ### Configure trade execution parameters in Python Source: https://docs.jesse.trade/docs/strategies/entering-and-exiting The go_long and go_short methods define entry, stop-loss, and take-profit levels. Jesse automatically determines the order type (MARKET, LIMIT, or STOP) based on the relationship between entry_price and current_price. ```python def go_long(self): qty = 1 self.buy = qty, self.price self.stop_loss = qty, self.low - 10 self.take_profit = qty, self.high + 10 def go_short(self): qty = 1 self.sell = qty, self.price self.stop_loss = qty, self.high + 10 self.take_profit = qty, self.low - 10 ``` -------------------------------- ### Binary Classification Deploy Pattern in Python Source: https://docs.jesse.trade/docs/research/ml/deploying Implements a binary classification model for trading signals. The model outputs a probability between 0 and 1, which is then compared against a threshold to decide whether to allow a trade. This pattern requires loading the ML model and scaler, calculating features, and transforming them before prediction. ```python import numpy as np import jesse.indicators as ta from jesse import utils from jesse.strategies import Strategy class MyStrategy(Strategy): ML_MODE = "deploy" ML_THRESHOLD = 0.62 # minimum confidence to allow a trade # ──────────────────────────────────────────────────────────────────────── # Inference # ──────────────────────────────────────────────────────────────────────── def _ml_confidence(self) -> float: """Return the model's probability that this signal is the positive class.""" self.load_ml_model() atr = ta.atr(self.candles) + 1e-9 price = self.price # Columns in alphabetical order: adx_centered, atr_pct, ema9_dist, # rsi_centered, supertrend_dist features = np.array([[ (float(ta.adx(self.candles)) - 25) / 25, # adx_centered atr / price, # atr_pct (price - ta.ema(self.candles, 9)) / (ta.ema(self.candles, 9) + 1e-9), # ema9_dist (float(ta.rsi(self.candles)) - 50) / 50, # rsi_centered (price - ta.supertrend(self.candles).trend) / atr, # supertrend_dist ]]) X_scaled = self._ml_scaler.transform(features) return float(self._ml_model.predict_proba(X_scaled)[0, 1]) # ──────────────────────────────────────────────────────────────────────── # Entry # ──────────────────────────────────────────────────────────────────────── def should_long(self) -> bool: # Check the primary signal first — only call the model when the signal # fires. Calling the model on every bar wastes CPU and adds latency. signal = ( ta.supertrend(self.candles).trend < self.price and ta.adx(self.candles) > 25 ) if not signal: return False if self.ML_MODE == "deploy": return self._ml_confidence() >= self.ML_THRESHOLD return True def should_short(self) -> bool: return False def should_cancel_entry(self) -> bool: return True def go_long(self): entry = self.price stop = entry - ta.atr(self.candles) * 2.5 qty = utils.risk_to_qty( self.available_margin, 2, entry, stop, fee_rate=self.fee_rate ) self.buy = qty, entry ``` -------------------------------- ### Retrieve Current Candle Data Source: https://docs.jesse.trade/docs/strategies/api Accesses the current market candle as a numpy array containing timestamp, open, close, high, low, and volume. The timestamp represents the start of the time period. ```python from pprint import pprint # Accessing the full array pprint(self.current_candle) # Accessing individual components timestamp = self.current_candle[0] open_price = self.current_candle[1] close_price = self.current_candle[2] high_price = self.current_candle[3] low_price = self.current_candle[4] volume = self.current_candle[5] ``` -------------------------------- ### Initial SMA Calculation with Hardcoded Values in Python Source: https://docs.jesse.trade/docs/optimize/hyperparameters Presents an initial implementation of calculating Simple Moving Averages (SMA) using hardcoded integer values for the periods (200 and 50). This serves as a baseline before introducing dynamic hyperparameters. ```python @property def slow_sma(self): return ta.sma(self.candles, 200) @property def fast_sma(self): return ta.sma(self.candles, 50) ``` -------------------------------- ### Import Candles from Exchange Source: https://docs.jesse.trade/docs/research/candles Imports candle data from a specified exchange for a given symbol starting from a specific date. Returns a success message and supports an optional progress bar for interactive environments. ```python import_candles(exchange, symbol, start_date, show_progressbar=True) ``` -------------------------------- ### Optimize performance with @cached decorator Source: https://docs.jesse.trade/docs/strategies/api The @cached decorator caches function or property results to avoid redundant calculations, which is ideal for computationally intensive indicators. It must be used with @property and is cleared automatically at the start of every new candle. ```python from jesse.strategies import Strategy, cached @property @cached def donchian(self): return ta.donchian(self.candles) ``` -------------------------------- ### Retrieve and Prepare Trading Routes Source: https://docs.jesse.trade/docs/research/monte_carlo Extracts trading and data route configurations from global settings. Returns a tuple containing lists of dictionaries for both trading and data-specific route parameters. ```python def get_configured_routes(): routes = [] for route in TRADING_ROUTES: routes.append({ 'exchange': route['exchange'], 'symbol': route['symbol'], 'timeframe': route['timeframe'], 'strategy': route['strategy'] }) data_routes = [] for route in DATA_ROUTES: data_routes.append({ 'exchange': route['exchange'], 'symbol': route['symbol'], 'timeframe': route['timeframe'] }) return routes, data_routes ```