All Projects → wisespace-io → Binance Rs

wisespace-io / Binance Rs

Licence: other
Rust Library for the Binance API

Programming Languages

rust
11053 projects

Projects that are alternatives of or similar to Binance Rs

Tardis Node
Convenient access to tick-level real-time and historical cryptocurrency market data via Node.js
Stars: ✭ 126 (-23.17%)
Mutual labels:  cryptocurrency-exchanges, trading, binance
Bitprophet
Node crypto trading platform for Binance exchange.
Stars: ✭ 166 (+1.22%)
Mutual labels:  cryptocurrency, trading, binance
Python Bittrex
Python bindings for bittrex
Stars: ✭ 601 (+266.46%)
Mutual labels:  cryptocurrency, cryptocurrency-exchanges, trading
Php Binance Api
PHP Binance API is an asynchronous PHP library for the Binance API designed to be easy to use. https://github.com/binance-exchange/php-binance-api
Stars: ✭ 326 (+98.78%)
Mutual labels:  cryptocurrency, cryptocurrency-exchanges, binance
Crypto Whale Watcher
An app to keep a watch on big volume trades of cryptocurrecies on different exchanges by sending alerts via a Telegram Bot.
Stars: ✭ 60 (-63.41%)
Mutual labels:  cryptocurrency, cryptocurrency-exchanges, binance
Crypto Exchanges Gateway
Your gateway to the world of crypto !
Stars: ✭ 343 (+109.15%)
Mutual labels:  cryptocurrency, trading, binance
Node Binance Api
Node Binance API is an asynchronous node.js library for the Binance API designed to be easy to use.
Stars: ✭ 896 (+446.34%)
Mutual labels:  cryptocurrency, cryptocurrency-exchanges, binance
crypto-database
Database for crypto data, supporting several exchanges. Can be used for TA, bots, backtest, realtime trading, etc.
Stars: ✭ 72 (-56.1%)
Mutual labels:  trading, cryptocurrency-exchanges, binance
Crypto Trading Bot
Cryptocurrency trading bot in javascript for Bitfinex, Bitmex, Binance, FTX, Bybit ... (public edition)
Stars: ✭ 1,089 (+564.02%)
Mutual labels:  cryptocurrency, trading, binance
Siis
Trading bot including terminal, for crypto and traditionals markets. Assisted or fully automated strategy.
Stars: ✭ 45 (-72.56%)
Mutual labels:  cryptocurrency, trading, binance
Cassandre Trading Bot
Cassandre makes it easy to create your Java crypto trading bot. Our Spring boot starter takes care of exchange connections, accounts, orders, trades, and positions.
Stars: ✭ 120 (-26.83%)
Mutual labels:  cryptocurrency, trading, binance
Marketstore
DataFrame Server for Financial Timeseries Data
Stars: ✭ 1,290 (+686.59%)
Mutual labels:  cryptocurrency, trading, binance
Binance
A wrapper for the Binance REST and WebSocket APIs. Also beautifies responses
Stars: ✭ 304 (+85.37%)
Mutual labels:  cryptocurrency, cryptocurrency-exchanges, binance
Ccxws
WebSocket client for 38 cryptocurrency exchanges
Stars: ✭ 341 (+107.93%)
Mutual labels:  cryptocurrency, cryptocurrency-exchanges, binance
Binance Api Node
💹 A complete and heavily tested wrapper with typings for the Binance API.
Stars: ✭ 260 (+58.54%)
Mutual labels:  cryptocurrency, cryptocurrency-exchanges, binance
Cryptofeed
Cryptocurrency Exchange Websocket Data Feed Handler
Stars: ✭ 643 (+292.07%)
Mutual labels:  cryptocurrency, trading, binance
binance-downloader
Python tool to download Binance Candlestick (k-line) data from REST API
Stars: ✭ 44 (-73.17%)
Mutual labels:  trading, cryptocurrency-exchanges, binance
Bybit-Auto-Trading-Bot-Ordes-placed-via-TradingView-Webhook
Python based Trading Bot that uses TradingView.com webhook JSON alerts to place orders(buy/sell/close/manage positions/TP/SL/TS etc.) on Bybit.com. Hire me directly here https://www.freelancer.com/u/Beannsofts for any assistance
Stars: ✭ 235 (+43.29%)
Mutual labels:  trading, cryptocurrency-exchanges, binance
Gekko Strategies
Strategies to Gekko trading bot with backtests results and some useful tools.
Stars: ✭ 1,022 (+523.17%)
Mutual labels:  cryptocurrency, cryptocurrency-exchanges, trading
Cryptotik
deprecated
Stars: ✭ 78 (-52.44%)
Mutual labels:  cryptocurrency, cryptocurrency-exchanges, binance

binance-rs

Unofficial Rust Library for the Binance API and Binance Futures API

Crates.io Build Status MIT licensed Apache-2.0 licensed

Documentation on docs.rs

Binance API Telegram

https://t.me/binance_api_english

Risk Warning

It is a personal project, use at your own risk. I will not be responsible for your investment losses. Cryptocurrency investment is subject to high market risk.

Usage

Add this to your Cargo.toml

[dependencies]
binance = { git = "https://github.com/wisespace-io/binance-rs.git" }

Rust >= 1.41

rustup install stable

Table of Contents

MARKET DATA

use binance::api::*;
use binance::market::*;

fn main() {
    let market: Market = Binance::new(None, None);

    // Order book at default depth
    match market.get_depth("BNBETH") {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {}", e),
    }

    // Order book at depth 500
    match market.get_custom_depth("BNBETH", 500) {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {}", e),
    }

    // Latest price for ALL symbols
    match market.get_all_prices() {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    // Latest price for ONE symbol
    match market.get_price("BNBETH") {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    // Current average price for ONE symbol
    match market.get_average_price("BNBETH") {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    // Best price/qty on the order book for ALL symbols
    match market.get_all_book_tickers() {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    // Best price/qty on the order book for ONE symbol
    match market.get_book_ticker("BNBETH") {
        Ok(answer) => println!(
            "Bid Price: {}, Ask Price: {}",
            answer.bid_price, answer.ask_price
        ),
        Err(e) => println!("Error: {:?}", e),
    }

    // 24hr ticker price change statistics
    match market.get_24h_price_stats("BNBETH") {
        Ok(answer) => println!(
            "Open Price: {}, Higher Price: {}, Lower Price: {:?}",
            answer.open_price, answer.high_price, answer.low_price
        ),
        Err(e) => println!("Error: {:?}", e),
    }

    // last 10 5min klines (candlesticks) for a symbol:
    match market.get_klines("BNBETH", "5m", 10, None, None) {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }
}

ACCOUNT DATA

use binance::api::*;
use binance::account::*;

fn main() {
    let api_key = Some("YOUR_API_KEY".into());
    let secret_key = Some("YOUR_SECRET_KEY".into());

    let account: Account = Binance::new(api_key, secret_key);

    match account.get_account() {
        Ok(answer) => println!("{:?}", answer.balances),
        Err(e) => println!("Error: {:?}", e),
    }

    match account.get_open_orders("WTCETH") {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    match account.limit_buy("WTCETH", 10, 0.014000) {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    match account.market_buy("WTCETH", 5) {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    match account.limit_sell("WTCETH", 10, 0.035000) {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    match account.market_sell("WTCETH", 5) {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    match account.custom_order("WTCETH", 9999, 0.0123, "SELL", "LIMIT", "IOC") {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    let order_id = 1_957_528;
    match account.order_status("WTCETH", order_id) {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    match account.cancel_order("WTCETH", order_id) {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    match account.cancel_all_open_orders("WTCETH") {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    match account.get_balance("KNC") {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }

    match account.trade_history("WTCETH") {
        Ok(answer) => println!("{:?}", answer),
        Err(e) => println!("Error: {:?}", e),
    }
}

ERROR HANDLING

Provides more detailed error information

You can check out the Binance Error Codes

use binance::errors::ErrorKind as BinanceLibErrorKind;

[...]

Err(err) => {
    println!("Can't put an order!");

    match err.0 {
        BinanceLibErrorKind::BinanceError(response) => match response.code {
            -1013_i16 => println!("Filter failure: LOT_SIZE!"),
            -2010_i16 => println!("Funds insufficient! {}", response.msg),
            _ => println!("Non-catched code {}: {}", response.code, response.msg),
        },
        BinanceLibErrorKind::Msg(msg) => {
            println!("Binancelib error msg: {}", msg)
        }
        _ => println!("Other errors: {}.", err.0),
    };
}

TESTNET AND API CLUSTERS

You can overwrite the default binance api urls if there are performance issues with the endpoints.

You can check out the Binance API Clusters.

The same is applicable for Testnet and Binance.US support. See example below:

let general: General = if use_testnet {
    let config = Config::default().set_rest_api_endpoint("https://testnet.binance.vision");
                                  // .set_ws_endpoint("wss://testnet.binance.vision/ws")
                                  // .set_futures_rest_api_endpoint("https://testnet.binancefuture.com/api")
                                  // .set_futures_ws_endpoint("https://testnet.binancefuture.com/ws")
    Binance::new_with_config(None, None, &config)
} else {
    Binance::new(None, None)
};

USER STREAM CONFIGURATION

use binance::api::*;
use binance::userstream::*;

fn main() {
    let api_key_user = Some("YOUR_API_KEY".into());
    let user_stream: UserStream = Binance::new(api_key_user.clone(), None);

    if let Ok(answer) = user_stream.start() {
        println!("Data Stream Started ...");
        let listen_key = answer.listen_key;

        match user_stream.keep_alive(&listen_key) {
            Ok(msg) => println!("Keepalive user data stream: {:?}", msg),
            Err(e) => println!("Error: {:?}", e),
        }

        match user_stream.close(&listen_key) {
            Ok(msg) => println!("Close user data stream: {:?}", msg),
            Err(e) => println!("Error: {:?}", e),
        }
    } else {
        println!("Not able to start an User Stream (Check your API_KEY)");
    }
}

USER STREAM

use binance::api::*;
use binance::userstream::*;
use binance::websockets::*;
use std::sync::atomic::{AtomicBool};

fn main() {
    let api_key_user = Some("YOUR_KEY".into());
    let keep_running = AtomicBool::new(true); // Used to control the event loop
    let user_stream: UserStream = Binance::new(api_key_user, None);

    if let Ok(answer) = user_stream.start() {
	let listen_key = answer.listen_key;

	let mut web_socket: WebSockets = WebSockets::new(|event: WebsocketEvent| {
	    match event {
		WebsocketEvent::AccountUpdate(account_update) => {
		    for balance in &account_update.balance {
			println!("Asset: {}, free: {}, locked: {}", balance.asset, balance.free, balance.locked);
		    }
		},
		WebsocketEvent::OrderTrade(trade) => {
		    println!("Symbol: {}, Side: {}, Price: {}, Execution Type: {}", trade.symbol, trade.side, trade.price, trade.execution_type);
		},
		_ => (),
	    };
	    Ok(())
	});

	web_socket.connect(&listen_key).unwrap(); // check error
	    if let Err(e) = web_socket.event_loop(&keep_running) {
		match e {
		    err => {
		        println!("Error: {:?}", err);
		    }
		}
	     }
	} else {
	    println!("Not able to start an User Stream (Check your API_KEY)");
	}
}

TRADES

use binance::websockets::*;
use std::sync::atomic::{AtomicBool};

fn main() {
    let keep_running = AtomicBool::new(true); // Used to control the event loop
    let agg_trade: String = format!("[email protected]"); // All Symbols
    let mut web_socket: WebSockets = WebSockets::new(|event: WebsocketEvent| {
	match event {
        // 24hr rolling window ticker statistics for all symbols that changed in an array.
	    WebsocketEvent::DayTickerAll(ticker_events) => {
	        for tick_event in ticker_events {
		    if tick_event.symbol == "BTCUSDT" {
			let btcusdt: f32 = tick_event.average_price.parse().unwrap();
			let btcusdt_close: f32 = tick_event.current_close.parse().unwrap();
			println!("{} - {}", btcusdt, btcusdt_close);
		    }
		}
	    },
	    _ => (),
        };

        Ok(())
    });

    web_socket.connect(&agg_trade).unwrap(); // check error
    if let Err(e) = web_socket.event_loop(&keep_running) {
	match e {
	    err => {
	        println!("Error: {:?}", err);
	    }
	}
     }
}

KLINE

use binance::websockets::*;
use std::sync::atomic::{AtomicBool};

fn main() {
    let keep_running = AtomicBool::new(true); // Used to control the event loop
    let kline: String = format!("{}", "[email protected]_1m");
    let mut web_socket: WebSockets = WebSockets::new(|event: WebsocketEvent| {
        match event {
            WebsocketEvent::Kline(kline_event) => {
                println!("Symbol: {}, high: {}, low: {}", kline_event.kline.symbol, kline_event.kline.low, kline_event.kline.high);
            },
            _ => (),
        };
        Ok(())
    });
 
    web_socket.connect(&kline).unwrap(); // check error
    if let Err(e) = web_socket.event_loop(&keep_running) {
        match e {
          err => {
             println!("Error: {:?}", err);
          }
        }
     }
     web_socket.disconnect().unwrap();
}

MULTIPLE STREAMS

use binance::websockets::*;
use std::sync::atomic::{AtomicBool};

fn main() {
    let symbols: Vec<_> = vec!["ethbtc", "bnbeth"].into_iter().map(String::from).collect();
    let mut endpoints: Vec<String> = Vec::new();

    for symbol in symbols.iter() {
        endpoints.push(format!("{}@[email protected]", symbol.to_lowercase()));
    }

    let keep_running = AtomicBool::new(true);
    let mut web_socket: WebSockets<'_> = WebSockets::new(|event: WebsocketEvent| {
        if let WebsocketEvent::DepthOrderBook(depth_order_book) = event {
            println!("{:?}", depth_order_book);
        }

        Ok(())
    });

    web_socket.connect_multiple_streams(&endpoints).unwrap(); // check error
    if let Err(e) = web_socket.event_loop(&keep_running) {
        println!("Error: {:?}", e);
    }
    web_socket.disconnect().unwrap();
}

Other Exchanges

If you use Bitfinex check out my Rust library for bitfinex API

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].