← All articles

Build an AI crypto trading bot in TypeScript: an LLM step behind risk checks and a Siebly SDK

An AI crypto trading bot, for a developer, is a normal trading bot with a language model inside it. The model reads an instruction such as “rest a small buy on BTC 5% under mid” plus a snapshot of the market, and replies with a proposal in a fixed JSON shape. Plain TypeScript then validates that reply, applies hard risk limits, and only then hands an order to an exchange SDK. The model never holds a key, never picks a raw price or size, and never talks to the exchange.

This guide builds an AI crypto trading bot with that structure in Node.js and TypeScript, on Hyperliquid testnet, using the Siebly Hyperliquid SDK, @siebly/hyperliquid-api. All of the code is in the companion gist: 10 TypeScript files that pass strict tsc and run against the real SDK and live testnet public data. It contains no trading strategy, signals or performance claims; it is the plumbing that keeps a model’s output under control.

What “AI” means in an AI crypto trading bot

The phrase covers two different things, and both are useful:

  • An AI coding agent writes the bot. You describe the bot, the agent writes the code against an SDK, and you review and run it. The model is a development tool and is not present at run time.
  • A model is one step inside the bot. At run time the bot asks a model for a proposal, and deterministic code decides what happens next.

This guide is about the second one, because that is where the design questions are: what the model is allowed to return, what happens when it is slow or wrong, and which code is the final authority before an order is signed. The coding agent section near the end covers the first.

The model’s job here is operational. It turns a plain-English instruction into a structured proposal, or declines with "action": "none". It does not predict prices, and nothing in this guide treats its output as a reason to trade. If you want the model to make market decisions, the same structure still applies: every one of its replies goes through the same validation and limits.

The architecture: provider, validation, risk gate, executor

Each pass of the AI crypto trading bot runs five steps, each in its own file:

Step File What it does Can it send an order?
Snapshot market.ts Reads the mid price and size decimals for each allowed coin from testnet No, public data only
Proposal provider.ts Asks a model provider for a reply, with a timeout No
Validation proposal.ts Checks the reply against a JSON schema by hand No
Risk gate risk.ts Applies the allow-list and limits, and computes price and size No
Executor executor.ts Builds the SDK request, then prints it (dry run) or sends it (testnet) Yes, and only here

Only executor.ts creates a client, and that client always has testnet: true. A reply that fails any earlier step ends the pass with a logged reason and no request. That is the fail-closed rule the rest of the code follows.

If you are planning the bot from scratch, building a safe first crypto trading bot covers the milestones around this structure in more depth: public data first, paper intents, risk state and gated live execution. This guide adds the model-specific layer.

Pick an exchange with a testnet

The worked example uses Hyperliquid because its testnet takes the same signed requests as mainnet, and the SDK switches between them with one option. new RestClient({ testnet: true }) sends REST calls to https://api.hyperliquid-testnet.xyz and signs actions for the testnet chain. Public calls, such as metadata and mid prices, need no wallet at all.

Signed testnet requests need two things from Hyperliquid’s side:

Without a balance, testnet refuses account actions. This is the reply when an unfunded main account calls the SDK’s approveApiWallet():

Must deposit before performing actions. User: 0x538322084862c88dbe56b647e0ad134a2a346f87

For a different venue, choosing a JavaScript crypto exchange SDK compares the options. The structure in this guide does not change. Only market.ts and executor.ts touch the exchange.

Set up the project

The gist is a flat folder. Node.js 22.18 and later run .ts files directly by stripping the types, so there is no build step. TypeScript is only used for npm run typecheck.

npm install @siebly/[email protected]
npm install -D typescript @types/node
cp .env.example .env
{
  "name": "ai-crypto-trading-bot-ts",
  "private": true,
  "type": "module",
  "engines": { "node": ">=22.18" },
  "scripts": {
    "typecheck": "tsc",
    "start": "node --env-file-if-exists=.env main.ts"
  },
  "dependencies": { "@siebly/hyperliquid-api": "1.0.5" },
  "devDependencies": { "@types/node": "^24", "typescript": "^7.0.2" }
}

Configuration comes from environment variables, loaded from .env with Node’s own --env-file-if-exists flag. EXECUTION_MODE accepts DRY_RUN, which is the default, or TESTNET. Any other value stops the process before a client exists, so there is no live mode to switch on by accident:

Error: EXECUTION_MODE must be DRY_RUN or TESTNET, got "LIVE"

The limits sit in the same file: the coin allow-list, a maximum order value in USDC, an allowed distance band from the mid price, a cap on resting orders and the provider timeout. The values in .env.example are placeholders for testnet. Wallet keys are read only in TESTNET mode, and only by executor.ts. API key security best practices covers storing them.

The model step: a provider interface and a JSON schema

The model’s reply has to match one schema. Pass PROPOSAL_JSON_SCHEMA to your model provider as its structured-output or JSON schema setting, if it has one, and still validate the reply yourself. A provider-side schema setting reduces malformed replies, and parseProposal() is what the bot relies on.

// The only shape a model reply may take. Pass this schema to your model
// provider as its structured-output or JSON schema setting.
export const PROPOSAL_JSON_SCHEMA = {
  type: 'object',
  additionalProperties: false,
  required: ['action', 'reason'],
  properties: {
    action: { type: 'string', enum: ['none', 'place_post_only', 'cancel_own'] },
    coin: { type: 'string', description: 'Perp name, for example BTC' },
    side: { type: 'string', enum: ['buy', 'sell'] },
    offsetPct: {
      type: 'number',
      description: 'Distance from the mid price in percent, away from the book',
    },
    notionalUsd: { type: 'number', description: 'Order value in USDC' },
    reason: { type: 'string', maxLength: 200 },
  },
} as const;

export type Proposal =
  | { action: 'none'; reason: string }
  | { action: 'cancel_own'; reason: string }
  | {
      action: 'place_post_only';
      coin: string;
      side: 'buy' | 'sell';
      offsetPct: number;
      notionalUsd: number;
      reason: string;
    };

export type Parsed = { ok: true; proposal: Proposal } | { ok: false; error: string };

const KEYS = new Set(Object.keys(PROPOSAL_JSON_SCHEMA.properties));

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);

// Check a raw model reply (text or parsed JSON) against the schema by hand.
export function parseProposal(raw: unknown): Parsed {
  let value = raw;
  if (typeof raw === 'string') {
    try {
      value = JSON.parse(raw);
    } catch {
      return { ok: false, error: 'reply is not valid JSON' };
    }
  }
  if (!isRecord(value)) return { ok: false, error: 'reply is not a JSON object' };

  const unknownKey = Object.keys(value).find((k) => !KEYS.has(k));
  if (unknownKey) return { ok: false, error: `unexpected field "${unknownKey}"` };

  const { action, reason } = value;
  if (typeof reason !== 'string' || reason.length > 200) {
    return { ok: false, error: 'reason must be a string of up to 200 characters' };
  }
  if (action === 'none' || action === 'cancel_own') return { ok: true, proposal: { action, reason } };
  if (action !== 'place_post_only') return { ok: false, error: `unknown action "${String(action)}"` };

  const { coin, side, offsetPct, notionalUsd } = value;
  if (typeof coin !== 'string' || coin === '') return { ok: false, error: 'coin is required' };
  if (side !== 'buy' && side !== 'sell') return { ok: false, error: 'side must be buy or sell' };
  if (!finite(offsetPct)) return { ok: false, error: 'offsetPct must be a number' };
  if (!finite(notionalUsd)) return { ok: false, error: 'notionalUsd must be a number' };

  return { ok: true, proposal: { action, coin, side, offsetPct, notionalUsd, reason } };
}

Three choices in this schema carry most of the safety:

  • There is no price or size field. The model gives a distance from the mid in percent and an order value, and the risk gate turns those into exchange-valid numbers.
  • additionalProperties: false, enforced by parseProposal(), rejects a reply that adds fields such as price or leverage.
  • "none" is a valid answer, so the model has a correct way to decline an unclear instruction.

Plug in a real model: the provider contract

The bot talks to any model through one interface, ProposalProvider. It receives the instruction, the market snapshot and the schema, and returns the raw reply as text or parsed JSON. getProposal() wraps every call with a timeout and turns every failure into { ok: false }:

import type { Snapshot } from './market.ts';
import { parseProposal, PROPOSAL_JSON_SCHEMA, type Parsed } from './proposal.ts';

export interface ProposalRequest {
  instruction: string;
  snapshot: Snapshot;
  schema: typeof PROPOSAL_JSON_SCHEMA;
}

// Implement this for the model you use. Return the model's reply as text or
// parsed JSON, stop work when `signal` aborts, and never sign or send anything.
export interface ProposalProvider {
  readonly name: string;
  propose(request: ProposalRequest, signal: AbortSignal): Promise<unknown>;
}

// Ask the provider once. A timeout, an error or an invalid reply all come
// back as { ok: false }, and the caller does nothing.
export async function getProposal(
  provider: ProposalProvider,
  request: ProposalRequest,
  timeoutMs: number,
): Promise<Parsed> {
  const controller = new AbortController();
  let timer: NodeJS.Timeout | undefined;
  const timeout = new Promise<never>((_, reject) => {
    timer = setTimeout(() => {
      reject(new Error(`provider timed out after ${timeoutMs} ms`));
      controller.abort();
    }, timeoutMs);
  });
  try {
    const raw = await Promise.race([provider.propose(request, controller.signal), timeout]);
    return parseProposal(raw);
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : String(error) };
  } finally {
    clearTimeout(timer);
  }
}

An implementation for a hosted model follows the same contract:

  • Input. Put the instruction and JSON.stringify(request.snapshot) in the prompt, and pass request.schema as the response schema.
  • Output. Return the reply body as it arrives. Do not repair or reinterpret it; parseProposal() decides.
  • Timeout. Pass signal to the HTTP call so a slow request is cancelled. After PROVIDER_TIMEOUT_MS, the pass ends with no action whether or not the request stops.
  • Errors. Throw on HTTP errors, rate limits or an empty reply. getProposal() catches it and the pass does nothing.
  • Credentials. The model’s API key is separate from the exchange keys, and the provider never sees the exchange keys.

The gist ships StubProvider, a deterministic provider that returns a fixed reply after an optional delay and honours the abort signal. main.ts uses it, so the whole pipeline runs without any model account.

Validate everything the model returns

parseProposal() accepts text or an object, so a provider that returns a JSON string and one that returns parsed JSON both work. Each failure has its own message, and the bot logs it. With PROVIDER_TIMEOUT_MS=500, the stub dry run prints one line per bad reply, against live testnet data. The five replies are one slower than the timeout, one in prose instead of JSON, a provider error, a coin outside the allow-list and an order value over the limit:

no action, provider reply rejected: provider timed out after 500 ms
no action, provider reply rejected: reply is not valid JSON
no action, provider reply rejected: rate limited
no action, risk check failed: DOGE is not on the allow-list
no action, risk check failed: notional 5000 is outside 0 to 20

A provider that answers in prose, throws, takes longer than the timeout or proposes a coin outside the allow-list all end the same way: one log line and no request. The rejection reason is the only part that differs, which keeps the logs useful when you change models or prompts.

Deterministic risk checks before any order

riskGate() is the final authority in an AI crypto trading bot built this way. It takes a validated proposal, the snapshot and the configured limits, and returns either an order intent or a reason:

import { randomBytes } from 'node:crypto';
import type { Limits } from './config.ts';
import type { Snapshot } from './market.ts';
import { roundPerpPrice, toPerpSize } from './prices.ts';
import type { Proposal } from './proposal.ts';

export interface OrderIntent {
  coin: string;
  side: 'buy' | 'sell';
  price: string;
  size: string;
  cloid: string;
}

export type Decision =
  | { ok: true; kind: 'none' }
  | { ok: true; kind: 'cancel_own' }
  | { ok: true; kind: 'place'; order: OrderIntent }
  | { ok: false; reason: string };

// Hyperliquid client order ids are 128-bit hex strings.
export const newCloid = () => '0x' + randomBytes(16).toString('hex');

// Deterministic checks between a proposal and the exchange. The model never
// supplies a price or a size: both are computed here from live market data.
export function riskGate(proposal: Proposal, snapshot: Snapshot, limits: Limits): Decision {
  if (proposal.action === 'none') return { ok: true, kind: 'none' };
  if (proposal.action === 'cancel_own') return { ok: true, kind: 'cancel_own' };

  const { coin, side, offsetPct, notionalUsd } = proposal;
  if (!limits.allowedCoins.includes(coin)) {
    return { ok: false, reason: `${coin} is not on the allow-list` };
  }
  const market = snapshot.markets.find((m) => m.coin === coin);
  if (!market) return { ok: false, reason: `no market data for ${coin}` };
  if (snapshot.ownRestingOrders >= limits.maxRestingOrders) {
    return { ok: false, reason: `already ${snapshot.ownRestingOrders} resting order(s)` };
  }
  if (offsetPct < limits.minOffsetPct || offsetPct > limits.maxOffsetPct) {
    return {
      ok: false,
      reason: `offset ${offsetPct}% is outside ${limits.minOffsetPct}% to ${limits.maxOffsetPct}%`,
    };
  }
  if (notionalUsd <= 0 || notionalUsd > limits.maxNotionalUsd) {
    return { ok: false, reason: `notional ${notionalUsd} is outside 0 to ${limits.maxNotionalUsd}` };
  }

  // Buys go below the mid and sells above it, so a post-only order rests.
  const mid = Number(market.mid);
  const target = side === 'buy' ? mid * (1 - offsetPct / 100) : mid * (1 + offsetPct / 100);
  const price = roundPerpPrice(target, market.szDecimals, side);
  const size = toPerpSize(notionalUsd / Number(price), market.szDecimals);
  if (Number(size) === 0) {
    return { ok: false, reason: `size rounds to zero at ${market.szDecimals} size decimals` };
  }

  return { ok: true, kind: 'place', order: { coin, side, price, size, cloid: newCloid() } };
}

The price comes from the live mid price and the requested distance, rounded to Hyperliquid’s perp rules: at most five significant figures and at most 6 - szDecimals decimal places. Buys round down and sells round up, so rounding only moves an order further from the book. Size is the order value divided by that price, truncated to the coin’s size decimals. Hyperliquid tick size and szDecimals explains those rules in detail.

The resting-order cap counts orders this process placed. A model that repeats the same proposal every pass cannot stack orders, because the second proposal fails with already 1 resting order(s).

The execution layer on the Siebly Hyperliquid SDK

The executor is the only file that signs. It builds one post-only (Alo) limit order with a client order ID, then prints it in dry-run mode or sends it with submitOrder() on testnet:

import { HyperliquidApiError, RestClient, type OrderStatus } from '@siebly/hyperliquid-api';
import type { Config } from './config.ts';
import type { Decision, OrderIntent } from './risk.ts';

// Always testnet. Keys are only read when TESTNET mode needs to sign.
export function createClient(config: Config, env: NodeJS.ProcessEnv = process.env): RestClient {
  if (config.mode === 'DRY_RUN') return new RestClient({ testnet: true });
  const privateKey = env.HYPERLIQUID_API_WALLET_KEY;
  const accountAddress = env.HYPERLIQUID_ACCOUNT_ADDRESS;
  if (!privateKey || !accountAddress) {
    throw new Error('TESTNET mode needs HYPERLIQUID_API_WALLET_KEY and HYPERLIQUID_ACCOUNT_ADDRESS');
  }
  return new RestClient({ testnet: true, privateKey, accountAddress });
}

// One post-only (Alo) limit order with a client order id.
export function toOrderRequest(order: OrderIntent) {
  return {
    grouping: 'na' as const,
    orders: [
      {
        a: order.coin,
        b: order.side === 'buy',
        p: order.price,
        s: order.size,
        r: false,
        t: { limit: { tif: 'Alo' as const } },
        c: order.cloid,
      },
    ],
  };
}

function describe(status: OrderStatus | undefined): string {
  if (!status) return 'no status returned';
  if ('error' in status) return `rejected: ${status.error}`;
  if ('resting' in status) return `resting, oid ${status.resting.oid}`;
  return `filled ${status.filled.totalSz} at ${status.filled.avgPx}`;
}

// Turn an approved decision into SDK calls. `own` holds the cloids this
// process placed, so it only ever cancels its own orders.
export async function execute(
  client: RestClient,
  decision: Decision,
  config: Config,
  own: Map<string, string>,
): Promise<string> {
  if (!decision.ok) return `not executed: ${decision.reason}`;
  if (decision.kind === 'none') return 'nothing to do';
  if (decision.kind === 'cancel_own') return cancelOwn(client, config, own);

  const request = toOrderRequest(decision.order);
  if (config.mode === 'DRY_RUN') return `dry run, not sent: ${JSON.stringify(request)}`;

  try {
    const res = await client.submitOrder(request);
    if (res.status !== 'ok') return `order failed: ${String(res.response)}`;
    const status = res.response.data.statuses[0];
    if (status && 'resting' in status) own.set(decision.order.cloid, decision.order.coin);
    return `order ${decision.order.cloid}: ${describe(status)}`;
  } catch (error) {
    if (error instanceof HyperliquidApiError) return `exchange rejected the order: ${error.message}`;
    throw error;
  }
}

export async function cancelOwn(
  client: RestClient,
  config: Config,
  own: Map<string, string>,
): Promise<string> {
  if (own.size === 0) return 'no own orders to cancel';
  const cancels = [...own].map(([cloid, asset]) => ({ asset, cloid }));
  if (config.mode === 'DRY_RUN') return `dry run, not sent: ${JSON.stringify({ cancels })}`;
  const res = await client.cancelOrdersByClientOrderId({ cancels });
  if (res.status === 'ok') own.clear();
  return `cancel: ${JSON.stringify(res)}`;
}

A post-only order is rejected rather than filled if it would cross the book, which suits a bot whose orders are meant to rest away from the mid. The client order ID is a random 128-bit hex string from the risk gate. The executor records it, so the cancel path only touches orders this process placed. Client order IDs and scheduleCancel covers cancelling by ID and the exchange-side dead man’s switch.

The SDK throws HyperliquidApiError for exchange-level rejections. The executor turns that into a log line and lets anything unexpected propagate to the loop. The SDK error handling guide lists the other error cases.

The loop, the kill switch and cleanup

runOnce() wires the steps together:

import type { RestClient } from '@siebly/hyperliquid-api';
import type { Config } from './config.ts';
import { execute } from './executor.ts';
import { getSnapshot } from './market.ts';
import { PROPOSAL_JSON_SCHEMA } from './proposal.ts';
import { getProposal, type ProposalProvider } from './provider.ts';
import { riskGate } from './risk.ts';

export interface Bot {
  client: RestClient;
  provider: ProposalProvider;
  config: Config;
  own: Map<string, string>;
}

// One pass: read state, ask the model, check the reply, then act or stop.
export async function runOnce(bot: Bot, instruction: string): Promise<string> {
  const { client, provider, config, own } = bot;
  const snapshot = await getSnapshot(client, config.limits.allowedCoins, own.size);

  const parsed = await getProposal(
    provider,
    { instruction, snapshot, schema: PROPOSAL_JSON_SCHEMA },
    config.providerTimeoutMs,
  );
  if (!parsed.ok) return `no action, provider reply rejected: ${parsed.error}`;

  const decision = riskGate(parsed.proposal, snapshot, config.limits);
  if (!decision.ok) return `no action, risk check failed: ${decision.reason}`;

  return execute(client, decision, config, own);
}

main.ts runs it on an interval. Ctrl+C or a file named STOP in the working directory ends the loop, and on the way out it cancels the orders this process placed:

import { existsSync } from 'node:fs';
import { setTimeout as sleep } from 'node:timers/promises';
import { runOnce, type Bot } from './bot.ts';
import { loadConfig } from './config.ts';
import { cancelOwn, createClient } from './executor.ts';
import { StubProvider } from './stub-provider.ts';

const instruction = process.argv.slice(2).join(' ') || 'Rest a small buy on BTC 5% under mid';
const config = loadConfig();

const bot: Bot = {
  client: createClient(config),
  // Replace with your own ProposalProvider implementation.
  provider: new StubProvider({
    action: 'place_post_only',
    coin: 'BTC',
    side: 'buy',
    offsetPct: 5,
    notionalUsd: 15,
    reason: 'stub reply for the instruction',
  }),
  config,
  own: new Map(),
};

// Kill switch: Ctrl+C, or create a file named STOP in the working directory.
const stop = new AbortController();
process.on('SIGINT', () => stop.abort());

console.log(`mode ${config.mode}, testnet, provider ${bot.provider.name}`);
while (!stop.signal.aborted && !existsSync('STOP')) {
  try {
    console.log(await runOnce(bot, instruction));
  } catch (error) {
    console.error('pass failed, nothing sent:', error instanceof Error ? error.message : error);
  }
  if (process.env.BOT_ONCE === '1') break;
  await sleep(config.intervalMs, undefined, { signal: stop.signal }).catch(() => undefined);
}

// On the way out, cancel only the orders this process placed.
console.log(await cancelOwn(bot.client, config, bot.own));

A pass that throws, for example on a network error while reading the snapshot, is logged and skipped. The next pass starts from a fresh snapshot. For a bot that needs state between passes from a stream instead of polling, WebSocket reliability and account state covers reconnects and resynchronising.

Run the AI crypto trading bot end to end with a stub

Versions: @siebly/hyperliquid-api 1.0.5, TypeScript 7.0.2, Node.js 24.22.1.

In DRY_RUN mode, one pass with the stub reply reads testnet, computes a price 5% under the mid and prints the exact request it would send:

mode DRY_RUN, testnet, provider stub
dry run, not sent: {"grouping":"na","orders":[{"a":"BTC","b":true,"p":"56556","s":"0.00026","r":false,"t":{"limit":{"tif":"Alo"}},"c":"0xbfbffbb2802abb208d5d7f6bfc741db1"}]}
no own orders to cancel

In TESTNET mode with a wallet that Hyperliquid does not know, the same pass signs the request, testnet rejects it, and the bot logs the reply:

mode TESTNET, testnet, provider stub
exchange rejected the order: User or API Wallet 0xdccb24c06f3ed774c942687eea53e9734a7b72df does not exist.
no own orders to cancel

With a funded testnet account and an approved API wallet in .env, the same line reports a resting order ID instead, and the exit path cancels it.

npm run typecheck checks every file in strict mode against the SDK’s own type declarations. In DRY_RUN, execute() and cancelOwn() return the printed request before they reach submitOrder() or a cancel.

When you replace the stub with a real provider, keep the stub for dry runs. The five bad replies above show what the bot does when a model misbehaves, and that behaviour must not change when the model does.

Let an AI coding agent build the bot

The other meaning of an AI trading bot is a coding agent writing the code. An agent that builds on a maintained SDK does not have to write request signing, nonces and payload encoding from Hyperliquid’s raw API docs. The Siebly agent skill gives a coding agent those rules in one file: use the official SDK, read keys from the environment only, and keep write modes behind an explicit EXECUTION_MODE. The Siebly guide for AI coding agents has the prompt framework.

Whichever agent you use, ask for the parts in this guide one at a time: the schema and validator, the risk gate, then the executor. Review each part and run it in DRY_RUN before moving on. A dedicated walkthrough of building a Hyperliquid bot with a coding agent is coming.

Before anything goes near mainnet

This code stops at testnet on purpose. Moving any bot beyond it is a separate decision, and the checks below are the minimum to cover first:

  • Add a live mode deliberately, with its own lower limits and a separate key, and keep DRY_RUN as the default.
  • Rotate and expire API wallets. Hyperliquid API wallet expiry and rotation covers the lifecycle.
  • Reconcile open orders from the exchange at start-up instead of trusting in-memory state.
  • Log every proposal, rejection and request, so a model’s behaviour can be reviewed afterwards.
  • Read the SDK’s production guide and orders guide.

The Siebly SDKs, with over 4.8 million npm downloads across 10+ SDKs, cover Hyperliquid, Binance, Bybit, OKX and other exchanges. The Hyperliquid SDK documentation and the Hyperliquid SDK tutorial are the next places to go.

FAQ

Can ChatGPT or Claude trade crypto for me?

A model can only act through code you connect it to. In this structure a model proposes, and your code decides and places the order through an exchange SDK. Which model you use does not change that; any provider that implements ProposalProvider fits.

Is an AI crypto trading bot safe to run?

The model is the least predictable part, so the safety lives elsewhere: schema validation, a deterministic risk gate, a timeout that fails closed, testnet by default and no live mode in the code. None of that makes trading itself safe. It limits what a bad model reply can do.

Do I need Python to build a trading bot?

No. Everything here is TypeScript on Node.js, and the Siebly SDKs work the same from plain JavaScript.

Which crypto exchanges have a testnet?

Hyperliquid has a full testnet, used here. Binance and OKX also have test environments, which their Siebly SDKs reach with a testnet or demoTrading option. Some do not: testing KuCoin orders without a testnet covers one of those.

Why does the model not set the price?

Exchange prices and sizes follow strict precision rules, and a model has no reliable way to apply them. Letting it give a distance from the mid and an order value keeps the numbers that reach the exchange in code you can read and check.