Skip to content

Rewrite of cointrader: a crypto trading bot built from the ground up, with a new design. Currently supports trading any cryptocurrencies on Coinbase Advanced out of the box, and it is designed to be extendable. Refer to my original implementation of cointrader, which supported multiple exchanges.

License

Notifications You must be signed in to change notification settings

scottgl9/cointraderv2

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CoinTraderV2

CoinTraderV2 is a cryptocurrency trading bot designed to automate trading strategies and provide real-time market analysis. This trading bot is built from the ground up from scratch, and is designed to be easily extendable. This README provides an overview of the project structure and descriptions of each subfolder.

Project Structure

The project is organized into the following subfolders:

1. cointrader

This folder contains the source code for the CoinTraderV2 application. It includes all the core functionalities and trading algorithms.

cointrader/account

Manages user accounts and their associated data. This module handles interactions with the exchange (via cointrader/exchange), including fetching and updating account balances, retrieving symbol and asset information, and ensuring accurate precision for trades. It provides methods for accessing and managing account-specific details, such as available balances, held assets, and current prices. The AccountBase class serves as the foundation for implementing account-related functionalities, ensuring secure and efficient management of user accounts within the trading bot.

cointrader/exchange

Contains modules for interacting with various cryptocurrency exchanges. The TraderExchangeBase class serves as the foundation for all exchange-specific implementations. It provides a standardized interface for fetching market data, placing orders, and managing exchange-specific settings. This module ensures that the trading bot can seamlessly connect to and operate with different exchanges by implementing the necessary methods for each exchange's API. This is the only API specific code section, and the other code has zero dependencies on the exchanges' API.

cointrader/common

Includes common utilities and helper functions used throughout the application. This folder contains essential classes and modules such as Kline, Signal, and Strategy, which provide foundational structures and functionalities. The Kline class handles candlestick data representation, Signal class manages the generation and processing of trading signals, and Strategy class defines the framework for implementing trading strategies. Additionally, this folder contains code for logging, configuration management, and other shared functionalities that are utilized across different modules of the application.

cointrader/execute

Responsible for executing trading strategies. This module processes signals generated by the strategies and places buy or sell orders accordingly. It leverages the ExecuteBase class, which provides methods for executing various types of orders, including market, limit, and stop-loss orders. The ExecuteBase class ensures that trades are executed efficiently and accurately by interacting with the exchange through the TraderExchangeBase class and managing order details with the OrderRequest and OrderResult classes.

cointrader/indicators

Implements various technical indicators used in trading strategies. These indicators analyze market data to generate signals for potential trading opportunities.

cointrader/market

Handles market data collection and analysis. It fetches real-time and historical market data from exchanges and processes it for use in trading strategies and indicators.

cointrader/order

Manages order creation, tracking, and management. It ensures that orders are placed correctly and monitors their status until they are filled or canceled.

cointrader/signals

Generates trading signals based on predefined criteria and technical indicators. These signals are used by the execute module to make trading decisions.

All signals are written from scratch, and have minimal dependency on external libraries:

Technical Indicators Descriptions

ADX (Average Directional Index)

Measures the strength of a trend without indicating its direction, helping to identify strong trending conditions.

AO (Awesome Oscillator)

Calculates the difference between two simple moving averages (SMA) to gauge market momentum.

ATR (Average True Range)

Quantifies market volatility by averaging the range of price movement over a specified period.

BB (Bollinger Bands)

Plots bands above and below a moving average to identify volatility and potential reversal zones.

CCI (Commodity Channel Index)

Evaluates price deviations from a moving average to identify overbought or oversold conditions.

CMF (Chaikin Money Flow)

Measures money flow volume to assess buying or selling pressure over a specified period.

ConnorsRSI

A composite indicator that combines RSI, streak length, and magnitude to measure momentum.

Coppock Curve

A long-term momentum indicator designed to identify buying opportunities in markets.

Donchian Channels

Displays the highest high and lowest low over a specified period to track price ranges.

DPO (Detrended Price Oscillator)

Removes long-term trends from price data to focus on short-term cycles.

EMA (Exponential Moving Average)

A moving average that gives more weight to recent prices for faster trend recognition.

EOM (Ease of Movement)

Combines price and volume data to assess the ease with which a price moves in a given direction.

Fibonacci

A tool using retracement and extension levels based on Fibonacci ratios to predict price movements.

Fisher Transform

Transforms prices into a Gaussian normal distribution to identify turning points in price.

Gann Fan

A technical tool using angular lines to identify support and resistance based on time and price.

HeikinAshi

A candlestick charting method that smooths price action for clearer trend visualization.

HULL (Hull Moving Average)

A fast and smooth moving average that reduces lag to improve trend detection.

IchimokuCloud

A comprehensive indicator combining trend, momentum, and support/resistance analysis in one chart.

KAMA (Kaufman’s Adaptive Moving Average)

An adaptive moving average that adjusts to market volatility to smooth trends.

Keltner Channels

Envelopes drawn around an EMA, using ATR to set the width, indicating potential price reversals.

KST (Know Sure Thing)

A momentum oscillator combining multiple smoothed rate-of-change calculations.

KVO (Klinger Volume Oscillator)

Tracks long- and short-term money flow to identify price trends with volume confirmation.

MACD (Moving Average Convergence Divergence)

Tracks the relationship between two EMAs to identify trend direction and momentum.

MarketProfile

A charting technique that displays price distribution over time to identify value areas.

MFI (Money Flow Index)

A volume-weighted RSI that identifies overbought and oversold conditions.

NATR (Normalized Average True Range)

Standardizes the ATR to make it comparable across assets with different price levels.

OBV (On-Balance Volume)

Measures buying and selling pressure by combining price movement with volume.

PPO (Percentage Price Oscillator)

A momentum oscillator similar to MACD but expressed as a percentage.

PriceChannel

Plots the highest high and lowest low over a specified period to highlight price extremes.

PSAR (Parabolic Stop and Reverse)

Identifies potential reversals and provides trailing stop levels during a trend.

PVO (Percentage Volume Oscillator)

Tracks the difference between two volume EMAs as a percentage.

ROC (Rate of Change)

Measures the percentage change in price over a specified period to assess momentum.

RSI (Relative Strength Index)

A momentum oscillator that identifies overbought and oversold levels.

RVI (Relative Vigor Index)

Measures price strength by comparing closing prices to trading ranges.

SAMA (Smoothed Moving Average)

A slower-moving average that emphasizes long-term price trends.

SLOPE

Calculates the slope of a linear regression line over a specified period.

SMA (Simple Moving Average)

An average of prices over a specified period, equally weighted.

SqueezeMomentum

Identifies periods of market contraction and expansion using Bollinger Bands and Keltner Channels.

STOCH (Stochastic Oscillator)

Measures momentum by comparing a closing price to a price range over a period.

SuperSmoother

A smoothing filter that reduces noise in price data for clearer trend detection.

SuperTrend

Plots trend lines based on ATR to identify prevailing trends and reversals.

TRIX (Triple Exponential Moving Average)

Tracks the rate of change of a triple-smoothed EMA to identify trends and momentum.

UlcerIndex

Measures downside risk by quantifying the depth and duration of price declines.

UO (Ultimate Oscillator)

Combines short-, medium-, and long-term momentum to avoid false divergences.

VO (Volume Oscillator)

Tracks the difference between two volume moving averages to identify volume trends.

VolumeProfile

Shows the distribution of traded volume across different price levels over a period.

VPT (Volume Price Trend)

Combines price and volume changes to identify trends and reversals.

VWAP (Volume-Weighted Average Price)

Tracks the average price an asset has traded at, weighted by volume, over a period.

WILLR (Williams %R)

A momentum indicator showing overbought and oversold conditions as a percentage.

WMA (Weighted Moving Average)

A moving average giving more weight to recent prices.

ZLEMA (Zero Lag Exponential Moving Average)

A moving average designed to eliminate lag by adjusting for price smoothing.

ZScore

Measures the number of standard deviations a data point is from the mean.

cointrader/strategies

Contains various trading strategies implemented in the application. Each strategy defines a specific set of rules and conditions for making trading decisions.

cointrader/trade

Handles the overall trading logic, integrating signals, strategies, and order execution. It ensures that the trading process runs smoothly and efficiently.

2. config

This folder holds configuration files required for the application. These files include API keys, database configurations, and other settings.

4. tests

Includes tests to validate that certain aspects of cointrader are working, such as plotting indicators, and simple account testing.

5. tools

Contains tools for live trading and simulated trading (back testing).

7. data

Stores historical market data and other datasets used for backtesting and analysis.

8. logs

Contains log files generated by the application for monitoring and debugging purposes.

Getting Started

To get started with CoinTrader:

git checkout https://github.com/scottgl9/cointraderv2.git
cd cointraderv2

Create a file config.py in the cointrader directory, and add your API information from coinbase:

Update config.py with your API key and secret

CBADV_KEY = "organizations/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
CBADV_SECRET = "-----BEGIN EC PRIVATE KEY-----\nXXXXXXXXXXXXXXXXXXXXXXXXXX-----END EC PRIVATE KEY-----\n"

For creating an API key, you can refer to this site: How to create and set up Coinbase Advanced API key

Run the following to get started trading!

python3 tools/trader_live_klines.py

Before live trading, you can try backtesting (trading simulation) using:

python3 trade_simulate_past_klines_csv.py

Contributing

I welcome contributions! Please reach out to me if you have an questions.

Project Status

This project is a work in progress, but it is definitely functional with Coinbase Advanced. I designed the bot to be extendable to other exchanges, so please reach out if you would like to add support for other exchanges. I primarily use coinbase at present due to restrictions on what exchanges I have access to in my area.

Support

I am an indivual developer who wanted to create a trading bot much better than paid trading bots available (3commas, cryptohopper, etc). If you find value in my trading bot, please consider contributing. Either with helping me improve the bot, or by financial contribution. I also accept crypto donations, and anything would be greatly appreciated since I'm working on this project in my free time.

Below are my personal crypto wallet addresses:

Solana: 4fhZBfHkZDB4G5iJaKQvGMvZhn9TQGFCh6ujFAv6yEXM

Ethereum: 0x477d4FF469581d34738B3d160e81140e36CCF35b

Base: 0x477d4FF469581d34738B3d160e81140e36CCF35b

Polygon: 0x477d4FF469581d34738B3d160e81140e36CCF35b

Features

  • Everything is designed to be modular, and is not dependent on exchange (only cointrader/exchange)
  • Sophisticated execution pipeline, which allows trade execution handling to run in another thread
  • Adaptive strategy which works extremely well for making profit (SignalStrength is currently the best)
  • Supports idea of managing positions, opening and closing positions. Similar concept to the big name crypto bot services
  • Support for automatic recovery from errors from the exchange, either websocket or REST API errors
  • Dynamic stop loss adjustments based on loss strategy
  • Dynamic trade sizing based on trade size strategy
  • Built in historical hourly data from 2019 through 2023, for backtesting and potentially AI model training
  • Fully configurable, with working examples of configuration in the cointrader/config folder

Planned features

  • Add AI based trading approaches
  • Improve upon return of trading bot. Current profit strategy works very well, but can always be improved!
  • Add support for other exchanges

Disclaimer

This program and its contributors are not financial advisers. Use this tool strictly for educational purposes. None of the contributors to this project bear any responsibility for any financial losses you may incur. Exercise caution and always conduct your own thorough research.

We encourage you to start by familiarizing yourself with the foundational principles of traditional asset classes, as they tend to be less volatile. Apply this knowledge in simulated trading environments before risking real capital to achieve your goals.

License

This project is licensed under the GNU Affero General Public License Version 3, 19 November 2007. See the LICENSE file for more details.

The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.

You should have received a copy of the GNU Affero General Public License along with this program. If not, see GNU licenses.

About

Rewrite of cointrader: a crypto trading bot built from the ground up, with a new design. Currently supports trading any cryptocurrencies on Coinbase Advanced out of the box, and it is designed to be extendable. Refer to my original implementation of cointrader, which supported multiple exchanges.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages