> For the complete documentation index, see [llms.txt](https://docs.sigrex.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sigrex.io/startegies/llm-session/signal-generation.md).

# Signal generation

LLM Session with Send Signal enabled

This feature enables the AI to not only reason about market conditions but also execute real trading actions.\
When enabled, all trading decisions are automatically **sent to your webhook for live processing**.

{% hint style="danger" %}

### &#x20;Disclaimer

This feature is experimental and high-risk. LLMs can make mistakes, misinterpret market conditions, and overreact to price movements. Trading with it can result in financial loss.

Use it carefully with a webhook setup, preferably with no real capital attached, and monitor all signals and logs continuously.
{% endhint %}

***

### ⚙️ Execution Flow

When Signal Generation is active:

1. The system builds the final prompt using:
   * **System prompt (auto-injected)**
   * **User strategy prompt with resolved template variables**
2. The AI evaluates the strategy and decides whether to act
3. If conditions are met, it executes an action:
   * Open position (BUY / SELL)
   * Close position (EXIT)
   * Request market price if needed
4. Executed actions are processed and forwarded as trading signals (e.g. webhook)

If no valid setup is found, no action is executed.

### 📡 Signal Symbol Configuration

The user must define the trading symbol(s) used for execution.

#### Format

Single symbol (recommended):

```
BTCUSDT
```

Multiple symbols (optional):

```
BTCUSDT,ETHUSDT,SOLUSDT
```

{% hint style="warning" %}

#### Scope Rules

* Symbols define **execution scope only**
* Symbols are **not injected into the prompt**
* The AI does not assume available symbols unless explicitly referenced in the user prompt
  {% endhint %}

## 🛠️ LLM Tooling Reference

These tools allow LLMs to execute trading actions, access market and external data, manage persistent state, communicate with other automations, inspect strategy performance and errors, and dynamically control and modify other strategies.

### `open_position`

Opens a new trading position (**BUY (LONG)** or **SELL (SHORT)**) on one or more selected symbols.

Used to execute entry signals directly through the trading system.

***

### `close_position`

Closes an active trading position.

Used for exiting trades based on strategy logic such as profit targets, stop losses, or signal reversals.

***

### `get_symbol_price`

Returns the current market price of a trading pair.

Useful for making live trading decisions and evaluating strategy conditions.

***

### `set_storage`

Stores a persistent JSON object for the strategy.

Calling this tool **replaces the entire existing storage** with the provided value.

Storage is persisted between executions, allowing the LLM to maintain long-term memory and state across strategy runs.

> **Storage Limit:** The maximum storage size is **25 MB**. Attempting to store more data will result in an error.

***

### `get_storage`

Retrieves the strategy's currently saved storage.

Returns the complete persistent JSON object previously stored by the strategy.

***

### `append_storage`

Appends new data to the existing strategy storage without replacing it.

Unlike `set_storage`, this tool preserves the current storage and merges or appends the provided data, making it ideal for gradually building logs, histories, or other persistent datasets.

> **Storage Limit:** The combined storage size cannot exceed **25 MB**. If the limit is exceeded, the tool will return an error.

***

### `web_fetch`

Performs an HTTP **GET** request to a specified URL.

Useful for retrieving external data such as market information, APIs, news feeds, or other publicly available resources.

***

### `execute_javascript`

Executes custom JavaScript code inside the strategy sandbox.

The tool expects the **body of an asynchronous function**, executes it, and returns the function's return value.

The execution environment uses the same secure sandbox as [**Code Strategies**](/startegies/code.md), including the same runtime restrictions, resource limits, and security policies. This allows the LLM to perform custom calculations, data transformations, or other logic that would be difficult to express through tool calls alone.

***

### `send_email`

Sends an email to the strategy owner.

Useful for delivering alerts, reports, trade summaries, or other custom notifications generated by the AI strategy.

***

### `get_current_date_time`

Returns the current date and time.

Useful for time-sensitive decisions, scheduling logic, calculating time ranges, or working with timestamps.

***

### `get_candlestick_data`

Fetches historical OHLCV candlestick data for a trading pair.

Allows the LLM to retrieve market history for a specific **symbol**, **timeframe**, and optional time range or candle limit. Useful for technical analysis, pattern detection, and evaluating historical price action.

***

### `get_signal_logs`

Retrieves signal logs from other strategies.

Allows the LLM to analyze historical signals and evaluate strategy performance, including signal outcomes and profitability.

Useful for comparing strategies, measuring performance, identifying patterns, and making data-driven decisions.

***

### `get_error_logs`

Retrieves error logs from strategies.

Allows the LLM to inspect historical strategy errors and execution failures, helping it identify recurring problems, diagnose issues, and learn from previous failures.

***

### `set_strategy_status`

Changes the active status of another strategy.

Allows the LLM to start or stop strategies dynamically based on its own analysis or predefined conditions.

Useful for coordinating multiple strategies and building autonomous strategy-management workflows.

***

### `get_strategy`

Retrieves the configuration of another strategy.

Allows the LLM to inspect other strategies and understand their configuration, including their prompts, code, and available settings.

Useful for analyzing, comparing, and coordinating multiple strategies.

***

### `set_strategy`

Updates the configurable logic of another strategy.

LLMs can modify the **code** of Code Strategies or the **prompt** of LLM Strategies.

This enables AI strategies to dynamically adapt and improve other strategies based on performance, market conditions, historical data, or detected errors.

### 🧠 System Prompt (Automatically Added)

When signal sending is enabled, two things happen automatically:

1. **Prepending context** to your prompt:

   ```
   You are a trading bot now.
      
   The last order was {{last_trigger_action}}.
   That executed at {{last_trigger_at}}.
   Storage: {{storage}}
   The current time is {{current_time}}.

   IMPORTANT: if the last order was not "EXIT" or "HOLD" that means a position is open and we need to close it or hold it.
   We can only have one position at a time and have to close it before we can open a new one.
   You can make BUY (long) or SELL (short) orders with the help of provided tools. 
   ```

***

### ⚙️ Writing a Good Prompt

To ensure reliable signals, your custom prompt should focus on the **decision-making logic**, not the output format. Here's an example:

#### 📝 Example Custom Prompt

```
Trade on BTCUSDT, The goal is to exit with at least 0.8% profit or stop out with a 1% loss.  
If either level is hit, the position must be closed.

You are analyzing a trading chart.  
Based on current indicators and chart patterns, choose the best action.  
Consider the previous order when making your decision.
```

> 🔁 The system will handle formatting instructions [automatically](#system-prompt-automatically-added) — no need to repeat them.

***

## 🧩 Template Variables

To make prompt creation easier and more dynamic, you can now use the following **template variables** in your prompt:

| Template                               | Description                                                                                                                                                                                                                                                                                                                                                            |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `{{last_trigger_action}}`              | The last executed signal (e.g., `LONG`, `SHORT`, `EXIT`)                                                                                                                                                                                                                                                                                                               |
| `{{last_trigger_at}}`                  | Timestamp when the last signal was executed (e.g., `2025-06-04 15:32 UTC`)                                                                                                                                                                                                                                                                                             |
| `{{current_time}}`                     | The current time (automatically filled before execution)                                                                                                                                                                                                                                                                                                               |
| `{{val:<name>=<value>}}`               | <p>Declares a <strong>custom value</strong> within your prompt. You can define it once and reuse it anywhere. For example:<br><code>{{val:user=Joe}}</code> then later use <code>{{user}}</code> → will be replaced with <code>Joe</code>.</p>                                                                                                                         |
| `{{price:<exhange>:<service>:<pair>}}` | Returns the live market price for a given trading pair from a specific exchange and market type (e.g. spot, futures). [See available exchanges](#price-variable-reference)                                                                                                                                                                                             |
| `{{comment:<text>}} or {{#:<text>}}`   | Adds inline comments to the prompt for readability and documentation. Comment content is **stripped before the final prompt is sent** and never reaches the model.                                                                                                                                                                                                     |
| `{{get:<url>}}`                        | Fetches data via an **HTTPS GET request** from the specified URL and injects the response into the prompt. Requests are limited to **HTTPS** and have a **timeout of 1750 ms**.                                                                                                                                                                                        |
| `{{toon:<json>}}`                      | Converts JSON into [**Toon**](https://toonformat.dev/) **format**, a compact link-based representation that helps **reduce final prompt token count** while preserving the original content semantics.                                                                                                                                                                 |
| `{{storage}}`                          | Persistent JSON storage associated with the strategy. The stored data is automatically injected into the model's system instructions on every execution, so the AI already has access to it without needing to include `{{storage}}` in the prompt. Use this variable only when you need to explicitly reference or manipulate the storage content inside your prompt. |

These help the AI reason based on **past actions and current context**.

***

#### 📝 Example Prompt with Templates

```
{{comment: example comment }}

{{val:target_profit=0.8}}
{{val:max_loss=1.0}}
{{val:symbol=BTCUSDT}}

You're observing a live trading chart for {{symbol}} with real funds in play.
Your mission: secure at least {{target_profit}}% profit or exit the position if losses reach {{max_loss}}%.
Stay calm and act based on structure, momentum, and signal context.

Previous signal: {{last_trigger_action}} at ({{last_trigger_at}})
Current time: {{current_time}}

External data sources:

Market sentiment: {{get:https://api.example.com/sentiment?symbol={{symbol}}}}

{{#: toon combined with get }}
Technical summary: {{toon: {{get:https://api.example.com/ta-summary?symbol={{symbol}}}} }}

Review the current chart carefully.
Consider trend strength, candle behavior, and volatility.
Weigh the previous signal and the data above before deciding on the next move.

```

### Price Variable Reference

The `{{price:<exchange>:<service>:<pair>}}` template variable allows you to dynamically inject real-time market prices into your LLM prompts or strategy logic.

It automatically fetches the latest price for a given trading pair from a specified exchange and market type.

<table><thead><tr><th width="177.666748046875">Exchange</th><th width="136.3333740234375">Service</th><th>Example</th></tr></thead><tbody><tr><td><code>binance</code></td><td><code>spot</code></td><td><code>{{price:binance:spot:btcusdt}}</code></td></tr><tr><td><code>bitget</code></td><td><code>spot</code></td><td><code>{{price:bitget:spot:btcusdt}}</code></td></tr><tr><td><code>kraken</code></td><td><code>spot</code></td><td><code>{{price:kraken:spot:btcusdt}}</code></td></tr><tr><td><code>gateio</code></td><td><code>spot</code></td><td><code>{{price:gateio:spot:btcusdt}}</code></td></tr><tr><td><code>hyperliquid</code></td><td><code>spot</code></td><td><code>{{price:hyperliquid:spot:btcusdt}}</code></td></tr></tbody></table>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.sigrex.io/startegies/llm-session/signal-generation.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
