### Backtesting Configuration Example Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Defines the configuration for a backtesting simulation, including the data files to use, the starting portfolio balance, and trading fees. ```python # Backtesting configuration backtesting_config = { "data_files": ["binance_BTC_USDT_1h.data"], "starting_portfolio": { "BTC": 1, "USDT": 10000 }, "fees": { "maker": 0.001, "taker": 0.001 } } ``` -------------------------------- ### Example Profile Configuration for OctoBot Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Example profile.json configuration for OctoBot, enabling Binance exchange, trader simulator, and defining trading parameters. ```json { "config": { "crypto-currencies": { "Bitcoin": { "enabled": true, "pairs": ["BTC/USDT"] } }, "exchanges": { "binance": {"enabled": true} }, "trader-simulator": { "enabled": true, "fees": {"maker": 0.1, "taker": 0.1}, "starting-portfolio": {"BTC": 10, "USDT": 1000} }, "trading": { "reference-market": "USDT", "risk": 0.5 } } } ``` -------------------------------- ### Exchange Configuration Example Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Shows how to configure enabled cryptocurrency exchanges within the profile.json file. Only enabled exchanges will be used by OctoBot. ```json { "exchanges": { "binance": {"enabled": true}, "binanceus": {"enabled": false}, "bybit": {"enabled": false}, "kucoin": {"enabled": false}, "kraken": {"enabled": false}, "coinbase": {"enabled": false}, "okx": {"enabled": false}, "bitget": {"enabled": false}, "gateio": {"enabled": false}, "huobi": {"enabled": false}, "mexc": {"enabled": false}, "phemex": {"enabled": false}, "ascendex": {"enabled": false}, "bitfinex": {"enabled": false}, "bitstamp": {"enabled": false}, "poloniex": {"enabled": false}, "hyperliquid": {"enabled": false}, "polymarket": {"enabled": false} } } ``` -------------------------------- ### Jinja Macro for Pending Tentacle Installation Modal Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/community/tentacle_packages.html Use this macro to display a modal informing the user that new tentacles are available and require an OctoBot restart for installation. It prompts the user to restart their OctoBot. ```Jinja {% macro pending_tentacles_install_modal(show_by_default) -%} ##### New tentacles are available! × 🎉 Your OctoBot has to restart to install your new tentacles. Please restart your OctoBot. Cancel Restart and install {%- endmacro %} ``` -------------------------------- ### Jinja Macro for Get Package Button Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/community/tentacle_packages.html This macro generates a button for acquiring a package. The button's text and functionality change based on whether the user already owns the open-source version, is authenticated, or needs to log in to install the package. ```Jinja {% macro get_package_button(name, is_authenticated, has_open_source_package) -%} {% if has_open_source_package() %} {{name}} already purchased {% elif is_authenticated %} Get your {{name}} {% else %} [Login to install the {{name}}]({{ url_for('community_login', next='extensions') }}) {% endif %} {%- endmacro %} ``` -------------------------------- ### Jinja2 Macro for Displaying Cloud Strategies Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/community/cloud_strategies_selector.html This macro iterates through a list of strategies, displaying key details for each. It conditionally renders 'Use' or 'Install' based on the `post_install_action` parameter and includes strategy logos, names, profitability, traded coins, exchanges, risk levels, and categories. Use this macro to present strategy information within the OctoBot interface. ```jinja {% macro cloud_strategies_selector(strategies, locale, post_install_action) -%} {% for strategy in strategies %} {% if strategy.results %} {% else %} {% endif %} {% endfor %} Strategy Profitability Traded coins Exchange Risk level Type {{'Use' if post_install_action else 'Install'}} [ ![Strategy illustration]({{strategy.get_logo_url(url_for('static', filename='img/community/tentacles_packages_previews/'))}}) {{strategy.get_name(locale) | capitalize}} ]({{ strategy.get_product_url() }}?utm_source=octobot&utm_medium=dk&utm_campaign=regular_open_source_content&utm_content=cloud_strategies_selector_strategy_name) {{ (strategy.results.get_max_value()) | round(2) }}% over {{ strategy.results.get_max_unit() }} {{ strategy.attributes['coins'] | join(', ') }} {{ strategy.attributes['exchanges'] | join(', ') }} {{ strategy.get_risk().name | capitalize }} {% if strategy.category %} {% if strategy.category.get_url() %} [{{ strategy.category.get_name(locale) }}]({{strategy.category.get_url()}}?utm_source=octobot&utm_medium=dk&utm_campaign=regular_open_source_content&utm_content=cloud_strategies_selector_strategy_category) {% else %} {{ strategy.category.get_name(locale) }} {% endif %} {% endif %} {%- endmacro %} ``` -------------------------------- ### Jinja Macro for Waiting for Payment Confirmation Modal Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/community/tentacle_packages.html This macro displays a modal to inform the user that their payment is being processed and they need to wait for confirmation before installing their extension. It includes a note about potential delays with crypto payments. ```Jinja {% macro waiting_for_owned_packages_to_install_modal(show_by_default) -%} ##### Waiting for payment to succeed Thank you for your purchase. You will be able to install your extension as soon as your payment is confirmed. Note: when paying in crypto, it might take a few minutes {%- endmacro %} ``` -------------------------------- ### Get Backtesting Portfolio History Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Retrieves the portfolio value over time for equity curve analysis during backtesting. Requires a context object. ```python portfolio = await get_portfolio_history(context) # Returns portfolio value over time for equity curve analysis ``` -------------------------------- ### Get Backtesting Report Data Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Retrieves the backtesting report, including metrics like total profit, win rate, and drawdown. Requires a context object. ```python from tentacles.Meta.Keywords.scripting_library.backtesting.run_data_analysis import ( get_backtesting_report, get_trades_history, get_portfolio_history ) report = await get_backtesting_report(context) # Returns: total_profit, win_rate, max_drawdown, sharpe_ratio, etc. ``` -------------------------------- ### Binance Exchange Specific Features Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Illustrates exchange-specific features for Binance, including supported order types, futures contract types, and an example of a WebSocket feed for real-time data. ```python # Exchange-specific features (example: Binance) class BinanceExchange: # Supported features SUPPORTED_ORDER_TYPES = [ "LIMIT", "MARKET", "STOP_LOSS", "STOP_LOSS_LIMIT", "TAKE_PROFIT", "TAKE_PROFIT_LIMIT" ] # Contract types for futures FUTURES_CONTRACT_TYPES = ["PERPETUAL", "CURRENT_QUARTER", "NEXT_QUARTER"] # WebSocket feed for real-time data class BinanceWebSocketFeed: async def subscribe_to_trades(self, symbol): pass async def subscribe_to_order_book(self, symbol, depth=20): pass async def subscribe_to_klines(self, symbol, interval="1m"): pass ``` -------------------------------- ### Get Backtesting Trades History Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Fetches the history of all executed trades during backtesting, including timestamps and prices. Requires a context object. ```python trades = await get_trades_history(context) # Returns list of all executed trades with timestamps, prices, quantities ``` -------------------------------- ### Calculate Custom Price Value Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/dsl_help.html Performs arithmetic operations on the last hourly close price. This example multiplies the close price by 2 and adds 10. Use with caution as it involves calculations on market data. ```OctoBot DSL close("BTC/USDT", "1h")[-1] * 2 + 10 ``` -------------------------------- ### Get Last Close Price Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/dsl_help.html Retrieves the closing price of the most recent hourly candle for a specified market. Ensure the market symbol and timeframe are correct. ```OctoBot DSL close("BTC/USDT", "1h")[-1] ``` -------------------------------- ### Define Bots Stats Card Macro Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/community/bots_stats.html This Jinja macro, bots_stats_card, is used to generate a card displaying the total number of installed OctoBots. It takes a 'stats' dictionary as input. ```jinja {% macro bots_stats_card(stats) -%} Welcome to the OctoBot community and its {{ stats["total_bots"] }} already installed OctoBots {%- endmacro %} ``` -------------------------------- ### Set DCA Mode Default Configuration Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Defines the default configuration values for the DCA trading mode, including buy amount, trigger mode, take profit, stop loss, and maximum asset holding percentage. This ensures a sensible starting point for the strategy. ```python DCATradingMode.get_default_config( buy_amount="50$", # Buy $50 per entry trigger_mode=TriggerMode.TIME_BASED, use_take_profit_exit_orders=True, exit_limit_orders_price_percent=0.05, # 5% take profit enable_stop_loss=True, stop_loss_price=0.10, # 10% stop loss max_asset_holding_percent=0.5 # Max 50% portfolio in single asset ) ``` -------------------------------- ### Create Order with Take Profit Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Creates a limit buy order with a specified offset and includes a take-profit order. The take-profit is defined by an offset from the entry price and has a unique tag. ```python from tentacles.Meta.Keywords.scripting_library.orders.order_types.create_order import create_order_instance # Create order with take profit orders = await create_order_instance( context, side="buy", symbol="ETH/USDT", order_amount="0.5ETH", # Fixed quantity order_type_name="limit", order_offset="-1%", take_profit_offset="+5%", # Take profit 5% above entry take_profit_tag="tp_1", tag="entry_order" ) ``` -------------------------------- ### Initialize User Inputs for Grid Trading Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Defines the user inputs required for configuring the Grid Trading Mode. This includes settings for each traded pair, such as spread, increment, and the number of buy/sell orders, as well as options for trailing grid adjustments. ```python class GridTradingMode(StaggeredOrdersTradingMode): CONFIG_FLAT_SPREAD = "flat_spread" CONFIG_FLAT_INCREMENT = "flat_increment" CONFIG_BUY_ORDERS_COUNT = "buy_orders_count" CONFIG_SELL_ORDERS_COUNT = "sell_orders_count" def init_user_inputs(self, inputs: dict) -> None: # Pair-specific configurations self.UI.user_input( self.CONFIG_PAIR_SETTINGS, commons_enums.UserInputTypes.OBJECT_ARRAY, None, inputs, item_title="Pair configuration", title="Configuration for each traded pair." ) # Trading pair name self.UI.user_input( "pair", commons_enums.UserInputTypes.TEXT, "BTC/USDT", inputs, parent_input_name=self.CONFIG_PAIR_SETTINGS, title="Name of the traded pair." ) # Spread: price gap between closest buy and sell orders self.UI.user_input( self.CONFIG_FLAT_SPREAD, commons_enums.UserInputTypes.FLOAT, 600, inputs, # 600 USDT spread on BTC/USDT min_val=0, parent_input_name=self.CONFIG_PAIR_SETTINGS, title="Spread: price difference between closest buy/sell orders." ) # Increment: price gap between same-side orders self.UI.user_input( self.CONFIG_FLAT_INCREMENT, commons_enums.UserInputTypes.FLOAT, 200, inputs, # 200 USDT increment min_val=0, parent_input_name=self.CONFIG_PAIR_SETTINGS, title="Increment: price difference between orders on same side." ) # Number of buy/sell orders self.UI.user_input( self.CONFIG_BUY_ORDERS_COUNT, commons_enums.UserInputTypes.INT, 20, inputs, min_val=0, title="Buy orders count: number of initial buy orders." ) self.UI.user_input( self.CONFIG_SELL_ORDERS_COUNT, commons_enums.UserInputTypes.INT, 20, inputs, min_val=0, title="Sell orders count: number of initial sell orders." ) # Trailing options for dynamic grid adjustment self.UI.user_input( "enable_trailing_up", commons_enums.UserInputTypes.BOOLEAN, False, inputs, title="Trailing up: recreate grid when price exceeds upper bound." ) self.UI.user_input( "enable_trailing_down", commons_enums.UserInputTypes.BOOLEAN, False, inputs, title="Trailing down: recreate grid when price drops below lower bound." ) ``` -------------------------------- ### Initialize PostHog Analytics Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/community/user_details.html This macro initializes PostHog analytics. It includes conditional logic to only load the script and initialize if not in demo/cloud mode or if tracking is allowed. Ensure PH_TRACKING_ID is provided. ```javascript {% if IS_DEMO or IS_CLOUD or IS_ALLOWING_TRACKING%} !function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossorigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagPayload isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n None: # Configure trigger mode self.trigger_mode = TriggerMode( self.UI.user_input( "trigger_mode", commons_enums.UserInputTypes.OPTIONS, TriggerMode.TIME_BASED.value, inputs, options=[mode.value for mode in TriggerMode], title="Trigger mode: When DCA entry orders should be triggered." ) ) # Time-based trigger interval (minutes) self.minutes_before_next_buy = int(self.UI.user_input( "minutes_before_next_buy", commons_enums.UserInputTypes.INT, 10080, inputs, # Default: 1 week min_val=1, title="Minutes between each transaction. 1440=1 day, 10080=1 week." )) # Enable take profit exit orders self.use_take_profit_exit_orders = self.UI.user_input( "use_take_profit_exit_orders", commons_enums.UserInputTypes.BOOLEAN, False, inputs, title="Enable take profit exit orders when entries are filled." ) # Exit price difference percentage self.exit_limit_orders_price_multiplier = decimal.Decimal(str( self.UI.user_input( "exit_limit_orders_price_percent", commons_enums.UserInputTypes.FLOAT, 5.0, inputs, min_val=0, title="Exit percent difference from entry price." ) )) / 100 # Enable stop losses self.use_stop_loss = self.UI.user_input( "use_stop_losses", commons_enums.UserInputTypes.BOOLEAN, False, inputs, title="Enable stop losses when entries are filled." ) ``` -------------------------------- ### Create OCO Group and Take Profit Order Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Demonstrates creating an One-Cancels-Other (OCO) group and then adding a take-profit order to that group. This allows for a take-profit order to be placed that will be cancelled if another order in the OCO group is filled. ```python from tentacles.Meta.Keywords.scripting_library.orders.grouping import create_one_cancels_the_other_group oco_group = create_one_cancels_the_other_group(context) # Take profit order in group await create_order_instance( context, side="sell", symbol="BTC/USDT", order_amount="100%", order_type_name="limit", order_offset="+5%", group=oco_group, tag="tp" ) ``` -------------------------------- ### Configure DailyTradingMode in Python Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Configure user inputs for the DailyTradingMode, including target profits and stop loss settings. This mode evaluates strategy signals for buy/sell orders. ```python from octobot_trading.modes import trading_modes class DailyTradingMode(trading_modes.AbstractTradingMode): def init_user_inputs(self, inputs: dict) -> None: # Enable target profits mode for automatic TP/SL self.UI.user_input( "target_profits_mode", commons_enums.UserInputTypes.BOOLEAN, False, inputs, title="Target profits mode: Enable target profits mode." ) # Configure take profit percentage self.UI.user_input( "target_profits_mode_take_profit", commons_enums.UserInputTypes.FLOAT, 5, inputs, min_val=0, title="Take profit: percent profits for take profit order price." ) # Enable stop loss orders self.UI.user_input( "use_stop_orders", commons_enums.UserInputTypes.BOOLEAN, True, inputs, title="Stop orders: Create a stop loss alongside sell orders." ) # Configure stop loss percentage self.UI.user_input( "target_profits_mode_stop_loss", commons_enums.UserInputTypes.FLOAT, 2.5, inputs, min_val=0, max_val=100, title="Stop loss: maximum percent losses for stop loss price." ) ``` -------------------------------- ### Create Market Buy Order Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Creates a market buy order for a specified symbol and amount. The amount can be a fixed currency value (e.g., "100$") or a percentage of available balance (e.g., "50%"). ```python from tentacles.Meta.Keywords.scripting_library.orders.order_types.create_order import create_order_instance # Create a market buy order orders = await create_order_instance( context, side="buy", symbol="BTC/USDT", order_amount="100$", # $100 worth order_type_name="market", tag="dip_buy" ) ``` -------------------------------- ### TrendAnalysis: Get Market Trend Direction Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Calculates the market trend direction using multiple moving averages. A positive result indicates an uptrend, while a negative result suggests a downtrend. Requires numpy and TrendAnalysis. ```python import numpy as np from tentacles.Evaluator.Util.trend_analysis import TrendAnalysis # Get trend direction using multiple moving averages # Returns: negative = downtrend, positive = uptrend data = np.array([100, 102, 105, 103, 108, 112, 110, 115]) averages_to_use = [7, 5, 4, 3, 2, 1] trend = TrendAnalysis.get_trend(data, averages_to_use) # trend > 0 = uptrend, trend < 0 = downtrend ``` -------------------------------- ### Editable Key Macro (Jinja) Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/config/editable_config.html The main macro for creating editable configuration keys. It dynamically selects the appropriate helper macro based on the data type of the configuration value. ```Jinja {% macro editable_key(config, key, config_key, config_type, config_value, startup_config_value, suggestions="", no_select=False, number_step=0.01, force_title=False, tooltip=None, identifier="", placeholder_str="", allow_create_for=None, edit_key=False, dict_as_option_group=False) -%} {% if config[key]|default (config_value) is string %} {{ editable_key_string(config, key, config_key, config_type, config_value, startup_config_value, suggestions, placeholder_str) }} {% elif config[key]|default (config_value) | is_dict %} {{ editable_key_dict(config, key, config_key, config_type, config_value, startup_config_value, suggestions, no_select, number_step, force_title, tooltip, identifier, placeholder_str, allow_create_for, dict_as_option_group=dict_as_option_group) }} {% elif config[key]|default (config_value) | is_list %} {{ editable_key_list(config, key, config_key, config_type, config_value, startup_config_value, suggestions, no_select, force_title, identifier, placeholder_str, dict_as_option_group=dict_as_option_group) }} {% elif config[key]|default (config_value) | is_bool %} {{ editable_key_bool(config, key, config_key, config_type, config_value, startup_config_value, suggestions, tooltip) }} {% elif config[key]|default (config_value) is number %} {{ editable_key_number(config, key, config_key, config_type, config_value, startup_config_value, suggestions, number_step, edit_key) }} {% else %} {{ editable_key_string(config, key, config_key, config_type, config_value, startup_config_value, suggestions, placeholder_str) }} {% endif %} {%- endmacro %} ``` -------------------------------- ### BBMomentumEvaluator Class Implementation Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Implements Bollinger Bands for evaluating overbought/oversold conditions. Requires tulipy and math libraries. The evaluate method calculates bands and determines signals based on price position. ```python import tulipy import math class BBMomentumEvaluator(evaluators.TAEvaluator): def __init__(self, tentacles_setup_config): super().__init__(tentacles_setup_config) self.period_length = 20 def init_user_inputs(self, inputs: dict) -> None: self.period_length = self.UI.user_input( "period_length", enums.UserInputTypes.INT, 20, inputs, min_val=1, title="Bollinger bands period length." ) async def evaluate(self, cryptocurrency, symbol, time_frame, candle_data, candle): if len(candle_data) >= self.period_length: # Calculate Bollinger Bands (20-period, 2 std dev) lower_band, middle_band, upper_band = tulipy.bbands( candle_data, self.period_length, 2 ) current_value = candle_data[-1] current_up = upper_band[-1] current_middle = middle_band[-1] current_low = lower_band[-1] # Above upper band = strong sell (1) if current_value > current_up: self.eval_note = 1 # Below lower band = strong buy (-1) elif current_value < current_low: self.eval_note = -1 # On middle band = neutral elif current_value == current_middle: self.eval_note = 0 # Between bands = parabolic factor based on distance from middle else: delta_up = current_up - current_middle delta_low = current_middle - current_low if current_middle < current_value: self.eval_note = math.pow((current_value - current_middle) / delta_up, 2) else: self.eval_note = -1 * math.pow((current_middle - current_value) / delta_low, 2) ``` -------------------------------- ### Create Limit Sell Order with Stop Loss Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Creates a limit sell order with a specified offset from the current price and includes a stop-loss order. The stop-loss is defined by an offset from the entry price and has a unique tag. ```python from tentacles.Meta.Keywords.scripting_library.orders.order_types.create_order import create_order_instance # Create a limit sell order with stop loss orders = await create_order_instance( context, side="sell", symbol="BTC/USDT", order_amount="50%", # 50% of available balance order_type_name="limit", order_offset="-2%", # 2% below current price stop_loss_offset="-5%", # Stop loss 5% below entry stop_loss_tag="sl_1", tag="limit_sell" ) ``` -------------------------------- ### Display Loading Message Macro Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/macros/starting_waiter.html Use this Jinja macro to display a loading message with optional details and a next URL. It provides a default message if no text is supplied. ```Jinja {% macro display_loading_message(text=None, details=None, next_url=None) -%} {{ text or "OctoBot is starting, please refresh this page in a few seconds." }} ------------------------------------------------------------------------------- {% if details %} #### {{ details }} {% endif %} {% if next_url %} [Proceed anyway]({{next_url}}) {% else %} Refresh {% endif %} {%- endmacro %} ``` -------------------------------- ### Jinja Macro for Payment Method Selection Modal Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/community/tentacle_packages.html Use this macro to display a modal allowing the user to select their preferred payment method for a given item. It includes options for credit card and crypto payments, with a note that crypto payment is coming soon. A direct payment link is provided if the page does not refresh automatically. ```Jinja {% macro select_payment_method_modal(name) -%} ##### Select your payment method × Please choose how you want to pay for your {{name}} Pay by credit card Pay with crypto (coming back soon) If this page is not refreshing, please click on the following link to pay for your {{name}}: Cancel {%- endmacro %} ``` -------------------------------- ### Initialize SimpleStrategyEvaluator Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Initializes the SimpleStrategyEvaluator with default timeouts and configuration for social and technical analysis re-evaluation. User inputs are processed to customize these settings. ```python class SimpleStrategyEvaluator(evaluators.StrategyEvaluator): def __init__(self, tentacles_setup_config): super().__init__(tentacles_setup_config) self.social_evaluators_default_timeout = 3600 # 1 hour self.re_evaluate_TA_when_social_or_realtime_notification = True self.background_social_evaluators = [] def init_user_inputs(self, inputs: dict) -> None: self.social_evaluators_default_timeout = self.UI.user_input( "social_evaluators_notification_timeout", enums.UserInputTypes.INT, 3600, inputs, min_val=0, title="Seconds to consider a social evaluation valid." ) self.re_evaluate_TA_when_social_or_realtime_notification = self.UI.user_input( "re_evaluate_TA_when_social_or_realtime_notification", enums.UserInputTypes.BOOLEAN, True, inputs, title="Recompute TA evaluators on real-time evaluator signal." ) self.background_social_evaluators = self.UI.user_input( "background_social_evaluators", enums.UserInputTypes.MULTIPLE_OPTIONS, [], inputs, options=["RedditForumEvaluator", "TwitterNewsEvaluator", "TelegramSignalEvaluator", "GoogleTrendsEvaluator"], title="Social evaluators that won't trigger TA re-evaluation." ) ``` -------------------------------- ### Create Target Position Order (Futures) Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Creates a market order to target a specific percentage of the current position, suitable for futures trading. The `reduce_only` flag ensures that the order only reduces an existing position. ```python from tentacles.Meta.Keywords.scripting_library.orders.order_types.create_order import create_order_instance # Target position-based order (futures) orders = await create_order_instance( context, symbol="BTC/USDT", order_target_position="50%", # Target 50% of position order_type_name="market", reduce_only=True # Only reduce existing position ) ``` -------------------------------- ### Basic Alert Signal Format Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Trading/Mode/trading_view_signals_trading_mode/resources/TradingViewSignalsTradingMode.md Use this format for basic trading signals. Ensure EXCHANGE, SYMBOL, and SIGNAL are correctly set. ```text EXCHANGE=BINANCE SYMBOL=BTCUSD SIGNAL=BUY ``` -------------------------------- ### Editable String Key Macro (Jinja) Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/config/editable_config.html Renders an editable configuration key for string types. It displays the key and its value, with special handling for password fields. ```Jinja {% macro editable_key_string(config, key, config_key, config_type, config_value, startup_config_value, suggestions, placeholder_str="", password_val="******") -%} {{ key }} : {% if key == "password" %} [{{ password_val }}](#) {% else %} [{{ config[key]|default (config_value) }}](#) {% endif %} {%- endmacro %} ``` -------------------------------- ### Create Stop Loss Order in Same Group Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Creates a stop-loss order that is part of a group. If this order fills, other orders in the same group will be canceled. ```python await create_order_instance( context, side="sell", symbol="BTC/USDT", order_amount="100%", order_type_name="stop_loss", order_offset="-3%", group=oco_group, tag="sl" ) ``` -------------------------------- ### Define User Details Object Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/community/user_details.html Use this macro to create a JavaScript object containing user-specific details. It dynamically sets boolean values based on input parameters. ```html {% macro user_details( USER_EMAIL, USER_SELECTED_BOT_ID, has_open_source_package, PROFILE_NAME, TRADING_MODE_NAME, EXCHANGE_NAMES, IS_REAL_TRADING) -%} const _USER_DETAILS = { email: "{{ USER_EMAIL }}", botId: "{{ USER_SELECTED_BOT_ID }}", hasPremiumExtension: {{ 'true' if has_open_source_package() else 'false'}}, profileName: "{{ PROFILE_NAME }}", tradingMode: "{{ TRADING_MODE_NAME }}", exchanges: "{{ EXCHANGE_NAMES }}".split(","), isRealTrading: {{ 'true' if IS_REAL_TRADING else 'false' }}, } {%- endmacro %} ``` -------------------------------- ### Editable List Key Macro (Jinja) Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/config/editable_config.html Renders an editable configuration key for list types. It supports displaying list items and optionally integrates with Select2 for enhanced selection, including tag support and placeholders. ```Jinja {% macro editable_key_list(config, key, config_key, config_type, config_value, startup_config_value, suggestions, no_select, force_title, identifier="", placeholder_str="", dict_as_option_group=False) -%} {% if force_title %} {{ key }} : {% endif %} {% if dict_as_option_group and suggestions is mapping %} {% for group_name, values in suggestions.items() %} {% for name in values %} {{ name }} {% endfor %} {% endfor %} {% else %} {% for name in config[key] %} {{ name }} {% endfor %} {% for name in suggestions %} {% if name not in config[key] %} {{ name }} {% endif %} {% endfor %} {% endif %} {% if not no_select %} $("select[editable_config_id=\"multi-select-element-{{ identifier }}\"]").select2({ dropdownAutoWidth : true, tags: true, placeholder:"{{ placeholder_str }}" }); {% endif %} {%- endmacro %} ``` -------------------------------- ### Set Default Configuration for SimpleStrategyEvaluator Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Sets the default configuration for SimpleStrategyEvaluator, specifying the timeframes to be used for evaluation. In this case, it's set to use the 1-hour timeframe. ```python # Default Strategy Configuration SimpleStrategyEvaluator.get_default_config( time_frames=["1h"] # Use 1-hour timeframe ) ``` -------------------------------- ### Editable Number Key Macro (Jinja) Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/config/editable_config.html Renders an editable configuration key for number types. It displays the key and its value, with an option to make the key itself editable. ```Jinja {% macro editable_key_number(config, key, config_key, config_type, config_value, startup_config_value, suggestions, number_step, edit_key) -%} {% if edit_key %} [{{ key }}](#) {% else %} {{ key }} {% endif %}: [{{ config[key]|default (config_value) }}](#) {%- endmacro %} ``` -------------------------------- ### Generate EMA Signals with Threshold and Reversal Options Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Generates trading signals based on price position relative to an Exponential Moving Average (EMA). Allows configuration of period length, price threshold percentage, and signal reversal. ```python import tulipy class EMAMomentumEvaluator(evaluators.TAEvaluator): def __init__(self, tentacles_setup_config): super().__init__(tentacles_setup_config) self.period_length = 21 self.price_threshold_percent = 2 # 2% threshold self.reverse_signal = False def init_user_inputs(self, inputs: dict) -> None: self.period_length = self.UI.user_input( "period_length", enums.UserInputTypes.INT, 21, inputs, min_val=1, title="EMA period length." ) self.price_threshold_percent = self.UI.user_input( "price_threshold_percent", enums.UserInputTypes.FLOAT, 2, inputs, min_val=0, title="Percent difference from EMA to trigger signal." ) self.reverse_signal = self.UI.user_input( "reverse_signal", enums.UserInputTypes.BOOLEAN, False, inputs, title="Reverse signal: short when below EMA, long when above." ) async def evaluate(self, cryptocurrency, symbol, time_frame, candle_data, candle): self.eval_note = 0 if len(candle_data) >= self.period_length: ema_values = tulipy.ema(candle_data, self.period_length) threshold_multiplier = self.price_threshold_percent / 100 # Price above EMA + threshold = sell signal if candle_data[-1] >= ema_values[-1] * (1 + threshold_multiplier): self.eval_note = 1 # Price below EMA - threshold = buy signal elif candle_data[-1] <= ema_values[-1] * (1 - threshold_multiplier): self.eval_note = -1 if self.reverse_signal: self.eval_note *= -1 ``` ```python # EMA Configuration Example EMAMomentumEvaluator.get_default_config( period_length=21, price_threshold_percent=2, reverse_signal=False ) ``` -------------------------------- ### Editable Boolean Key Macro (Jinja) Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/config/editable_config.html Renders an editable configuration key for boolean types. It simply displays the key name. ```Jinja {% macro editable_key_bool(config, key, config_key, config_type, config_value, startup_config_value, suggestions, tooltip) -%} {{ key }} {%- endmacro %} ``` -------------------------------- ### Cancel Order with Additional Parameters Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Trading/Mode/trading_view_signals_trading_mode/resources/TradingViewSignalsTradingMode.md Optionally, specify PARAM_SIDE or TAG to filter which orders to cancel. This allows for more precise cancellation of buy/sell orders or orders with a specific tag. ```bash EXCHANGE=binance SYMBOL=ETHBTC SIGNAL=CANCEL PARAM_SIDE=buy TAG=my_order_tag ``` -------------------------------- ### Editable Dictionary Key Macro (Jinja) Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/components/config/editable_config.html Handles rendering editable configuration keys for dictionary types. It iterates through dictionary keys and recursively calls the `editable_key` macro for nested values. ```Jinja {% macro editable_key_dict(config, key, config_key, config_type, config_value, startup_config_value, suggestions, no_select, number_step, force_title, tooltip, identifier, placeholder_str, allow_create_for, dict_as_option_group) -%} {{ key }} : {% for new_key in config[key] %}  {{ editable_key( config[key], new_key, config_key + "_" + new_key, config_type, config_value[new_key], startup_config_value[new_key], suggestions, no_select, number_step, force_title, tooltip, identifier, placeholder_str, edit_key=(allow_create_for == key), dict_as_option_group=dict_as_option_group) }} {% if loop.last and allow_create_for == key %} {{ editable_key( config[key], "Empty", config_key + "_Empty", config_type, config_value[new_key], startup_config_value[new_key], suggestions, no_select, number_step, force_title, tooltip, identifier, placeholder_str, edit_key=True, dict_as_option_group=dict_as_option_group) }} {% endif %} {% endfor %} {%- endmacro %} ``` -------------------------------- ### Format Order Row Macro Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Services/Interfaces/web_interface/templates/macros/tables.html Use this macro to format a single row of order data for display. It handles simulated and real orders, including virtual orders. ```Jinja {% macro order_tr(order, type='', timestamp='', sim_or_real='Simulated') -%} {{ order.symbol }} {{ type.replace("_", " ") }} {{ order.origin_price if not order.origin_stop_price else order.origin_stop_price}} {{ order.origin_quantity }} {{ order.exchange_manager.exchange.name if order.exchange_manager else '' }} {{ timestamp }} {{ order.total_cost }} {{ order.market }} {% if sim_or_real == 'Simulated' %} {{ sim_or_real }} {% else %} {{ sim_or_real }} {{" (virtual)" if order.is_self_managed()}} {% endif %} {%- endmacro %} ``` -------------------------------- ### Collect Backtesting Historical Data Source: https://context7.com/drakkar-software/octobot-tentacles/llms.txt Asynchronously collects historical market data from a specified exchange for backtesting purposes. Requires context, exchange name, symbols, timeframes, and start/end timestamps. ```python from tentacles.Backtesting.collectors.exchanges.exchange_history_collector import HistoryCollector from tentacles.Meta.Keywords.scripting_library.backtesting import backtesting_data_collector # Collect historical data for backtesting async def collect_backtesting_data(context): await backtesting_data_collector.collect_backtesting_data( context, exchange_name="binance", symbols=["BTC/USDT", "ETH/USDT"], time_frames=["1h", "4h", "1d"], start_timestamp=1609459200, # Jan 1, 2021 end_timestamp=1640995200 # Jan 1, 2022 ) ``` -------------------------------- ### Advanced Order Details for Alerts Source: https://github.com/drakkar-software/octobot-tentacles/blob/master/Trading/Mode/trading_view_signals_trading_mode/resources/TradingViewSignalsTradingMode.md Add optional order details to signals for more control. Supported parameters include ORDER_TYPE, VOLUME, PRICE, STOP_PRICE, TAKE_PROFIT_PRICE, and REDUCE_ONLY. ```text ORDER_TYPE=LIMIT VOLUME=0.01 PRICE=42000 STOP_PRICE=25000 TAKE_PROFIT_PRICE=50000 REDUCE_ONLY=true ```