bitbank 0.0.7
bitbank: ^0.0.7 copied to clipboard
Dart API wrapper for Bitbank.
bitbank #
A comprehensive Dart API wrapper for Bitbank cryptocurrency exchange with built-in weighted average cost calculation functionality.
English | 日本語
🚀 Features #
- Complete Bitbank API Integration: Seamlessly interact with Bitbank's private API
- Asset Management: Retrieve detailed information about your cryptocurrency holdings
- Trade History: Access comprehensive trading history with detailed transaction data
- Spot Order Management: Create/cancel orders, bulk cancel, fetch active orders and orders info
- Public Market Data: Fetch candlesticks, order book depth, tickers, and recent transactions (no API key required)
- Weighted Average Cost Calculation: Built-in functionality to calculate investment cost basis
- Type-Safe Models: Robust data structures using Freezed for immutable, serializable models
- HMAC-SHA256 Authentication: Secure API authentication implementation
- Network Information: Detailed network and withdrawal fee information for each asset
📦 Installation #
Add this to your package's pubspec.yaml file:
dependencies:
bitbank: ^0.0.2
Then run:
dart pub get
🔧 Setup #
- Obtain your API credentials from Bitbank
- Create API key and secret in your Bitbank account settings
- Ensure your API key has the necessary permissions for the endpoints you plan to use
📖 Usage #
Basic Setup #
import 'package:bitbank/bitbank.dart';
final bitbank = Bitbank(
apiKey: 'your_api_key_here',
apiSecret: 'your_api_secret_here',
);
Get Asset Information #
Retrieve detailed information about your cryptocurrency holdings:
try {
final assetsResponse = await bitbank.assets();
print('Success: ${assetsResponse.success}');
print('Number of assets: ${assetsResponse.data.assets.length}');
for (final asset in assetsResponse.data.assets) {
print('Asset: ${asset.asset}');
print('Free Amount: ${asset.freeAmount}');
print('Onhand Amount: ${asset.onhandAmount}');
print('Locked Amount: ${asset.lockedAmount}');
print('Withdrawal Fee: ${asset.withdrawalFee}');
print('---');
}
} catch (e) {
print('Error: $e');
}
Get Trade History #
Access your trading history for specific currency pairs:
try {
final tradeHistory = await bitbank.tradeHistory(coinType: CoinType.btc);
print('Number of trades: ${tradeHistory.data.trades.length}');
for (final trade in tradeHistory.data.trades) {
print('Trade ID: ${trade.tradeId}');
print('Pair: ${trade.pair}');
print('Side: ${trade.side}'); // 'buy' or 'sell'
print('Amount: ${trade.amount}');
print('Price: ${trade.price}');
print('Fee: ${trade.feeAmountBase}');
print('Executed At: ${DateTime.fromMillisecondsSinceEpoch(trade.executedAt)}');
print('---');
}
} catch (e) {
print('Error: $e');
}
Place and Manage Spot Orders #
Create, fetch, list, and cancel spot orders:
// Create a limit order
final created = await bitbank.createOrder(
coinType: CoinType.btc,
side: 'buy',
type: 'limit',
amount: '0.001',
price: '5000000',
);
// Fetch the created order
final fetched = await bitbank.getOrder(
coinType: CoinType.btc,
orderId: created.data.orderId,
);
// List active orders for a pair
final activeOrders = await bitbank.getActiveOrders(coinType: CoinType.btc);
// Fetch multiple orders info
final infoOrders = await bitbank.getOrdersInfo(
coinType: CoinType.btc,
orderIds: [created.data.orderId],
);
// Cancel the order
final cancelled = await bitbank.cancelOrder(
coinType: CoinType.btc,
orderId: created.data.orderId,
);
// Bulk cancel orders
final bulkCancelled = await bitbank.cancelOrders(
coinType: CoinType.btc,
orderIds: [12345678, 98765432],
);
Public Market Data (no API key required) #
You can call public endpoints using static methods on Bitbank:
// Latest ticker
final ticker = await Bitbank.ticker(coinType: CoinType.btc);
// Candlesticks
final candles = await Bitbank.candlestick(
coinType: CoinType.btc,
candleType: '1day',
yyyymmdd: '20240101',
);
// Order book depth
final depth = await Bitbank.depth(coinType: CoinType.btc);
// Recent transactions (optionally pass date like '20240101')
final txs = await Bitbank.transactions(coinType: CoinType.btc);
Calculate Weighted Average Cost #
Automatically calculate the weighted average cost of your investments:
try {
final tradeHistory = await bitbank.tradeHistory(coinType: CoinType.btc);
// Calculate weighted average cost from trade history
final result = tradeHistory.calculateWeightedAverageCost();
print('Current Quantity: ${result.currentQuantity}');
print('Average Cost: ${result.averageCost}');
print('Total Cost: ${result.totalCost}');
} catch (e) {
print('Error: $e');
}
Manual Weighted Average Cost Calculation #
You can also calculate weighted average cost manually with custom transaction data:
import 'package:bitbank/bitbank.dart';
// Create transaction list manually
final transactions = [
Transaction(quantity: 1.0, price: 5000000), // Buy 1 BTC at 5,000,000 JPY
Transaction(quantity: 0.5, price: 6000000), // Buy 0.5 BTC at 6,000,000 JPY
Transaction(quantity: -0.3, price: 7000000), // Sell 0.3 BTC at 7,000,000 JPY
];
final result = calWeightedAverageCost(transactions);
print('Current Holdings: ${result.currentQuantity} BTC');
print('Average Cost: ${result.averageCost} JPY per BTC');
print('Total Investment: ${result.totalCost} JPY');
🧪 Tests #
Integration tests are provided and are skipped unless the following environment variables are set (actual orders may be created/cancelled; use with caution):
BITBANK_API_KEYBITBANK_SECRETBITBANK_TEST_PAIR(e.g.btc_jpy)BITBANK_TEST_ORDER_AMOUNT(e.g.0.001)BITBANK_TEST_ORDER_PRICE(e.g.5000000for limit orders)BITBANK_TEST_ORDER_PRICE2(optional, used for bulk cancel second order)BITBANK_TEST_SIDE(optional, defaultbuy)BITBANK_TEST_TYPE(optional, defaultlimit)
Run tests:
dart test
Note: Bitbank imposes request rate limits. In the integration tests we space calls by ~166ms (≈6 req/sec). Consider adding small delays when chaining multiple private API calls.
📊 Data Models #
This library provides comprehensive, type-safe data models:
Asset #
- Asset information including balances, fees, and network details
- Free, onhand, locked, and withdrawing amounts
- Withdrawal fees and deposit/withdrawal status
- Network-specific information for multi-chain assets
Trade #
- Complete trade information including IDs, amounts, and fees
- Execution timestamps and maker/taker information
- Automatic conversion to Transaction objects for cost calculation
WeightedAverageCostResult #
- Current quantity holdings
- Calculated average cost per unit
- Total cost basis of current holdings
🔒 Security #
- All API requests are authenticated using HMAC-SHA256 signatures
- API credentials are never logged or exposed
- Secure nonce generation for request authentication
🤝 Contributing #
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
📄 License #
This project is licensed under the MIT License - see the LICENSE file for details.
🆘 Support #
If you find this package helpful, please consider:
- ⭐ Starring the repository
- 🐛 Reporting bugs via GitHub Issues
- 💡 Suggesting new features
- 💖 Sponsoring the project
🔗 Links #
- Bitbank Official Website
- Bitbank API Documentation
- Private/Spot endpoints used in this library, including order creation/cancellation and order queries, follow the official REST API signing rules (HMAC-SHA256 over
nonce + path [+ body]) as documented here: Bitbank REST API docs
- Private/Spot endpoints used in this library, including order creation/cancellation and order queries, follow the official REST API signing rules (HMAC-SHA256 over
- Package on pub.dev