### Get Coinbase Exchange Product Details Source: https://context7_llms Shows how to retrieve details for a specific trading product (e.g., BTC-USD) on Coinbase Exchange using the Go SDK. The example initializes the client, sets up a request with the desired Product ID, calls the products service, and prints the formatted JSON response. It relies on environment credentials for API access. ```go func main() { credentials, err := credentials.ReadEnvCredentials("EXCHANGE_CREDENTIALS") if err != nil { panic(fmt.Sprintf("unable to read exchange credentials: %v", err)) } httpClient, err := core.DefaultHttpClient() if err != nil { panic(fmt.Sprintf("unable to load default http client: %v", err)) } client := client.NewRestClient(credentials, httpClient) productsSvc := products.NewProductsService(client) request := &products.GetProductRequest{ ProductId: "BTC-USD", } response, err := productsSvc.GetProduct(context.Background(), request) if err != nil { panic(fmt.Sprintf("unable to get product: %v", err)) } jsonResponse, err := json.MarshalIndent(response, "", " ") if err != nil { panic(fmt.Sprintf("error marshaling response to JSON: %v", err)) } fmt.Println(string(jsonResponse)) } ``` -------------------------------- ### Install Coinbase Exchange Go SDK Source: https://context7_llms Commands to initialize a Go module, install the Coinbase Exchange Go SDK, and tidy dependencies. Ensure you replace example.com/test with your project path. ```bash go mod init example.com/test go get github.com/coinbase-samples/exchange-sdk-go go mod tidy go build ``` -------------------------------- ### Coinbase Balance Channel Subscription Example Source: https://context7_llms Provides an example of a WebSocket subscription message for the Coinbase Balance channel. It demonstrates how to specify the channel name and associate it with one or more account IDs for tracking balance updates. ```json { "type": "subscribe", "channels": [ { "name": "balance", "account_ids": [ "d50ec984-77a8-460a-b958-66f114b0de9b", "d50ec984-77a8-460a-b958-66f114b0de9a" ] } ] } ``` -------------------------------- ### Coinbase WebSocket Subscribe Request Example Source: https://context7_llms An example of a JSON payload for subscribing to channels on the Coinbase Exchange WebSocket API. This includes essential parameters like product_ids, channels, and authentication details such as signature, key, passphrase, and timestamp. ```JSON { "type": "subscribe", "product_ids": ["BTC-USD"], "channels": ["full"], "signature": "...", "key": "...", "passphrase": "...", "timestamp": "..." } ``` -------------------------------- ### Coinbase Exchange Get Product Stats Response Properties Source: https://context7_llms Added new response properties to the Get product stats API: `rfq_volume_24hour`, `conversions_volume_24hour`, `rfq_volume_30day`, and `conversions_volume_30day`. ```APIDOC API Endpoint: Get product stats Added Properties: - rfq_volume_24hour - conversions_volume_24hour - rfq_volume_30day - conversions_volume_30day Example Response Snippet: "apiProductStats": { "type": "object", "example": { "open": "5414.18000000", "high": "6441.37000000", "low": "5261.69000000", "volume": "53687.76764233", "last": "6250.02000000", "volume_30day": "786763.72930864", "rfq_volume_24hour": "78.23", "conversions_volume_24hour": "0.000000", "rfq_volume_30day": "0.000000", "conversions_volume_30day": "0.000000" } } ``` -------------------------------- ### Coinbase Exchange REST API Base URL and Setup Source: https://context7_llms Provides the base URL for making REST API calls to the Coinbase Exchange and outlines the initial setup steps, including account creation, API key generation, and authentication guidance. ```APIDOC REST API URL: https://api.exchange.coinbase.com Initial Setup: 1. Create a Coinbase Exchange Account: Sign up at https://exchange.coinbase.com/. 2. Generate an API Key: Navigate to https://exchange.coinbase.com/apikeys from the web UI. 3. Authenticate API Requests: Ensure all API requests are authenticated. Refer to https://docs.cdp.coinbase.com/exchange/docs/rest-auth for detailed guidance. ``` -------------------------------- ### Coinbase WebSocket Authenticated Feed Message Example Source: https://context7_llms An example of a JSON message received from an authenticated WebSocket feed on Coinbase Exchange. It includes fields like user_id and profile_id, which are present in messages related to your user account. ```JSON { "type": "open", // "received" | "open" | "done" | "match" | "change" | "activate" "user_id": "5844eceecf7e803e259d0365", "profile_id": "765d1549-9660-4be2-97d4-fa2d65fa3352" // ... } ``` -------------------------------- ### WebSocket Change Message Example Source: https://context7_llms This example shows a JSON payload for a 'change' message from the Coinbase Exchange WebSocket API. It illustrates the structure of updates related to order modifications, including the newly added fields: `new_price`, `old_price`, and `reason`. ```JSON { "type": "change", "reason": "modify_order", "time": "2022-06-06T22:55:43.433114Z", "sequence": 24753, "order_id": "c3f16063-77b1-408f-a743-88b7bc20cdcd", "side": "buy", "product_id": "ETH-USD", "old_size": "80", "new_size": "80", "old_price": "7", "new_price": "6" } ``` -------------------------------- ### Coinbase WebSocket Compression Extension Handshake Source: https://context7_llms Demonstrates the client's opening handshake to enable the permessage-deflate WebSocket compression extension, as defined in RFC7692. This header is added to the GET request. ```APIDOC GET wss://ws-feed.exchange.coinbase.com Sec-WebSocket-Extensions: permessage-deflate ``` -------------------------------- ### Coinbase WebSocket Full Channel FIX Execution Reports Source: https://context7_llms Examples of FIX Execution Report messages from the Coinbase WebSocket Full channel, illustrating order lifecycle events. ```FIX <- 35=8|37=OrderID123|198=OrderID789|39=Partially_Filled|32=0.3|151=0.4|14=0.6|137=0.0004 <- 35=8|37=OrderID123|198=OrderID789|39=Done_For_Day|32=0|151=0.4|14=0.6 <- 35=8|37=OrderID123|39=Partially_Filled|32=0.4|151=0|14=1.0|137=0.00045 <- 35=8|37=OrderID123|39=Done_For_Day|32=0|151=0|14=1.0 ``` -------------------------------- ### LZ77 Sliding Window Payload Example Source: https://datatracker.ietf.org/doc/html/rfc7692 An example payload referencing the history in the LZ77 sliding window. This sequence is part of a message that utilizes LZ77 compression techniques within the WebSocket protocol. ```APIDOC 0xf2 0x00 0x11 0x00 0x00 So, the payload of the second message will be: 0xf2 0x00 0x11 0x00 0x00. So, 2 bytes are saved in total. ``` -------------------------------- ### Initialize Exchange Client in Go Source: https://context7_llms Code snippet to initialize the Coinbase Exchange Go SDK client. It reads credentials from the EXCHANGE_CREDENTIALS environment variable and sets up a default HTTP client. ```go credentials, err := credentials.ReadEnvCredentials("EXCHANGE_CREDENTIALS") if err != nil { panic(fmt.Sprintf("unable to read exchange credentials: %v", err)) } httpClient, err := core.DefaultHttpClient() if err != nil { panic(fmt.Sprintf("unable to load default http client: %v", err)) } client := client.NewRestClient(credentials, httpClient) ``` -------------------------------- ### Coinbase Exchange Get User Exchange Limits Update Source: https://context7_llms The Get user exchange limits API has been updated to remove all properties except `exchange_withdraw`. ```APIDOC API Endpoint: Get user exchange limits Removed Properties: buy, sell, ach, ach_no_balance, credit_debit_card, secure3d_buy, paypal_buy, paypal_withdrawal, ideal_deposit, sofort_deposit, instant_ach_withdrawal Remaining Property: exchange_withdraw ``` -------------------------------- ### Python QuickFIX Logon for FIX 5.0 Source: https://context7_llms Example Python code using the QuickFIX library to set up a FIX 5.0 logon message. It includes details on signing the message using API key, secret, and passphrase, and setting required FIX tags like Username (553), RawData (96), and DefaultAppVerID (1137). ```Python """Example Python QuickFIX Application.py logon message setup""" class Application(fix.Application): PASSPHRASE = [ENTER PASSPHRASE] API_KEY = [ENTER API_KEY] SECRET = [ENTER SECRET] """Setup the Logon message & call sign function""" def toAdmin(self, message, sessionID): rawData = self.sign(message.getHeader().getField(52), message.getHeader().getField(35), message.getHeader().getField(34), self.API_KEY, message.getHeader().getField(56), self.PASSPHRASE) message.setField(fix.StringField(554, self.PASSPHRASE)) message.setField(fix.StringField(96, rawData)) message.setField(fix.StringField(8013, "Y")) message.setField(fix.StringField(553, self.API_KEY)) message.setField(fix.IntField(95, len(rawData.encode('utf-8')))) """Create base64 encoded signature""" def sign(self, timestamp, msg_type, seq_num, api_key, target_comp_id, passphrase): message = '\x01'.join([timestamp, msg_type, seq_num, api_key, target_comp_id, passphrase]).encode("utf-8") hmac_key = base64.b64decode(self.SECRET) signature = hmac.new(hmac_key, message, hashlib.sha256) sign_b64 = base64.b64encode(signature.digest()).decode() return sign_b64 ``` -------------------------------- ### DEFLATE Block with No Compression Example Source: https://datatracker.ietf.org/doc/html/rfc7692 Illustrates a WebSocket frame containing a DEFLATE block with no compression, used for the text message 'Hello'. The RSV1 bit is set, indicating DEFLATE is applied. The example shows the frame header and the compressed payload. ```APIDOC 0xc1 0x0b 0x00 0x05 0x00 0xfa 0xff 0x48 0x65 0x6c 0x6c 0x6f 0x00 This is a frame constituting a text message "Hello" built using a DEFLATE block with no compression. The first 2 octets (0xc1 0x0b) are the WebSocket frame header (FIN=1, RSV1=1, RSV2=0, RSV3=0, opcode=text, MASK=0, Payload length=7). Note that the RSV1 bit is set for this message (only on the first fragment if the message is fragmented) because the RSV1 bit is set when DEFLATE is applied to the message, including the case when only DEFLATE blocks with no compression are used. The 3rd to 13th octets consist of the payload data containing "Hello" compressed using a DEFLATE block with no compression. ``` -------------------------------- ### List Accounts using Coinbase Exchange Go SDK Source: https://context7_llms Demonstrates how to list all accounts associated with your Coinbase Exchange API key. It initializes the accounts service and makes a ListAccounts API call. ```go func main() { credentials, err := credentials.ReadEnvCredentials("EXCHANGE_CREDENTIALS") if err != nil { panic(fmt.Sprintf("unable to read exchange credentials: %v", err)) } httpClient, err := core.DefaultHttpClient() if err != nil { panic(fmt.Sprintf("unable to load default http client: %v", err)) } client := client.NewRestClient(credentials, httpClient) accountsSvc := accounts.NewAccountsService(client) request := &accounts.ListAccountsRequest{} response, err := accountsSvc.ListAccounts(context.Background(), request) if err != nil { panic(fmt.Sprintf("unable to list accounts: %v", err)) } jsonResponse, err := json.MarshalIndent(response, "", " ") if err != nil { panic(fmt.Sprintf("error marshaling response to JSON: %v", err)) } fmt.Println(string(jsonResponse)) } ``` -------------------------------- ### Coinbase API: Get Wrapped Assets Response Format Change Source: https://context7_llms Notifies a breaking change to the `GET /wrapped-assets/` endpoint. The response format has been updated from a list of strings to a list of JSON objects. ```APIDOC API Breaking Change: Endpoint: GET /wrapped-assets/ Change: Response format updated from list of strings to list of JSON objects. ``` -------------------------------- ### List Coinbase Exchange Profiles Source: https://context7_llms Demonstrates how to list all profile IDs associated with a Coinbase Exchange account using the Go SDK. It initializes the client, creates a request for the profiles service, executes the request, and prints the JSON response. Requires environment credentials for authentication. ```go func main() { credentials, err := credentials.ReadEnvCredentials("EXCHANGE_CREDENTIALS") if err != nil { panic(fmt.Sprintf("unable to read exchange credentials: %v", err)) } httpClient, err := core.DefaultHttpClient() if err != nil { panic(fmt.Sprintf("unable to load default http client: %v", err)) } client := client.NewRestClient(credentials, httpClient) profilesSvc := profiles.NewProfilesService(client) request := &profiles.ListProfilesRequest{} response, err := profilesSvc.ListProfiles(context.Background(), request) if err != nil { panic(fmt.Sprintf("unable to list profiles: %v", err)) } jsonResponse, err := json.MarshalIndent(response, "", " ") if err != nil { panic(fmt.Sprintf("error marshaling response to JSON: %v", err)) } fmt.Println(string(jsonResponse)) } ``` -------------------------------- ### Coinbase API: Get Wrapped Asset Details Endpoint Source: https://context7_llms Details the new `GET /wrapped-assets/{wrapped_asset_id}/` endpoint for retrieving specific details about wrapped assets. It returns circulating supply, total supply, and conversion rate. ```APIDOC New API Endpoint: GET /wrapped-assets/{wrapped_asset_id}/ Purpose: Retrieves detailed information for a specific wrapped asset. Response Properties: - circulating_supply: Customer-held wrapped assets. - total_supply: Total minted wrapped assets on-chain. - conversion_rate: Underlying staked units per wrapped asset. Example Response: { "wrapped_assets":[ { "id":"CBETH", "circulating_supply":"314666.9334401934801646", "total_supply":"1067354.0841178434801646", "conversion_rate":"1.0241755005866786" } ] } Sandbox Test URL: https://api-public.sandbox.exchange.coinbase.com/wrapped-assets/CBETH/ ``` -------------------------------- ### Implement Coinbase FIX Logon Message Source: https://context7_llms Example code for creating and signing a FIX Logon message using JavaScript. It demonstrates setting message fields, generating the prehash string, signing it with SHA256, and sending the message. ```JavaScript var logon = new Msgs.Logon(); logon.SendingTime = new Date(); logon.HeartBtInt = 30; logon.EncryptMethod = 0; logon.passphrase = "..."; var presign = [ logon.SendingTime, logon.MsgType, session.outgoing_seq_num, session.sender_comp_id, session.target_comp_id, passphrase, ].join("\x01"); // add the presign string to the RawData field of the Logon message logon.RawData = sign(presign, secret); // send the logon message to the server session.send(logon); function sign(what, secret) { var key = Buffer.from(secret, "base64"); var hmac = crypto.createHmac("sha256", key); return hmac.update(what).digest("base64"); } ``` -------------------------------- ### Configure Exchange Credentials Environment Variable Source: https://context7_llms Example of how to set the EXCHANGE_CREDENTIALS environment variable in your shell configuration file (e.g., ~/.zshrc) to securely store API keys, passphrase, and signing key. ```bash export EXCHANGE_CREDENTIALS='{ "apiKey":"YOUR_API_KEY", "passphrase":"YOUR_PASSPHRASE", "signingKey":"YOUR_SIGNING_KEY" }' ``` -------------------------------- ### REST API /products//book and /fills Endpoint Updates Source: https://context7_llms Details changes to the `/products//book` endpoint for Level 2 queries and the `/fills` endpoint for pagination support. ```APIDOC REST API Endpoint Enhancements: - `GET /products//book`: Returns the full aggregated order book for Level 2 queries. - `GET /fills`: Added pagination support. ``` -------------------------------- ### Coinbase Exchange Get Account Ledger Date Filtering Source: https://context7_llms Rule for the Get a single account's ledger API: if neither `start_date` nor `end_date` is provided, the endpoint defaults to returning ledger activity for the past 1 day. ```APIDOC API Endpoint: Get a single account's ledger Rule: If start_date and end_date are not set, returns ledger activity for the past 1 day only. ``` -------------------------------- ### FIX 5.0 Logon Procedure Source: https://context7_llms Details the FIX 5.0 logon process, including session and application layer versions, sequence number formatting, fractional second precision, and the prehash string construction for message signing. ```APIDOC FIX 5.0 Logon Details: - Session Layer: T1.1 - Application Layer: 5.0 (DefaultAppVerID tag 1137 = 9) - Logon Message Requirements: - MsgSeqNum: 1 - Username (553): API Key - Session Limit: One session per API Key. Maximum 75 connections per profile. - Sequence Numbers: - Must not include leading zeros (e.g., "1" is valid, "0001" is invalid). - Fractional Seconds: - Must use exactly three digits (e.g., 52=20230822-20:43:30.000). - Incorrect precision results in signature calculation error. - Message Signing: - Prehash String Fields: SendingTime, MsgType, MsgSeqNum, SenderCompID (API KEY), TargetCompID, Passphrase. - No trailing separator in prehash string. - RawData (96): Base64 encoding of the HMAC-SHA256 signature of the prehash string. - Related Tags: - 554: Passphrase - 96: RawData (Signature) - 8013: "Y" (Indicates signature is present) - 553: Username (API Key) - 95: Length of RawData ``` -------------------------------- ### Generating an Empty Fragment Example Source: https://datatracker.ietf.org/doc/html/rfc7692 Provides an example of generating an empty fragment for WebSocket compression when the data source is empty. This involves sending a final fragment with the FIN bit set and a payload containing 0 bytes of DEFLATE data, typically using an empty uncompressed DEFLATE block. ```APIDOC 0x00 The single octet 0x00 contains the header bits with "BFINAL" set to 0 and "BTYPE" set to 00, and 5 padding bits of 0. ``` -------------------------------- ### Coinbase WebSocket Subscription Example Source: https://context7_llms This JSON payload demonstrates how to subscribe to specific WebSocket channels, such as the 'balance' channel, by providing account IDs. It's used to receive real-time updates from the Coinbase Exchange. ```json { "type": "subscribe", "channels": [ "balance" ], "account_ids": [ "d50ec984-77a8-460a-b958-66f114b0de9b", "d50ec984-77a8-460a-b958-66f114b0de9a" ] } ``` -------------------------------- ### DEFLATE Block with BFINAL Set to 1 Example Source: https://datatracker.ietf.org/doc/html/rfc7692 Demonstrates the payload of a message containing 'Hello' compressed using a DEFLATE block where 'BFINAL' is set to 1. This method is an alternative for flushing data when an empty DEFLATE block with no compression is not available. The example shows the DEFLATE block structure and padding. ```APIDOC 0xf3 0x48 0xcd 0xc9 0xc9 0x07 0x00 0x00 This is the payload of a message containing "Hello" compressed using a DEFLATE block with "BFINAL" set to 1. The first 7 octets constitute a DEFLATE block with "BFINAL" set to 1 and "BTYPE" set to 01 containing "Hello". The last 1 octet (0x00) contains the header bits with "BFINAL" set to 0 and "BTYPE" set to 00, and 5 padding bits of 0. This octet is necessary to allow the payload to be decompressed in the same manner as messages flushed using DEFLATE blocks with "BFINAL" unset. ``` -------------------------------- ### Python WebSocket Authentication Example Source: https://context7_llms Demonstrates how to authenticate a WebSocket connection to the Coinbase Exchange using Python. It includes generating a signature based on API keys, passphrase, and timestamp for secure communication. ```Python API_KEY = str(os.environ.get('API_KEY')) PASSPHRASE = str(os.environ.get('PASSPHRASE')) SECRET_KEY = str(os.environ.get('SECRET_KEY')) URI = 'wss://ws-feed.exchange.coinbase.com' SIGNATURE_PATH = '/users/self/verify' channel = 'level2' product_ids = 'ETH-USD' async def generate_signature(): timestamp = str(time.time()) message = f'{timestamp}GET{SIGNATURE_PATH}' hmac_key = base64.b64decode(SECRET_KEY) signature = hmac.new( hmac_key, message.encode('utf-8'), digestmod=hashlib.sha256).digest() signature_b64 = base64.b64encode(signature).decode().rstrip('\n') return signature_b64, timestamp async def websocket_listener(): signature_b64, timestamp = await generate_signature() subscribe_message = json.dumps({ 'type': 'subscribe', 'channels': [{'name': channel, 'product_ids': [product_ids]}], 'signature': signature_b64, 'key': API_KEY, 'passphrase': PASSPHRASE, 'timestamp': timestamp }) ``` -------------------------------- ### Two DEFLATE Blocks in One Message Example Source: https://datatracker.ietf.org/doc/html/rfc7692 Shows an example of a WebSocket message containing two DEFLATE blocks. The first block compresses 'He' and the second, an empty DEFLATE block with no compression, is followed by a block compressing 'llo'. This demonstrates how multiple blocks can be sequenced within a single message. ```APIDOC 0xf2 0x48 0x05 0x00 0x00 0x00 0xff 0xff 0xca 0xc9 0xc9 0x07 0x00 The first 3 octets (0xf2 0x48 0x05) and the least significant two bits of the 4th octet (0x00) constitute one DEFLATE block with "BFINAL" set to 0 and "BTYPE" set to 01 containing "He". The rest of the 4th octet contains the header bits with "BFINAL" set to 0 and "BTYPE" set to 00, and the 3 padding bits of 0. Together with the following 4 octets (0x00 0x00 0xff 0xff), the header bits constitute an empty DEFLATE block with no compression. A DEFLATE block containing "llo" follows the empty DEFLATE block. ``` -------------------------------- ### Subscribe to RFQ Matches Channel (All Products) Source: https://context7_llms JSON payload to subscribe to the RFQ Matches channel for all products by sending an empty list for product_ids. This ensures all RFQ matches are received. ```json { "type": "subscriptions", "channels": [ { "name": "rfq_matches", "product_ids": [ "", ], }, ] } ```