Flutter加密货币交易插件coinbase_exchange的使用
Flutter加密货币交易插件coinbase_exchange的使用
本项目是一个用于Coinbase云交易所的Dart SDK。
开始使用
此项目是一个用于Coinbase交易所API的Dart SDK。该SDK允许你通过Coinbase WebSocket获取实时价格数据,并获取有关Coinbase和Coinbase Pro个人资料的信息。它还允许你在Coinbase Pro平台上进行加密货币交易。此包使用必须从Coinbase Pro或Coinbase Pro沙盒生成的API密钥。
为了确保你正确生成了密钥,创建一个名为test/secrets.dart
的文件,内容如下:
class Secrets {
static const String apiKey = ''; // 填入你的apiKey
static const String secretKey = ''; // 填入你的secretKey
static const String passphrase = ''; // 填入你的passphrase
}
然后在coinbase_exchange_test.dart
文件中调用以下命令:
pub run test --chain-stack-traces test/coinbase_exchange_test.dart
这将默认执行Coinbase Pro沙盒中的测试,因此请确保你使用了正确的密钥。目前测试还不完整,仅测试了账户、Coinbase账户、转换和币种。
WebSocket Feed
WebSocket Feed允许你订阅特定的产品ID和通道以接收实时数据。
// 确保导入包时不要污染你的环境。
import 'package:coinbase_exchange/coinbase_exchange.dart' as cb;
// 创建一个WebSocket客户端实例
cb.WebsocketClient wsClient = cb.WebsocketClient(sandbox: false); // 设置是否为沙盒模式
// 订阅特定的产品ID和通道
var stream = wsClient.subscribe(
productIds: ['BTC-USD'], // 指定要订阅的产品ID
channels: [
cb.ChannelEnum.heartBeat, // 订阅心跳通道
],
);
// 监听流中的事件
stream.listen((event) {
print(event.toJson().toString()); // 打印接收到的事件
wsClient.close(); // 关闭WebSocket连接
});
API
你可以使用API来获取账户信息等。
// 确保导入包时不要污染你的环境。
import 'package:coinbase_exchange/coinbase_exchange.dart' as cb;
// 获取账户列表
var accounts = await cb.accountsClient.listAccounts();
// 遍历并打印每个账户的货币类型
for (cb.Account account in accounts) {
print(account.currency);
}
完整示例
以下是完整的示例代码:
import 'dart:async';
import 'package:candlesticks/candlesticks.dart' as graph;
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:coinbase_exchange/coinbase_exchange.dart' as cb;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Coinbase Exchange Demo',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
[@override](/user/override)
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _client = cb.WebsocketClient();
final _streamController = StreamController.broadcast();
final oCcy = NumberFormat("#,##0.00", "en_US");
final _textStyle = const TextStyle(
fontSize: 28.0,
color: Colors.white70,
);
var btcPrice = '';
var ethPrice = '';
var ltePrice = '';
// 初始化ProductsClient
final cb.ProductsClient productsClient = cb.ProductsClient(
apiKey: '', // 填入你的apiKey
secretKey: '', // 填入你的secretKey
passphrase: '', // 填入你的passphrase
);
[@override](/user/override)
void initState() {
_client.connect();
_streamController.addStream(
_client.subscribe(
productIds: ['ETH-USD', 'BTC-USD', 'LTC-USD'], // 订阅的产品ID
channels: [cb.ChannelEnum.ticker], // 订阅通道
),
);
super.initState();
}
[@override](/user/override)
void dispose() {
_client.close();
_streamController.close();
super.dispose();
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color(0xff113650),
title: const Text(
'Coinbase Exchange Demo',
style: TextStyle(color: Colors.white70),
),
),
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xff1d3f64),
Color(0xff62467d),
],
)),
child: Center(
child: Column(
children: [
FutureBuilder(
future: productsClient.getProductCandles(
productId: 'BTC-USD',
),
builder: (BuildContext context,
AsyncSnapshot<List<cb.Candle>> snapshot) {
if (snapshot.hasData) {
List<graph.Candle> candles = snapshot.data!
.map((e) => graph.Candle(
date: e.time!,
high: e.high!,
low: e.low!,
open: e.open!,
close: e.close!,
volume: e.volume!,
))
.toList();
return AspectRatio(
aspectRatio: 1.2,
child: graph.Candlesticks(
candles: candles,
onIntervalChange: (_) async {},
interval: '1m',
),
);
}
return Container();
},
),
const SizedBox(height: 28.0),
StreamBuilder<dynamic>(
stream: _streamController.stream,
builder:
(BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (snapshot.connectionState == ConnectionState.none) {
return const Text('None');
} else if (snapshot.connectionState == ConnectionState.waiting) {
return const Text('Waiting...');
} else if (snapshot.connectionState == ConnectionState.active) {
var data = snapshot.data;
if (data is cb.StreamTicker) {
if (data.productId == 'ETH-USD') {
ethPrice = '\$' + oCcy.format(data.price);
} else if (data.productId == 'LTC-USD') {
ltePrice = '\$' + oCcy.format(data.price);
} else {
btcPrice = '\$' + oCcy.format(data.price);
}
return Column(
children: [
Text(
'Bitcoin Price: $btcPrice',
style: _textStyle,
),
const SizedBox(height: 18.0),
Text(
'Litecoin Price: $ltePrice',
style: _textStyle,
),
const SizedBox(height: 18.0),
Text(
'Etherium Price $ethPrice',
style: _textStyle,
),
],
);
} else {
return const Text('Something Else');
}
} else if (snapshot.connectionState == ConnectionState.done) {
return const Text('Done');
}
return Container();
},
),
],
),
),
),
);
}
}
更多关于Flutter加密货币交易插件coinbase_exchange的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复