> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cdp.coinbase.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Make Your First Trade with the REST SDK

This quickstart guide explains how to make a trade, from setup to execution, using the **Advanced API Python REST Client**.

This REST Client is a Python package that makes it easy to interact with the [REST API](https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/rest-api.md).

## Introduction

See the SDK [README](https://github.com/coinbase/coinbase-advanced-py/blob/master/README.md) for detailed instructions, plus the full suite of SDK functions.

> [accordion] Full Code for this Quickstart
>
> ```python lines wrap theme={null}
> # This is a summary of all the code for this tutorial
> from coinbase.rest import RESTClient
> from json import dumps
> import math
>
> api_key = "organizations/{org_id}/apiKeys/{key_id}"
> api_secret = "-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n"
>
> client = RESTClient(api_key=api_key, api_secret=api_secret)
>
> product = client.get_product("BTC-USD")
> btc_usd_price = float(product["price"])
> adjusted_btc_usd_price = str(math.floor(btc_usd_price - (btc_usd_price * 0.05)))
>
> order = client.limit_order_gtc_buy(
>     client_order_id="00000002",
>     product_id="BTC-USD",
>     base_size="0.0002",
>     limit_price=adjusted_btc_usd_price
> )
>
> if order['success']:
>     order_id = order['success_response']['order_id']
>     client.cancel_orders(order_ids=[order_id])
> else:
>     error_response = order['error_response']
>     print(error_response)
> ```

## Prerequisites

### Creating API Keys

To you use the SDK, you must first create your own [API key](https://docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication.md) on the Coinbase Developer Platform (CDP).

### Installing the SDK

To install the Coinbase Advanced API Python SDK, run the following command in a terminal:

```
pip3 install coinbase-advanced-py
```

## Setting up your Client

Create a Python project with the following code we have set up for you. Replace the `api_key` and `api_secret` with your own [API key and Secret](https://docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication.md).

```python lines wrap theme={null}
from coinbase.rest import RESTClient
from json import dumps

api_key = "organizations/{org_id}/apiKeys/{key_id}"
api_secret = "-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n"

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

You are now ready to start sending out requests!

## Sending your First Request

Let's start by calling [List Accounts](https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/accounts/list-accounts.md) to retrieve a list of authenticated accounts for the current user.

Optional parameters:

* `limit` = A pagination limit with default of 49 and maximum of 250
* `cursor` = Cursor used for pagination.

Add `get_accounts` to your code, using the same client you just created. This retrieves the accounts associated with the user account and immediately prints them in formatted JSON.

```python lines wrap theme={null}
accounts = client.get_accounts()
print(dumps(accounts.to_dict(), indent=2))
```

## Placing a Market Order

You are ready to place your first order!

The [Create Order](https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/create-order.md) endpoint creates an order with a specified `product_id` (i.e., "BTC-USD"), `side` (i.e. "BUY"/"SELL"), and other parameters listed in the API docs.

In this example, we use the same client to place a \$10 *market-buy* order on BTC-USD. Then, if the order was executed successfully, we retrieve the order's specific fill information using the `order_id`. If the order failed to execute, then we print the error information.

Required parameters:

* `client_order_id`: UUID for the order, generated by the client. Must be unique for each order.
* `product_id`: The product this order was created for.
* `quote_size`: Amount of quote currency to spend on order.

> [!NOTE]
>
> Don’t forget to add your own custom `client_order_id`. For learning purposes, we’ve pre-filled it to an arbitrary string.

```python lines wrap theme={null}
order = client.market_order_buy(
    client_order_id="00000001",
    product_id="BTC-USD",
    quote_size="10"
)

if order['success']:
    order_id = order['success_response']['order_id']
    fills = client.get_fills(order_id=order_id)
    print(json.dumps(fills.to_dict(), indent=2))
else:
    error_response = order['error_response']
    print(error_response)
```

## Placing a Limit-buy Order

Now let’s get a bit more... *advanced!*

In this final section, we combine various calls to:

1. Retrieve the current price of BTC-USD.
2. Place a limit-buy order 5% below said price.
3. Cancel the order using the `order_id`.

Let's dive in!

### Retrieving the Current Price

First, retrieve the current price of BTC-USD using the [Get Product](https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/products/get-product.md) endpoint. The `product_id` is required as a parameter. In this case, it’s "BTC-USD".

Later, we'll calculate and obtain the price 5% below the current price. This will be stored in `adjusted_btc_usd_price` to later indicate our limit price.

```python lines wrap theme={null}
import math

product = client.get_product("BTC-USD")
btc_usd_price = float(product["price"])
adjusted_btc_usd_price = str(math.floor(btc_usd_price - (btc_usd_price * 0.05)))
```

### Placing an Order 5% Below Price

Now, we place a *limit-buy* order using the **Create Order** endpoint. It’s similar to placing a *market-buy* order, but with some new parameters:

* `base_size`: Amount of base currency to spend on order.
* `limit_price`: Ceiling price for which the order should get filled.

Here we place a *limit-buy* order for 0.0002 BTC at a price of 5% below the current price of BTC-USD. We also set the `client_order_id` to "00000002" to differentiate it from the previous order we placed. In this example, we will keep it simple and only store the `order_id` if the order executed successfully; otherwise, we print the error information.

```python lines wrap theme={null}
order = client.limit_order_gtc_buy(
    client_order_id="00000002",
    product_id="BTC-USD",
    base_size="0.0002",
    limit_price=adjusted_btc_usd_price
)

if order['success']:
    order_id = order['success_response']['order_id']
else:
    error_response = order['error_response']
    print(error_response)
```

### Cancelling the Order

Finally, cancel the order you just placed with the [Cancel Orders](https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/cancel-order.md) endpoint:

```python lines wrap theme={null}
...
if order['success']:
    order_id = order['success_response']['order_id']
    client.cancel_orders(order_ids=[order_id])
...
```

And we are done!

You successfully placed Market and Limit orders using the Advanced API Python REST SDK.
