| sidebar_position | 1 |
|---|
:::tip Skip the boilerplate Everything on this page is the manual path: you wire up the client, the candles, the risk checks and the deployment yourself. If you would rather go from idea to backtested strategy in an afternoon, ChipaEditor generates the strategy from a plain language description in CHTL, backtests it on historical data, and deploys it to a live broker connection. Free to start — then come back here when you need full control. :::
Complete API reference for BinaryOptionsTools with examples in all supported languages.
pip install binaryoptionstoolsv2The Node.js bindings are built from source; Node.js 18+ and a Rust toolchain are required.
cd nodejs
npm run build[dependencies]
binary_options_tools = "0.2.17"
tokio = { version = "1", features = ["full"] }
tokio-stream = "0.1"These bindings are not published to any package registry — there is no Maven,
NuGet, RubyGems or Go module to install, and no Swift package. They are generated
from this repository with uniffi-bindgen (proc-macro based, no .udl file):
# supported languages: kotlin, swift, python, ruby
cargo run -p binary_options_tools_uni --bin uniffi-bindgen generate --library --language kotlin --out-dir out/kotlin
cargo run -p binary_options_tools_uni --bin uniffi-bindgen generate --library --language swift --out-dir out/swift
# then add the generated sources plus the compiled library to your project
cargo build --release -p binary_options_tools_uniGo and C# are not supported by the in-repo generator; use the community
uniffi-bindgen-go / uniffi-bindgen-cs against the same compiled library. See
crates/bindings_uniffi/README.md for the
per-language build notes and the examples for the API shape.
import asyncio
from BinaryOptionsToolsV2 import PocketOptionAsync
async def main():
async with PocketOptionAsync("your_ssid") as client:
balance = await client.balance()
print(f"Balance: ${balance}")
asyncio.run(main())from BinaryOptionsToolsV2 import PocketOption
with PocketOption("your_ssid") as client:
balance = client.balance()
print(f"Balance: ${balance}")const { PocketOption } = require("binary-options-tools");
async function main() {
// The constructor connects in the background; every method awaits it.
const client = new PocketOption("your_ssid");
const balance = await client.balance();
console.log(`Balance: $${balance}`);
await client.shutdown();
}
main();use binary_options_tools::pocketoption::PocketOption;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = PocketOption::new("your_ssid").await?;
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
let balance = client.balance().await?;
println!("Balance: ${}", balance);
client.shutdown().await?;
Ok(())
}# Place a $1 call trade on EURUSD_otc for 60 seconds
trade_id, trade = await client.buy("EURUSD_otc", 1.0, 60)
print(f"Trade ID: {trade.id}")
print(f"Asset: {trade.asset}")
print(f"Amount: ${trade.amount}")// Place a $1 call trade on EURUSD_otc for 60 seconds
const [tradeId, deal] = await client.buy("EURUSD_otc", 1.0, 60);
console.log(`Trade ID: ${tradeId}`);
console.log(`Asset: ${deal.asset}`);
console.log(`Amount: $${deal.amount}`);// Place a $1 call trade on EURUSD_otc for 60 seconds
let trade = client.buy("EURUSD_otc", 60, 1.0).await?;
println!("Trade ID: {}", trade.id);
println!("Asset: {}", trade.asset);
println!("Amount: ${}", trade.amount);# Place a $1 put trade on EURUSD_otc for 60 seconds
trade_id, trade = await client.sell("EURUSD_otc", 1.0, 60)
print(f"Trade ID: {trade.id}")// Place a $1 put trade on EURUSD_otc for 60 seconds
const [tradeId] = await client.sell("EURUSD_otc", 1.0, 60);
console.log(`Trade ID: ${tradeId}`);// Place a $1 put trade on EURUSD_otc for 60 seconds
let trade = client.sell("EURUSD_otc", 60, 1.0).await?;
println!("Trade ID: {}", trade.id);# Check if a trade won or lost
result = await client.check_win(trade_id)
print(f"Result: {'WIN' if result.profit > 0 else 'LOSS'}")
print(f"Profit: ${result.profit}")// Waits for the trade to settle, then reports it
const result = await client.result(tradeId);
console.log(`Result: ${result.profit > 0 ? "WIN" : "LOSS"}`);
console.log(`Profit: $${result.profit}`);// Check if a trade won or lost
let result = client.result(trade.id).await?;
println!("Result: {}", if result.profit > 0 { "WIN" } else { "LOSS" });
println!("Profit: ${}", result.profit);balance = await client.balance()
print(f"Current balance: ${balance:.2f}")const balance = await client.balance();
console.log(`Current balance: $${balance.toFixed(2)}`);let balance = client.balance().await?;
println!("Current balance: ${:.2}", balance);is_demo = client.is_demo()
account_type = "Demo" if is_demo else "Real"
print(f"Account type: {account_type}")const isDemo = await client.isDemo();
const accountType = isDemo ? "Demo" : "Real";
console.log(`Account type: ${accountType}`);let is_demo = client.is_demo().await?;
let account_type = if is_demo { "Demo" } else { "Real" };
println!("Account type: {}", account_type);open_deals = await client.opened_deals()
print(f"Open trades: {len(open_deals)}")
for deal in open_deals:
print(f" {deal.asset}: ${deal.amount} ({deal.action})")// Running deals, keyed by deal id
const openDeals = await client.openedDeals();
console.log(`Open trades: ${Object.keys(openDeals).length}`);
for (const deal of Object.values(openDeals)) {
console.log(` ${deal.asset}: $${deal.amount} (${deal.action})`);
}let open_deals = client.get_opened_deals().await?;
println!("Open trades: {}", open_deals.len());
for deal in open_deals {
println!(" {}: ${} ({})", deal.asset, deal.amount, deal.action);
}closed_deals = await client.closed_deals()
print(f"Closed trades: {len(closed_deals)}")
for deal in closed_deals:
result = "WIN" if deal.profit > 0 else "LOSS"
print(f" {deal.asset}: {result} (${deal.profit:.2f})")// Settled deals, keyed by deal id
const closedDeals = await client.closedDeals();
console.log(`Closed trades: ${Object.keys(closedDeals).length}`);
for (const deal of Object.values(closedDeals)) {
const result = deal.profit > 0 ? "WIN" : "LOSS";
console.log(` ${deal.asset}: ${result} ($${deal.profit.toFixed(2)})`);
}let closed_deals = client.get_closed_deals().await?;
println!("Closed trades: {}", closed_deals.len());
for deal in closed_deals {
let result = if deal.profit > 0 { "WIN" } else { "LOSS" };
println!(" {}: {} (${})", deal.asset, result, deal.profit);
}Note: Historical candles are fetched and manually compiled locally on the client from 1-second raw ticks. Timestamps are grouped strictly according to UTC calendar boundaries (
timestamp / period * period), avoiding server-side candle time-alignment mismatches, gaps, or overlaps ("merges"). This applies to both.candles()(default 1000 periods lookback) and.compile_candles()(custom lookback period).
# Get last 100 candles with 60-second period
candles = await client.get_candles("EURUSD_otc", 60, 100)
print(f"Retrieved {len(candles)} candles")
for candle in candles[:5]: # Show first 5
print(f" Time: {candle.time}, Close: {candle.close}")// 60-second candles, looking back one hour
const candles = await client.getCandles("EURUSD_otc", 60, 3600);
console.log(`Retrieved ${candles.length} candles`);
candles.slice(0, 5).forEach((candle) => {
console.log(` Time: ${candle.time}, Close: ${candle.close}`);
});// Get last 100 candles with 60-second period
let candles = client.get_candles("EURUSD_otc", 60, 100).await?;
println!("Retrieved {} candles", candles.len());
for candle in candles.iter().take(5) {
println!(" Time: {}, Close: {}", candle.time, candle.close);
}server_time = await client.get_server_time()
print(f"Server timestamp: {server_time}")const serverTime = await client.serverTime();
console.log(`Server timestamp: ${serverTime}`);let server_time = client.server_time().await?;
println!("Server timestamp: {}", server_time);# Subscribe to 60-second candles
subscription = await client.subscribe_symbol("EURUSD_otc")
print("Subscribed to EURUSD_otc")
# Iterate over candles
async for candle in subscription:
print(f"Candle: {candle}")// Subscribe to 60-second candles
const subscription = await client.subscribe("EURUSD_otc", 60);
console.log("Subscribed to EURUSD_otc");
// Receive candles (async iterator)
for await (const candle of subscription) {
console.log(`Candle: ${JSON.stringify(candle)}`);
}use binary_options_tools::pocketoption::candle::SubscriptionType;
// Subscribe to 60-second candles
let mut subscription = client
.subscribe("EURUSD_otc", SubscriptionType::time(Duration::from_secs(60)))
.await?;
println!("Subscribed to {}", subscription.asset());
// `SubscriptionStream` is not a `Stream`: it yields completed candles via receive()
loop {
match subscription.receive().await {
Ok(candle) => println!("Candle {} -> {}", candle.timestamp, candle.close),
Err(e) => {
eprintln!("stream ended: {e}");
break;
}
}
}await client.unsubscribe("EURUSD_otc")
print("Unsubscribed from EURUSD_otc")await client.unsubscribe("EURUSD_otc");
console.log("Unsubscribed from EURUSD_otc");client.unsubscribe("EURUSD_otc").await?;
println!("Unsubscribed from EURUSD_otc");await client.reconnect()
await asyncio.sleep(2) # Wait for reconnection
print("Reconnected to server")await client.reconnect();
await new Promise((resolve) => setTimeout(resolve, 2000));
console.log("Reconnected to server");client.reconnect().await?;
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
println!("Reconnected to server");await client.shutdown()
print("Client shut down gracefully")await client.shutdown();
console.log("Client shut down gracefully");client.shutdown().await?;
println!("Client shut down gracefully");from BinaryOptionsToolsV2 import PocketOptionAsync, PocketError
try:
client = await PocketOptionAsync("invalid_ssid")
balance = await client.balance()
except PocketError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")const { PocketOption } = require("binary-options-tools");
try {
const client = new PocketOption("invalid_ssid");
const balance = await client.balance();
} catch (e) {
// The message is prefixed with the error kind, e.g.
// "PocketOptionError: ..." or "TimeoutError: ...".
console.log(`Error: ${e.message}`);
}use binary_options_tools::error::PocketError;
match PocketOption::new("invalid_ssid").await {
Ok(client) => {
match client.balance().await {
Ok(balance) => println!("Balance: {}", balance),
Err(e) => eprintln!("Error: {}", e),
}
}
Err(e) => eprintln!("Error: {}", e),
}Wait 2 seconds after creating the client:
- Python:
await asyncio.sleep(2) - Rust:
tokio::time::sleep(Duration::from_secs(2)).await
JavaScript is the exception: every method already awaits the pending
connection, so no sleep is needed. Use await PocketOption.create(ssid) when
a failed connection should reject up front.
Call shutdown() when done to clean up resources.
Always verify account type before trading with real money:
if not client.is_demo():
print("WARNING: Using REAL account!")Use try-catch blocks to handle connection errors and invalid operations.
For time-sensitive operations, use result_with_timeout():
result = await client.check_win(trade_id, timeout_seconds=120)See the examples directory for complete working examples in each language:
The Rust core is the source of truth; the bindings rename a few methods. Python optically renamed the trade-result and deal accessors, which is why a Python snippet cannot be pasted into the other examples:
| Concept | Rust / UniFFI | Node | Python |
|---|---|---|---|
| Place a trade | buy(asset, time, amount) |
buy(asset, amount, time) |
buy(asset, amount, time) |
| Trade settled | result(id) |
result(id) |
check_win(id, timeout_seconds=None) |
| Open trades | get_opened_deals() |
openedDeals() / get_opened_deals() |
opened_deals() |
| Closed trades | get_closed_deals() |
closedDeals() / get_closed_deals() |
closed_deals() |
| Broker clock | server_time() |
serverTime() / server_time() |
get_server_time() |
| Subscribe | subscribe(asset) |
subscribe(asset) |
subscribe_symbol(asset) |
The time/amount order differs between Rust and Node/Python — the most common
porting mistake. Node also exposes snake_case aliases for its camelCase methods
(getOpenedDeals() / get_opened_deals(), checkWin() / check_win()), all
documented in nodejs/index.d.ts.
For the complete, current list per language see
Python API, nodejs/index.d.ts and the
PocketOption impl.
- Discord: Join our community
- GitHub Issues: Report bugs
- Documentation: Docs index
Version: 0.2.17
Last Updated: October 2026
Platform Support: PocketOption (Quick Trading)