# Code

Your strategy runs in a sandboxed environment where you can analyze the current market data, store custom information, and trigger actions using the built-in `$` object.

***

## 🧩 Available Variables

Each run of your strategy includes access to the following objects and functions:

***

### **`$.Action`**

Enum representing all available trade actions:

* `LONG` → Open a long position
* `SHORT` → Open a short position
* `EXIT` → Close the current position

***

### **`$.Price`**

{% hint style="warning" %}
The current market price info of the selected symbol only if "use price" option enabled.
{% endhint %}

| Property   | Description                                  |
| ---------- | -------------------------------------------- |
| `symbol`   | Price symbol, e.g. `"BTCUSDT"`               |
| `price`    | Current price of the `symbol`                |
| `exchange` | Source Exchange identifier, e.g. `"binance"` |
| `service`  | Market type, e.g. `"spot"` or `"futures"`    |

Example:

```js
if ($.Price.price > 25000) {
    await $.Strategy.action($.Action.LONG);
}
```

***

### `$.Env`

Provides access to user-defined environment variables.

Users can define global environment variables that are automatically available across all strategy executions.

These values can be accessed at runtime using the `$.Env` object.

***

Example:

```ts
const apiKey = $.Env.API_KEY;
const risk = $.Env.RISK;
```

***

### **`$.Strategy`** Properties

Provides context for the current trading session and allows you to execute actions.

| Property             | Description                                                            |
| -------------------- | ---------------------------------------------------------------------- |
| `signalSymbols`      | Array of symbols where signal actions are sent (`["BTCUSDT",ETHUSDT]`) |
| `lastTrigger.action` | The most recent action (`LONG`, `SHORT`, or `EXIT`)                    |
| `lastTrigger.price`  | The price when the last action was executed                            |
| `lastTrigger.at`     | Timestamp of the last action, or `null` if none                        |

### **`$.Strategy`** Methods

#### `roi(percentage?: boolean, openPrice?: number, currentPrice?: number): number|null`

Calculates the current Return on Investment (ROI) based on the difference between open and current price.

If no prices are provided, it automatically uses the last trigger price as the open price and the current system price. You can override these by passing custom values.

Returns the result as a percentage when enabled, otherwise as a decimal. If no valid price data is available, it returns `null`.

ROI Example:

```ts
// Default usage (uses last trigger price + current price if enabled)
const roiValue = $.Strategy.roi();

// ROI as percentage
const roiPercent = $.Strategy.roi(true);

// Using custom prices
const customRoi = $.Strategy.roi(false, 100, 120);
```

> ⚠️ Keep in mind: for short positions, profitable trades will result in a negative ROI value.

#### `async action(type: $.Action, options?: ActionOption)`

Executes a strategy action such as `$.Action.LONG`, `SHORT`, or `EXIT`.

You can optionally pass additional settings like `id`, `size`, `dilution`, or `flag` to control how the action is handled. The structure is similar to a [signal payload](https://docs.sigrex.io/getting-started/signal-payload-format).

#### Options

```typescript
type ActionOption = {
    id?: string;                    // A custom name/id for the alert (optional)
    dilution?: boolean;             // If true, allows partial stacking of positions (optional)
    size?: number;                  // Trade size (open in quote, close in base currency), overrides default (optional)
    flag?: FlagType | FlagType[];   // Additional tags like 'TEST', 'DEBUG', 'REVERSE' (optional)
}
```

Action Example:

```ts
// Simple action
await $.Strategy.action($.Action.LONG);

// Action with options
await $.Strategy.action($.Action.SHORT, {
  id: "trade-1",
  dilution: true,
  flag: "TEST"
});

// Multiple flags
await $.Strategy.action($.Action.EXIT, {
  flag: ["REVERSE", "TEST"]
});
```

The function sends the action to the system and returns the execution result. If the provided options are invalid, it returns an error.

***

### **`$.Storage`**

Persistent JSON storage (up to **24 KB**) that remains between strategy runs.

| Function         | Description                                                 |
| ---------------- | ----------------------------------------------------------- |
| `byteLimit`      | Constant holding the maximum allowed bytes (24,576)         |
| `async get()`    | Retrieves the current stored data (returns `null` if empty) |
| `async set(obj)` | Saves a new data object (overwrites existing data)          |

Example:

```js
const state = await $.Storage.get() || { trades: 0 };
state.trades++;
await $.Storage.set(state);
```

***

### `$.Http`

Utility for sending HTTP requests from within your strategy.

Each request has a maximum timeout of `1750 ms`.

***

| Method or Property                         | Description                                           |
| ------------------------------------------ | ----------------------------------------------------- |
| `timeout`                                  | Constant timeout value in milliseconds (`1750`)       |
| `async get(url, params?, headers?)`        | Sends a GET request                                   |
| `async post(url, data, headers?)`          | Sends a POST request                                  |
| `async put(url, data, headers?)`           | Sends a PUT request                                   |
| `async delete(url, params?, headers?)`     | Sends a DELETE request                                |
| `async generateSignature(payload, secret)` | Generates an HMAC signature from a payload and secret |

***

#### Response Format

All HTTP methods return an object in the following format:

```ts
{ 
  status: number,
  text: string,
  cache: boolean
}
```

* `status` → HTTP status code (e.g. `200`, `404`, `500`)
* `text` → Raw response body as string
* `cache` → Indicates whether the response was cached

***

#### Caching

> ⚠️ All HTTP requests are cached for **5 seconds**.\
> During this period, repeated requests return the same response.\
> You can check the `cache` field to see if the response was served from cache.

***

Example:

```ts
const params = { symbol: "BTCUSDT" };

const response = await $.Http.get(
  "https://api.binance.com/api/v3/ticker/price",
  params
);

if (response.status === 200) {
  const data = JSON.parse(response.text);
}
```

***

Signature Example:

```ts
const API_KEY = "your_public_api_key";
const API_SECRET = "your_private_api_secret";

const method = "POST";
const path = "/api/v2/strategy/llm-session";

const body = {
  name: "My Strategy",
  cron_interval: "15m"
};

const timestamp = Math.floor(Date.now() / 1000).toString();

const payload =
  method + path + JSON.stringify(body) + timestamp;

const signature = await $.Http.generateSignature(payload, API_SECRET);
```

***

### **`$.Ta`**

Provides access to a built-in **technical analysis library** for calculating indicators and signals directly inside your strategy or reaction.

The `$.Ta` object exposes the functionality of the **trading-signals** library:

👉 <https://github.com/bennycode/trading-signals/tree/main/packages/trading-signals>

***

#### What You Can Do

With `$.Ta`, you can:

* Calculate indicators like **RSI, EMA, SMA, MACD, ATR, Bollinger Bands**
* Build custom technical strategies
* Combine indicators with webhook data or price logic
* Perform calculations without external API calls

***

#### Usage

Indicators are typically used by feeding values sequentially.

Example: RSI

```typescript
const rsi = new $.Ta.RSI(14);

rsi.update(30000);
rsi.update(30100);
rsi.update(29950);

if (rsi.isStable) {
  const value = rsi.getResult();

  if (value < 30) {
    await $.Strategy.action($.Action.LONG);
  }
}
```

***

## ⚡ Rules & Limits

To ensure fair and safe execution, the following rules apply:

* Maximum **execution time:** 5000 ms per run
* Maximum **HTTP request time:** 1750 ms
* **HTTP cache :** 5 s
* Maximum **storage size:** 24 KB
* Only **one action per run** is allowed
* Maximum **five actions per second** globally
* Two consecutive `EXIT` actions are **not permitted**
* Violating these limits will **suspend** the strategy temporarily

***

## 🧠 Example Strategy

```js
// Example: simple entry and exit logic

if ($.Strategy.lastTrigger.action === $.Action.EXIT) {
    if ($.Price.price < 19000) {
        await $.Strategy.action($.Action.LONG);
    }
} else {
    if ($.Price.price > 20000) {
        await $.Strategy.action($.Action.EXIT);
    }
}
```

This example demonstrates:

* Checking the last executed action (`$.Strategy.lastTrigger.action`)
* Using current market data (`$.Price`)
* Executing a new action with (`$.Strategy.action()`)

***

## 🏁 Summary

| Feature                | Description                              |
| ---------------------- | ---------------------------------------- |
| **Action trigger**     | `await $.Strategy.action($.Action.LONG)` |
| **Available actions**  | `LONG`, `SHORT`, `EXIT`                  |
| **Actions per run**    | 1                                        |
| **Actions per second** | 5                                        |
| **Execution time**     | 5000 ms                                  |
| **Storage limit**      | 24 KB                                    |
| **HTTP timeout**       | 1750 ms                                  |
| **HTTP cache**         | 5 seconds (see `response.cache`)         |
| **Duplicate EXITs**    | Not allowed                              |

## 🔒 Sandbox Restrictions & Forbidden Identifiers

Your strategy code runs inside a **strictly sandboxed environment**.\
For security, stability, and fair usage, **certain JavaScript identifiers are completely blocked** and **cannot be used anywhere in your code** — not even indirectly or in comments.

If your strategy references any of the identifiers listed below, **execution will fail** and the strategy may be suspended.

***

#### 🚫 Forbidden Identifiers

The following identifiers are **not available** and **must not appear** in your strategy code:

**Networking & Communication**

* `fetch`
* `WebSocket`
* `EventSource`
* `Worker`, `SharedWorker`
* `XMLHttpRequest`
* `navigator`, `location`
* `postMessage`
* `onmessage`, `onmessageerror`
* `MessageChannel`, `BroadcastChannel`
* `import`
* `importScripts`
* `close`

> ✅ Use `$.Http.get()` and `$.Http.post()` instead.

***

**Dynamic Code Execution**

* `eval`
* `Function`
* `AsyncFunction`
* `generatorFunction`
* `constructor`

> ❗ Dynamic or runtime-generated code is not permitted.

***

**Global Objects & DOM-Like APIs**

* `globalThis`
* `window`
* `self`
* `frames`
* `parent`
* `top`
* `document`

> ℹ️ There is **no DOM, browser, or global scope access**.

***

**Timers & Scheduling**

* `setTimeout`, `setInterval`, `setImmediate`
* `clearTimeout`, `clearInterval`, `clearImmediate`
* `queueMicrotask`

> ⏱ Strategies are **event-driven** and executed automatically — manual scheduling is not allowed.

***

**Crypto, Performance & Parallelism**

* `crypto`
* `performance`
* `structuredClone`
* `Atomics`
* `SharedArrayBuffer`

***

**Reflection & Obfuscation**

* `Reflect`
* `Proxy`

***

**Node.js / Deno Environment**

* `process`
* `require`
* `module`
* `exports`
* `export`&#x20;
* `global`
* `Deno`

> ❌ This is **not** a Node.js or Deno runtime.

***

**Encoding / Decoding**

* `atob`
* `btoa`

***

**User Interaction & Debugging**

* `alert`
* `confirm`
* `prompt`
* `console`
* `Intl`
* `FinalizationRegistry`
* `WeakRef`

> 🛑 Logging, dialogs, locale detection, and memory introspection are intentionally disabled.

***

#### ✅ What You *Can* Use

Instead of the blocked APIs, always rely on:

* **Market data:** `$.Price`
* **Trading actions:** `$.Strategy.action(...)`
* **Persistent state:** `$.Storage.get()` / `$.Storage.set()`
* **HTTP requests:** `$.Http.get()` / `$.Http.post()`

These are **the only supported interfaces** for interacting with the outside world.

***

#### ⚠️ Important Notes

* Forbidden identifiers cannot be used **anywhere**:
  * Not in variables
  * Not in functions
  * Not in comments
  * Not via aliases
  * Not via destructuring
* Even unused references may cause execution failure
* Violations may result in **temporary strategy suspension**


---

# Agent Instructions: 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:

```
GET https://docs.sigrex.io/startegies/code.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
