
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 Call | Description |
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.byteLimit | Constant 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);
}
- 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:
- Always provide a fallback default object when calling
$.Storage.get(). - Remember to explicitly call
await $.Storage.set(S)after modifying local properties to persist changes. - Keep object payloads lean and well under the 24 KB limit by pruning outdated historical data arrays regularly.


