OpenTrader Documentation

repository·dev·Indexed 25 days ago

https://github.com/open-trader/opentrader

A self-hosted cryptocurrency trading bot supporting high-frequency and cross-exchange trading. OpenTrader includes built-in strategies (Grid, DCA, RSI), backtesting capabilities, and a web-based UI. It provides a modular architecture with packages for exchange integration (@opentrader/exchanges), database management (@opentrader/db), and tRPC API integration for Next.js and Nest.js applications. Supported exchanges include OKX, BYBIT, BINANCE, KRAKEN, COINBASE, GATEIO, and BITGET.

Tokens
21.8K
Snippets
30
Records
165
Agent score
81%

What's inside OpenTrader

  1. Use predefined TSConfigs from @opentrader/tsconfig

    dev

    The @opentrader/tsconfig package provides several base configurations to ensure consistent TypeScript settings across the project. You can inherit from these files depending on your environment:

    • base.json: The foundational configuration used as a base for all other configs.
    • module.json: A common configuration designed for every package located in the /packages directory.
    • nextjs.json: Optimized configuration for Next.js applications.
    • nestjs.json: Optimized configuration for Nest.js applications.
  2. Setup tRPC Backend with Next.js

    dev

    To integrate the @opentrader/trpc router into a Next.js application, create a route handler at src/app/api/trpc/[trpc]/route.ts. Use the fetchRequestHandler from @trpc/server/adapters/fetch to handle requests, passing in the appRouter and a createContext function.

    // src/app/api/trpc/[trpc]/route.ts
    import { appRouter, createContext } from "@opentrader/trpc";
    import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
    
    const handler = (req: Request) =>
      fetchRequestHandler({
        endpoint: "/api/trpc",
        req,
        router: appRouter,
        createContext: () => ({
          //...
        }),
      });
    
    export { handler as GET, handler as POST };
  3. Use @opentrader/exchanges on the Server

    dev

    To use the exchanges package in a server-side environment (e.g., Next.js Server Components), you should configure a persistent cache provider using PrismaCacheProvider from @opentrader/exchanges/server. This ensures that data like markets loaded via exchange.loadMarkets() are cached in your database.

    import { ExchangeCode } from "@opentrader/types";
    import { exchanges, cache } from "@opentrader/exchanges";
    import { PrismaCacheProvider } from "@opentrader/exchanges/server";
    
    // Configure the cache provider to use Prisma
    cache.setCacheProvider(new PrismaCacheProvider());
    
    export default async function Page() {
      // Access a specific exchange using its ExchangeCode
      const exchange = exchanges[ExchangeCode.OKX]();
      
      // Load markets (this call will be cached in Prisma)
      const markets = await exchange.loadMarkets(); 
    
      return <div>Markets: {Object.keys(markets).length}</div>;
    }
  4. Setup tRPC Backend with Nest.js

    dev

    To use @opentrader/trpc in a Nest.js application, create a middleware class that uses @trpc/server/adapters/express to mount the appRouter at the /api/trpc endpoint. Then, inject and apply this middleware in your application's bootstrap function.

    // src/trpc.middleware.ts
    import { INestApplication, Injectable } from "@nestjs/common";
    import * as trpcExpress from "@trpc/server/adapters/express";
    
    import { appRouter } from "@opentrader/trpc";
    
    @Injectable()
    export class TrpcMiddleware {
      applyMiddleware(app: INestApplication) {
        app.use(
          `/api/trpc`,
          trpcExpress.createExpressMiddleware({
            router: appRouter,
            createContext: () => ({
              // ...
            }),
          }),
        );
      }
    }
    
    // main.ts
    import { TrpcMiddleware } from "src/trpc.middleware";
    
    async function bootstrap() {
      // ...
      const trpc = app.get(TrpcMiddleware);
      trpc.applyMiddleware(app);
      // ...
    }
    bootstrap();
  5. Use @opentrader/exchanges on the Client

    dev

    When using the exchanges package in a client-side environment (e.g., React Client Components), you can use MemoryCacheProvider from @opentrader/exchanges/client to manage caching in memory. Note that MemoryCacheProvider is used by default, so explicitly setting it is optional.

    "use client";
    
    import { useEffect, useState } from "react";
    import { ExchangeCode } from "@opentrader/types";
    import { exchanges, cache } from "@opentrader/exchanges";
    import { MemoryCacheProvider } from "@opentrader/exchanges/client";
    
    // Configure memory cache (optional, as it is the default)
    cache.setCacheProvider(new MemoryCacheProvider());
    
    const exchange = exchanges[ExchangeCode.OKX]();
    
    export default function Page() {
      const [markets, setMarkets] = useState<Awaited<
        ReturnType<typeof exchange.loadMarkets>
      > | null>(null);
    
      useEffect(() => {
        exchange.loadMarkets().then((data) => {
          setMarkets(data);
        });
      }, []);
    
      if (markets === null) {
        return <div>Loading...</div>;
      }
    
      return <div>Markets: {Object.keys(markets).length}</div>;
    }
  6. Install and set up OpenTrader

    dev

    OpenTrader requires Node.js v22 or higher.

    1. Install the package globally via npm:
    npm install -g opentrader
    1. Set an admin password for the UI:
    opentrader set-password <password>
    1. Start the application:
    opentrader up

    The app starts an RPC server on port 8000. To run the app as a daemon, use opentrader up -d. To stop the application, use opentrader down.

    npm install -g opentrader
    opentrader set-password <password>
    opentrader up
  7. Configure a strategy with config.json5

    dev

    Create a config.json5 file to define your strategy parameters. Below is an example configuration for the grid strategy.

    {
      // Grid strategy params
      settings: {
        highPrice: 70000, // upper price of the grid
        lowPrice: 60000, // lower price of the grid
        gridLevels: 20, // number of grid levels
        quantityPerGrid: 0.0001, // quantity in base currency per each grid
      },
      pair: "BTC/USDT",
      exchange: "DEFAULT",
    }