Rust Documentation
High-performance Rust bindings for BinaryOptionsToolsV2
Zero-Cost Abstractions
Memory Safe
Ultra Fast
Async/Await
Installation
Add BinaryOptionsToolsV2 to your Rust project
toml
# Add to your Cargo.toml
[dependencies]
binary-options-tools-v2 = "2.0"
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
bash
cargo add binary-options-tools-v2 tokio serde
Quick Start
Basic usage examples for Rust applications
rust
use binary_options_tools_v2::{PocketOption, OrderOptions, Result};
#[tokio::main]
async fn main() -> Result<()> {
// Initialize the client
let client = PocketOption::new("your_ssid_here").await?;
// Get account balance
let balance = client.get_balance().await?;
println!("Balance: ${}", balance);
// Get candles data
let candles = client.get_candles("EURUSD_otc", 60, 100).await?;
for candle in candles {
println!("Open: {}, Close: {}", candle.open, candle.close);
}
// Create a raw order
let order_options = OrderOptions {
asset: "EURUSD_otc".to_string(),
amount: 10.0,
action: "call".to_string(),
expiration: 60,
};
let order_result = client.create_raw_order(order_options).await?;
println!("Order ID: {}", order_result.order_id);
// Check win status
let win_status = client.check_win(&order_result.order_id).await?;
println!("Win status: {:?}", win_status);
Ok(())
}
rust
use binary_options_tools_v2::{PocketOption, StreamEvent};
use tokio::time::{Duration, timeout};
use futures::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box> {
let client = PocketOption::new("your_ssid_here").await?;
// Concurrent operations
let (balance, candles, history) = tokio::try_join!(
client.get_balance(),
client.get_candles("EURUSD_otc", 60, 100),
client.get_history(50)
)?;
println!("Balance: ${}", balance);
println!("Candles count: {}", candles.len());
println!("History count: {}", history.len());
// Stream real-time candles with timeout
let mut stream = client.stream_candles("EURUSD_otc", 60).await?;
while let Ok(Some(event)) = timeout(Duration::from_secs(30), stream.next()).await {
match event? {
StreamEvent::Candle(candle) => {
println!("New candle: {} -> {}", candle.open, candle.close);
// Implement your trading logic here
if should_place_order(&candle) {
let order = client.create_raw_order(OrderOptions {
asset: "EURUSD_otc".to_string(),
amount: 10.0,
action: determine_action(&candle),
expiration: 60,
}).await?;
println!("Placed order: {}", order.order_id);
}
}
StreamEvent::Error(e) => {
eprintln!("Stream error: {}", e);
break;
}
}
}
Ok(())
}
fn should_place_order(candle: &CandleData) -> bool {
// Your trading logic here
candle.close > candle.open
}
fn determine_action(candle: &CandleData) -> String {
if candle.close > candle.open {
"call".to_string()
} else {
"put".to_string()
}
}
rust
use binary_options_tools_v2::{PocketOption, TradingBot, Strategy};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Serialize, Deserialize)]
struct TradingConfig {
ssid: String,
assets: Vec,
max_concurrent_orders: usize,
risk_percentage: f64,
}
struct AdvancedTradingBot {
client: PocketOption,
config: TradingConfig,
active_orders: HashMap,
}
impl AdvancedTradingBot {
async fn new(config: TradingConfig) -> Result> {
let client = PocketOption::new(&config.ssid).await?;
Ok(Self {
client,
config,
active_orders: HashMap::new(),
})
}
async fn run(&mut self) -> Result<(), Box> {
// Initialize multiple asset streams
let mut streams = Vec::new();
for asset in &self.config.assets {
let stream = self.client.stream_candles(asset, 60).await?;
streams.push(stream);
}
// Process streams concurrently
let mut combined_stream = futures::stream::select_all(streams);
while let Some(event) = combined_stream.next().await {
match event? {
StreamEvent::Candle(candle) => {
self.process_candle(candle).await?;
}
StreamEvent::OrderUpdate(update) => {
self.handle_order_update(update).await?;
}
_ => {}
}
}
Ok(())
}
async fn process_candle(&mut self, candle: CandleData) -> Result<(), Box> {
// Check if we can place more orders
if self.active_orders.len() >= self.config.max_concurrent_orders {
return Ok(());
}
// Analyze candle with multiple strategies
let strategies = vec![
MACDStrategy::new(),
RSIStrategy::new(),
BollingerBandsStrategy::new(),
];
let mut signals = Vec::new();
for strategy in strategies {
if let Some(signal) = strategy.analyze(&candle) {
signals.push(signal);
}
}
// Consensus-based trading
if signals.len() >= 2 {
let action = determine_consensus_action(&signals);
let amount = self.calculate_position_size().await?;
let order = self.client.create_raw_order(OrderOptions {
asset: candle.asset.clone(),
amount,
action,
expiration: 60,
}).await?;
self.active_orders.insert(order.order_id.clone(), OrderInfo {
id: order.order_id,
asset: candle.asset,
amount,
timestamp: std::time::SystemTime::now(),
});
}
Ok(())
}
async fn calculate_position_size(&self) -> Result> {
let balance = self.client.get_balance().await?;
let risk_amount = balance * self.config.risk_percentage / 100.0;
Ok(risk_amount.min(100.0).max(1.0)) // Min $1, Max $100
}
async fn handle_order_update(&mut self, update: OrderUpdate) -> Result<(), Box> {
if let Some(order_info) = self.active_orders.remove(&update.order_id) {
match update.status {
OrderStatus::Win => {
println!("✅ Order {} won! Profit: ${}", order_info.id, update.profit);
}
OrderStatus::Lose => {
println!("❌ Order {} lost. Loss: ${}", order_info.id, order_info.amount);
}
_ => {}
}
}
Ok(())
}
}
#[tokio::main]
async fn main() -> Result<(), Box> {
let config = TradingConfig {
ssid: "your_ssid_here".to_string(),
assets: vec![
"EURUSD_otc".to_string(),
"GBPUSD_otc".to_string(),
"USDJPY_otc".to_string(),
],
max_concurrent_orders: 3,
risk_percentage: 2.0,
};
let mut bot = AdvancedTradingBot::new(config).await?;
bot.run().await?;
Ok(())
}
Core Structs & Traits
Rust API reference with type safety
PocketOption
Main client struct for trading operations
async fn get_balance(&self) -> Result<f64>
Get account balance
async fn get_candles(&self, asset: &str, timeframe: u32, count: u32) -> Result<Vec<CandleData>>
Retrieve candlestick data
async fn create_raw_order(&self, options: OrderOptions) -> Result<OrderResult>
Place binary options order
async fn stream_candles(&self, asset: &str, timeframe: u32) -> Result<impl Stream<Item = StreamEvent>>
Stream real-time candles
Data Structures
Core data types with serde support
struct CandleData
{ open: f64, high: f64, low: f64, close: f64, volume: f64, timestamp: i64 }
struct OrderOptions
{ asset: String, amount: f64, action: String, expiration: u32 }
struct OrderResult
{ order_id: String, success: bool, message: String }
enum WinStatus
Win | Lose | Pending
Performance Features
Rust-powered performance optimizations
Zero-Cost Abstractions
High-level APIs with no runtime overhead
// Compiled to optimal machine code
let candles: Vec<CandleData> = client
.get_candles("EURUSD_otc", 60, 1000)
.await?
.into_iter()
.filter(|c| c.volume > 1000.0)
.collect();
Memory Safety
No null pointer dereferences or buffer overflows
// Compile-time guarantees
async fn safe_trading(client: &PocketOption) -> Result<f64, Error> {
let balance = client.get_balance().await?;
Ok(balance * 0.02) // 2% risk
}
Async Streams
Efficient async/await with Stream trait
use futures::StreamExt;
let mut stream = client.stream_candles("EURUSD_otc", 60).await?;
while let Some(candle) = stream.next().await {
process_candle(candle?).await?;
}
Type Safety
Compile-time error detection
// Compiler prevents runtime errors
let order = OrderOptions {
asset: "EURUSD_otc".to_string(),
amount: 10.0,
action: OrderAction::Call, // Enum prevents typos
expiration: Duration::from_secs(60),
};
Minimal Dependencies
Small binary size with selective features
# Only include what you need
[dependencies.binary-options-tools-v2]
version = "2.0"
default-features = false
features = ["tokio-runtime", "serde"]
Cross Compilation
Target multiple platforms from single codebase
# Build for different targets
cargo build --target x86_64-pc-windows-gnu
cargo build --target x86_64-unknown-linux-gnu
cargo build --target aarch64-apple-darwin
Error Handling
Robust error handling with Result type
rust
use binary_options_tools_v2::{PocketOption, Error, ErrorKind};
use thiserror::Error;
#[derive(Error, Debug)]
enum TradingError {
#[error("Insufficient balance: required {required}, available {available}")]
InsufficientBalance { required: f64, available: f64 },
#[error("Invalid asset: {asset}")]
InvalidAsset { asset: String },
#[error("API error: {0}")]
ApiError(#[from] Error),
}
async fn safe_order_placement(
client: &PocketOption,
asset: &str,
amount: f64,
) -> Result {
// Check balance first
let balance = client.get_balance().await?;
if balance < amount {
return Err(TradingError::InsufficientBalance {
required: amount,
available: balance,
});
}
// Validate asset
if !is_valid_asset(asset) {
return Err(TradingError::InvalidAsset {
asset: asset.to_string(),
});
}
// Place order with comprehensive error handling
match client.create_raw_order(OrderOptions {
asset: asset.to_string(),
amount,
action: "call".to_string(),
expiration: 60,
}).await {
Ok(result) => {
if result.success {
Ok(result.order_id)
} else {
Err(TradingError::ApiError(Error::new(
ErrorKind::OrderFailed,
result.message,
)))
}
}
Err(e) => match e.kind() {
ErrorKind::NetworkError => {
// Retry logic for network errors
tokio::time::sleep(Duration::from_secs(1)).await;
safe_order_placement(client, asset, amount).await
}
ErrorKind::AuthenticationError => {
// Handle auth errors
Err(TradingError::ApiError(e))
}
_ => Err(TradingError::ApiError(e)),
}
}
}
fn is_valid_asset(asset: &str) -> bool {
const VALID_ASSETS: &[&str] = &[
"EURUSD_otc", "GBPUSD_otc", "USDJPY_otc", "AUDUSD_otc"
];
VALID_ASSETS.contains(&asset)
}
#[tokio::main]
async fn main() -> Result<(), Box> {
let client = PocketOption::new("your_ssid").await?;
match safe_order_placement(&client, "EURUSD_otc", 10.0).await {
Ok(order_id) => println!("Order placed successfully: {}", order_id),
Err(TradingError::InsufficientBalance { required, available }) => {
eprintln!("Cannot place order: need ${}, have ${}", required, available);
}
Err(TradingError::InvalidAsset { asset }) => {
eprintln!("Invalid asset: {}", asset);
}
Err(TradingError::ApiError(e)) => {
eprintln!("API error: {}", e);
}
}
Ok(())
}
Need High-Performance Trading Solutions?
Get custom Rust trading applications built by experts at chipa.tech