Coder Social home page Coder Social logo

bludnic / opentrader Goto Github PK

View Code? Open in Web Editor NEW
3.0 4.0 2.0 8.83 MB

Open-source crypto trading bot

Home Page: https://opentrader.dev

License: Apache License 2.0

Dockerfile 1.54% JavaScript 3.02% TypeScript 94.02% PLpgSQL 1.19% Shell 0.22%
bot cryptocurrency custom-strategy dca-bot grid-bot rsi-strategy technical-indicators

opentrader's Introduction

OpenTrader logo

GitHub Actions Workflow Status GitHub commit activity Static Badge

OpenTrader is an advanced cryptocurrency trading bot offering high-frequency, cross-exchange arbitrage and event-based strategies, including technical analysis with indicators. Features a user-friendly management UI, robust backtesting capabilities, and support for 100+ exchanges via CCXT.

Strategies:

  • Grid: A grid trading strategy that profits from the price fluctuation of an asset.
  • RSI: A Relative Strength Index (RSI) strategy that buys and sells based on the RSI indicator.
  • DCA: Dollar-Cost Averaging (DCA) strategy that buys an asset at regular intervals.

Supported exchanges: OKX, BYBIT, BINANCE, KRAKEN, COINBASE, GATEIO

Quick start

Requirements

# NodeJS v20 or higher
$ node -v

# `pnpm` must be installed
$ pnpm -v

# Install Turborepo globally
$ pnpm install turbo --global

# Docker (optional)
$ docker -v

Environment variables

The project uses a single .env file in the root directory. Frameworks such as Next.js require the .env file to be located directly in the project directory. To address this, some apps/packages might include a symlink pointing to the root .env file.

  1. Create environment file .env in the root directory
$ cp .env.example .env
  1. Replace the DATABASE_URL if your URL is different from the actual one.

Installation

  1. Install dependencies
$ pnpm install
  1. Build packages
$ turbo run build
  1. Run db migrations
$ turbo run prisma:migrate
  1. Seed the database
$ turbo run prisma:seed

โš ๏ธ Note: Since the packages do not have a dev server, running the build command is mandatory on the first run.

Basic usage

Connect an exchange

Copy the exchanges.sample.json5 file to exchanges.json5 and add your API keys.

Supported exchanges: OKX, BYBIT, BINANCE, KRAKEN, COINBASE, GATEIO

Choose a strategy

Create the strategy configuration file config.json5. We will use the grid strategy as an example.

{
  // 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",
}

Currently supported strategies: grid, rsi

Run a backtest

Command: ./bin/cli.sh backtest <strategy> --from <date> --to <date> -t <timeframe>

Example running a grid strategy on 1h timeframe.

$ bin/cli.sh backtest grid --from 2024-03-01 --to 2024-06-01 -t 1h

To get more accurate results, use a smaller timeframe, e.g. 1m, however, it will take more time to download OHLC data from the exchange.

Live trading

Starting the daemon

Before running live trading, you need to start the daemon:

$ bin/cli.sh up

Now the daemon is ready to listen for incoming commands.

Tip: To run the daemon in the background, use: bin/cli.sh up -d

Running a Live Trading

Command: bin/cli.sh trade <strategy>

Example running a live trading with grid strategy.

$ bin/cli.sh trade grid

To stop the live trading, run bin/cli.sh stop

Stop the daemon

To stop the daemon, run the following command:

$ bin/cli.sh down

UI

The user interface allows managing multiple bots and strategies, viewing backtest results, and monitoring live trading.

UI Preview

Currently, the UI is under development. For early access, please email me at [email protected]

After getting the access, run the following command to pull the UI into monorepo:

$ git submodule update --init

Run frontend app:

$ pnpm i
$ turbo run build
$ turbo run dev

Project structure

๐Ÿชช License

Licensed under the Apache 2.0 License. See the LICENSE file for more information.

opentrader's People

Contributors

bludnic avatar

Stargazers

 avatar Bruno Gomes avatar Hari Om Batra avatar

Watchers

 avatar  avatar  avatar  avatar

opentrader's Issues

Pre-launch checklist

Documentation

  • Project has a LICENSE file with an open source license
  • Project has basic documentation (README, CONTRIBUTING, CODE_OF_CONDUCT)
  • The name is easy to remember, gives some idea of what the project does, and does not conflict with an existing project or infringe on trademarks
  • The issue queue is up-to-date, with issues clearly organized and labeled

Code

  • Project uses consistent code conventions and clear function/method/variable names
  • The code is clearly commented, documenting intentions and edge cases
  • There are no sensitive materials in the revision history, issues, or pull requests (for example, passwords or other non-public information)

Deploy a demo app

Do it after Paper Trading support #38
Disable all real trading features.
Add a banner at the top of the page indicating that this is a DEMO only.
Separate workflow in Github Actions.

Bot strategy run policy

export function* strategy() {
  // ...
}

strategy.runPolicy = {
  // Option 1: Run every hour
  interval: "1h",
  // Option 2: Run every timeframe interval
  candleClosed: (botConfig) => botConfig.timeframe,
  // Option 3: Run on order status change
  orderStatusChangedTo: "filled",
  // Option 3.1: Run on order status change (list of statuses)
  orderStatusChangedTo: ["filled", "partially-filled"],
  // Option 4: On orderbook change (for arb strategies)
  watchOrderBook: true,
  // Option 5: On public trade happened
  watchTrades: true
}

CLI & Telegram bot

Commands

  • opentrader start [strategy]: Start bot
  • opentrader stop: Stop bot
  • opentrader stats: Get bot statistics
  • opentrader orders: Current open orders
  • opentrader history: Closed orders
  • opentrader trades: Get trades
  • opentrader performance: Bot performance
  • opentrader profit: Profit statistics
  • opentrader new [name] [params=JSON]: Create a bot

Fix: Replace `ccxt.loadMarkets()` with the `IExchange.loadMarkets()` wrapper to cache markets across exchange instances

This will probably not work. The second exchange will load markets from the exchange and not the database.

import { exchanges, cache } from '@opentrader/exchanges'
import { PrismaCacheProvider } from '@opentrader/exchanges/server'

cache.setCacheProvider(new PrismaCacheProvider())

const exchange1 = exchanges.OKX()
await exchange1.loadMarkets() // from cache

const exchange2 = exchanges.OKX()
await exchange2.fetchTicker('BTC/USDT') // will call `ccxt.loadMarkets()`

Processing different types of SmartTrades

Currently we have two types of SmartTrades:

type SmartTradeType = "SmartTrade" | "DCA"

Entry and TakeProfit may be Order or Ladder.

type EntryType  = "Order" | "Ladder"
type TakeProfitType = "Order" | "Ladder"

Therefore there are 4 possible varieties of SmartTrade:

Buy Sell
Order Order
Order Ladder
Ladder Order
Ladder Ladder

Need to create a package for processing every type and variety of SmartTrade. The API may be something like this:

SmartTrade

const entity = prisma.smartTrade.findUnique({ where: { id: 1 } })
const smartTrade = new SmartTradeProcessor(entity)

// must cancel all open orders and mark SmartTrade as closed
await smartTrade.cancel() 

// place the entry order (entryType == "Order")
// or the first order of ladder (entryType == "Ladder")
await smartTrade.entry() 

// OR using hooks
// e.g. using WebSockets and receiving events from the exchange
await smartTrade.handleOrderFilled(orderId) // the processor will decide by itself what to do with that event
await smartTrade.handleOrderCanceled(orderId)

// @internal
// place the next entry buy order if needed (entryType === "Ladder")
// place TP sell order if entry buy order was filled (entryType === "Order")
await smartTrade.publishNext()

DCA

const entity = prisma.smartTrade.findUnique({ where: { id: 2 } })
const dca = new DCATradeProcessor(entity)

await dca.cancel() // same as for SmartTrade
await dca.entry() // same as for SmartTrade

// if TP was filled, then mark DCA as completed
// if SO (Safety Order) was filled, then it must update the TP order limit price
// if SL was filled, the mark DCA as completed
await dca.handleOrderFilled(orderId)

// @internal
await dca.updateTakeProfit()

Rewrite the context to support cross exchange strategy

Current context:

type TBotContext<T extends IBotConfiguration> = {
  control: IBotControl;
  config: T;
  command: "start" | "stop" | "process";
  onStart: boolean;
  onStop: boolean;
  onProcess: boolean;
}
  • Add persistent storage ctx.store
  • Split ctx.config into ctx.exchanges and ctx.params (botParams)

Exchanges config sample:

{
  OKX: {
    name: "OKX Account",
    apiKey: "your-api-key",
    secretKey: "your-secret",
    password: "your-password",
  },
  BYBIT: {
    name: "ByBit Account",
    apiKey: "your-api-key",
    secretKey: "your-secret",
  },
  BYBIT2: {
    name: "ByBit Account #2",
    apiKey: "your-api-key",
    secretKey: "your-secret",
  },
}

README: Add shields

  • Telegram link
  • Stars
  • License
  • Commit activity
  • Build: passing
  • Donate
  • Test coverage (maybe)

GridBot: add Console to track the bot running events

Something like this:
image

The bot events may be:

  • START command received
  • Getting the current asset price: $10.25 USDT
  • Executing the bot template: template:GridBot
  • SmartTrade with ref 0 and status Placed/Idle and { buy: 10, sell: 15 } was queued
  • SmartTrade with ref 1 and status Filled/Idle and { buy: 15, sell: 20 } was queued
  • Template execution done with no errors
  • OrderPublisher: Sell Order of SmartTrade with ref 1 was placed on the exchange orderId: abc123
  • OrderPublisher: An error occurred: OKXExchange: { message: "Rate limit exceeded" }

Upgrade ReactQuery to v5

Update dependency @tanstack/react-query from v4 -> v5.
Note: The @trpc/react-query still uses v4 of ReactQuery. Must wait until tRPC will support v5.

Add possibility to control the fetch implementation of CCXT

Need a similar solution as controlling the cache strategy:

import { ExchangeCode } from "@opentrader/types";
import { exchanges, cache } from "@opentrader/exchanges";
import { PrismaCacheProvider } from '@opentrader/exchanges/server'

cache.setCacheProvider(new PrismaCacheProvider());

const exchange = exchanges[ExchangeCode.OKX]();
const markets = await exchange.loadMarkets();

Checklist

  • Implement cache.setFetchImplementation()
  • Test without specifying fetch implementation in browser
  • Test without specifying fetch implementation in any Node.js server (e.g. ExpressJS or NestJS)
  • Test with NextJS fetch cache.setFetchImplementation(fetch)
  • Check if the request are not cached by NextJS (may require to disable the cache)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.