DEV Community

mattleeee
mattleeee

Posted on Originally published at hkcode.dpdns.org

Idempotent Signals: One Candle, One Entry, Whatever Happens Afterward

A 15-minute scanner is a reasonable choice for most strategies: it reacts quickly, it's cheap to run, and it doesn't need a websocket connection that might drop at 3 a.m. The problem is that the scanner runs 96 times a day while the strategy's decision bar is a 4h candle, which closes only 6 times a day. Every 4h candle is therefore observed by 24 consecutive scanner runs. If the scanner's entry logic is "a golden cross just happened on the last closed bar," that condition is true for roughly six hours, and the scanner will happily open a position on every run unless something stops it.

Most systems stop it by accident: after the first fill, the position exists, the slot is occupied, and the entry path is skipped. That works until the position goes away for a reason other than the strategy changing its mind. A delisting, a 70% catastrophic stop, or a manual flatten frees the slot while the same candle is still the latest closed bar. On the next run the scanner sees the cross again and re-enters the trade it was just stopped out of, at the worst possible moment. The strategy didn't generate a second signal. The scanner simply forgot that it had already consumed the first one.

The real bug is missing state, not a missing check

It's tempting to fix this with a cooldown ("don't re-enter within N bars") or a flag ("already traded this candle"). Both are patches on a deeper issue: the entry path has no memory of which signal events it has consumed. A signal here is not "the pair is in a crossed state." A signal is an event: this specific candle closed with a cross on this pair. Events have identities. The identity is the candle's close timestamp, which is stable, unique per pair, and cheap to store.

Once you frame it that way, the fix is the same one message queues have used for decades: consumers dedupe by event id. Exactly-once consumption of a signal means the entry path checks whether this event id has been seen before, and records it atomically with the order.

The state: signal_bar_used

Persist a map from pair to the timestamp of the candle whose cross was consumed:

# state.json (conceptual)
{
  "signal_bar_used": {
    "PAIR_A": 1717027200,
    "PAIR_B": 1717027200
  }
}
Enter fullscreen mode Exit fullscreen mode

Timestamps are candle close times in epoch seconds (or milliseconds — pick one and never mix). The entry rule becomes a single comparison:

def cross_is_fresh(pair: str, candle_ts: int, state: dict) -> bool:
    used = state.get("signal_bar_used", {}).get(pair)
    return used != candle_ts
Enter fullscreen mode Exit fullscreen mode

If the recorded timestamp equals the current candle's, the event has been consumed. It doesn't matter whether the position still exists, was stopped out, or was closed by a delisting — the event is spent. A new entry requires a new crossing on a later candle, which is what the strategy actually intends.

Write at open time, not at signal time

The record must be written when the order is opened, in the same critical section that decides to open it. If you record the signal first and then place the order, a crash between the two leaves you with a consumed signal and no position — you miss the trade. If you place the order first and record afterward, a crash between the two leaves you with a position and an unconsumed signal — you re-enter on the next run. Neither ordering is safe without atomicity.

The practical approach for a single-process scanner is to serialize the whole entry path behind one lock and write state before releasing it, accepting that a crash mid-order is handled by reconciliation at startup rather than by the signal logic:

import json, os, tempfile
from contextlib import contextmanager

STATE_PATH = "state.json"

@contextmanager
def state_lock():
    # Single-process scanner: an in-process lock plus atomic file replace
    # is sufficient. Multi-process setups need a real file lock or a DB.
    yield

def load_state() -> dict:
    if not os.path.exists(STATE_PATH):
        return {"version": 2, "signal_bar_used": {}}
    with open(STATE_PATH) as f:
        return json.load(f)

def save_state(state: dict) -> None:
    fd, tmp = tempfile.mkstemp(dir=os.path.dirname(STATE_PATH))
    with os.fdopen(fd, "w") as f:
        json.dump(state, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, STATE_PATH)  # atomic on POSIX

def try_open(pair: str, candle_ts: int, open_position) -> bool:
    with state_lock():
        state = load_state()
        used = state.setdefault("signal_bar_used", {})
        if used.get(pair) == candle_ts:
            return False  # event already consumed
        open_position(pair)          # may raise; state untouched on failure
        used[pair] = candle_ts       # consume the event
        save_state(state)
        return True
Enter fullscreen mode Exit fullscreen mode

If open_position raises (rejected order, insufficient margin), the state is not written and the signal remains unconsumed — the next run can retry the same event. That's the correct behavior: the event was offered, not consumed. If the process dies after the fill but before save_state, startup reconciliation should detect the open position and backfill signal_bar_used[pair] with the current candle timestamp before the scanner resumes. Keep that reconciliation step small and explicit; it's the only place where the "position exists" heuristic is allowed to touch signal state.

Edge cases

Delisting wipes the pair's state gracefully

When a pair is delisted, its entry in signal_bar_used is dead weight, and worse, a stale timestamp could suppress a legitimate first signal if the symbol is ever relisted. Handle removal as part of the delisting routine, not as a background cleanup:

def on_delist(pair: str) -> None:
    state = load_state()
    state.get("signal_bar_used", {}).pop(pair, None)
    save_state(state)
Enter fullscreen mode Exit fullscreen mode

Use pop(..., None) so the routine is idempotent itself — running it twice, or running it for a pair that never traded, must not raise. If the delisting arrives as an exchange event that the scanner processes asynchronously, make the removal tolerant of ordering: a delist event for an unknown pair is a no-op, and an entry attempt for a pair that is being delisted should fail at the order layer and leave state untouched.

Schema migration when adding the map

Existing state files won't have signal_bar_used. Don't scatter .get("signal_bar_used", {}) through the codebase and hope; migrate once, on load, with a version field:

def migrate(state: dict) -> dict:
    version = state.get("version", 1)
    if version < 2:
        # v1 had no signal dedupe. Seed from currently open positions so
        # that live trades aren't re-entered on the first run after deploy.
        state["signal_bar_used"] = {
            pair: pos["entry_candle_ts"]
            for pair, pos in state.get("positions", {}).items()
        }
        state["version"] = 2
    return state
Enter fullscreen mode Exit fullscreen mode

The seeding step matters. If you deploy the new code while a position opened on the current candle is live, an empty map means the first run after deploy sees a fresh cross and opens a second position. Backfilling from open positions closes that window. Write the migrated state back immediately so the migration runs exactly once, and keep the function pure so it's testable.

The unit test: replay the same candle twice, open exactly once

This is the test that would have caught the original bug, and it's the one to keep forever:

def test_same_candle_opens_once(tmp_path, monkeypatch):
    monkeypatch.setattr("scanner.STATE_PATH", str(tmp_path / "state.json"))
    opens = []

    def fake_open(pair):
        opens.append(pair)

    candle_ts = 1717027200
    assert scanner.try_open("PAIR_A", candle_ts, fake_open) is True
    assert scanner.try_open("PAIR_A", candle_ts, fake_open) is False

    assert opens == ["PAIR_A"]
    assert scanner.load_state()["signal_bar_used"]["PAIR_A"] == candle_ts
Enter fullscreen mode Exit fullscreen mode

Then extend it with the scenario that motivated all of this — position force-closed, same candle still current:

def test_no_reentry_after_stopout_on_same_candle(tmp_path, monkeypatch):
    monkeypatch.setattr("scanner.STATE_PATH", str(tmp_path / "state.json"))
    candle_ts = 1717027200

    scanner.try_open("PAIR_A", candle_ts, lambda p: None)
    force_close("PAIR_A", reason="catastrophic_stop")   # slot freed
    assert scanner.try_open("PAIR_A", candle_ts, lambda p: None) is False

    # A genuinely new crossing on a later candle is allowed.
    assert scanner.try_open("PAIR_A", candle_ts + 14400, lambda p: None) is True
Enter fullscreen mode Exit fullscreen mode

And one for the failed-order case, asserting the event is not consumed when the open raises:

def test_failed_open_does_not_consume_signal(tmp_path, monkeypatch):
    monkeypatch.setattr("scanner.STATE_PATH", str(tmp_path / "state.json"))
    candle_ts = 1717027200

    def boom(pair):
        raise RuntimeError("order rejected")

    with pytest.raises(RuntimeError):
        scanner.try_open("PAIR_A", candle_ts, boom)
    assert "PAIR_A" not in scanner.load_state()["signal_bar_used"]
Enter fullscreen mode Exit fullscreen mode

Why this framing pays off

Calling the timestamp signal_bar_used rather than last_trade_candle keeps the semantics honest: it records consumption of an event, not a property of the position. That distinction is what makes the delisting case, the stop-out case, and the restart case all fall out of the same comparison instead of needing three separate guards. It also makes the scanner's behavior auditable — for any pair, the state file tells you exactly which crossing was acted on, and any entry whose candle timestamp differs from that value is explainable.

The general principle is worth restating because it generalizes past this one scanner: any scheduled consumer of a slower event stream needs an event id and a dedupe record, or it will eventually double-consume during the window when the event is still current and the consumer's side effects have been undone. Candle close timestamps make good event ids for bar-driven strategies. Use them.

More notes like this ship every week on this site.

Top comments (0)