# How to Build an Automated Trading Strategy Engine: Rules, Backtesting and Safe Execution

> A step-by-step guide to a rule-based trading engine: a strategy format, an evaluator, an honest backtester, risk limits, and on-chain execution that simulates before it sends.

- Author: OnChain Team
- Published: 2026-11-04
- Page: https://www.onchain.ro/blog/automated-trading-strategy-engine

An automated trading strategy engine has five parts: a strategy format that describes entry and exit rules as data, an evaluator that turns market data into signals, a backtester that replays history without cheating, a risk manager that can veto any order, and an execution layer that simulates every transaction before sending it. Keeping these separate is what makes the system testable: the same strategy and risk code run in backtests, paper trading and live trading, and only the execution layer changes. This guide builds each part in TypeScript, with Solana as the live venue.

This is an engineering guide. Nothing here is a trading strategy recommendation, and automated strategies can and do lose money.

```diagram
title: Every order passes the same checks, in backtests and live
node feed at 0,1 external "Market data" "Closed candles only"
node strat at 1,0 store "Strategy JSON" "Validated rules"
node eval at 1,1 default "Evaluator" "Enter, exit or nothing"
node risk at 2,1 default "Risk manager" "Size, loss, rate limits"
node blocked at 2,2.1 warn "Blocked" "Logged with a reason"
node paper at 3,0.3 default "Paper broker" "Fees and slippage"
node live at 3,1.7 default "Solana broker" "Simulates before sending"
node chain at 4,1.7 external "Solana" "Send and confirm"
node state at 4,0.3 store "Fills and state" "Saved after every step"
edge feed -> eval "candle closed"
edge strat -> eval
edge eval -> risk "signal"
edge risk -> blocked "veto" fail
edge risk -> paper "paper mode"
edge risk -> live "live mode"
edge live -> chain "simulate, send"
edge paper -> state "fill"
edge chain -> state "confirmed fill"
edge state -> risk "P&L, halt flag" dashed up
```

## Step 1: Describe strategies as data

If strategies are code, every change needs a deploy and a review of arbitrary logic. If they are data, users or an assistant can compose them from parts you have already tested, and you can validate them before they run.

```ts
// strategy.ts
export type Indicator =
  { kind: "price" } | { kind: "sma"; period: number } | { kind: "ema"; period: number };

export type Condition =
  | { op: "crossesAbove" | "crossesBelow"; left: Indicator; right: Indicator }
  | { op: "above" | "below"; left: Indicator; right: Indicator };

export type Strategy = {
  id: string;
  market: string; // e.g. "SOL/USDC"
  entry: Condition[]; // all must be true
  exit: Condition[]; // any can be true
  stopLossPct: number; // e.g. 0.05 = exit if 5% below entry
  takeProfitPct: number | null;
  positionSize: number; // in quote currency, e.g. USDC
};

export const maBreakout: Strategy = {
  id: "ma-breakout",
  market: "SOL/USDC",
  entry: [
    { op: "crossesAbove", left: { kind: "price" }, right: { kind: "sma", period: 20 } },
  ],
  exit: [
    { op: "crossesBelow", left: { kind: "price" }, right: { kind: "sma", period: 20 } },
  ],
  stopLossPct: 0.05,
  takeProfitPct: 0.12,
  positionSize: 100,
};
```

Validate a strategy before accepting it: periods within a sane range, a stop loss always present, a position size under the account's limit. Reject anything else with a clear message.

## Step 2: Evaluate rules on closed candles

Evaluate only on closed candles. Using the candle that is still forming is the most common way to build a strategy that looks great in testing and fails live.

```ts
// evaluate.ts
import type { Condition, Indicator, Strategy } from "./strategy";

export type Candle = {
  time: number;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
};

function series(candles: Candle[], ind: Indicator): number[] {
  const closes = candles.map((c) => c.close);
  if (ind.kind === "price") return closes;
  if (ind.kind === "sma") {
    return closes.map((_, i) =>
      i + 1 < ind.period
        ? NaN
        : closes.slice(i + 1 - ind.period, i + 1).reduce((a, b) => a + b, 0) /
          ind.period,
    );
  }
  const k = 2 / (ind.period + 1);
  const out: number[] = [];
  closes.forEach((c, i) => out.push(i === 0 ? c : c * k + out[i - 1] * (1 - k)));
  return out.map((v, i) => (i + 1 < ind.period ? NaN : v));
}

function holds(cond: Condition, candles: Candle[]): boolean {
  const a = series(candles, cond.left);
  const b = series(candles, cond.right);
  const n = candles.length - 1;
  if ([a[n], b[n], a[n - 1], b[n - 1]].some(Number.isNaN)) return false;
  switch (cond.op) {
    case "above":
      return a[n] > b[n];
    case "below":
      return a[n] < b[n];
    case "crossesAbove":
      return a[n - 1] <= b[n - 1] && a[n] > b[n];
    case "crossesBelow":
      return a[n - 1] >= b[n - 1] && a[n] < b[n];
  }
}

export type Signal = "enter" | "exit" | null;

export function evaluate(
  strategy: Strategy,
  closed: Candle[],
  inPosition: boolean,
  entryPrice: number | null,
): Signal {
  const last = closed[closed.length - 1].close;
  if (inPosition && entryPrice !== null) {
    if (last <= entryPrice * (1 - strategy.stopLossPct)) return "exit";
    if (
      strategy.takeProfitPct !== null &&
      last >= entryPrice * (1 + strategy.takeProfitPct)
    )
      return "exit";
    return strategy.exit.some((c) => holds(c, closed)) ? "exit" : null;
  }
  return !inPosition && strategy.entry.every((c) => holds(c, closed)) ? "enter" : null;
}
```

Recomputing the moving average over the whole history on each candle is slow but obviously correct. Optimise it with rolling sums once the tests pass.

## Step 3: Backtest without fooling yourself

A backtest replays history through the same `evaluate` function. Three rules keep it honest:

1. **Fill at the next candle's open**, not at the close that produced the signal. You cannot trade at a price you only learned about after the fact.
2. **Charge fees and slippage** on every fill.
3. **Hold out data.** Tune on one period, then check the result on a later period you did not look at.

```ts
// backtest.ts
import { evaluate, type Candle } from "./evaluate";
import type { Strategy } from "./strategy";

export function backtest(
  strategy: Strategy,
  candles: Candle[],
  feePct = 0.003,
  slippagePct = 0.002,
) {
  let cash = 1000;
  let qty = 0;
  let entryPrice: number | null = null;
  let peak = cash;
  let maxDrawdown = 0;
  const trades: { time: number; side: "buy" | "sell"; price: number; qty: number }[] =
    [];

  for (let i = 30; i < candles.length - 1; i++) {
    const signal = evaluate(strategy, candles.slice(0, i + 1), qty > 0, entryPrice);
    const next = candles[i + 1]; // the fill happens on the next candle

    if (signal === "enter") {
      const price = next.open * (1 + slippagePct);
      const spend = Math.min(strategy.positionSize, cash);
      qty = (spend * (1 - feePct)) / price;
      cash -= spend;
      entryPrice = price;
      trades.push({ time: next.time, side: "buy", price, qty });
    } else if (signal === "exit") {
      const price = next.open * (1 - slippagePct);
      cash += qty * price * (1 - feePct);
      trades.push({ time: next.time, side: "sell", price, qty });
      qty = 0;
      entryPrice = null;
    }

    const equity = cash + qty * candles[i + 1].close;
    peak = Math.max(peak, equity);
    maxDrawdown = Math.max(maxDrawdown, (peak - equity) / peak);
  }

  const finalEquity = cash + qty * candles[candles.length - 1].close;
  return {
    finalEquity,
    returnPct: (finalEquity / 1000 - 1) * 100,
    maxDrawdownPct: maxDrawdown * 100,
    trades,
  };
}
```

Report maximum drawdown next to return, every time. A strategy that returned 40% with a 60% drawdown is one that most people would have abandoned halfway. And treat a backtest that looks too good as a bug until proven otherwise.

## Step 4: Put a risk manager in front of every order

The risk manager is the only component allowed to say no, and it says no by default. It knows nothing about strategies, only about limits.

```ts
// risk.ts
export type OrderRequest = {
  strategyId: string;
  side: "buy" | "sell";
  quoteAmount: number;
};

export class RiskManager {
  private realisedToday = 0;
  private recent: number[] = [];
  private halted = false;

  constructor(
    private limits = {
      maxOrderQuote: 500,
      maxDailyLossQuote: 200,
      maxOrdersPerMinute: 6,
    },
  ) {}

  halt(reason: string) {
    this.halted = true;
    console.error("TRADING HALTED:", reason); // also page a human
  }

  recordPnl(quote: number) {
    this.realisedToday += quote;
    if (this.realisedToday <= -this.limits.maxDailyLossQuote)
      this.halt("daily loss limit reached");
  }

  check(order: OrderRequest): { ok: true } | { ok: false; reason: string } {
    if (this.halted) return { ok: false, reason: "trading is halted" };
    if (order.side === "buy" && order.quoteAmount > this.limits.maxOrderQuote) {
      return { ok: false, reason: "order larger than limit" };
    }
    const now = Date.now();
    this.recent = this.recent.filter((t) => now - t < 60_000);
    if (this.recent.length >= this.limits.maxOrdersPerMinute)
      return { ok: false, reason: "order rate limit" };
    this.recent.push(now);
    return { ok: true };
  }
}
```

Exits should always be allowed past the size check, as here, so the system can reduce risk even when it is near its limits. Reset the daily figure on a fixed schedule, and keep the halt flag in a database so a restart cannot quietly clear it.

## Step 5: Define one broker interface, with paper and live versions

```ts
// broker.ts
export type Fill = {
  clientOrderId: string;
  side: "buy" | "sell";
  price: number;
  qty: number;
  txId?: string;
};

export interface Broker {
  submit(
    clientOrderId: string,
    side: "buy" | "sell",
    quoteAmount: number,
  ): Promise<Fill>;
}

export class PaperBroker implements Broker {
  constructor(
    private lastPrice: () => number,
    private feePct = 0.003,
    private slippagePct = 0.002,
  ) {}

  async submit(
    clientOrderId: string,
    side: "buy" | "sell",
    quoteAmount: number,
  ): Promise<Fill> {
    const price =
      this.lastPrice() * (side === "buy" ? 1 + this.slippagePct : 1 - this.slippagePct);
    return {
      clientOrderId,
      side,
      price,
      qty: (quoteAmount * (1 - this.feePct)) / price,
    };
  }
}
```

Run every new strategy on the paper broker for a while before it touches real funds. Paper results that differ a lot from the backtest usually point to a bug in one of them.

## Step 6: Execute on-chain, simulating first

On Solana, the live broker builds a swap transaction, usually from a DEX aggregator's API, then simulates it, checks the result, and only then signs and sends. [`simulateTransaction`](https://solana.com/docs/rpc/http/simulatetransaction) runs the transaction against current state without committing it, so you find failures before you pay for them.

```ts
// solana-broker.ts
import { Connection, Keypair, VersionedTransaction } from "@solana/web3.js";
import type { Broker, Fill } from "./broker";

export class SolanaBroker implements Broker {
  constructor(
    private connection: Connection,
    // a dedicated trading key with limited funds, never your treasury key
    private signer: Keypair,
    private buildSwap: (
      side: "buy" | "sell",
      quoteAmount: number,
    ) => Promise<{ tx: VersionedTransaction; expectedOut: number }>,
  ) {}

  async submit(
    clientOrderId: string,
    side: "buy" | "sell",
    quoteAmount: number,
  ): Promise<Fill> {
    // includes a slippage limit
    const { tx, expectedOut } = await this.buildSwap(side, quoteAmount);

    // 1. Simulate: catch failures and surprises before signing
    const sim = await this.connection.simulateTransaction(tx, {
      sigVerify: false,
      replaceRecentBlockhash: true,
    });
    if (sim.value.err)
      throw new Error(`simulation failed: ${JSON.stringify(sim.value.err)}`);

    // 2. Sign and send with a fresh blockhash
    const { blockhash, lastValidBlockHeight } =
      await this.connection.getLatestBlockhash("confirmed");
    tx.message.recentBlockhash = blockhash;
    tx.sign([this.signer]);
    const signature = await this.connection.sendRawTransaction(tx.serialize(), {
      skipPreflight: true,
      maxRetries: 3,
    });

    // 3. Confirm, or fail clearly when the blockhash expires
    const result = await this.connection.confirmTransaction(
      { signature, blockhash, lastValidBlockHeight },
      "confirmed",
    );
    if (result.value.err)
      throw new Error(`transaction failed: ${JSON.stringify(result.value.err)}`);

    // Read the real fill from the confirmed transaction's balance changes in production
    return {
      clientOrderId,
      side,
      price: quoteAmount / expectedOut,
      qty: expectedOut,
      txId: signature,
    };
  }
}
```

Points that matter in production:

- **Always set a slippage limit** in the swap itself, so the transaction fails rather than filling at a bad price.
- **Record the real fill** from the confirmed transaction's balance changes, not the quote.
- **Handle "unknown" outcomes.** If confirmation times out, the transaction may still land. Check its status by signature before retrying, or you can buy twice.
- **Fees.** Add a priority fee when the network is busy, and include it in your cost accounting.

## Step 7: Run the engine loop

The loop ties it together. It persists state after every action, so a restart picks up where it left off, and it uses a deterministic client order ID so a retried signal cannot place a second order.

```ts
// engine.ts
import { evaluate, type Candle } from "./evaluate";
import type { Strategy } from "./strategy";
import type { Broker } from "./broker";
import type { RiskManager } from "./risk";

type State = {
  inPosition: boolean;
  entryPrice: number | null;
  qty: number;
  lastCandle: number;
};

export async function onCandleClosed(
  strategy: Strategy,
  closed: Candle[],
  state: State,
  broker: Broker,
  risk: RiskManager,
  save: (s: State) => Promise<void>,
) {
  const candle = closed[closed.length - 1];
  if (candle.time <= state.lastCandle) return; // already handled this candle

  const signal = evaluate(strategy, closed, state.inPosition, state.entryPrice);
  if (signal) {
    const side = signal === "enter" ? "buy" : "sell";
    const amount = side === "buy" ? strategy.positionSize : state.qty * candle.close;
    const verdict = risk.check({ strategyId: strategy.id, side, quoteAmount: amount });
    if (!verdict.ok) {
      console.warn(`order blocked: ${verdict.reason}`);
    } else {
      const clientOrderId = `${strategy.id}:${candle.time}:${side}`; // same signal => same ID
      const fill = await broker.submit(clientOrderId, side, amount);
      if (side === "buy")
        Object.assign(state, {
          inPosition: true,
          entryPrice: fill.price,
          qty: fill.qty,
        });
      else {
        risk.recordPnl((fill.price - (state.entryPrice ?? fill.price)) * state.qty);
        Object.assign(state, { inPosition: false, entryPrice: null, qty: 0 });
      }
    }
  }
  state.lastCandle = candle.time;
  await save(state);
}
```

## Step 8: Watch it like a production system

Log every signal, every risk decision with its reason, every simulation and every fill. Alert on a halt, on repeated simulation failures, and on any difference between the position the engine thinks it holds and the balance the chain reports. Check that balance on a schedule, and halt if they disagree.

## What we would do

Build the risk manager and the backtester's fill rules first, before adding indicators. Run every strategy through paper trading before live funds. Keep trading keys separate from treasury keys, funded with only what the strategy needs. Most of the work in a reliable engine is in the unhappy paths: failed simulations, unknown outcomes and restarts.

We build trading engines and platforms like this in our [trading platform work](/services/solana-trading-platforms). The event pipeline behind order flow is covered in [building a crypto trading pipeline with Kafka](/blog/crypto-trading-pipeline-kafka).

---

OnChain · 15 Bld. Iuliu Maniu, 061075 Bucharest, Romania · contact@onchain.ro · https://www.onchain.ro
