Practical tutorials

Prevent duplicate orders

Combine an in-flight guard, timestamp checks, snapshot checks, and an explicit attempt limit.

Prerequisites

Use a fresh single-instrument historical experiment with no other execution source. This entry-only exercise allows at most one placement attempt per in-memory session when price exceeds an illustrative threshold of 100. It has no exit logic.

Add the complete source

export async function app({ context, bar, log }) {
  const frame = bar?.date == null ? NaN : new Date(bar.date).getTime();
  if (!Number.isFinite(frame) || typeof bar.close !== "number"
    || !Number.isFinite(bar.close)) return "waiting: invalid bar";
  const state = (context.sjsState ??= {}).oneAttempt ??= {};
  if (state.busy || state.attempted) return "hold: busy or already attempted";
  if (state.lastFrame != null && frame <= state.lastFrame) return "ignored: old frame";
  state.lastFrame = frame;
  if (bar.close <= 100) return "hold: threshold not met";
  state.busy = true;
  try {
    if (typeof context.getOrders !== "function") return "waiting: orders unavailable";
    const orders = await context.getOrders();
    const positions = await context.getPositions();
    if (!Array.isArray(orders) || !Array.isArray(positions)) return "waiting: invalid snapshot";
    if (orders.length || positions.length) return "waiting: exposure exists";
    state.attempted = true;
    state.lastAttempt = { frame, outcome: "pending" };
    const result = await context.placeOrder({
      id: `one-attempt-${frame}`, instrument: context.instrument,
      action: "BUY", quantity: 1, type: "MARKET",
    }, { source: "sjs", metadata: { strategy: "one-attempt", frame } });
    state.lastAttempt.outcome = result !== false && result != null ? "accepted" : "not-accepted";
    log?.("one-attempt", state.lastAttempt);
    return state.lastAttempt.outcome;
  } catch (error) {
    state.lastError = String(error);
    if (state.lastAttempt?.frame === frame) state.lastAttempt.outcome = "error";
    log?.("one-attempt-error", state.lastError);
    return "error";
  } finally {
    state.busy = false;
  }
}

Exercise four boundaries

CaseExpected result
Same timestamp delivered twiceThe frame is consumed once
Another callback arrives during order inspectionThe busy flag blocks overlap
An order or position already existsNo new entry attempt
Placement rejects or throws after submission startsThe attempted flag remains set; no automatic retry

If inspection fails before submission starts, a later timestamp can inspect again. If exposure blocks the attempt, the same frame is consumed, but a later above-threshold frame can try again after exposure clears.

Verify and understand the limit

Inspect oneAttempt.lastAttempt, orders, and positions. The attempt ID and in-memory flag help explain this instance's behavior; they are not durable broker idempotency. A process restart resets the guard, and an order snapshot is not an atomic account lock across multiple writers.

Common mistakes are clearing the attempt flag as soon as a request returns, interpreting acceptance as a fill, or restarting after an uncertain broker response without reconciliation. This exercise intentionally does not retry a rejected submission.

Next: session-aware strategy.

On this page