All articles
Risk·December 20, 2025·4 min read

Best Open-Source Risk Management Libraries for Solana Trading Bots

From position sizing utilities to on-chain transaction simulation, a handful of battle-tested libraries handle the heavy lifting so you are not reinventing drawdown math. We review the top options compatible with Anchor and raw Solana web3.js.

Running a Solana trading bot without a dedicated risk layer is how you blow up an account on a Sunday morning when latency spikes and a validator stalls. The good news is that several open-source projects have absorbed the hard lessons already — proper Kelly sizing, simulation-before-submit, and circuit breaker patterns — so you can integrate rather than rebuild. Here is what is worth using and how each one actually fits into a production system.

@solana/spl-token and Raw Balance Guards

Before reaching for anything exotic, the most reliable position-size check is a synchronous read of your on-chain token balance before every order. The official @solana/spl-token library exposes getAccount and getMint, which together give you the decimal-adjusted balance and supply in one round trip. The pattern is straightforward: fetch balance, apply your maximum-notional-per-trade constant, and gate the transaction behind a hard if before you build the instruction. No external dependency needed, no oracle trust assumption. Where this breaks down is latency — if your polling interval is 400ms and the market moves 2% in 80ms, the stale balance check is fiction. Pair it with a local in-memory ledger that tracks pending instructions that have been submitted but not yet confirmed.

marginfi-client-v2 for Borrow-Side Exposure

If your strategy involves any leverage — borrowing USDC on MarginFi to go long a token — their TypeScript client (@mrgnlabs/marginfi-client-v2) exposes a MarginfiAccount.computeHealthComponents method that returns assets, liabilities, and a derived health factor as BigNumber values. You can call this in a pre-flight loop before submitting. The interesting part is that computeHealthComponents uses the same oracle prices as the protocol itself (Pyth by default), so your risk check and the protocol's liquidation trigger are using identical inputs. The practical threshold to enforce is a health factor above 1.25 before entry; anything tighter and a single Pyth update can push you into liquidation territory during the same block your transaction lands.

simulate-transaction via Solana's simulateTransaction RPC

This is the one most bot developers skip and later regret. The Solana JSON-RPC simulateTransaction endpoint runs your transaction against a recent blockhash and returns the resulting account diffs, logs, and compute-unit consumption — without broadcasting. The @solana/web3.js Connection.simulateTransaction wrapper makes this a single awaited call. Use it to:

  • Verify that a swap instruction will not exceed your max-slippage parameter before it goes on-chain
  • Catch 0x1 custom program errors (typically insufficient funds or bad account state) before they burn priority fees
  • Read the simulated post-trade balance and compare it against your drawdown floor

The tradeoff is an extra 50-120ms of latency per trade. For strategies executing at human timescales (seconds, not milliseconds) this is free money. For HFT-adjacent work on Solana you will need to pipeline the simulation against a dedicated RPC node and accept that some slippage checks only happen on a sampled basis.

@coral-xyz/anchor for CPI-Safe Instruction Validation

Anchor's client-side IDL parsing gives you typed instruction builders that reject malformed accounts at construction time rather than at runtime. The relevant pattern for risk is using program.methods.<instruction>().accounts({...}).simulate() — Anchor wraps the same RPC simulation call but also runs its own account constraint checks against the IDL. For any bot that uses Anchor-based protocols (Drift, Jupiter aggregator routing, Kamino) this is the correct integration path. Beyond simulation, Anchor's BN arithmetic and its toBuffer helpers are useful for building slippage tolerances as basis-point integers rather than floating-point percentages, which avoids the precision loss that bites you at large notional sizes.

technicalindicators for In-Process ATR-Based Sizing

Position sizing keyed off volatility requires computing Average True Range or a similar measure in-process. The technicalindicators npm package (no native dependencies, pure TypeScript) provides ATR.calculate({period, high, low, close}) and returns an array of values you can consume directly. The standard production pattern is to maintain a rolling OHLCV buffer — 50-100 candles at your strategy's resolution — and recompute ATR on each new close. Your position size is then (account_equity * risk_fraction) / (ATR_value * contract_size). Set risk_fraction between 0.005 and 0.01 per trade to keep individual loss bounded at 0.5-1% of equity. This math is not exotic, but having it in a tested, versioned package means it is covered by the library's unit tests, not just yours.

p-limit for Concurrent RPC Request Throttling

This is unglamorous but operationally critical. When a bot fans out to check multiple position states simultaneously it is trivial to hit the default RPC rate limit (typically 100 requests/10s on public endpoints, lower on congested validators). p-limit from Sindre Sorhus lets you wrap every RPC call in a concurrency-limited queue with a single line. Set the concurrency to 5-10 for a dedicated private RPC node. The risk angle is that rate-limit errors are silent if you do not handle them explicitly — your balance check silently fails, you proceed with stale data, and the position-sizing logic runs on fiction. Wrapping RPC calls in p-limit and surfacing 429 responses as hard circuit breakers is one of those changes that looks trivial in code review and prevents a real incident.


If you want these components wired together in a production architecture rather than assembled piecemeal, get in touch — our team has deployed this stack across live Solana strategies and can accelerate your path from prototype to running capital.

Need a bot like this built?

We design, build and run trading bots on Solana, Hyperliquid and Polymarket.

Start a project
#risk#solana#open-source#trading-bots#anchor#web3js#position-sizing#drawdown