coinbase-advancedtrade-python


Namecoinbase-advancedtrade-python JSON
Version 0.3.2 PyPI version JSON
download
home_pagehttps://github.com/rhettre/coinbase-advancedtrade-python
SummaryThe unofficial Python client for the Coinbase Advanced Trade API
upload_time2024-10-13 16:32:53
maintainerNone
docs_urlNone
authorRhett Reisman
requires_python>=3.9
licenseMIT
keywords gdax gdax-api cbpro cbpro-api orderbook trade bitcoin ethereum btc eth client api wrapper exchange crypto currency trading trading-api coinbase advanced-trade prime coinbaseadvancedtrade coinbase-advanced-trade fear-and-greed-index
VCS
bugtrack_url
requirements coinbase-advanced-py requests urllib3 PyYAML cryptography cffi alphasquared-py
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Coinbase Advanced Trade API Python Client

This is the unofficial Python client for the Coinbase Advanced Trade API. It allows users to interact with the API to manage their cryptocurrency trading activities on the Coinbase platform.

## 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
- Added support for trading strategies covered on the [YouTube channel](https://rhett.blog/youtube)

## Setup

1. Install the package using pip:
   ```bash
   pip install coinbase-advancedtrade-python
   ```

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 using the new method:

```python
from coinbase_advanced_trader.enhanced_rest_client import EnhancedRESTClient

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)
```

## Using the Official SDK

The `EnhancedRESTClient` inherits from the Coinbase SDK's `RESTClient`, which means you can use all the functions provided by the official SDK. Here's an example of how to use the `get_product` function:

```python
product_info = client.get_product(product_id="BTC-USDC")

print(product_info)
```

## Using Wrapper Strategies

Here's an example of how to use the strategies package to buy $10 worth of Bitcoin. By making assumptions about limit price in [trading_config.py](coinbase_advanced_trader/trading_config.py) we are able to simplify the syntax for making orders:

```python
# Perform a market buy
client.fiat_market_buy("BTC-USDC", "10")

#Place a $10 buy order for BTC-USD near the current spot price of BTC-USDC
client.fiat_limit_buy("BTC-USDC", "10")

#Place a $10 buy order for BTC-USD at a limit price of $10,000
client.fiat_limit_buy("BTC-USDC", "10", "10000")

#Place a $10 buy order for BTC-USD at a 10% discount from the current spot price of BTC-USDC
client.fiat_limit_buy("BTC-USDC", "10", price_multiplier=".90")

#Place a $10 sell order for BTC-USD at a limit price of $100,000
client.fiat_limit_sell("BTC-USDC", "10", "100000")

#Place a $10 sell order for BTC-USD near the current spot price of BTC-USDC
client.fiat_limit_sell("BTC-USDC", "5")

#Place a $10 sell order for BTC-USD at a 10% premium to the current spot price of BTC-USDC
client.fiat_limit_sell("BTC-USDC", "5", price_multiplier="1.1")
```

### Account Balance Operations

The `EnhancedRESTClient` provides methods to retrieve account balances for cryptocurrencies. These methods are particularly useful for managing and monitoring your cryptocurrency holdings on Coinbase.

#### Listing All Non-Zero Crypto Balances

To get a dictionary of all cryptocurrencies with non-zero balances in your account:

```python
balances = client.list_held_crypto_balances()
print(balances)
```

#### Getting a Specific Crypto Balance

To get the available balance of a specific cryptocurrency in your account (returns 0 if the specified cryptocurrency is not found in the account):

```python
balance = client.get_crypto_balance("BTC")
print(balance)
```

Note: Both methods use a caching mechanism to reduce API calls. The account data is cached for one hour before a fresh fetch is made from Coinbase.

### Usage of Fear and Greed Index

```python
# Trade based on Fear and Greed Index
client.trade_based_on_fgi("BTC-USDC", "10")
```

You can also update and retrieve the Fear and Greed Index schedule:

```python
# Get current FGI schedule
current_schedule = client.get_fgi_schedule()

# 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)
```

## AlphaSquared Integration

This client now includes integration with AlphaSquared, allowing you to execute trading strategies based on AlphaSquared's risk analysis.

### Setup

1. Obtain your AlphaSquared API key from [AlphaSquared](https://alphasquared.io/).

2. Initialize the AlphaSquared client along with the Coinbase client:

```python
from coinbase_advanced_trader import EnhancedRESTClient, AlphaSquaredTrader
from alphasquared import AlphaSquared

# Initialize Coinbase client
coinbase_api_key = "YOUR_COINBASE_API_KEY"

coinbase_api_secret = "YOUR_COINBASE_API_SECRET"

coinbase_client = EnhancedRESTClient(api_key=coinbase_api_key, api_secret=coinbase_api_secret)

# Initialize AlphaSquared client
alphasquared_api_key = "YOUR_ALPHASQUARED_API_KEY"

alphasquared_client = AlphaSquared(alphasquared_api_key, cache_ttl=60)

# Create AlphaSquaredTrader
trader = AlphaSquaredTrader(coinbase_client, alphasquared_client)
```

### Executing AlphaSquared Strategies

To execute a trading strategy based on AlphaSquared's risk analysis:

```python
# Set trading parameters
product_id = "BTC-USDC"

# Your custom strategy name from AlphaSquared
strategy_name = "My Custom Strategy"

# Execute strategy
trader.execute_strategy(product_id, strategy_name)
```

This will:
1. Fetch the current risk level for the specified asset from AlphaSquared.
2. Determine the appropriate action (buy/sell) and value based on the custom strategy defined in AlphaSquared and the current risk.
3. Execute the appropriate trade on Coinbase if the conditions are met.

> **Note:** Make sure to handle exceptions and implement proper logging in your production code. This integration only works with custom strategies; it does not work with the default strategies provided by AlphaSquared.

### Customizing Strategies

You can create custom strategies by modifying the `execute_strategy` method in the `AlphaSquaredTrader` class. This allows you to define specific trading logic based on the risk levels provided by AlphaSquared.

## 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

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.

## Author

Rhett Reisman

Email: rhett@rhett.blog

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

## 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.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/rhettre/coinbase-advancedtrade-python",
    "name": "coinbase-advancedtrade-python",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "gdax, gdax-api, cbpro, cbpro-api, orderbook, trade, bitcoin, ethereum, BTC, ETH, client, api, wrapper, exchange, crypto, currency, trading, trading-api, coinbase, advanced-trade, prime, coinbaseadvancedtrade, coinbase-advanced-trade, fear-and-greed-index",
    "author": "Rhett Reisman",
    "author_email": "rhett@rhett.blog",
    "download_url": "https://files.pythonhosted.org/packages/a0/72/274d3777273482574703e53227f8cffe6692ecb875889c227de9c48fddae/coinbase_advancedtrade_python-0.3.2.tar.gz",
    "platform": null,
    "description": "# Coinbase Advanced Trade API Python Client\n\nThis is the unofficial Python client for the Coinbase Advanced Trade API. It allows users to interact with the API to manage their cryptocurrency trading activities on the Coinbase platform.\n\n## Features\n\n- Easy-to-use Python wrapper for the Coinbase Advanced Trade API\n- Supports the new Coinbase Cloud authentication method\n- Built on top of the official [Coinbase Python SDK](https://github.com/coinbase/coinbase-advanced-py) for improved stability\n- Supports all endpoints and methods provided by the official API\n- Added support for trading strategies covered on the [YouTube channel](https://rhett.blog/youtube)\n\n## Setup\n\n1. Install the package using pip:\n   ```bash\n   pip install coinbase-advancedtrade-python\n   ```\n\n2. Obtain your API key and secret from the Coinbase Developer Platform. The new API key format looks like this:\n   ```\n   API Key: organizations/{org_id}/apiKeys/{key_id}\n   API Secret: -----BEGIN EC PRIVATE KEY-----\\n...\\n-----END EC PRIVATE KEY-----\\n\n   ```\n\n## Authentication\n\nHere's an example of how to authenticate using the new method:\n\n```python\nfrom coinbase_advanced_trader.enhanced_rest_client import EnhancedRESTClient\n\napi_key = \"organizations/{org_id}/apiKeys/{key_id}\"\napi_secret = \"-----BEGIN EC PRIVATE KEY-----\\n...\\n-----END EC PRIVATE KEY-----\\n\"\n\nclient = EnhancedRESTClient(api_key=api_key, api_secret=api_secret)\n```\n\n## Using the Official SDK\n\nThe `EnhancedRESTClient` inherits from the Coinbase SDK's `RESTClient`, which means you can use all the functions provided by the official SDK. Here's an example of how to use the `get_product` function:\n\n```python\nproduct_info = client.get_product(product_id=\"BTC-USDC\")\n\nprint(product_info)\n```\n\n## Using Wrapper Strategies\n\nHere's an example of how to use the strategies package to buy $10 worth of Bitcoin. By making assumptions about limit price in [trading_config.py](coinbase_advanced_trader/trading_config.py) we are able to simplify the syntax for making orders:\n\n```python\n# Perform a market buy\nclient.fiat_market_buy(\"BTC-USDC\", \"10\")\n\n#Place a $10 buy order for BTC-USD near the current spot price of BTC-USDC\nclient.fiat_limit_buy(\"BTC-USDC\", \"10\")\n\n#Place a $10 buy order for BTC-USD at a limit price of $10,000\nclient.fiat_limit_buy(\"BTC-USDC\", \"10\", \"10000\")\n\n#Place a $10 buy order for BTC-USD at a 10% discount from the current spot price of BTC-USDC\nclient.fiat_limit_buy(\"BTC-USDC\", \"10\", price_multiplier=\".90\")\n\n#Place a $10 sell order for BTC-USD at a limit price of $100,000\nclient.fiat_limit_sell(\"BTC-USDC\", \"10\", \"100000\")\n\n#Place a $10 sell order for BTC-USD near the current spot price of BTC-USDC\nclient.fiat_limit_sell(\"BTC-USDC\", \"5\")\n\n#Place a $10 sell order for BTC-USD at a 10% premium to the current spot price of BTC-USDC\nclient.fiat_limit_sell(\"BTC-USDC\", \"5\", price_multiplier=\"1.1\")\n```\n\n### Account Balance Operations\n\nThe `EnhancedRESTClient` provides methods to retrieve account balances for cryptocurrencies. These methods are particularly useful for managing and monitoring your cryptocurrency holdings on Coinbase.\n\n#### Listing All Non-Zero Crypto Balances\n\nTo get a dictionary of all cryptocurrencies with non-zero balances in your account:\n\n```python\nbalances = client.list_held_crypto_balances()\nprint(balances)\n```\n\n#### Getting a Specific Crypto Balance\n\nTo get the available balance of a specific cryptocurrency in your account (returns 0 if the specified cryptocurrency is not found in the account):\n\n```python\nbalance = client.get_crypto_balance(\"BTC\")\nprint(balance)\n```\n\nNote: Both methods use a caching mechanism to reduce API calls. The account data is cached for one hour before a fresh fetch is made from Coinbase.\n\n### Usage of Fear and Greed Index\n\n```python\n# Trade based on Fear and Greed Index\nclient.trade_based_on_fgi(\"BTC-USDC\", \"10\")\n```\n\nYou can also update and retrieve the Fear and Greed Index schedule:\n\n```python\n# Get current FGI schedule\ncurrent_schedule = client.get_fgi_schedule()\n\n# Update FGI schedule\nnew_schedule = [\n    {'threshold': 15, 'factor': 1.2, 'action': 'buy'},\n    {'threshold': 37, 'factor': 1.0, 'action': 'buy'},\n    {'threshold': 35, 'factor': 0.8, 'action': 'sell'},\n    {'threshold': 45, 'factor': 0.6, 'action': 'sell'}\n]\nclient.update_fgi_schedule(new_schedule)\n```\n\n## AlphaSquared Integration\n\nThis client now includes integration with AlphaSquared, allowing you to execute trading strategies based on AlphaSquared's risk analysis.\n\n### Setup\n\n1. Obtain your AlphaSquared API key from [AlphaSquared](https://alphasquared.io/).\n\n2. Initialize the AlphaSquared client along with the Coinbase client:\n\n```python\nfrom coinbase_advanced_trader import EnhancedRESTClient, AlphaSquaredTrader\nfrom alphasquared import AlphaSquared\n\n# Initialize Coinbase client\ncoinbase_api_key = \"YOUR_COINBASE_API_KEY\"\n\ncoinbase_api_secret = \"YOUR_COINBASE_API_SECRET\"\n\ncoinbase_client = EnhancedRESTClient(api_key=coinbase_api_key, api_secret=coinbase_api_secret)\n\n# Initialize AlphaSquared client\nalphasquared_api_key = \"YOUR_ALPHASQUARED_API_KEY\"\n\nalphasquared_client = AlphaSquared(alphasquared_api_key, cache_ttl=60)\n\n# Create AlphaSquaredTrader\ntrader = AlphaSquaredTrader(coinbase_client, alphasquared_client)\n```\n\n### Executing AlphaSquared Strategies\n\nTo execute a trading strategy based on AlphaSquared's risk analysis:\n\n```python\n# Set trading parameters\nproduct_id = \"BTC-USDC\"\n\n# Your custom strategy name from AlphaSquared\nstrategy_name = \"My Custom Strategy\"\n\n# Execute strategy\ntrader.execute_strategy(product_id, strategy_name)\n```\n\nThis will:\n1. Fetch the current risk level for the specified asset from AlphaSquared.\n2. Determine the appropriate action (buy/sell) and value based on the custom strategy defined in AlphaSquared and the current risk.\n3. Execute the appropriate trade on Coinbase if the conditions are met.\n\n> **Note:** Make sure to handle exceptions and implement proper logging in your production code. This integration only works with custom strategies; it does not work with the default strategies provided by AlphaSquared.\n\n### Customizing Strategies\n\nYou can create custom strategies by modifying the `execute_strategy` method in the `AlphaSquaredTrader` class. This allows you to define specific trading logic based on the risk levels provided by AlphaSquared.\n\n## Legacy Support\n\nThe 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:\n\n```python\nfrom coinbase_advanced_trader.legacy.legacy_config import set_api_credentials\nfrom coinbase_advanced_trader.legacy.strategies.limit_order_strategies import fiat_limit_buy\n\nlegacy_key = \"your_legacy_key\"\nlegacy_secret = \"your_legacy_secret\"\n\nset_api_credentials(legacy_key, legacy_secret)\n\n# Use legacy functions\nlimit_buy_order = fiat_limit_buy(\"BTC-USDC\", 10)\n```\n\n## Documentation\n\nFor 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/).\n\n## License\n\nThis project is licensed under the MIT License. See the LICENSE file for more information.\n\n## Author\n\nRhett Reisman\n\nEmail: rhett@rhett.blog\n\nGitHub: https://github.com/rhettre/coinbase-advancedtrade-python\n\n## Disclaimer\n\nThis 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.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "The unofficial Python client for the Coinbase Advanced Trade API",
    "version": "0.3.2",
    "project_urls": {
        "Homepage": "https://github.com/rhettre/coinbase-advancedtrade-python"
    },
    "split_keywords": [
        "gdax",
        " gdax-api",
        " cbpro",
        " cbpro-api",
        " orderbook",
        " trade",
        " bitcoin",
        " ethereum",
        " btc",
        " eth",
        " client",
        " api",
        " wrapper",
        " exchange",
        " crypto",
        " currency",
        " trading",
        " trading-api",
        " coinbase",
        " advanced-trade",
        " prime",
        " coinbaseadvancedtrade",
        " coinbase-advanced-trade",
        " fear-and-greed-index"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b60689793a4ef6b822d2e90e02a36b836345f53bd7431b4b337a3e45becf70db",
                "md5": "f58c9e9ebe6829470641f1e7c03e188f",
                "sha256": "23ade66dba60c9e37c011cd406bf7ba80521e1a6c9407fd3583f6534bdd5371b"
            },
            "downloads": -1,
            "filename": "coinbase_advancedtrade_python-0.3.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "f58c9e9ebe6829470641f1e7c03e188f",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 49015,
            "upload_time": "2024-10-13T16:32:48",
            "upload_time_iso_8601": "2024-10-13T16:32:48.673785Z",
            "url": "https://files.pythonhosted.org/packages/b6/06/89793a4ef6b822d2e90e02a36b836345f53bd7431b4b337a3e45becf70db/coinbase_advancedtrade_python-0.3.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a072274d3777273482574703e53227f8cffe6692ecb875889c227de9c48fddae",
                "md5": "3a486a734d82f0557d2b5f7a9b2d12d0",
                "sha256": "0c99e2cf024a27cc656013aa395ba9866f4f22b5cb6087e44a05ff6e0ac0f6ab"
            },
            "downloads": -1,
            "filename": "coinbase_advancedtrade_python-0.3.2.tar.gz",
            "has_sig": false,
            "md5_digest": "3a486a734d82f0557d2b5f7a9b2d12d0",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 34844,
            "upload_time": "2024-10-13T16:32:53",
            "upload_time_iso_8601": "2024-10-13T16:32:53.778539Z",
            "url": "https://files.pythonhosted.org/packages/a0/72/274d3777273482574703e53227f8cffe6692ecb875889c227de9c48fddae/coinbase_advancedtrade_python-0.3.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-13 16:32:53",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "rhettre",
    "github_project": "coinbase-advancedtrade-python",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "coinbase-advanced-py",
            "specs": []
        },
        {
            "name": "requests",
            "specs": [
                [
                    ">=",
                    "2.31.0"
                ]
            ]
        },
        {
            "name": "urllib3",
            "specs": [
                [
                    ">=",
                    "2.2.2"
                ]
            ]
        },
        {
            "name": "PyYAML",
            "specs": [
                [
                    ">=",
                    "6.0.1"
                ]
            ]
        },
        {
            "name": "cryptography",
            "specs": [
                [
                    ">=",
                    "42.0.4"
                ]
            ]
        },
        {
            "name": "cffi",
            "specs": []
        },
        {
            "name": "alphasquared-py",
            "specs": [
                [
                    ">=",
                    "0.3.0"
                ]
            ]
        }
    ],
    "lcname": "coinbase-advancedtrade-python"
}
        
Elapsed time: 0.40900s