Code
With the Code feature, you can write your own trading strategy directly in JavaScript.
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 positionSHORT→ Open a short positionEXIT→ Close the current position
$.Exchange
Enum representing the exchanges supported by the Sigrex live exchange-rate system.
Value
Description
$.Exchange.BINANCE
Binance
$.Exchange.GATEIO
Gate.io
$.Exchange.BITGET
Bitget
$.Exchange.HYPERLIQUID
Hyperliquid
$.Exchange.KRAKEN
Kraken
The enum is used with $.getExchangeRate() to specify which exchange should be queried.
$.Price
The current market price info of the selected symbol only if "use price" option enabled.
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:
$.Env
Provides access to user-defined environment variables.
Users can define global or folder scope environment variables that are automatically available across all strategy executions.
These values can be accessed at runtime using the $.Env object.
Example:
$.Strategy Properties
Provides context for the current trading session and allows you to execute actions.
id
The unique numeric ID of the current strategy
type
The type of strategy: code-strategy or code-reaction
Available if "send signal" enabled
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:
⚠️ Keep in mind: for short positions, profitable trades will result in a negative ROI value.
async action(type: $.Action, options?: ActionOption)
Available only if "send signal" option enabled.
Executes a strategy action such as $.Action.LONG, SHORT, or EXIT.
You can optionally pass additional settings like id, size, or dilution to control how the action is handled. The structure is similar to a signal payload.
Options
Action Example:
The function sends the action to the system and returns the execution result. If the provided options are invalid, it returns an error.
async stop(notify?: boolean): boolean
Stops the strategy from executing again by setting its status to INACTIVE.
Important: stop() does not terminate the currently running strategy process. The current execution continues after calling stop(). To stop the current execution as well, use return after calling stop().
If notify is true, the system sends a notification email about the strategy being stopped.
Parameters
Example
⚠️ Use
returnafterstop()if you want to terminate the current execution. Withoutreturn, the current process continues, but the strategy will not execute again.
$.Storage
Persistent JSON storage (up to 24 KB) that remains between strategy runs.
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:
$.Http
Utility for sending HTTP requests from within your strategy.
Each request has a maximum timeout of 1750 ms.
POSTandPUTrequests default toContent-Type: application/json.
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, algo?)
Generates an HMAC or ML-DSA44 signature from a payload and secret. Algo options: "HMAC" or "ML-DSA" Default is: HMAC
createApiClient({ apiKey, apiSecret })
Creates an instance of the official Sigrex API Client that can be used to interact with the services directly from your strategy.
Response Format
All HTTP methods return an object in the following format:
status→ HTTP status code (e.g.200,404,500)text→ Raw response body as stringcache→ 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
cachefield to see if the response was served from cache.
Example:
API Client Example:
Signature Example:
$.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:
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
Utils
async getExchangeRate(exchange: $.Exchange, symbol: string): number|null
Returns the current exchange rate for a symbol on the specified exchange.
The exchange parameter must be one of the supported values from the $.Exchange enum. If a current rate is available, the function returns it as a number; otherwise, it returns null.
Parameters
Example
⚡ 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
EXITactions are not permittedViolating these limits will suspend the strategy temporarily
🧠 Example Strategy
This example demonstrates:
Checking the last executed action (
$.Strategy.lastTrigger.action)Using current market data (
$.Price)Executing a new action with (
$.Strategy.action())
🏁 Summary
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
fetchWebSocketEventSourceWorker,SharedWorkerXMLHttpRequestnavigator,locationpostMessageonmessage,onmessageerrorMessageChannel,BroadcastChannelimportimportScriptsclose
✅ Use
$.Http.get()and$.Http.post()instead.
Dynamic Code Execution
evalFunctionAsyncFunctiongeneratorFunctionconstructor
❗ Dynamic or runtime-generated code is not permitted.
Global Objects & DOM-Like APIs
globalThiswindowselfframesparenttopdocument
ℹ️ There is no DOM, browser, or global scope access.
Timers & Scheduling
setTimeout,setInterval,setImmediateclearTimeout,clearInterval,clearImmediatequeueMicrotask
⏱ Strategies are event-driven and executed automatically — manual scheduling is not allowed.
Crypto, Performance & Parallelism
cryptoperformancestructuredCloneAtomicsSharedArrayBuffer
Reflection & Obfuscation
ReflectProxy
Node.js / Deno Environment
processrequiremoduleexportsexportglobalDeno
❌ This is not a Node.js or Deno runtime.
Encoding / Decoding
atobbtoa
User Interaction & Debugging
alertconfirmpromptconsoleIntlFinalizationRegistryWeakRef
🛑 Logging, dialogs, locale detection, and memory introspection are intentionally disabled.
✅ What You Can Use
Instead of the blocked APIs, always rely on:
Market data:
$.PriceTrading 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
Last updated