A fast cryptocurrency trading bot implemented in Go

Overview

image

tests Go Reference

A fast cryptocurrency bot framework implemented in Go. Ninjabot permits users to create and test custom strategies for spot markets.

⚠️ Caution: Working in progress - It's not production ready 🚧

Installation

go get -u github.com/rodrigo-brito/ninjabot

Examples of Usage

Check example directory:

  • Paper Wallet (Live Simulation)
  • Backtesting
  • Real Account (Binance)

CLI

To download historical data you can download ninjabot CLI from release page

  • Download 30 days: ninjabot download --pair BTCUSDT --timeframe 1d --days 30 --output ./btc.csv

Backtesting Example

  • Backtesting from example directory:
go run example/backtesting/main.go

Output:

[SETUP] Using paper wallet                   
[SETUP] Initial Portfolio = 10000.000000 USDT 
+---------+--------+-----+------+--------+--------+------------+
|  PAIR   | TRADES | WIN | LOSS | % WIN  | PAYOFF |   PROFIT   |
+---------+--------+-----+------+--------+--------+------------+
| ETHUSDT |     19 |   9 |   10 | 47.4 % |  6.975 |  6334.1268 |
| BTCUSDT |     17 |   6 |   11 | 35.3 % |  7.734 |  4803.0181 |
+---------+--------+-----+------+--------+--------+------------+
|   TOTAL |     36 |  15 |   21 | 41.7 % |  7.333 | 11137.1449 |
+---------+--------+-----+------+--------+--------+------------+
--------------
WALLET SUMMARY
--------------
0.000000 ETH
0.000000 BTC
21137.144920 USDT
--------------
START PORTFOLIO =  10000 USDT
FINAL PORTFOLIO =  21137.14492013396 USDT
GROSS PROFIT    =  11137.144920 USDT (111.37%)
MARKET CHANGE   =  396.71%

--------------
Chart available at http://localhost:8080

Plot result:

Roadmap:

  • Live Trading

    • Order Limit, Market, OCO
    • Custom Strategy
    • Stop Orders
  • Backtesting

    • Paper Wallet (Live Trading with fake wallet)
    • Load Feed from CSV
    • Market Orders
    • Limit Orders (WIP #6)
    • OCO Orders (wIP #6)
    • Stop Orders
  • Bot CLI - Utilities to support studies

    • Download
    • Plot (Candles + Orders)
    • Support indicator in plot result

Exchanges:

Currently, we only support Binance exchange. If you want to include support for other exchanges, you need to implement a new struct that implements the interface Exchange. You can check some examples in exchange directory.

Comments
  • Fee Validation on Market orders

    Fee Validation on Market orders

    Trying to understand why taker/maker commission is added to validation for amounts when doing a market sell or buy on Binance

    Lets say I have 10 ETH as balance, if I try to sell 10 ETH with bot currently, validate will fail ErrInsufficientFunds since it adds TakerCommission

    How should I calculate the size to pass to a sell amount? Should I calculate it as 10 / (1 + b.userInfo.TakerCommission)?

    question 
    opened by jafri 8
  • Turtle trading strategy added.

    Turtle trading strategy added.

    What have you changed and why?

    Turtle trading strategy added. (https://www.investopedia.com/articles/trading/08/turtle-trading.asp)

    Related Issues

    Link related issues here.

    opened by gunebakan 7
  • should it be `>=`?

    should it be `>=`?

    this line https://github.com/rodrigo-brito/ninjabot/blob/main/exchange/paperwallet.go#L250

    it seems a bug? when the order is buy, should buy only when order.Price >= candle.Close?

    opened by davidxiao 6
  • Create a template for issues and pull requests

    Create a template for issues and pull requests

    We need a template for issues and pull requests

    How Github template works: https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/manually-creating-a-single-issue-template-for-your-repository

    Examples of issues templates: https://github.com/search?utf8=%E2%9C%93&q=in%3Apath+issue_template.md&type=Code&ref=searchresults

    Examples of PR templates: https://github.com/search?utf8=%E2%9C%93&q=in%3Apath+pull_request_template.md&type=Code&ref=searchresults

    kind/documentation hacktoberfest 
    opened by rodrigo-brito 6
  • Fix backtest  errors; enforce QtyDecimalPrecision

    Fix backtest errors; enforce QtyDecimalPrecision

    For me, when I do

    go run ./examples/backtesting

    I get the following:

    Screenshot 2022-07-12 at 22 22 49

    This seems to be caused by rounding errors in market orders. My fix enforces QtyDecimalPrecision and this gets rid of the errors.

    opened by rene-post 5
  • Fix Heikin-Ashi code  and incorrect test data

    Fix Heikin-Ashi code and incorrect test data

    The Heikin-Ashi implementation should determine High and Low based on the calculated HK open en HK close. When implemented correctly this way the test case fails. Turns out the test data does NOT match the actual data in TradingView when looking at the Heikin-Ashi candles from the start of trading in 2017.

    What have you changed and why?

    Fixed the Heikin-Ashi implementation Entered the correct test data from TradingView, (publicly available information, feel free to verify)

    opened by rene-post 5
  • the queue seems deadlock with latest changes,

    the queue seems deadlock with latest changes,

    With latest code change, the priority queue seems deadlock when tested by running paperwallet example.

    wrapping the below code block in anonymous function works, but not so sure it has other potential issues. https://github.com/rodrigo-brito/ninjabot/blob/main/model/priorityqueue.go#L30-L35

    Reckon it's not necessary to use priority queue at all for the bot? sorry maybe i could be wrong because i have limited knowledge yet. but what I can think of is,

    • the bot doesn't maintain items in the queue, even potentially it's possible to accumulate some, but it's because the downstreams can not handle in time.

    • with above concern, then in most cases, it will be not used as expected because no items in it, or even if there are occasionally, it's no point to maintain the order according to time?

    • probably strategy controller is the place to maintain the queue if needed, but i think candles are maintained from onCandle as below, and it reckon be reliable?

    https://github.com/rodrigo-brito/ninjabot/blob/main/strategy/controller.go#L34

    It'll be great if you can pls share more thoughts :)

    Thanks very much

    kind/bug 
    opened by davidxiao 5
  • code=-2014, API-key format invalid

    code=-2014, API-key format invalid

    Hello,

    I am getting this error

    ERRO[2022-01-23 05:00] <APIError> code=-2014, msg=API-key format invalid. 
    ERRO[2022-01-23 05:00] <APIError> code=-2014, msg=API-key format invalid. 
    ERRO[2022-01-23 09:00] <APIError> code=-2014, msg=API-key format invalid. 
    ERRO[2022-01-23 09:00] <APIError> code=-2014, msg=API-key format invalid. 
    ERRO[2022-01-23 13:00] <APIError> code=-2014, msg=API-key format invalid. 
    ERRO[2022-01-23 13:00] <APIError> code=-2014, msg=API-key format invalid.
    

    I am assuming it is coming from somewhere in here? https://github.com/rodrigo-brito/ninjabot/blob/main/exchange/binance.go

    Any pointers as to why or how to solve this problem are welcome.

    opened by bh90210 5
  • feat(backtesting) include button to export csv

    feat(backtesting) include button to export csv

    What did not work before?

    Include button to export CSV with orders in chart page #53

    What have you changed and why?

    add button for download trading history add new api to get trading history by pair

    This PR has:
    • [x] Been doubled checked by the author
    • [x] Tested for newly introduced bugs
    • [x] Included documentation

    image

    opened by panapol-p 5
  • Include progressbar in dowloading

    Include progressbar in dowloading

    Description

    sometime when I downlaod big data I didnt know it is working or not (no result more than 10 min)

    Relevant Context

    add progress bar to show progress by revise func Download in download.go

    Steps to Solution(s)

    revise download.go and try to download big historical data

    Links to Resources

    progress bar https://github.com/schollz/progressbar

    kind/improvement 
    opened by panapol-p 5
  • small websocket reliabilty improvements.

    small websocket reliabilty improvements.

    https://github.com/rodrigo-brito/ninjabot/blob/67e91b0ba93f7aabbb18f048e85c039e03c1d50e/exchange/binance.go#L470

    setting this to true helps.

    binance.WebsocketKeepalive = true

    func StartListenIn(ccandle chan Candle, cerr chan error, symbol Symbol, period string) error {

    done, _, err := binance.WsKlineServe(string(symbol), period, func(event *binance.WsKlineEvent) {
    	ccandle <- CandleFromWsKline(symbol, event.Kline)
    }, func(err error) {
    	cerr <- err
    })
    
    if err != nil {
    	<-done
    	return err
    }
    return nil
    

    }

    Im using this now:

    func StartListenIn(ccandle chan Candle, cerr chan error, symbol Symbol, period string) error {
    
    	done, _, err := binance.WsKlineServe(string(symbol), period, func(event *binance.WsKlineEvent) {
    		ccandle <- CandleFromWsKline(symbol, event.Kline)
    	}, func(err error) {
    		cerr <- err
    	})
    
    	if err != nil {
    		<-done
    		return err
    	}
    	return nil
    }
    
    
    func (b *Binance) CandlesSubscription(symbol Symbol, period string) (chan Candle, chan error) {
    	ccandle := make(chan Candle)
    	cerr := make(chan error)
    
    	binance.WebsocketKeepalive = true
    
    	go func() {
    		errors := 0
    		for {
    			err := StartListenIn(ccandle, cerr, symbol, period)
    
    			if err != nil {
    				cerr <- err
    				log.Error(err)
    				errors++
    			}
    
    			//lets continue..
    
    			if errors > 10 {
    				break
    				panic(err)
    			}
    		}
    
    		close(cerr)
    		close(ccandle)
    		return
    	}()
    
    	return ccandle, cerr
    }
    
    opened by spreeker 5
  • support more storage type for persist order history

    support more storage type for persist order history

    when we run ninjabot on serverless, cloud container, etc. I think better way if we persist data on external db or external file storage like postgresql , mongodb , s3 , etc. Now, this bot support only file and memory.

    kind/feature 
    opened by panapol-p 0
  • Update orders status with user data stream

    Update orders status with user data stream

    In the discussion https://github.com/rodrigo-brito/ninjabot/discussions/130, @davidxiao suggest to use Binance user stream instead of orders polling.

    When we have orders with status PENDNG, the bot will poll from Binance the order status each second. It can be replaced by a stream that receive updates from Binance.

    We found the logic here: https://github.com/rodrigo-brito/ninjabot/blob/1a3585bedbaf66ba35e9377635877aa688e5a1e0/order/controller.go#L278-L287

    kind/improvement env/core 
    opened by rodrigo-brito 3
  • Merge indictors from strategy and chart module

    Merge indictors from strategy and chart module

    Today, we need to define custom indicators in the Indicator function and also include custom indicators for the chart module. When we need to change a parameter, we have to change in both places. A good improvement is a merge between both parts.

    • When we include an indicator in your strategy, it is automatically include in the chart module.
    • We have to provide an option to hide a given indicator
    • We have to provide an option to include additional indicators besides the ones from strategy
    kind/improvement env/core env/frontend 
    opened by rodrigo-brito 0
  • Extract chart from ninjabot core

    Extract chart from ninjabot core

    We have some issues with the evolution of the Javascript Module. We can use only vanilla JS because it's is compiled in runtime with ES Build.

    A good approach will be an isolated development of Chart Module. Then, we can use complex components with modern libraries such as React / Vue.

    The chart in Ninjabot core will work exactly as it does now. But, it will include only a simple HTML template with an external import.

    kind/improvement env/frontend 
    opened by rodrigo-brito 0
  • Improve `/balance` command performance

    Improve `/balance` command performance

    When we request the balance summary, ninjabot will request the position for each trading pair and report a summary. But in this case, we request the same function multiple times: binance.Account()

    https://github.com/rodrigo-brito/ninjabot/blob/1a3585bedbaf66ba35e9377635877aa688e5a1e0/exchange/binance.go#L444-L455

    A good approach to improve the performance are: Request binance.Account() once and calculate the summary for all pairs in the same time.

    kind/improvement help wanted env/telegram 
    opened by rodrigo-brito 6
Releases(v0.2.2)
Owner
Rodrigo Brito
Rodrigo Brito
The modern cryptocurrency trading bot written in Go.

bbgo A trading bot framework written in Go. The name bbgo comes from the BB8 bot in the Star Wars movie. aka Buy BitCoin Go! Current Status Features E

Yo-An Lin 700 Sep 26, 2022
CryptoPump is a cryptocurrency trading bot that focuses on high speed and flexibility

CryptoPump is a cryptocurrency trading bot that focuses on high speed and flexibility. The algorithms utilize Go Language and WebSockets to react in real-time to market movements based on Bollinger statistical analysis and pre-defined profit margins.

null 56 Sep 25, 2022
A golang implementation of a console-based trading bot for cryptocurrency exchanges

Golang Crypto Trading Bot A golang implementation of a console-based trading bot for cryptocurrency exchanges. Usage Download a release or directly bu

Daniel Leon 6 Jun 4, 2022
Cryptocurrency implemented using the Go programming language

Nomadcoin Making a Cryptocurrency using the Go programming language. Features Mining Transactions Database Backend Wallets REST API HTML Explorer P2P

Nomad Coders 25 Jun 27, 2022
A telegram bot that fetches multiple RSS cryptocurrency news feeds for sentiment analysis

Crypto News Telegram Bot A simple telegram bot that will help you stay updated on your latest crypto news This bot will help you keep track of the lat

Cha 4 Aug 22, 2021
Kelp is a free and open-source trading bot for the Stellar DEX and 100+ centralized exchanges

Kelp Kelp is a free and open-source trading bot for the Stellar universal marketplace and for centralized exchanges such as Binance, Kraken, CoinbaseP

Stellar 925 Sep 23, 2022
BlueBot is an open-source trading bot that can be customized to handle specific investment strategies.

BlueBot Quick Note BlueBot and all mentioned services are free to use, including supported financial APIs. Overview BlueBot is a self-healing trading

Coby Eastwood 18 Sep 7, 2022
Crypto signal trading bot

Crypto-signal-trading-bot Firstly a warning This project has the ability to spen

MoonR 5 Sep 21, 2022
Bot-template - A simple bot template for creating a bot which includes a config, postgresql database

bot-template This is a simple bot template for creating a bot which includes a c

Disgo 2 Sep 9, 2022
Automated Trader (at). Framework for building trading bots.

Automated Trader (at) Purpose: Framework for building automated trading strategies in three steps: Build your own strategy. Verify it with the backtes

Simon Klinkert 55 Sep 12, 2022
Tripwire is trading platform interface

Tripwire A Golang SDK for binance API. All the REST APIs listed in binance API document are implemented, as well as the websocket APIs. For best compa

Workfoxes 0 Nov 28, 2021
A trading robot, that can submit basic orders in an automated fashion.

Source: https://github.com/harunnryd/btrade Issues: https://github.com/harunnryd/btrade/issues Twitter: @harunnryd LinkedIn: @harunnryd btrade is a ro

harun nur rasyid 2 Jan 26, 2022
A bot based on Telegram Bot API written in Golang allows users to download public Instagram photos, videos, and albums without receiving the user's credentials.

InstagramRobot InstagramRobot is a bot based on Telegram Bot API written in Golang that allows users to download public Instagram photos, videos, and

FTC Team 8 Dec 16, 2021
Dlercloud-telegram-bot - A Telegram bot for managing your Dler Cloud account

Dler Cloud Telegram Bot A Telegram bot for managing your Dler Cloud account. Usa

Beta Kuang 1 Dec 30, 2021
Quote-bot - Un bot utilisant l'API Twitter pour tweeter une citation par jour sur la programmation et les mathématiques.

Description Ceci est un simple bot programmé en Golang qui tweet une citation sur la programmation tout les jours. Ce bot est host sur le compte Twitt

Liam Cornu 0 Jan 1, 2022
Discord-bot - A Discord bot with golang

JS discord bots Install Clone repo git clone https://github.com/fu-js/discord-bo

JS Club 4 Aug 2, 2022
Bot - Telegram Music Bot in Go

Telegram Music Bot in Go An example bot using gotgcalls. Setup Install the serve

null 9 Jun 28, 2022
Pro-bot - A telegram bot to play around with the community telegram channels

pro-bot ?? Pro Bot A Telegram Bot to Play Around With The Community Telegram Cha

TechProber 1 Jan 24, 2022
Slack-emoji-bot - This Slack bot will post the newly created custom Slack emojis to the channel of your choice

Slack Emoji Bot This Slack bot will post the newly created custom Slack emojis t

Ryan Hollis 7 Sep 23, 2022