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
    • Fees
    • 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 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
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 Dec 29, 2022
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
A Rust library for working with Bitcoin SV

Rust-SV A library to build Bitcoin SV applications in Rust. Documentation Features P2P protocol messages (construction and serialization) Address enco

Brenton Gunning 51 Oct 13, 2022
Custom Ethereum vanity address generator made in Rust

ethaddrgen Custom Ethereum address generator Get a shiny ethereum address and stand out from the crowd! Disclaimer: Do not use the private key shown i

Jakub Hlusička 153 Dec 27, 2022
The new, performant, and simplified version of Holochain on Rust (sometimes called Holochain RSM for Refactored State Model)

Holochain License: This repository contains the core Holochain libraries and binaries. This is the most recent and well maintained version of Holochai

Holochain 737 Dec 28, 2022
DEPRECATED. The Holochain framework implemented in rust with a redux style internal state-model.

Holochain-rust Travis: Circle CI: Codecov: License: This code is loosely based on the previous Golang prototype. Code Status: This Rust version is alp

Holochain 1k Jan 3, 2023
IBC modules and relayer - Formal specifications and Rust implementation

ibc-rs Rust implementation of the Inter-Blockchain Communication (IBC) protocol. This project comprises primarily four crates: The ibc crate defines t

Informal Systems 296 Jan 4, 2023
A Rust implementation of BIP-0039

bip39-rs A Rust implementation of BIP0039 Changes See the changelog file, or the Github releases for specific tags. Documentation Add bip39 to your Ca

Infincia LLC 49 Dec 9, 2022
Official Rust implementation of the Nimiq protocol

Nimiq Core implementation in Rust (core-rs) Rust implementation of the Nimiq Blockchain Core Nimiq is a frictionless payment protocol for the web. Thi

Nimiq 72 Sep 23, 2022
Rust implementation of Zcash protocol

The Parity Zcash client. Gitter Blog: Parity teams up with Zcash Foundation for Parity Zcash client Installing from source Installing the snap Running

Parity Technologies 183 Sep 8, 2022
Tendermint in Rust!

tendermint.rs Tendermint in Rust with TLA+ specifications. Tendermint is a high-performance blockchain consensus engine for Byzantine fault tolerant a

Informal Systems 439 Jan 1, 2023
A Rust library for generating cryptocurrency wallets

Table of Contents 1. Overview 2. Build Guide 2.1 Install Rust 2.2a Build from Homebrew 2.2b Build from Crates.io 2.2c Build from Source Code 3. Usage

Aleo 554 Dec 31, 2022
Rust port of the Terry Davis' (RIP) "god says" program

RIP Terry A. Davis 1969-2018 god says Rust port of the programmer Terry Davis' "god says" (AKA GodSpeaks) program. Terrence Andrew Davis (December 15,

Orhun Parmaksız 54 Dec 26, 2022
Implementation of the Kademlia DHT protocol in Rust

kademlia-dht Simple implementation of the Kademlia DHT protocol in Rust with state dumping features for educational purposes (not production-ready). T

Leonardo Folgoni 18 Sep 24, 2022
Collection of Key Derivation Functions written in pure Rust

RustCrypto: Key Derivation Functions Collection of Key Derivation Functions (KDF) written in pure Rust. Supported Algorithms Algorithm Crate Crates.io

Rust Crypto 44 Dec 25, 2022
Cryptocurrencies trend-following trading bot sandbox written in Rust.

Trend trading bot Experiments repo about (crypto) trend trading. By "trend" I mean trading following the trend using technical indicators (vs other ki

Julien 6 Oct 2, 2022
Martinez is vNext Ethereum implementation written in pure Rust with Erigon architecture as design.

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