Back to Blog
How to Use $.Storage in Code Strategies
Code Strategy2 min read

How to Use $.Storage in Code Strategies

When building continuous algorithmic trading strategies, keeping track of historical context across loop iterations is essential. Because Code Strategies execute in an isolated runtime environment, standard in-memory variables reset between runs.

To maintain continuity—such as tracking open position sizes, counting trade entries, storing indicator states, or logging timestamp markers—your strategy needs a reliable way to persist data.

This is where $.Storage comes in.

What is $.Storage?

$.Storage is a built-in asynchronous key-value mechanism that allows your strategy to read and write persistent JSON data across executions.

It acts as your script's private, dedicated memory bank, ensuring critical values remain available as the execution engine loops continuous iterations.

Core Interface

The $.Storage API consists of two primary asynchronous methods and an execution limit constant:

API CallDescription
await $.Storage.get()Retrieves the currently stored state object. Returns null if empty.
await $.Storage.set(object)Saves a new state object, completely replacing existing stored data.
$.Storage.byteLimitConstant specifying the maximum storage payload size (24,576 bytes / 24 KB).

The Standard State Pattern

Because $.Storage.get() returns null on the very first run of a strategy, the standard implementation uses a logical fallback to initialize default values.

// 1. Fetch existing state or initialize default structure
const S = (await $.Storage.get()) || {
    tradeCount: 0,
    lastEntryPrice: 0,
    isPositionOpen: false,
};

// 2. Perform strategy operations using S
if (!S.isPositionOpen && $.Price.price < 50000) {
    await $.Strategy.action($.Action.LONG);
    
    // 3. Update local state representation
    S.isPositionOpen = true;
    S.lastEntryPrice = $.Price.price;
    S.tradeCount++;

    // 4. Persist updated state back to storage
    await $.Storage.set(S);
}

Common Use Cases for $.Storage

1. Position and Entry Tracking

While $.Strategy.lastTrigger provides basic action history, storing custom position data directly in $.Storage allows you to track partial entries, average entry prices, and position scaling:

const S = (await $.Storage.get()) || {
    entries: 0,
    avgPrice: 0,
};

// Scaling into a position
if (shouldAddPosition && S.entries < 3) {
    await $.Strategy.action($.Action.LONG);
    
    S.entries++;
    S.avgPrice = $.Price.price;
    
    await $.Storage.set(S);
}
  1. Time Gates and Execution Throttling

Combining $.Storage with timestamp checks allows strategies running in infinite loops to throttle heavy operations, such as external HTTP requests:

const NOW = Math.floor(Date.now() / 1000);
const S = (await $.Storage.get()) || { lastRun: 0 };

// Throttle loop execution to run once every 60 seconds
if (NOW - S.lastRun < 60) {
    return;
}

S.lastRun = NOW;
await $.Storage.set(S);

// Execute periodic strategy analysis...

3. Preserving Indicator History

When working with technical analysis indicators via $.Ta, updating indicator instances sequentially over time requires storing historical value arrays or state indicators between loop passes:

const S = (await $.Storage.get()) || {
    priceHistory: [],
};

// Maintain a rolling window of the last 14 price points
S.priceHistory.push($.Price.price);
if (S.priceHistory.length > 14) {
    S.priceHistory.shift();
}

await $.Storage.set(S);

Operational Rules and Payload Limits

To maintain performance across execution runs, $.Storage operates under specific technical bounds:

  • Size Restriction: The maximum payload limit per strategy is 24 KB (24,576 bytes). Attempting to save objects exceeding this threshold will result in execution failure.
  • Overwriting Behavior: Calling $.Storage.set(obj) replaces the entire stored JSON object. If you only want to update a single key, load the complete state object first, modify the property, and save the updated object back.
  • Supported Data Types: Since data is serialized internally as JSON, stored objects should contain standard primitives (numbers, strings, booleans), plain objects, and arrays. Complex objects like active functions or class instances cannot be persisted directly.

Summary Checklist

When implementing $.Storage in your Code Strategies:

  1. Always provide a fallback default object when calling $.Storage.get().
  2. Remember to explicitly call await $.Storage.set(S) after modifying local properties to persist changes.
  3. Keep object payloads lean and well under the 24 KB limit by pruning outdated historical data arrays regularly.

Related posts

Building Copy Trading Pipeline for Polymarket
Code Strategy·7 min read

Building Copy Trading Pipeline for Polymarket

Copy trading a wallet on Polymarket is straightforward in principle: every trade a wallet makes is public, on-chain, and available through a free API. The harder question is how to relay those trades into your own bot without inheriting the source wallet's exact position sizing, without double-processing the same fill twice, and without losing visibility into what actually got copied and why. This walks through one way to do that: a Code Strategy that polls a wallet, a Data Webhook that stores

2026-08-17
Connecting External APIs Securely with $.Http
Code Strategy·2 min read

Connecting External APIs Securely with $.Http

Standard JavaScript runtimes like Node.js or browsers rely on global functions like fetch or axios to interact with external web services. However, in secure algorithmic environments, accessing unmanaged networking interfaces can introduce significant latency, security risks, or memory overhead. In Code Strategies, external network communication is handled through the built-in $.Http object. $.Http provides a streamlined, secure utility for sending HTTP requests, managing caching automatically

2026-07-23
Time Gates in Code Strategies
Code Strategy·3 min read

Time Gates in Code Strategies

When building automated trading algorithms, controlling when your strategy evaluates the market is just as important as defining what it does. Because Code Strategies run continuously in an infinite loop—executing one iteration immediately after another—performing a full market evaluation or making external network requests on every single pass can lead to rate-limiting issues, noisy signal processing, and degraded performance. This is where Time Gates come in. A Time Gate creates a controlle

2026-07-23