Skip to content

Commit

Permalink
Merge pull request #28 from rhettre/feature/RefactorCBSDK
Browse files Browse the repository at this point in the history
Feature/refactor cbsdk
  • Loading branch information
rhettre authored Jul 6, 2024
2 parents a2e921d + 001abfd commit e75cccd
Show file tree
Hide file tree
Showing 44 changed files with 2,052 additions and 148 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@ dist/
venv/
*log.txt
coinbase_advanced_trader/__pycache__/
coinbase_advanced_trader/legacy/__pycache__/
.cache/
.coverage
tests/__pycache__/
.pytest_cache
.vscode/
test.py
promptlib/
promptlib/
*.log
.github/workflows
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
The MIT License (MIT)

Copyright (c) 2023 Rhett Reisman
Copyright (c) 2024 Rhett Reisman

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
123 changes: 71 additions & 52 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,96 +5,115 @@ This is the unofficial Python client for the Coinbase Advanced Trade API. It all
## Features

- Easy-to-use Python wrapper for the Coinbase Advanced Trade API
- Supports the new Coinbase Cloud authentication method
- Built on top of the official [Coinbase Python SDK](https://github.com/coinbase/coinbase-advanced-py) for improved stability
- Supports all endpoints and methods provided by the official API
- Lightweight and efficient wrapper
- Added support for trading strategies covered on the [YouTube channel](https://rhett.blog/youtube)

## Setup

1. Clone this repository or download the source files by running
```bash
pip install coinbase-advancedtrade-python
1. Install the package using pip:
```bash
pip install coinbase-advancedtrade-python
```

2. Set your API key and secret in config.py. To obtain your API key and secret, follow the steps below:
- Log in to your Coinbase account.
- Navigate to API settings.
- Create a new API key with the appropriate permissions.
- Copy the API key and secret to config.py.
2. Obtain your API key and secret from the Coinbase Developer Platform. The new API key format looks like this:
```
API Key: organizations/{org_id}/apiKeys/{key_id}
API Secret: -----BEGIN EC PRIVATE KEY-----\n...\n-----END EC PRIVATE KEY-----\n
```

## Authentication
Here's an example of how to authenticate:

````python
from coinbase_advanced_trader.config import set_api_credentials
Here's an example of how to authenticate using the new method:

# Set your API key and secret
API_KEY = "ABCD1234"
API_SECRET = "XYZ9876"
```python
from coinbase_advanced_trader.enhanced_rest_client import EnhancedRESTClient

# Set the API credentials once, and it updates the CBAuth singleton instance
set_api_credentials(API_KEY, API_SECRET)
````
api_key = "organizations/{org_id}/apiKeys/{key_id}"
api_secret = "-----BEGIN EC PRIVATE KEY-----\n...\n-----END EC PRIVATE KEY-----\n"

client = EnhancedRESTClient(api_key=api_key, api_secret=api_secret)
```

## Usage of Strategies

Here's an example of how to use the strategies package to buy $20 worth of Bitcoin:
Here's an example of how to use the strategies package to buy $10 worth of Bitcoin:

```python
from coinbase_advanced_trader.enhanced_rest_client import EnhancedRESTClient

````python
from coinbase_advanced_trader.strategies.limit_order_strategies import fiat_limit_buy
client = EnhancedRESTClient(api_key=api_key, api_secret=api_secret)

# Define the trading parameters
product_id = "BTC-USD" # Replace with your desired trading pair
usd_size = 20 # Replace with your desired USD amount to spend``
# Perform a market buy
client.fiat_market_buy("BTC-USDC", "10")

# Perform a limit buy
limit_buy_order = fiat_limit_buy(product_id, usd_size)
````
client.fiat_limit_buy("BTC-USDC", "10")
```

## Usage of Fear and Greed Index
````python
from coinbase_advanced_trader.strategies.fear_and_greed_strategies import trade_based_on_fgi_simple

# Define the product id
product_id = "BTC-USD"
```python
from coinbase_advanced_trader.enhanced_rest_client import EnhancedRESTClient

client = EnhancedRESTClient(api_key=api_key, api_secret=api_secret)

# Implement the strategy
trade_based_on_fgi_simple(product_id, 10)
# Trade based on Fear and Greed Index
client.trade_based_on_fgi("BTC-USDC", "10")
```

````
## Advanced Usage

## Usage of Fear and Greed Index (Pro)
````python
from coinbase_advanced_trader.strategies.fear_and_greed_strategies import trade_based_on_fgi_pro
You can also update and retrieve the Fear and Greed Index schedule:

# Define the product id
product_id = "BTC-USD"
```python
# Get current FGI schedule
current_schedule = client.get_fgi_schedule()

# Define the custom schedule
custom_schedule = [
{"threshold": 20, "factor": 1, "action": "buy"},
{"threshold": 80, "factor": 0.5, "action": "buy"},
{"threshold": 100, "factor": 1, "action": "sell"},
# Update FGI schedule
new_schedule = [
{'threshold': 15, 'factor': 1.2, 'action': 'buy'},
{'threshold': 37, 'factor': 1.0, 'action': 'buy'},
{'threshold': 35, 'factor': 0.8, 'action': 'sell'},
{'threshold': 45, 'factor': 0.6, 'action': 'sell'}
]
client.update_fgi_schedule(new_schedule)
```

## Legacy Support

The legacy authentication method is still supported but moved to a separate module. It will not receive the latest updates from the Coinbase SDK. To use the legacy method:

```python
from coinbase_advanced_trader.legacy.legacy_config import set_api_credentials
from coinbase_advanced_trader.legacy.strategies.limit_order_strategies import fiat_limit_buy

# Implement the strategy
response = trade_based_on_fgi_pro(product_id, 10, custom_schedule)
````
legacy_key = "your_legacy_key"
legacy_secret = "your_legacy_secret"

set_api_credentials(legacy_key, legacy_secret)

# Use legacy functions
limit_buy_order = fiat_limit_buy("BTC-USDC", 10)
```

## Documentation

For more information about the Coinbase Advanced Trader API, consult the [official API documentation](https://docs.cloud.coinbase.com/advanced-trade-api/docs/rest-api-overview/).

## License
This project is licensed under the MIT License. See the LICENSE file for more information.

This project is licensed under the MIT License. See the LICENSE file for more information.

## Author
Rhett Reisman

Email: [email protected]
Rhett Reisman

GitHub: https://github.com/rhettre/coinbase-advancedtrade-python
Email: [email protected]

## Disclaimer
GitHub: https://github.com/rhettre/coinbase-advancedtrade-python

This project is not affiliated with, maintained, or endorsed by Coinbase. Use this software at your own risk. Trading cryptocurrencies carries a risk of financial loss. The developers of this software are not responsible for any financial losses or damages incurred while using this software. Nothing in this software should be seen as an inducement to trade with a particular strategy or as financial advice.
## Disclaimer

This project is not affiliated with, maintained, or endorsed by Coinbase. Use this software at your own risk. Trading cryptocurrencies carries a risk of financial loss. The developers of this software are not responsible for any financial losses or damages incurred while using this software. Nothing in this software should be seen as an inducement to trade with a particular strategy or as financial advice.
1 change: 0 additions & 1 deletion coinbase_advanced_trader/.gitignore

This file was deleted.

103 changes: 51 additions & 52 deletions coinbase_advanced_trader/config.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,51 @@
import os
from coinbase_advanced_trader.cb_auth import CBAuth

API_KEY = None
API_SECRET = None

# Default price multipliers for limit orders
BUY_PRICE_MULTIPLIER = 0.995
SELL_PRICE_MULTIPLIER = 1.005

# Default schedule for the trade_based_on_fgi_simple function
SIMPLE_SCHEDULE = [
{'threshold': 20, 'factor': 1.2, 'action': 'buy'},
{'threshold': 80, 'factor': 0.8, 'action': 'sell'}
]

# Default schedule for the trade_based_on_fgi_pro function
PRO_SCHEDULE = [
{'threshold': 10, 'factor': 1.5, 'action': 'buy'},
{'threshold': 20, 'factor': 1.3, 'action': 'buy'},
{'threshold': 30, 'factor': 1.1, 'action': 'buy'},
{'threshold': 70, 'factor': 0.9, 'action': 'sell'},
{'threshold': 80, 'factor': 0.7, 'action': 'sell'},
{'threshold': 90, 'factor': 0.5, 'action': 'sell'}
]


def set_api_credentials(api_key=None, api_secret=None):
global API_KEY
global API_SECRET

# Option 1: Use provided arguments
if api_key and api_secret:
API_KEY = api_key
API_SECRET = api_secret

# Option 2: Use environment variables
elif 'COINBASE_API_KEY' in os.environ and 'COINBASE_API_SECRET' in os.environ:
API_KEY = os.environ['COINBASE_API_KEY']
API_SECRET = os.environ['COINBASE_API_SECRET']

# Option 3: Load from a separate file (e.g., keys.txt)
else:
try:
with open('keys.txt', 'r') as f:
API_KEY = f.readline().strip()
API_SECRET = f.readline().strip()
except FileNotFoundError:
print("Error: API keys not found. Please set your API keys.")

# Update the CBAuth singleton instance with the new credentials
CBAuth().set_credentials(API_KEY, API_SECRET)
"""Configuration management for Coinbase Advanced Trader."""

import logging
from pathlib import Path

import yaml

from coinbase_advanced_trader.constants import DEFAULT_CONFIG


class ConfigManager:
"""Singleton class for managing application configuration."""

_instance = None

def __new__(cls):
"""Create a new instance if one doesn't exist, otherwise return the existing instance."""
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.initialize()
return cls._instance

def initialize(self):
"""Initialize the ConfigManager with default configuration and user overrides."""
self.config_path = Path('config.yaml')
self.config = self._load_config()

def _load_config(self):
"""Load configuration from file, falling back to defaults if necessary."""
config = DEFAULT_CONFIG.copy()
if self.config_path.exists():
try:
with open(self.config_path, 'r') as f:
user_config = yaml.safe_load(f)
if user_config:
config.update(user_config)
except Exception as e:
logging.error(f"Error loading user config: {e}")
return config

def get(self, key, default=None):
"""Retrieve a configuration value by key, with an optional default."""
return self.config.get(key, default)

@classmethod
def reset(cls):
"""Reset the singleton instance."""
cls._instance = None


config_manager = ConfigManager()
10 changes: 10 additions & 0 deletions coinbase_advanced_trader/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""Constants and default configuration for the Coinbase Advanced Trader."""

DEFAULT_CONFIG = {
'BUY_PRICE_MULTIPLIER': 0.9995,
'SELL_PRICE_MULTIPLIER': 1.005,
'FEAR_AND_GREED_API_URL': 'https://api.alternative.me/fng/?limit=1',
'LOG_FILE_PATH': 'coinbase_advanced_trader.log',
'LOG_LEVEL': 'DEBUG',
'FGI_CACHE_DURATION': 3600
}
Loading

0 comments on commit e75cccd

Please sign in to comment.