Back to Blog
Time Gates in Code Strategies
Code Strategy3 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 controlled execution window inside your strategy's loop. It allows the loop to run freely, but instantly halts execution before heavy logic runs unless your specified time interval has passed.

What is a Time Gate?

A Time Gate is a simple timing check placed at the very top of your code. It acts as a filter that determines whether your strategy should proceed with market analysis or wait for the next iteration.

The Basic Time Gate Pattern

const RUN_EVERY_SECONDS = 5;
const NOW = Math.floor(Date.now() / 1000);

// 1. Load persisted state
const S = (await $.Storage.get()) || {
    lastRun: 0,
};

// 2. Check if the Time Gate is locked
if (NOW - S.lastRun < RUN_EVERY_SECONDS) {
    return; // Exit early, skipping market evaluation
}

// 3. Unlock the gate and update state
S.lastRun = NOW;
await $.Storage.set(S);

// 4. Your main strategy logic runs here

How Time Gates Work in Continuous Loops

Since Code Strategies cycle continuously, here is a breakdown of how a 5-second Time Gate (RUN_EVERY_SECONDS = 5) controls your execution flow:

00:00:00  Loop Pass ---> [Gate Passed]  ---> Fetch candles & evaluate indicators
00:00:01  Loop Pass ---> [Gate Locked]  ---> Return immediately
00:00:03  Loop Pass ---> [Gate Locked]  ---> Return immediately
00:00:05  Loop Pass ---> [Gate Passed]  ---> Fetch candles & evaluate indicators

By exiting early during the locked periods, your strategy skips unnecessary API calls and indicator recalculations while waiting for the target interval to mature.

Why Use Time Gates in Your Strategies?

1. Avoid Exchange API Rate Limits

Exchanges enforce strict rate limits on HTTP requests and market data endpoints. If your loop makes external API calls on every iteration, you risk getting temporarily blocked or banned by the exchange. Time Gates keep your data fetching predictable and within allowed limits.

2. Filter Market Noise

Evaluating technical indicators like RSI, MACD, or Moving Averages every fraction of a second can lead to false signals caused by micro-price fluctuations. Adding an execution window ensures your strategy processes indicators on meaningful timeframes.

3. Maintain Reliable Strategy State

Using $.Storage alongside a Time Gate allows your strategy to keep track of its internal timeline. This ensures that timed events—like waiting for candle closes or managing entry delays—happen at exact intervals.

Matching Execution Speed to Your Trading Style

Selecting the right interval depends on the type of trading system you are building:

Strategy StyleInterval (RUN_EVERY)Primary Objective
Scalping / Order Flow1 to 5 secondsCatching rapid momentum shifts and micro-spreads
Intraday / Indicators60 seconds (1 min)Evaluating candle closes, RSI, or trend crossovers
Swing Trading300+ seconds (5+ mins)High-timeframe market analysis and position balancing

Time Gates vs. Action Cooldowns

It is important to distinguish between controlling how often your script evaluates the market and how often it takes an action.

  • Time Gate (Global Throttle): Controls how frequently the script runs its core analysis.
  • Cooldown (Action Throttle): Controls when a specific action (e.g., re-entering a trade after an exit) is allowed again.

Combining Both Controls

const RUN_EVERY = 5;      // Evaluate market every 5 seconds
const COOLDOWN = 300;     // Restrict re-entry for 5 minutes

// 1. Global Time Gate Check
if (NOW - S.lastRun < RUN_EVERY) {
    return;
}
S.lastRun = NOW;

// 2. Action Cooldown Check
if (S.cooldownUntil && NOW < S.cooldownUntil) {
    console.log("Market evaluated, but trade entry is on cooldown.");
    await $.Storage.set(S);
    return;
}

// 3. Trade Entry Logic
if (signalDetected) {
    await placeOrder();
    S.cooldownUntil = NOW + COOLDOWN; // Set 5-minute trade cooldown
}

await $.Storage.set(S);

Ready-to-Use Boilerplate

You can copy and paste this standard template into any new Code Strategy to manage execution frequency from day one:

const RUN_EVERY_SECONDS = 5;
const NOW = Math.floor(Date.now() / 1000);

// Initialize persistent state
const S = (await $.Storage.get()) || {
    lastRun: 0,
    cooldownUntil: 0,
};

// Apply Time Gate
if (NOW - S.lastRun < RUN_EVERY_SECONDS) {
    return;
}

// Persist state update
S.lastRun = NOW;
await $.Storage.set(S);

// --- STRATEGY LOGIC GOES HERE ---

// ---------------------------------

By incorporating Time Gates into your development workflow, your automated strategies will run more reliably, adhere to exchange limits, and generate cleaner trading signals.

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
How to Use $.Storage in Code Strategies
Code Strategy·2 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? $.S

2026-07-23