Coinbase pro client for Rust

Overview

Build Status Crates.io Docs.rs

Coinbase pro client for Rust

Supports SYNC/ASYNC/Websocket-feed data support

Features

  • private and public API
  • sync and async support
  • websocket-feed support

Examples

Cargo.toml:

[dependencies]
coinbase-pro-rs = "0.6.9"

Async

use hyper::rt::Future;
use coinbase_pro_rs::{Public, ASync, SANDBOX_URL};

fn main() {
    let client: Public<ASync> = Public::Public::new_with_keep_alive(SANDBOX_URL, false);
    // if keep_alive is not disables - tokio::run will hold the connection without exiting the example
    let f = client.get_time()
        .map_err(|_| ())
        .and_then(|time| {
            println!("Coinbase.time: {}", time.iso);
            Ok(())
        });

    tokio::run(f); // waiting for tokio
}

Sync

use coinbase_pro_rs::{Public, Sync, SANDBOX_URL};

fn main() {
   let client: Public<Sync> = Public::new(SANDBOX_URL);
   let time = client.get_time().unwrap();
   println!("Coinbase.time: {}", time.iso);
}

Websocket

use futures::{Future, Stream};
use coinbase_pro_rs::{WSFeed, WS_SANDBOX_URL};
use coinbase_pro_rs::structs::wsfeed::*;

fn main() {
    let stream = WSFeed::new(WS_SANDBOX_URL,
        &["BTC-USD"], &[ChannelType::Heartbeat]);

    let f = stream
        .take(10)
        .for_each(|msg| {
        match msg {
            Message::Heartbeat {sequence, last_trade_id, time, ..} => println!("{}: seq:{} id{}",
                                                                               time, sequence, last_trade_id),
            Message::Error {message} => println!("Error: {}", message),
            Message::InternalError(_) => panic!("internal_error"),
            other => println!("{:?}", other)
        }
        Ok(())
    });

    tokio::run(f.map_err(|_| panic!("stream fail")));
}

Api supported:

  • SYNC
  • ASYNC
  • Websocket-Feed

API

  • Requests
  • Pagination
  • Types
  • Private
    • Authentication
    • Accounts
    • Orders
    • Fills
    • Deposits
    • Withdrawals
    • Payment Methods
    • Coinbase Accounts
    • Reports
    • User Account
  • Market Data
    • Products
    • Currencies
    • Time
  • Websocket Feed
    • heartbeat
    • ticker
    • level2
    • user
    • matches
    • full

FIX API

by request

OrderBook

https://github.com/inv2004/orderbook-rs

Tests

cargo test

Comments
  • fixing build and updating all dependencies to most recent versions

    fixing build and updating all dependencies to most recent versions

    When I tried to use coinbase-pro-rs it was not compiling: I had many errors related to serde.

    I fixed the errors by adding:

    features = ["derive"]
    

    I noticed that many dependencies are outdated, so I updated to the most recent versions and fixed the code when the API were slightly different.

    Also some of the tests are flaky: "check_latency" and "check_full", I increased the timeouts.

    opened by sebest 5
  • Check for presence of Zulu time symbol at end of datetime string prior to appending it and subsequently parsing.

    Check for presence of Zulu time symbol at end of datetime string prior to appending it and subsequently parsing.

    Of recent, when making orders that have a time_in_force parameter of GTT, there are errors when parsing the json representation of that order. The reason for this is that the "expire_time" in the json representation of the order has a format such as "2019-09-07T07:30:50.22512Z" with the Zulu symbol already at the end - and the utils datetime_from_string also goes ahead to append a Zulu symbol at the end of datetime.

    This change adds a check so that the Zulu symbol is only added if it is not already there.

    opened by obiesie 5
  • Private API Extensions

    Private API Extensions

    Thanks for your work on this repo! This PR has two additions.

    1. It extends the WS Match struct to include fields that come into the message when you are authenticated which makes it easier to figure out whether you were a maker or a taker.

    2. It allows sending the client_oid field with new orders which can be used to track an order when it comes in via the websocket (specifically via the Received message). Without this I had to do a bunch of nasty locking.

    2 is definitely a bit more abrasive of a change (it breaks the ordering APIs). Ultimately we might want to consider something like an order builder rather than all of the different functions. eg. something like:

    let order = Order::buy()
      .limit(1000.0)
      .client_oid(Uuid::new_v4())
      .time_in_force(OrderTimeInForce::FOK);
    
    client.place_order(order);
    

    This would let us continue to extend the API without (as many) breaking changes. It also saves the current 5-6 argument order methods that we have currently.

    Either way, let me know if you want me to break apart the pull request or need any changes.

    Cheers!

    opened by rschmukler 5
  • Update private.rs

    Update private.rs

    added missing attribute for f64 fields (#[serde(deserialize_with = "f64_from_string")]) to prevent error: "invalid type: string "13.0000000000000000", expected f64"

    changed account_id field for AccountHolds struct to id, which matches what is being reported by the API.

    removed struct field which was missing from API results: updated_at.

    opened by autumnmute 4
  • base_min_size not present in get_product, causing a crash

    base_min_size not present in get_product, causing a crash

    It seems that Coinbase has removed base_min_size from their product api, which causes get_product to crash to an error:

    thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value:
    Serde {
      error: Error("missing field `base_min_size`", line: 1, column: 388),
      data: "{\"id\":\"CRV-EUR\",\"base_currency\":\"CRV\",\"quote_currency\":\"EUR\",\"quote_increment\":\"0.0001\",\"base_increment\":\"0.01\",\"display_name\":\"CRV/EUR\",\"min_market_funds\":\"0.84\",\"margin_enabled\":false,\"fx_stablecoin\":false,\"max_slippage_percentage\":\"0.03000000\",\"post_only\":false,\"limit_only\":false,\"cancel_only\":false,\"trading_disabled\":false,\"status\":\"online\",\"status_message\":\"\",\"auction_mode\":false}"
    }
    
    opened by jehna 3
  • fix: visibility of reqs::Order constructors

    fix: visibility of reqs::Order constructors

    Please forgive me if this isn't actually necessary. I believe that pub(crate) is ambiguous on struct constructors and doesn't actually cause these functions to be exposed publicly.

    If I'm incorrect here, please excuse this PR and let me know the correct syntax to create a request using market or limit constructors from an external package.

    opened by rschmukler 3
  • feat: stop methods for order builder

    feat: stop methods for order builder

    Adds stop_loss, stop, and stop_entry methods to the order builder API.

    It also fixes the serialization of stop orders and adds it to the response.

    Note: GDAX's sandbox API is a bit wonky right now so I was getting some failed tests. I didn't dig too far.

    opened by rschmukler 2
  • refactor: switch reqs::Order to owned String

    refactor: switch reqs::Order to owned String

    This commit changes the internals of the reqs::Order struct to use an owned struct rather than a lifetime pointer. The main reason for this change is to allow implementing Into<Order> for structs that don't have pointer-based representations of strings for products. For example, consider the following scenario:

    enum Coin {
      BTC
      USD
    }
    
    enum Pair {
      quote: Coin,
      base: Coin,
    }
    
    enum AppOrder {
      pair: Pair,
      size: f64,
    }
    

    If you imagine trying to implement From<AppOrder> for reqs::Order it is currently impossible, as you would need to render the pair (eg. format!("{}-{}", pair.quote, pair.base) but the generated string would not live long enough to satisfy the lifetime requirement of the Order<'a>.

    Since an order is almost always followed by IO, and the frequency of making orders is relatively sparse, the performance overhead of potentially copying a string unnecessarily seems like a worthwhile sacrifice for ergonomics.

    I realize that this is a breaking change and that it might not be worth releasing immediately (or at all) so please reject this PR if you don't think it's worth it. That being said, I did run into this issue when using it in my application - and I think any application that tries to write bindings to multiple exchanges (and thus has it's own "OrderRequest" type) will run into something similar to this.

    opened by rschmukler 2
  • Serde { error: Error(

    Serde { error: Error("EOF while parsing a value", line: 1, column: 0), data: "" }

    I'm getting this error running the ws_url url of coinbase pro. Any ideas?

    ` extern crate coinbase_pro_rs; extern crate hyper; extern crate tokio;

    use coinbase_pro_rs::{ ASync, Public, WS_URL, structs }; use hyper::rt::Future;

    fn main() { let client: Public = Public::new_with_keep_alive(WS_URL, false);

    let btc_usd = client
        .get_book::<structs::public::BookRecordL1>("BTC-USD")
        .map_err(|err| {
            println!("{:?}", err);
        })
        .and_then(|book| {
            println!("BTC-USD: {:?}", book);
            Ok(())
        });
    tokio::run(btc_usd);
    

    } `

    opened by jsoneaday 2
  • - Update struct schemas and unit tests

    - Update struct schemas and unit tests

    • Update struct schemas based on https://docs.cloud.coinbase.com/exchange/reference
    • Fix unit tests
    running 56 tests
    test private::tests::test_get_account_holds ... ignored
    test private::tests::test_get_orders ... ignored
    test private::tests::test_get_trailing_volume ... ignored
    test private::tests::test_set_order_limit ... ignored
    test private::tests::test_set_order_market ... ignored
    test public::tests::send_test ... ignored
    test public::tests::test_check_latency ... ignored
    test public::tests::test_check_latency_async ... ignored
    test public::tests::test_check_latency_async_block_on ... ignored
    test public::tests::test_get_book ... ignored
    test private::tests::test_new_order_ser ... ok
    test adapters::tests::test_async ... ok
    test private::tests::test_buy_market_funds ... ok
    test adapters::tests::test_sync ... ok
    test structs::reqs::tests::test_order_builder ... ok
    test structs::reqs::tests::test_order_from ... ok
    test structs::wsfeed::tests::test_canceled_order_done ... ok
    test structs::wsfeed::tests::test_canceled_order_without_auth ... ok
    test structs::wsfeed::tests::test_change_without_price ... ok
    test structs::wsfeed::tests::test_parse_numbers ... ok
    test structs::wsfeed::tests::test_parse_uuid ... ok
    test private::tests::test_cancel_all ... ok
    test wsfeed::tests::test_full ... ignored
    test private::tests::test_fees ... ok
    test private::tests::test_cancel_order ... ok
    test private::tests::test_get_account ... ok
    test wsfeed::tests::test_status ... ok
    test private::tests::test_get_account_hist ... ok
    test wsfeed::tests::test_subscribe ... ok
    test wsfeed::tests::test_subscribe_auth ... ok
    test private::tests::test_get_accounts ... ok
    test private::tests::test_get_fills ... ok
    test private::tests::test_get_order ... ok
    test private::tests::test_get_order_market_funds ... ok
    test private::tests::test_get_order_market ... ok
    test private::tests::test_get_pub ... ok
    test private::tests::test_get_transfers ... ok
    test private::tests::test_sell_market_funds ... ok
    test private::tests::test_set_order_limit_gtc ... ok
    test private::tests::test_set_order_stop ... ok
    test public::tests::test_get_candles ... ok
    test public::tests::test_get_currencies ... ok
    test public::tests::test_get_product ... ok
    test public::tests::test_get_stats24h ... ok
    test public::tests::test_get_products ... ok
    test public::tests::test_get_ticker ... ok
    test public::tests::test_get_time ... ok
    test public::tests::test_get_trades ... ok
    test wsfeed::tests::test_dynamic_subscription ... ok
    test wsfeed::tests::test_heartbeat ... ok
    test wsfeed::tests::test_level2 ... ok
    test wsfeed::tests::test_match ... ok
    test wsfeed::tests::test_status_stream ... ok
    test wsfeed::tests::test_subscription ... ok
    test wsfeed::tests::test_ticker ... ok
    test wsfeed::tests::test_user ... ok
    
    test result: ok. 45 passed; 0 failed; 11 ignored; 0 measured; 0 filtered out; finished in 26.54s
    
       Doc-tests coinbase-pro-rs
    
    running 3 tests
    test src/lib.rs - (line 35) ... ok
    test src/lib.rs - (line 16) ... ok
    test src/lib.rs - (line 45) ... ok
    
    test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 7.64s
    
    opened by jeremy-prater 1
  • fix readme

    fix readme

    small typo here, working code looks like this:

    use coinbase_pro_rs::{Public, ASync, MAIN_URL};
    
    ...
    
        let client: Public<ASync> = Public::new_with_keep_alive(MAIN_URL, false);
    
    opened by blakehawkins 1
  • Add pagination to the Public::get_trades API

    Add pagination to the Public::get_trades API

    The Public::get_trades() method does not support pagination which is required to retrieve historical trade data. To avoid a breaking change this could be addressed by adding a new method resembling pub fn get_trades_paginated(&self, product_id: &str, before: Option<usize>, after: Option<usize>) ....

    opened by v1bri 0
  • Question on API Docs

    Question on API Docs

    All, where do you find the API docs for the api.pro.coinbase.com? When I go into their new cloud docs all I see is something that they call exchange; api.exchange.coinbase.com. Even the link at https://docs.pro.coinbase.com sends me to the same 'exchange' docs. I don't see the api.pro.coinbase.com anywhere in there docs.

    I tried using the same secret, passphrase and key with exchange but it doesn't work. Am I missing something or are trying to move the api url from api.pro.coinbase.com to api.exchange.coinbase.com? If not can someone send me a link to the pro docs?

    Thanks.

    opened by jbertovic 0
  • get_orders() API doesn't allow getting

    get_orders() API doesn't allow getting "all" orders

    The official API (and the docs copied from there) allow specifying "all" orders, but the code only allows passing Option<OrderStatus>:

    https://docs.rs/coinbase-pro-rs/0.6.9/src/coinbase_pro_rs/private.rs.html#357-372

    Not sure if the parameter would need it's own enum, or allow a list of order statuses, or if "all" should be the default. As is it is a bit clumsy to get "all", as that would require looping over the enum.

    opened by kaspar030 0
  • new_size value missing in Full::Change json message

    new_size value missing in Full::Change json message

    image

    new_size field is missing in Full::Change enum variant.

    I think that the corresponding value is an optional value, because one of the official coinbase pro API reference's example has no new_size field too.

    image

    we need to checks if there is a document specifying the fields of each variant, and that there are no problems with other variants.

    opened by SeanKim 0
Owner
null
Rust Ethereum 2.0 Client

Lighthouse: Ethereum 2.0 An open-source Ethereum 2.0 client, written in Rust and maintained by Sigma Prime. Documentation Overview Lighthouse is: Read

Sigma Prime 2.1k Jan 6, 2023
rust client libraries to deal with the current cardano mainnet (byron / cardano-sl)

Rust implementation of Cardano primitives, helpers, and related applications Cardano Rust is a modular toolbox of Cardano’s cryptographic primitives,

Input Output 275 Oct 9, 2022
Rust client to Opensea's APIs and Ethereum smart contracts

opensea.rs Rust bindings & CLI to the Opensea API and Contracts CLI Usage Run cargo r -- --help to get the top level help menu: opensea-cli 0.1.0 Choo

Georgios Konstantopoulos 226 Dec 27, 2022
Simple template for building smart contract(Rust) and RPC Client(web3.js) on Solana (WIP) ⛏👷🚧⚠️

Solana BPF Boilerplate Simple template for building smart contract(Rust) and RPC Client(web3.js) on Solana This boilerplate provides the following. Si

ono 6 Jan 30, 2022
An encrypted multi client messaging system written in pure Rust

?? Preamble This is a pure Rust multi-client encrypted messaging system, also known as Edode's Secured Messaging System. It is an end-to-end(s) commun

Edode 3 Sep 16, 2022
Rust implementation of the i2p client/server/router protocols

ri2p Rust implementation of the i2p client/server/router protocols Status Common Commands cargo build: Builds the ri2p binary cargo run: Runs the ri2p

Christopher Bilger 8 Nov 25, 2022
In addition to encryption library, pure RUST implementation of SSH-2.0 client protocol

In addition to encryption library, pure RUST implementation of SSH-2.0 client protocol

陈年旧事。 73 Jan 1, 2023
Next-generation implementation of Ethereum protocol ("client") written in Rust, based on Erigon architecture.

?? Martinez ?? Next-generation implementation of Ethereum protocol ("client") written in Rust, based on Erigon architecture. Why run Martinez? Look at

Arthur·Thomas 23 Jul 3, 2022
A Rust client for Flashbots Relay.

flashbots-relay-rs Rust client for interacting directly with the Flashbots Relays. How does it work ? Using a client from the reqwest crate, you can u

Luca G.F. 16 Jun 22, 2022
Ethereum JSON-RPC multi-transport client. Rust implementation of web3 library

Ethereum JSON-RPC multi-transport client. Rust implementation of web3 library. ENS address: rust-web3.eth

Tomasz Drwięga 1.2k Jan 8, 2023
🐰 Rust client library for the Leap Edge socket service

leap_edge_rs Utility library for connecting and receiving events from Leap Edge. Used for Channels and Pipe. Installation Add this to your Cargo.toml:

Hop 9 Sep 7, 2022
Rust API Client for ImageKit.io a file storage and image processing service

Rust API Client for ImageKit.io a file storage and image processing service Usage You must retrieve your Public and Private Keys from the ImageKit Dev

Esteban Borai 4 Jul 31, 2022
Rust client to Seaport's APIs and Ethereum smart contracts(WIP)

Seaport-rs WIP - WORK IN PROGRESS. REFER TO https://github.com/Alcibiades-Capital/quay FOR PRODUCTION READY CODE I'm new to Rust and seek to be legend

Perelyn 21 Nov 29, 2022
gRPC client/server for zero-knowledge proof authentication Chaum Pederson Zero-Knowledge Proof in Rust

gRPC client/server for zero-knowledge proof authentication Chaum Pederson Zero-Knowledge Proof in Rust. Chaum Pederson is a zero-knowledge proof proto

Advaita Saha 4 Jun 12, 2023
Rust client library for Flashbots MEV-Share

Flashbots MEV-Share Client   Rust client library for Flashbots MEV-Share. Based on the MEV-Share specs and the TypeScript reference implementation. Us

null 4 Aug 22, 2023
Rust bindings and SDK for the ELSTER Rich Client (ERiC)

Eric Rust bindings and SDK for the ELSTER Rich Client (ERiC) What is ELSTER? What is ERiC? Requirements Rust bindings Select bindings Generate binding

null 24 Sep 3, 2024
Reference client for NEAR Protocol

Reference implementation of NEAR Protocol About NEAR NEAR's purpose is to enable community-driven innovation to benefit people around the world. To ac

NEAR 2k Jan 3, 2023
The Parity Bitcoin client

The Parity Bitcoin client. Gitter Installing from source Installing the snap Running tests Going online Importing bitcoind database Command line inter

Parity Technologies 714 Dec 21, 2022
The fast, light, and robust client for the Ethereum mainnet.

OpenEthereum Fast and feature-rich multi-network Ethereum client. » Download the latest release « Table of Contents Description Technical Overview Bui

OpenEthereum 1.6k Dec 28, 2022