Ninjabot Framework

repository·main·Indexed 23 days ago

https://github.com/rodrigo-brito/ninjabot

A fast cryptocurrency trading bot framework implemented in Go for creating, backtesting, and deploying custom trading strategies in spot and futures markets. It includes a CLI for downloading historical candlestick data from Binance, support for custom exchange implementations via the Exchange interface, and tools for performance reporting and trade return exportation to CSV.

Tokens
1.9K
Snippets
4
Records
14
Agent score
82%

What's inside ninjabot

  1. How to add support for new exchanges

    main
    Ninjabot currently only supports Binance. To add support for a different exchange, you must implement a new struct that satisfies the Exchange interface. Reference the files in the exchange directory for implementation patterns.
  2. Install the Ninjabot CLI

    main

    The Ninjabot CLI is used for downloading historical data. You can install it using go install or download pre-built binaries from the GitHub releases page.

    go install github.com/rodrigo-brito/ninjabot/cmd/ninjabot@latest
  3. Run a Backtesting example

    main

    Ninjabot supports backtesting custom strategies using historical data. You can run the provided backtesting example from the examples directory to see how the framework generates performance reports and plots results.

    go run examples/backtesting/main.go
  4. Download historical candle data via CLI

    main

    Use the ninjabot download command to fetch historical candlestick data for a specific pair and save it to a CSV file.

    Available flags:

    • --pair: The trading pair (e.g., BTCUSDT).
    • --timeframe: The candle timeframe (e.g., 1d).
    • --days: Number of days of historical data to download.
    • --output: The destination file path.
    # Download candles of BTCUSDT to btc.csv file (Last 30 days, timeframe 1D)
    ninjabot download --pair BTCUSDT --timeframe 1d --days 30 --output ./btc.csv
  5. Initialize a new NinjaBot instance

    main

    Use NewBot to create a new instance of the bot. It requires a context.Context, model.Settings, an service.Exchange implementation, and a strategy.Strategy. You can optionally provide configuration Option functions to customize the bot's behavior (e.g., setting up storage, log levels, or notifiers).

    Note: If settings.Telegram.Enabled is true, the bot will automatically attempt to initialize and register a Telegram notifier.

  6. Use Ninjabot trading types and constants

    main

    Ninjabot provides type aliases and exported constants for core trading concepts like order types, side types, and order statuses. These are used to ensure type safety when interacting with the API and defining trading strategies.

    Side Types

    Use SideTypeBuy or SideTypeSell to specify the direction of a trade.

    Order Types

    Supported order types include:

    • OrderTypeLimit: A standard limit order.
    • OrderTypeMarket: A market order.
    • OrderTypeLimitMaker: A limit order specifically intended to be a maker order.
    • OrderTypeStopLoss: A stop loss order.
    • OrderTypeStopLossLimit: A stop loss limit order.
    • OrderTypeTakeProfit: A take profit order.
    • OrderTypeTakeProfitLimit: A take profit limit order.

    Order Status Types

    Track the state of an order using these constants:

    • OrderStatusTypeNew: Order is newly created.
    • OrderStatusTypePartiallyFilled: Order has been partially filled.
    • OrderStatusTypeFilled: Order is completely filled.
    • OrderStatusTypeCanceled: Order was canceled.
    • OrderStatusTypePendingCancel: Order is in the process of being canceled.
    • OrderStatusTypeRejected: Order was rejected.
    • OrderStatusTypeExpired: Order has expired.
  7. Run the NinjaBot

    main

    The Run(ctx context.Context) method starts the bot's lifecycle. It performs the following steps:

    1. Initializes strategy controllers for each pair.
    2. Preloads historical data for the strategy's warmup period.
    3. Starts the order feed, order controller, and any registered notifiers (like Telegram).
    4. Starts the data feed.
    5. Begins processing candles (either via backtestCandles in backtest mode or processCandles in live mode).
  8. Configure NinjaBot using Options

    main

    NewBot accepts variadic Option functions to configure the bot during initialization. Common options include:

    • WithBacktest(wallet *exchange.PaperWallet): Sets the bot to backtest mode and attaches a paper wallet. Required for backtesting environments.
    • WithStorage(storage storage.Storage): Sets a custom storage implementation. If not provided, it defaults to a local file named ninjabot.db.
    • WithLogLevel(level log.Level): Sets the global log level (e.g., log.DebugLevel, log.InfoLevel, etc.).
    • WithNotifier(notifier service.Notifier): Registers a notifier (like email or telegram) to receive order updates.
    • WithCandleSubscription(subscriber CandleSubscriber): Subscribes a struct to the candle feed.
    • WithOrderSubscription(subscriber OrderSubscriber): Subscribes a struct to the order feed.
    • WithPaperWallet(wallet *exchange.PaperWallet): Sets the paper wallet for use in backtesting or live simulation.
  9. Display performance results with Summary()

    main

    The Summary() method prints a comprehensive performance report to stdout. It includes:

    • A table of trades per pair, including Win/Loss counts, Win %, Payoff, Profit Factor, SQN, Profit, and Volume.
    • A histogram of returns.
    • A 95% confidence interval for Return, Payoff, and Profit Factor for each pair.
    • A summary of the paper wallet if one is being used.

    To access the raw data programmatically instead of printing to stdout, use bot.Controller().Results.

  10. Subscribe to Candle and Order updates

    main

    You can implement the CandleSubscriber or OrderSubscriber interfaces to react to market data or order events.

    • CandleSubscriber: Implement OnCandle(model.Candle) to receive candle updates.
    • OrderSubscriber: Implement OnOrder(model.Order) to receive order updates.

    Use SubscribeCandle and SubscribeOrder on the NinjaBot instance to register your subscribers. These subscriptions are applied to all pairs defined in the bot's settings.