运行命令:
python3 test.py
3个API库: 【binance.client】 ;binance-connector ;Binance_interface
环境安装:
pip3 install python-binance mysql-connector-python datetime ccxt
代码块【binance.client】
=========================================================================
#Mysql数据库初始化
import mysql.connector
# 建立数据库连接
mydb = mysql.connector.connect(
host=”localhost”,
user=”your_username”,
password=”your_password”,
database=”your_database”
)
# 创建游标对象
mycursor = mydb.cursor()
=========================================================================
# 创建新表如果数据库中不存在AA表
sql = “””
CREATE TABLE IF NOT EXISTS AA (
id INT AUTO_INCREMENT PRIMARY KEY, # INT 整数类型,自增主键,用于唯一标识每一行记录
name VARCHAR(255), # VARCHAR 类型,用于存储可变长度的字符串,最大长度为 255 个字符
price DECIMAL(10, 2), # DECIMAL 小数类型,存储精确的小数值,总共 10 位数字,其中小数部分占 2 位
created_at DATETIME, # DATETIME 类型,用于存储日期和时间信息
description TEXT, # TEXT 类型,用于存储较长的文本信息
is_active BOOL, # BOOL 类型,用于存储布尔值,True 或 False
extra_info JSON #保存json格式的数据
)
“””
# 执行创建表的SQL语句
mycursor.execute(sql)
print(“表 AA 创建成功”)
=========================================================================
# 增加数据
# 定义一个 SQL 插入语句,这里是向 AA 表的 name , price 和is_active列插入数据
# %s 是一个占位符,用于后续传递实际的值
sql = “INSERT INTO AA (name,price,is_active) VALUES (%s,%s,%s)”
# 定义要插入的值,这里是一个元组,因为 SQL 语句中有3个占位符
val = (“John Doe”,99.99,1)
# 执行 SQL 插入语句,并执行
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, “条记录插入成功,ID 为”, mycursor.lastrowid)
=========================================================================
# 查询最新3行的 name 列数据,取的行数 LIMIT 3
atest_row_sql = “SELECT name FROM AA ORDER BY id DESC LIMIT 3”
mycursor.execute(atest_row_sql)
#fetchall取多行的数据,类似[(‘John Doe88’,), (‘John Doe77’,), (‘John Doe66’,)],是嵌套元组,要两次转变
aa = mycursor.fetchall()
#数组转为单变量,要两次转变,元组的[0]是第1个值,元组的[1]是第2个值
bb = aa[0][0]
cc = aa[1][0]
print(bb)
print(cc)
=========================================================================
# 查询最新1行的 name ,price列数据,取的行数 LIMIT 1
latest_row_sql = “SELECT name, price FROM AA ORDER BY id DESC LIMIT 1”
mycursor.execute(latest_row_sql)
#fetchone只取一行的数据,类似(‘John Doe88’, Decimal(‘99.99’), 1),只有一个元组,只用1次转变
aa = mycursor.fetchone()
bb = aa[1]
print(bb)
=========================================================================
# 更新数据(修改数据)
# 要有数据,才能更新,没有数据不会作任何改变
# 这里有3个占位符,分别对应要更新的值(name,price)和条件中的 id 值,以id值来找更新的位置
sql = “UPDATE AA SET name = %s,price=%s WHERE id = %s”
# 定义要更新的值和条件中的 id 值,同样是一个元组
val = (“Jane Doe321”,555.321, 2)
# 执行 SQL 更新语句,执行
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, “条记录修改成功”)
=========================================================================
# 删除数据
# 定义一个 SQL 删除语句,删除 AA 表中 id 为指定值的记录
sql = “DELETE FROM AA WHERE id = %s”
# 定义要删除记录的 id 值,是一个元组
val = (2,)
# 执行 SQL 删除语句
mycursor.execute(sql, val)
mydb.commit()
# 打印删除操作影响的行数
print(mycursor.rowcount, “条记录删除成功”)
=========================================================================
#变量写入.txt文件里,其中data是变量
import json
#若文件不存在,则创建文件,保存在.py的根目录
with open(‘output.txt’, ‘w’, encoding=’utf-8′) as file:
# 转变为字符串
data = json.dumps(data)
# 将字符串写入文件
file.write(data)
=========================================================================
#从JSON中,读取变量
import json
# 模拟接收到的 JSON 数据
json_str = ‘{“name”: “John”, “age”: 30, “city”: “New York”}’
# 将 JSON 字符串解析为 Python 字典
aa = json.loads(json_str)
# 从字典中获取特定键的值
name = aa[“name”]
print(name)
=========================================================================
#等待XX秒
import time
# 暂停 5 秒
time.sleep(5)
=========================================================================
#unix纪元时间,转为UTC+8时间 ,安装命令 pip3 install datetime
import datetime
#把时间转换封装为函数
def ms_timestamp_to_utc8(timestamp_ms):
timestamp_s = timestamp_ms / 1000
utc_time = datetime.datetime.fromtimestamp(timestamp_s, datetime.UTC)
utc_plus_8 = datetime.timezone(datetime.timedelta(hours=8))
beijing_time = utc_time.astimezone(utc_plus_8)
return beijing_time
# 假设这是 Unix 纪元时间(毫秒)
timestamp_ms = 1744684107078
result = ms_timestamp_to_utc8(timestamp_ms)
print(result)
==========================================================================
#获取json里特定关键词:
#从字典的price键里取值
aa= bb.get(“price”)
#列表data中的字典获取变量,知道值在第几个字典时用
aa = data[0].get(‘price’)
#列表里有多个字典时,用for循环查找asset是XX的字典,再赋值;不知道值在第几个字典时使用
aa = None
for item in data:
if item[‘asset’] == ‘FDUSD’:
aa = item[‘accountAlias’]
break
==========================================================================
#binance.client实例初始化
from binance.client import Client
API_KEY = ‘3EMVyiwlLKFohYl7skG75BcNVrfRtfrSlw5IwqCF5aloq77gBdtmQGKExxxxxxxxxx’
API_SECRET = ‘ZkpvuT0Cvr6QJR3vk4GJb7v1A0rNpcMuVPsxNSluqw3ENngx6G77sxxxxxxxxxx’
client = Client(API_KEY, API_SECRET)
==========================================================================
#用于获取指定合约(如BTCUSDC)的最新价格。
ticker_price = client.futures_symbol_ticker(symbol=’BTCUSDC’)
返回:
{‘symbol’: ‘BTCUSDC’, ‘price’: ‘84836.80’, ‘time’: 1744684107078}
==========================================================================
#获取K线行情
# 获取最近 5 根 BTCUSDC 交易对的 1 分钟 K 线,包含正在进行,未收盘的K线
klines = client.futures_klines(
symbol=’BTCUSDC’,
interval=Client.KLINE_INTERVAL_1MINUTE,
limit=5
)
# 打印 K 线数据
for kline in klines:
print(kline)
返回:
[1744685400000, ‘84859.3’, ‘84884.0’, ‘84840.1’, ‘84884.0’, ‘6.320’, 1744685459999,
‘536298.5681’, 195, ‘5.322’, ‘451615.6983’, ‘0’]
时间戳相关,价格,成交量,195交易笔数,5.322主动买入量,451615.6983主动买入额
==========================================================================
#U 本位永续合约账户的【全部】信息,如账户余额、可用保证金等,此函数无需传入参数【数据太多】
account_info = client.futures_account()
print(account_info)
返回:【一大串300Kb】
{‘symbol’: ‘SUNUSDT’, ‘initialMargin’: ‘0’, ‘maintMargin’: ‘0’, ‘unrealizedProfit’:
‘0.00000000’, ‘positionInitialMargin’: ‘0’, ‘openOrderInitialMargin’: ‘0’, ‘leverage’:
’20’, ‘isolated’: False, ‘entryPrice’: ‘0.0’, ‘breakEvenPrice’: ‘0.0’, ‘maxNotional’:
‘5000’, ‘positionSide’: ‘SHORT’, ‘positionAmt’: ‘0’, ‘notional’: ‘0’, ‘isolatedWallet’:
‘0’, ‘updateTime’: 0, ‘bidNotional’: ‘0’, ‘askNotional’: ‘0’}
==========================================================================
#获取 U 本位永续合约账户的USDT、USDC、BNB 余额信息。
balance_info = client.futures_account_balance()
print(balance_info)
返回:
[{‘accountAlias’: ‘SgAusRuXSgsRSg’, ‘asset’: ‘FDUSD’, ‘balance’: ‘0.00000000’,
‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’:
‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘marginAvailable’: True, ‘updateTime’: 0},
{‘accountAlias’: ‘SgAusRuXSgsRSg’, ‘asset’: ‘LDUSDT’, ‘balance’: ‘0.00000000’,
‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’:
‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘marginAvailable’: True, ‘updateTime’: 0},
{‘accountAlias’: ‘SgAusRuXSgsRSg’, ‘asset’: ‘BFUSD’, ‘balance’: ‘0.00000000’,
‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’:
‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘marginAvailable’: True, ‘updateTime’: 0},
{‘accountAlias’: ‘SgAusRuXSgsRSg’, ‘asset’: ‘BNB’, ‘balance’: ‘0.00000000’,
‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’:
‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘marginAvailable’: True, ‘updateTime’: 0},
{‘accountAlias’: ‘SgAusRuXSgsRSg’, ‘asset’: ‘ETH’, ‘balance’: ‘0.00000000’,
‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’:
‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘marginAvailable’: True, ‘updateTime’: 0},
{‘accountAlias’: ‘SgAusRuXSgsRSg’, ‘asset’: ‘BTC’, ‘balance’: ‘0.00000000’,
‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’:
‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘marginAvailable’: True, ‘updateTime’: 0},
{‘accountAlias’: ‘SgAusRuXSgsRSg’, ‘asset’: ‘USDT’, ‘balance’: ‘0.00000000’,
‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’:
‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘marginAvailable’: True, ‘updateTime’: 0},
{‘accountAlias’: ‘SgAusRuXSgsRSg’, ‘asset’: ‘USDC’, ‘balance’: ‘10.00000000’,
‘crossWalletBalance’: ‘10.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’:
‘10.00000000’, ‘maxWithdrawAmount’: ‘10.00000000’, ‘marginAvailable’: True, ‘updateTime’:
1744682067394}]
==========================================================================
#该函数用于获取特定合约或所有合约的持仓信息。symbol(可选):合约符号,如 ‘BTCUSDC’
#不写symbol 等于返回所有的持仓信息
btc_positions = client.futures_position_information(symbol=’BTCUSDC’)
print(“BTCUSDT 合约的持仓信息:”, btc_positions)
返回: 单向持仓只返回long,双向持仓返回long和short
[{‘symbol’: ‘BTCUSDC’, ‘positionSide’: ‘LONG’, ‘positionAmt’: ‘0.002’, ‘entryPrice’: ‘83701.9’, ‘breakEvenPrice’: ‘83701.9’, ‘markPrice’: ‘83670.30000000’, ‘unRealizedProfit’: ‘-0.06320000’, ‘liquidationPrice’: ‘432525.32687500’, ‘isolatedMargin’: ‘0’, ‘notional’: ‘167.34060000’, ‘marginAsset’: ‘USDC’, ‘isolatedWallet’: ‘0’, ‘initialMargin’: ‘3.21808859’, ‘maintMargin’: ‘0.66936240’, ‘positionInitialMargin’: ‘3.21808859’, ‘openOrderInitialMargin’: ‘0’, ‘adl’: 0, ‘bidNotional’: ‘0’, ‘askNotional’: ‘0’, ‘updateTime’: 1744757414350}, {‘symbol’: ‘BTCUSDC’, ‘positionSide’: ‘SHORT’, ‘positionAmt’: ‘-0.002’, ‘entryPrice’: ‘83667.0’, ‘breakEvenPrice’: ‘83667.0’, ‘markPrice’: ‘83670.30000000’, ‘unRealizedProfit’: ‘-0.00660000’, ‘liquidationPrice’: ‘432525.32687500’, ‘isolatedMargin’: ‘0’, ‘notional’: ‘-167.34060000’, ‘marginAsset’: ‘USDC’, ‘isolatedWallet’: ‘0’, ‘initialMargin’: ‘3.21808859’, ‘maintMargin’: ‘0.66936240’, ‘positionInitialMargin’: ‘3.21808859’, ‘openOrderInitialMargin’: ‘0’, ‘adl’: 0, ‘bidNotional’: ‘0’, ‘askNotional’: ‘0’, ‘updateTime’: 1744757451984}]
==========================================================================
#函数用于当前U本位永续合约账户中,查看当前挂单。symbol=None 则返回全部交易对
aa = client.futures_get_open_orders(symbol=’BTCUSDC’)
print(aa)
返回:
[{‘orderId’: 12697388393, ‘symbol’: ‘BTCUSDC’, ‘status’: ‘NEW’, ‘clientOrderId’:
‘android_sbxR4o37g7lnYEj761QO’, ‘price’: ‘81394.6’, ‘avgPrice’: ‘0’, ‘origQty’: ‘0.004’,
‘executedQty’: ‘0’, ‘cumQuote’: ‘0.0000’, ‘timeInForce’: ‘GTC’, ‘type’: ‘LIMIT’,
‘reduceOnly’: False, ‘closePosition’: False, ‘side’: ‘BUY’, ‘positionSide’: ‘LONG’,
‘stopPrice’: ‘0’, ‘workingType’: ‘CONTRACT_PRICE’, ‘priceProtect’: False, ‘origType’:
‘LIMIT’, ‘priceMatch’: ‘NONE’, ‘selfTradePreventionMode’: ‘EXPIRE_MAKER’, ‘goodTillDate’:
0, ‘time’: 1744693357848, ‘updateTime’: 1744693357848}]
==========================================================================
#用于获取指定订单的详细信息。要记录订单ID;orderId和origClientOrderId二选一
aa = client.futures_get_order(symbol=’BTCUSDC’,orderId=12696885851,origClientOrderId=None)
print(aa)
返回:
{‘orderId’: 12696885851, ‘symbol’: ‘BTCUSDC’, ‘status’: ‘FILLED’, ‘clientOrderId’:
‘android_MVYF4iyY4dAzvIvzB0Ok’, ‘price’: ‘85322.6’, ‘avgPrice’: ‘85322.6000’, ‘origQty’:
‘0.002’, ‘executedQty’: ‘0.002’, ‘cumQuote’: ‘170.6452’, ‘timeInForce’: ‘GTC’, ‘type’:
‘LIMIT’, ‘reduceOnly’: True, ‘closePosition’: False, ‘side’: ‘SELL’, ‘positionSide’:
‘LONG’, ‘stopPrice’: ‘0.0’, ‘workingType’: ‘CONTRACT_PRICE’, ‘priceProtect’: False,
‘origType’: ‘LIMIT’, ‘priceMatch’: ‘QUEUE’, ‘selfTradePreventionMode’: ‘EXPIRE_MAKER’,
‘goodTillDate’: 0, ‘time’: 1744692601863, ‘updateTime’: 1744692608060}
==========================================================================
#订单簿,交易对,盘口档位数
aa= client.futures_order_book(symbol=”BTCUSDC”, limit=5)
print(aa)
返回:
{‘lastUpdateId’: 7285029100471, ‘E’: 1744772395986, ‘T’: 1744772395976, ‘bids’: [[‘83841.8’, ‘3.675’], [‘83841.6’, ‘0.048’], [‘83840.1’, ‘0.080’], [‘83840.0’, ‘0.242’], [‘83839.9’, ‘0.113’]], ‘asks’: [[‘83841.9’, ‘0.530’], [‘83842.1’, ‘0.002’], [‘83844.0’, ‘0.135’], [‘83844.9’, ‘0.002’], [‘83845.0’, ‘0.052’]]}
==========================================================================
#买一价、卖一价
new_order_book= client.futures_order_book(symbol=”BTCUSDC”, limit=1)
buy_first = new_order_book[“bids”][0][0] #买一价
sell_first = new_order_book[“asks”][0][0] #卖一价
print(buy_first)
print(sell_first)
订单函数:
#############################################
client.futures_create_order(
symbol,
side,
type,
timeInForce=None,
quantity=None,
price=None,
newClientOrderId=None,
stopPrice=None,
icebergQty=None,
newOrderRespType=None,
recvWindow=None,
timestamp=None,
reduceOnly=None,
closePosition=None,
activationPrice=None,
callbackRate=None,
workingType=None,
priceProtect=None,
positionSide=None,
trailingDelta=None
)
###############################################
【symbol】:交易对,例如 “BTCUSDT”
【side】:订单方向,可取值为 “BUY” 或 “SELL”。分别表示买入和卖出操作。
【type】:类型:字符串
说明:订单类型,常见的取值有:
“LIMIT”:限价订单,按照指定的价格进行交易。【同一仓位只能开一个,成交速度>触发订单】
“MARKET”:市价订单,以当前市场最优价格立即成交。
“STOP”:触发止损-限价订单,当市场价格达到或超过指定的止损价格时触发交易。无设置数量限制【不可与TAKE_PROFIT混用,价格方向不同】
“TAKE_PROFIT”:触发止盈-限价订单,当市场价格达到或超过指定的止盈价格时触发交易。无设置数量限制【不可与STOP混用】
“STOP_MARKET”:触发止损-市价订单,当达到止损价格时,以市价成交。
“TAKE_PROFIT_MARKET”:触发止盈-市价订单,当达到止盈价格时,以市价成交。
“TRAILING_STOP_MARKET”:跟踪止损市价订单。
“LIMIT_MAKER”:只做挂单【测试失败无法调用?】
【timeInForce】类型:字符串;说明:订单有效时间,仅适用于限价订单(type=”LIMIT”)。
“GTC”(Good Till Canceled):订单一直有效,直至手动取消。
“IOC”(Immediate or Cancel):订单必须立即全部成交,否则剩余部分取消。
“FOK”(Fill or Kill):订单必须立即全部成交,否则整个订单取消。
【quantity】类型:浮点数或字符串
说明:订单的交易数量,即要买入或卖出的合约数量,需按交易对规则和精度设置。
【price】类型:浮点数或字符串
说明:订单价格,适用于限价订单(type=”LIMIT”)、止损限价订单(type=”STOP”)和止盈限价订单(type=”TAKE_PROFIT”)。
【newClientOrderId】类型:字符串;说明:自定义的客户端订单 ID,用于唯一标识该订单,若不提供,系统自动生成。
【stopPrice】类型:浮点数或字符串
说明:止损或止盈的触发价格,适用于止损订单(type=”STOP”、type=”STOP_MARKET”)和止盈订单(type=”TAKE_PROFIT”、type=”TAKE_PROFIT_MARKET”)。
【icebergQty】类型:浮点数或字符串
说明:冰山订单数量,仅适用于限价订单(type=”LIMIT”),可将大订单拆分成多个小订单,避免对市场造成过大冲击。
【newOrderRespType】类型:字符串;说明:订单响应类型。
“ACK”:仅返回订单接受状态。
“RESULT”:返回订单结果。
“FULL”:返回订单完整信息,包括订单状态、成交情况等。
【recvWindow】类型:整数;说明:请求的有效时间窗口,单位为毫秒,默认值 5000 毫秒,用于防止重放攻击。
【timestamp】类型:整数;说明:请求的时间戳,单位为毫秒,通常由系统自动生成,某些情况下需手动指定。
【reduceOnly】类型:布尔值;说明:指定订单是否仅用于减少持仓(平仓)。True 表示仅平仓,不能开仓;False 或不提供时,可开仓或平仓。
【closePosition】类型:布尔值;说明:设置为 True 时,会尝试全部平仓,忽略 quantity 参数。
【activationPrice】类型:浮点数或字符串;说明:仅适用于跟踪止损市价订单(type=”TRAILING_STOP_MARKET”),用于设置触发跟踪止损的激活价格。
【callbackRate】类型:浮点数或字符串;说明:仅适用于跟踪止损市价订单(type=”TRAILING_STOP_MARKET”),回调率用于确定跟踪止损的距离。
【trailingDelta】类型:整数;说明:用于跟踪止损订单,设置跟踪止损的点数偏移
【workingType】类型:字符串;说明:止损 / 止盈订单的触发价格类型。
“MARK_PRICE”:使用标记价格触发。
“CONTRACT_PRICE”:使用合约价格触发。
【priceProtect】类型:布尔值;说明:仅适用于止损 / 止盈市价订单,设置为 True 时,会对触发价格进行保护,防止异常价格触发。
【positionSide】类型:字符串
说明:持仓方向,取值为 “LONG”(多头)、”SHORT”(空头)或 “BOTH”(双向)。默认情况下,如果是单向持仓模式,无需设置此参数;如果是双向持仓模式,则需要明确指定持仓方向。
==========================================================================
#调整杠杠倍数
symbol = “BTCUSDC”
leverage = 100 # 设置杠杆倍数为100
try:
result = client.futures_change_leverage(symbol=symbol, leverage=leverage)
print(f”成功将 {symbol} 的杠杆设置为 {leverage} 倍: {result}”)
except Exception as e:
print(f”设置杠杆时出错: {e}”)
==========================================================================
#限价单
#使用 futures_create_order 函数,将 type 参数设置为 LIMIT 来下限价单。
#symbol:交易对符号,例如 ‘BTCUSDC’。
#side:订单方向,可选值为 ‘BUY’(买入)或 ‘SELL’(卖出)。
#type:订单类型,这里设置为 ‘LIMIT’ 表示限价单。
#timeInForce:订单有效时间,’GTC’ 表示订单会一直有效,直到被成交或取消。
#quantity:订单数量。
#price:下单价格。
#positionSide 参数为 LONG 或者 SHORT,双向持仓模式填写做多还是做空
order = client.futures_create_order(
symbol=’BTCUSDC’,
side=’BUY’,
type=’LIMIT’,
timeInForce=’GTC’,
quantity=0.01,
price=58000,
positionSide=’LONG’
)
print(“限价做多单下单成功:”, order)
返回:
{‘orderId’: 12698271335, ‘symbol’: ‘BTCUSDC’, ‘status’: ‘NEW’, ‘clientOrderId’: ‘x-
Cb7ytekJf17e90ebabac9bcb1073ef’, ‘price’: ‘58000.0’, ‘avgPrice’: ‘0.00’, ‘origQty’:
‘0.002’, ‘executedQty’: ‘0.000’, ‘cumQty’: ‘0.000’, ‘cumQuote’: ‘0.0000’, ‘timeInForce’:
‘GTC’, ‘type’: ‘LIMIT’, ‘reduceOnly’: False, ‘closePosition’: False, ‘side’: ‘BUY’,
‘positionSide’: ‘LONG’, ‘stopPrice’: ‘0.0’, ‘workingType’: ‘CONTRACT_PRICE’,
‘priceProtect’: False, ‘origType’: ‘LIMIT’, ‘priceMatch’: ‘NONE’,
‘selfTradePreventionMode’: ‘EXPIRE_MAKER’, ‘goodTillDate’: 0, ‘updateTime’: 1744694839158}
==========================================================================
#撤销订单
# 通过实例调用 futures_cancel_order 方法,不能直接函数调用,要知道订单号
try:
cancel_order = client.futures_cancel_order(symbol=’BTCUSDC’, orderId=bbb)
print(cancel_order)
except Exception as e:
print(“订单撤销失败:”, e)
返回:
{‘orderId’: 12765068940, ‘symbol’: ‘BTCUSDC’, ‘status’: ‘CANCELED’, ‘clientOrderId’: ‘android_wHowdmihgV6FLXhPIDca’, ‘price’: ‘81068.6’, ‘avgPrice’: ‘0.00’, ‘origQty’: ‘0.002’, ‘executedQty’: ‘0.000’, ‘cumQty’: ‘0.000’, ‘cumQuote’: ‘0.0000’, ‘timeInForce’: ‘GTC’, ‘type’: ‘LIMIT’, ‘reduceOnly’: False, ‘closePosition’: False, ‘side’: ‘BUY’, ‘positionSide’: ‘LONG’, ‘stopPrice’: ‘0.0’, ‘workingType’: ‘CONTRACT_PRICE’, ‘priceProtect’: False, ‘origType’: ‘LIMIT’, ‘priceMatch’: ‘NONE’, ‘selfTradePreventionMode’: ‘EXPIRE_MAKER’, ‘goodTillDate’: 0, ‘updateTime’: 1744756574044}
==========================================================================
#修改订单
没有直接修改未成交订单的方法,通常的做法是先撤销未成交的订单,然后重新创建一个新的订单。
==========================================================================
#市价单【一般不用】
symbol:必需参数,代表交易对符号,例如’BTCUSDT’ 。
side:必需参数,指定订单方向,可选择’BUY’(买入)或’SELL’(卖出)。在双向持仓模式下,结合
positionSide共同决定开仓或平仓操作。
type:必需参数,设置为’MARKET’表示下市价单。
quantity:必需参数,为订单的交易数量。
positionSide:必需参数,在双向持仓模式下,需明确指定持仓方向,可选择’LONG’(做多)或’SHORT’
(做空)。
order = client.futures_create_order(
symbol=’BTCUSDC’,
side=’BUY’,
type=’MARKET’,
quantity=0.002,
positionSide=’LONG’
)
print(“市价做多单下单成功:”, order)
返回:
{‘orderId’: 12698450268, ‘symbol’: ‘BTCUSDC’, ‘status’: ‘NEW’, ‘clientOrderId’: ‘x-Cb7ytekJ59a8ce74769be46e51dde’, ‘price’: ‘0.0’, ‘avgPrice’: ‘0.00’, ‘origQty’: ‘0.002’, ‘executedQty’: ‘0.000’, ‘cumQty’: ‘0.000’, ‘cumQuote’: ‘0.0000’, ‘timeInForce’: ‘GTC’, ‘type’: ‘MARKET’, ‘reduceOnly’: False, ‘closePosition’: False, ‘side’: ‘BUY’, ‘positionSide’: ‘LONG’, ‘stopPrice’: ‘0.0’, ‘workingType’: ‘CONTRACT_PRICE’, ‘priceProtect’: False, ‘origType’: ‘MARKET’, ‘priceMatch’: ‘NONE’,
‘selfTradePreventionMode’: ‘EXPIRE_MAKER’, ‘goodTillDate’: 0, ‘updateTime’: 1744695154835}
==========================================================================
#获取 U 本位永续合约资金费率,limit是数量
btc_funding_rate = client.futures_funding_rate(symbol=”BTCUSDT”,limit=3)
返回:
[{‘symbol’: ‘BTCUSDT’, ‘fundingTime’: 1744704000000, ‘fundingRate’: ‘0.00006606’, ‘markPrice’: ‘85691.30000000’}, {‘symbol’: ‘BTCUSDT’, ‘fundingTime’: 1744732800001, ‘fundingRate’: ‘0.00001883’, ‘markPrice’: ‘84874.59705926’}, {‘symbol’: ‘BTCUSDT’, ‘fundingTime’: 1744761600000, ‘fundingRate’: ‘0.00002428’, ‘markPrice’: ‘83608.70000000’}]
==========================================================================
#获取 U 本位合约 实时成交订单
aa=client.futures_recent_trades(symbol=”BTCUSDC”, limit=3)
print(aa)
返回:
[{‘id’: 173628941, ‘price’: ‘83541.5’, ‘qty’: ‘0.002’, ‘quoteQty’: ‘167.0’, ‘time’: 1744785579085, ‘isBuyerMaker’: False}, {‘id’: 173628942, ‘price’: ‘83541.6’, ‘qty’: ‘0.002’, ‘quoteQty’: ‘167.0’, ‘time’: 1744785579085, ‘isBuyerMaker’: False}, {‘id’: 173628943, ‘price’: ‘83544.0’, ‘qty’: ‘0.004’, ‘quoteQty’: ‘334.1’, ‘time’: 1744785579180, ‘isBuyerMaker’: False}]
==========================================================================
==========================================================================
#现货函数的调用,用于作数据分析
==========================================================================
#获取现货最新价格
aa=client.get_symbol_ticker(symbol=’BTCUSDT’)
返回:
{‘symbol’: ‘BTCUSDT’, ‘price’: ‘83469.87000000’}
==========================================================================
#获取现货市场的最优五档挂单价
aa=client.get_order_book(symbol=”BTCUSDT”, limit=5)
print(aa)
返回:
{‘lastUpdateId’: 66931930214, ‘bids’: [[‘83562.39000000’, ‘2.62361000’], [‘83562.38000000’, ‘0.01520000’], [‘83562.15000000’, ‘0.00007000’], [‘83562.01000000’, ‘0.10796000’], [‘83562.00000000’, ‘0.07180000’]], ‘asks’: [[‘83562.40000000’, ‘1.61459000’], [‘83562.41000000’, ‘0.00031000’], [‘83562.45000000’, ‘0.00022000’], [‘83562.47000000’, ‘0.00007000’], [‘83562.48000000’, ‘0.00007000’]]}
==========================================================================
#获取现货 1 分钟 K 线,interval是K线周期,limit 是K线根数 ;startTime和endTime用的是UNIX纪元的毫秒
aa=client.get_klines(symbol=”BTCUSDT”, interval=”1m”, startTime=None, endTime=None, limit=5)
返回:
[[1744784640000, ‘83599.99000000’, ‘83610.00000000’, ‘83582.10000000’, ‘83594.47000000’, ‘6.58768000’, 1744784699999, ‘550722.66119300’, 1285, ‘4.31383000’, ‘360632.79505320’, ‘0’], [1744784700000, ‘83594.47000000’, ‘83594.47000000’, ‘83574.00000000’, ‘83574.00000000’, ‘3.25737000’, 1744784759999, ‘272264.85094700’, 1086, ‘1.75286000’, ‘146512.57475660’, ‘0’], [1744784760000, ‘83574.00000000’, ‘83574.00000000’, ‘83560.04000000’, ‘83560.04000000’, ‘3.39937000’, 1744784819999, ‘284060.90995330’, 657, ‘2.02561000’, ‘169266.13042230’, ‘0’], [1744784820000, ‘83560.04000000’, ‘83560.04000000’, ‘83514.00000000’, ‘83514.01000000’, ‘29.19428000’, 1744784879999, ‘2439037.45248080’, 1516, ‘0.59279000’, ‘49518.20849450’, ‘0’], [1744784880000, ‘83514.00000000’, ‘83514.00000000’, ‘83483.26000000’, ‘83487.72000000’, ‘17.03765000’, 1744784939999, ‘1422506.38470470’, 587, ‘0.09209000’, ‘7688.38413480’, ‘0’]]
==========================================================================
#现货实时成交信息
aa=client.get_recent_trades(symbol=”BTCUSDT”, limit=3)
print(aa)
返回:
[{‘id’: 4829511443, ‘price’: ‘83606.98000000’, ‘qty’: ‘0.00050000’, ‘quoteQty’: ‘41.80349000’, ‘time’: 1744785429832, ‘isBuyerMaker’: True, ‘isBestMatch’: True}, {‘id’: 4829511444, ‘price’: ‘83606.99000000’, ‘qty’: ‘0.00063000’, ‘quoteQty’: ‘52.67240370’, ‘time’: 1744785430121, ‘isBuyerMaker’: False, ‘isBestMatch’: True}, {‘id’: 4829511445, ‘price’: ‘83606.99000000’, ‘qty’: ‘0.00610000’, ‘quoteQty’: ‘510.00263900’, ‘time’: 1744785430383, ‘isBuyerMaker’: False, ‘isBestMatch’: True}]
==========================================================================
==========================================================================
#CCXT获取OKEX,COINBASE,huobi,GATE行情
#币安:’binance’ , 欧意:’okx’,COINBASE(只有现货):’coinbase’ ,火币:’huobi’,BG:’bitget’,芝麻:’gate’,库币(只有现货):’kucoin’ ,Bybit:’bybit’
==========================================================================
#CCXT交易所初始化
import ccxt
# 初始化 binance 交易所
binance = ccxt.binance({
‘apiKey’: ‘3EMVyiwlLKFohYl7skG75BcNVrfRtfrSlw5IwqCF5aloq77gBdtmQGxxxxxxxxxx’,
‘secret’: ‘ZkpvuT0Cvr6QJR3vk4GJb7v1A0rNpcMuVPsxNSluqw3ENngx6G77sHxxxxxxxxxx’,
})
# 初始化 OKx 交易所
okx = ccxt.okx({
‘apiKey’: ‘f2bf31cb-4413-4fc0-9faxxxxxxxxxx’,
‘secret’: ‘B3AAD69D23F83985E5A0B6xxxxxxxxx’,
‘password’: ‘778xxxxxxxxx’, # OKx 需要交易密码
})
# 初始化 Gate.io 交易所
gate= ccxt.gate({
‘apiKey’: ‘3de05f1c1965ee49110xxxxxxxx’,
‘secret’: ’22d262644e5b084501162edf3a8c2fd846ef860c3f537xxxxxxxxxx’,
})
# 初始化bitget交易所
bitget= ccxt.bitget({
‘apiKey’: ‘bg_14ab6fc4f702066edbcfxxxxxxxxx’,
‘secret’: ‘f66ded221336ecca5a3de8e76712cefe8fd8ec90964xxxxxxxxxx’,
‘password’: ‘778xxxxxxxxx’,
‘enableRateLimit’: True,
})
# 初始化coinbase交易所
coinbase=ccxt.coinbase()
# 初始化huobi交易所
huobi=ccxt.huobi()
# 初始化kucoin交易所
kucoin=ccxt.kucoin()
# 初始化bybit交易所
bybit=ccxt.bybit()
==========================================================================
#获取 现货、永续合约实时价格
# 获取 binance 上BTC现货的价格,现货写作’BTC/USDT’,永续合约写作 BTC/USDT:USDT
ticker_binance = binance.fetch_ticker(‘BTC/USDC:USDC’)
print(ticker_binance)
# 获取 OKx 上BTC现货的价格,现货写作’BTC/USDT’,永续合约写作 BTC/USDT:USDT
ticker_okx = okx.fetch_ticker(‘BTC/USDT’)
print(“OKX价格:”,ticker_okx)
# 获取 Gate.io 上BTC现货的价格
ticker_gate = gate.fetch_ticker(‘BTC/USDT’)
print(“gate价格:”,ticker_gate)
# 获取 bitget 上BTC现货的价格
ticker_bitget = bitget.fetch_ticker(‘BTC/USDT’)
print(“bitget价格:”,ticker_bitget)
# 获取 coinbase上BTC现货的价格
ticker_coinbase = coinbase.fetch_ticker(‘BTC/USDT’)
print(“coinbase价格:”,ticker_coinbase)
# 获取 huobi上BTC现货的价格
ticker_huobi = huobi.fetch_ticker(‘BTC/USDT’)
print(“huobi价格:”,ticker_huobi)
# 获取 kucoin上BTC现货的价格
ticker_kucoin= kucoin.fetch_ticker(‘BTC/USDT’)
print(“kucoin价格:”,ticker_kucoin)
# 获取 bybit上BTC现货的价格
ticker_bybit= bybit.fetch_ticker(‘BTC/USDT’)
print(“bybit价格:”,ticker_bybit)
返回:
{‘symbol’: ‘BTC/USDT’, ‘timestamp’: 1744928589410, ‘datetime’: ‘2025-04-17T22:23:09.410Z’, ‘high’: 85489.0, ‘low’: 83722.0, ‘bid’: 85002.0, ‘bidVolume’: 0.17890652, ‘ask’: 85002.1, ‘askVolume’: 0.23366753, ‘vwap’: 84641.81336746478, ‘open’: 84404.6, ‘close’: 85000.1, ‘last’: 85000.1, ‘previousClose’: None, ‘change’: 595.5, ‘percentage’: 0.7055302673077058, ‘average’: 84702.3, ‘baseVolume’: 6392.5701006, ‘quoteVolume’: 541078725.3934207, ‘markPrice’: None, ‘indexPrice’: None, ‘info’: {‘instType’: ‘SPOT’, ‘instId’: ‘BTC-USDT’, ‘last’: ‘85000.1’, ‘lastSz’: ‘0.00023529’, ‘askPx’: ‘85002.1’, ‘askSz’: ‘0.23366753’, ‘bidPx’: ‘85002’, ‘bidSz’: ‘0.17890652’, ‘open24h’: ‘84404.6’, ‘high24h’: ‘85489’, ‘low24h’: ‘83722’, ‘volCcy24h’: ‘541078725.393420744’, ‘vol24h’: ‘6392.5701006’, ‘ts’: ‘1744928589410’, ‘sodUtc0’: ‘84029.8’, ‘sodUtc8’: ‘84544.7’}}
==========================================================================
#获取订单簿信息
#binance的BTC现货订单簿,limit= 是深度
binance_orderbook_spot=binance.fetch_order_book(symbol=’BTC/USDC’, limit=5)
#binance的BTC永续合约期货订单簿,limit= 是深度
binance_orderbook_future=binance.fetch_order_book(symbol=’BTC/USDC:USDC’, limit=5)
print(binance_orderbook_spot)
print(binance_orderbook_future)
#OKX的BTC现货订单簿,limit= 是深度
okx_orderbook_spot=okx.fetch_order_book(symbol=’BTC/USDT’, limit=3)
#OKX的BTC永续合约期货订单簿,limit= 是深度
okx_orderbook_future=okx.fetch_order_book(symbol=’BTC/USDT:USDT’, limit=3)
print(okx_orderbook_spot)
print(okx_orderbook_future)
#gate的BTC现货订单簿,limit= 是深度
gate_orderbook_spot=gate.fetch_order_book(symbol=’BTC/USDT’, limit=3)
#gate的BTC永续合约期货订单簿,limit= 是深度
gate_orderbook_future=gate.fetch_order_book(symbol=’BTC/USDT:USDT’, limit=3)
print(gate_orderbook_spot)
print(gate_orderbook_future)
#bitget的BTC现货订单簿,limit= 是深度
bitget_orderbook_spot=bitget.fetch_order_book(symbol=’BTC/USDT’, limit=3)
#bitget的BTC永续合约期货订单簿,limit= 是深度
bitget_orderbook_future=bitget.fetch_order_book(symbol=’BTC/USDT:USDT’, limit=3)
print(bitget_orderbook_spot)
print(bitget_orderbook_future)
#coinbase的BTC现货订单簿,limit= 是深度
coinbase_orderbook_spot=coinbase.fetch_order_book(symbol=’BTC/USDT’, limit=3)
print(coinbase_orderbook_spot)
#huobi的BTC现货订单簿,limit= 是深度
huobi_orderbook_spot=huobi.fetch_order_book(symbol=’BTC/USDT’, limit=5)
#huobi的BTC永续合约期货订单簿,limit= 是深度
huobi_orderbook_future=huobi.fetch_order_book(symbol=’BTC/USDT:USDT’, limit=5)
print(huobi_orderbook_spot)
print(huobi_orderbook_future)
#kucoin的BTC现货订单簿,limit= 是深度
kucoin_orderbook_spot=kucoin.fetch_order_book(symbol=’BTC/USDT’, limit=20)
print(kucoin_orderbook_spot)
#bybit的BTC现货订单簿,limit= 是深度
bybit_orderbook_spot=bybit.fetch_order_book(symbol=’BTC/USDT’, limit=3)
#bybit的BTC永续合约期货订单簿,limit= 是深度
bybit_orderbook_future=bybit.fetch_order_book(symbol=’BTC/USDT:USDT’, limit=3)
print(bybit_orderbook_spot)
print(bybit_orderbook_future)
返回:
{‘symbol’: ‘BTC/USDT:USDT’, ‘bids’: [[84868.0, 739.02, 0], [84867.9, 0.43, 0], [84867.6, 1.21, 0]], ‘asks’: [[84868.1, 321.94, 0], [84869.0, 22.21, 0], [84870.0, 5.75, 0]], ‘timestamp’: 1744930042255, ‘datetime’: ‘2025-04-17T22:47:22.255Z’, ‘nonce’: None}
==========================================================================
#获取实时成交
#OKX的BTC现货成交;limit= 是深度;since是返回信息的起始时间,整数,UNIX毫秒时间戳
okx_trades_spot=okx.fetch_trades(symbol=’BTC/USDT’, since=None, limit=3)
#OKX的BTC永续合约期货成交;limit= 是深度;since是返回信息的起始时间,整数,UNIX毫秒时间戳
okx_trades_future=okx.fetch_trades(symbol=’BTC/USDT:USDT’, since=None, limit=3)
print(okx_trades_spot)
print(okx_trades_future)
#gate的BTC现货成交;limit= 是深度;since是返回信息的起始时间,整数,UNIX毫秒时间戳
gate_trades_spot=gate.fetch_trades(symbol=’BTC/USDT’, since=None, limit=3)
#gate的BTC永续合约期货成交;limit= 是深度;since是返回信息的起始时间,整数,UNIX毫秒时间戳
gate_trades_future=gate.fetch_trades(symbol=’BTC/USDT:USDT’, since=None, limit=3)
print(gate_trades_spot)
print(gate_trades_future)
#bitget的BTC现货成交;limit= 是深度;since是返回信息的起始时间,整数,UNIX毫秒时间戳
bitget_trades_spot=bitget.fetch_trades(symbol=’BTC/USDT’, since=None, limit=3)
#bitget的BTC永续合约期货成交;limit= 是深度;since是返回信息的起始时间,整数,UNIX毫秒时间戳
bitget_trades_future=bitget.fetch_trades(symbol=’BTC/USDT:USDT’, since=None, limit=3)
print(bitget_trades_spot)
print(bitget_trades_future)
#coinbase的BTC现货成交;limit= 是深度;since是返回信息的起始时间,整数,UNIX毫秒时间戳
coinbase_trades_spot=coinbase.fetch_trades(symbol=’BTC/USDT’, since=None, limit=3)
print(coinbase_trades_spot)
返回:
[{‘info’: {‘instId’: ‘BTC-USDT’, ‘side’: ‘sell’, ‘sz’: ‘0.00070754’, ‘px’: ‘84902.4’, ‘tradeId’: ‘719595855’, ‘ts’: ‘1744931747729’}, ‘timestamp’: 1744931747729, ‘datetime’: ‘2025-04-17T23:15:47.729Z’, ‘symbol’: ‘BTC/USDT’, ‘id’: ‘719595855’, ‘order’: None, ‘type’: None, ‘takerOrMaker’: None, ‘side’: ‘sell’, ‘price’: 84902.4, ‘amount’: 0.00070754, ‘cost’: 60.071844096, ‘fee’: {‘cost’: None, ‘currency’: None}, ‘fees’: []}, {‘info’: {‘instId’: ‘BTC-USDT’, ‘side’: ‘sell’, ‘sz’: ‘0.00032928’, ‘px’: ‘84902.4’, ‘tradeId’: ‘719595856’, ‘ts’: ‘1744931747762’}, ‘timestamp’: 1744931747762, ‘datetime’: ‘2025-04-17T23:15:47.762Z’, ‘symbol’: ‘BTC/USDT’, ‘id’: ‘719595856’, ‘order’: None, ‘type’: None, ‘takerOrMaker’: None, ‘side’: ‘sell’, ‘price’: 84902.4, ‘amount’: 0.00032928, ‘cost’: 27.956662272, ‘fee’: {‘cost’: None, ‘currency’: None}, ‘fees’: []}, {‘info’: {‘instId’: ‘BTC-USDT’, ‘side’: ‘sell’, ‘sz’: ‘0.00075046’, ‘px’: ‘84902.4’, ‘tradeId’: ‘719595857’, ‘ts’: ‘1744931747803’}, ‘timestamp’: 1744931747803, ‘datetime’: ‘2025-04-17T23:15:47.803Z’, ‘symbol’: ‘BTC/USDT’, ‘id’: ‘719595857’, ‘order’: None, ‘type’: None, ‘takerOrMaker’: None, ‘side’: ‘sell’, ‘price’: 84902.4, ‘amount’: 0.00075046, ‘cost’: 63.715855104, ‘fee’: {‘cost’: None, ‘currency’: None}, ‘fees’: []}]
==========================================================================
#获取实时买一价,卖一价
binance_orderbook_future=binance.fetch_order_book(symbol=’BTC/USDC:USDC’, limit=5)
#实时买一价
bid1=binance_orderbook_future[“bids”][0][0]
print(bid1)
#实时卖一价
ask1=binance_orderbook_future[“asks”][0][0]
print(ask1)
==========================================================================
#查询账户余额
#查询永续合约账户的USDC余额
yuer=binance.fetch_balance(params={“type”:”future”,”asset”:”USDC”})
#获取 合约账户的USDC可用余额,赋值给yuer_usdc
yuer_usdc=yuer[“USDC”][“free”]
print(yuer)
返回:
{‘info’: {‘totalInitialMargin’: ‘0.00000000’, ‘totalMaintMargin’: ‘0.00000000’, ‘totalWalletBalance’: ‘0.00000000’, ‘totalUnrealizedProfit’: ‘0.00000000’, ‘totalMarginBalance’: ‘0.00000000’, ‘totalPositionInitialMargin’: ‘0.00000000’, ‘totalOpenOrderInitialMargin’: ‘0.00000000’, ‘totalCrossWalletBalance’: ‘0.00000000’, ‘totalCrossUnPnl’: ‘0.00000000’, ‘availableBalance’: ‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘assets’: [{‘asset’: ‘FDUSD’, ‘walletBalance’: ‘0.00000000’, ‘unrealizedProfit’: ‘0.00000000’, ‘marginBalance’: ‘0.00000000’, ‘maintMargin’: ‘0.00000000’, ‘initialMargin’: ‘0.00000000’, ‘positionInitialMargin’: ‘0.00000000’, ‘openOrderInitialMargin’: ‘0.00000000’, ‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’: ‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘updateTime’: ‘0’}, {‘asset’: ‘LDUSDT’, ‘walletBalance’: ‘0.00000000’, ‘unrealizedProfit’: ‘0.00000000’, ‘marginBalance’: ‘0.00000000’, ‘maintMargin’: ‘0.00000000’, ‘initialMargin’: ‘0.00000000’, ‘positionInitialMargin’: ‘0.00000000’, ‘openOrderInitialMargin’: ‘0.00000000’, ‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’: ‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘updateTime’: ‘0’}, {‘asset’: ‘BFUSD’, ‘walletBalance’: ‘0.00000000’, ‘unrealizedProfit’: ‘0.00000000’, ‘marginBalance’: ‘0.00000000’, ‘maintMargin’: ‘0.00000000’, ‘initialMargin’: ‘0.00000000’, ‘positionInitialMargin’: ‘0.00000000’, ‘openOrderInitialMargin’: ‘0.00000000’, ‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’: ‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘updateTime’: ‘0’}, {‘asset’: ‘BNB’, ‘walletBalance’: ‘0.00000000’, ‘unrealizedProfit’: ‘0.00000000’, ‘marginBalance’: ‘0.00000000’, ‘maintMargin’: ‘0.00000000’, ‘initialMargin’: ‘0.00000000’, ‘positionInitialMargin’: ‘0.00000000’, ‘openOrderInitialMargin’: ‘0.00000000’, ‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’: ‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘updateTime’: ‘0’}, {‘asset’: ‘ETH’, ‘walletBalance’: ‘0.00000000’, ‘unrealizedProfit’: ‘0.00000000’, ‘marginBalance’: ‘0.00000000’, ‘maintMargin’: ‘0.00000000’, ‘initialMargin’: ‘0.00000000’, ‘positionInitialMargin’: ‘0.00000000’, ‘openOrderInitialMargin’: ‘0.00000000’, ‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’: ‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘updateTime’: ‘0’}, {‘asset’: ‘BTC’, ‘walletBalance’: ‘0.00000000’, ‘unrealizedProfit’: ‘0.00000000’, ‘marginBalance’: ‘0.00000000’, ‘maintMargin’: ‘0.00000000’, ‘initialMargin’: ‘0.00000000’, ‘positionInitialMargin’: ‘0.00000000’, ‘openOrderInitialMargin’: ‘0.00000000’, ‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’: ‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘updateTime’: ‘0’}, {‘asset’: ‘USDT’, ‘walletBalance’: ‘0.00000000’, ‘unrealizedProfit’: ‘0.00000000’, ‘marginBalance’: ‘0.00000000’, ‘maintMargin’: ‘0.00000000’, ‘initialMargin’: ‘0.00000000’, ‘positionInitialMargin’: ‘0.00000000’, ‘openOrderInitialMargin’: ‘0.00000000’, ‘crossWalletBalance’: ‘0.00000000’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’: ‘0.00000000’, ‘maxWithdrawAmount’: ‘0.00000000’, ‘updateTime’: ‘0’}, {‘asset’: ‘USDC’, ‘walletBalance’: ‘6.56740523’, ‘unrealizedProfit’: ‘0.00000000’, ‘marginBalance’: ‘6.56740523’, ‘maintMargin’: ‘0.00000000’, ‘initialMargin’: ‘0.00000000’, ‘positionInitialMargin’: ‘0.00000000’, ‘openOrderInitialMargin’: ‘0.00000000’, ‘crossWalletBalance’: ‘6.56740523’, ‘crossUnPnl’: ‘0.00000000’, ‘availableBalance’: ‘6.56740523’, ‘maxWithdrawAmount’: ‘6.56740523’, ‘updateTime’: ‘1744784101739’}], ‘positions’: []}, ‘FDUSD’: {‘free’: 0.0, ‘used’: 0.0, ‘total’: 0.0}, ‘LDUSDT’: {‘free’: 0.0, ‘used’: 0.0, ‘total’: 0.0}, ‘BFUSD’: {‘free’: 0.0, ‘used’: 0.0, ‘total’: 0.0}, ‘BNB’: {‘free’: 0.0, ‘used’: 0.0, ‘total’: 0.0}, ‘ETH’: {‘free’: 0.0, ‘used’: 0.0, ‘total’: 0.0}, ‘BTC’: {‘free’: 0.0, ‘used’: 0.0, ‘total’: 0.0}, ‘USDT’: {‘free’: 0.0, ‘used’: 0.0, ‘total’: 0.0}, ‘USDC’: {‘free’: 6.56740523, ‘used’: 0.0, ‘total’: 6.56740523}, ‘timestamp’: None, ‘datetime’: None, ‘free’: {‘FDUSD’: 0.0, ‘LDUSDT’: 0.0, ‘BFUSD’: 0.0, ‘BNB’: 0.0, ‘ETH’: 0.0, ‘BTC’: 0.0, ‘USDT’: 0.0, ‘USDC’: 6.56740523}, ‘used’: {‘FDUSD’: 0.0, ‘LDUSDT’: 0.0, ‘BFUSD’: 0.0, ‘BNB’: 0.0, ‘ETH’: 0.0, ‘BTC’: 0.0, ‘USDT’: 0.0, ‘USDC’: 0.0}, ‘total’: {‘FDUSD’: 0.0, ‘LDUSDT’: 0.0, ‘BFUSD’: 0.0, ‘BNB’: 0.0, ‘ETH’: 0.0, ‘BTC’: 0.0, ‘USDT’: 0.0, ‘USDC’: 6.56740523}}
==========================================================================
#限价单
#限价单买入,双向持仓要加上params={“positionSide”:”long”}
limit_buy=binance.create_limit_buy_order(symbol=”BTC/USDC:USDC”,amount=0.002,price=bid1)
#限价单卖出
limit_sell=binance.create_limit_sell_order(symbol=”BTC/USDC:USDC”,amount=0.002,price=ask1)
返回:
{‘info’: {‘orderId’: ‘12955637201’, ‘symbol’: ‘BTCUSDC’, ‘status’: ‘NEW’, ‘clientOrderId’: ‘x-cvBPrNm96ae057d02156316563a81a’, ‘price’: ‘84773.0’, ‘avgPrice’: ‘0.00’, ‘origQty’: ‘0.002’, ‘executedQty’: ‘0.000’, ‘cumQty’: ‘0.000’, ‘cumQuote’: ‘0.0000’, ‘timeInForce’: ‘GTC’, ‘type’: ‘LIMIT’, ‘reduceOnly’: False, ‘closePosition’: False, ‘side’: ‘SELL’, ‘positionSide’: ‘BOTH’, ‘stopPrice’: ‘0.0’, ‘workingType’: ‘CONTRACT_PRICE’, ‘priceProtect’: False, ‘origType’: ‘LIMIT’, ‘priceMatch’: ‘NONE’, ‘selfTradePreventionMode’: ‘EXPIRE_MAKER’, ‘goodTillDate’: ‘0’, ‘updateTime’: ‘1744949292707’}, ‘id’: ‘12955637201’, ‘clientOrderId’: ‘x-cvBPrNm96ae057d02156316563a81a’, ‘timestamp’: 1744949292707, ‘datetime’: ‘2025-04-18T04:08:12.707Z’, ‘lastTradeTimestamp’: None, ‘lastUpdateTimestamp’: 1744949292707, ‘symbol’: ‘BTC/USDC:USDC’, ‘type’: ‘limit’, ‘timeInForce’: ‘GTC’, ‘postOnly’: False, ‘reduceOnly’: False, ‘side’: ‘sell’, ‘price’: 84773.0, ‘triggerPrice’: None, ‘amount’: 0.002, ‘cost’: 0.0, ‘average’: None, ‘filled’: 0.0, ‘remaining’: 0.002, ‘status’: ‘open’, ‘fee’: None, ‘trades’: [], ‘fees’: [], ‘stopPrice’: None, ‘takeProfitPrice’: None, ‘stopLossPrice’: None}
==========================================================================
#市价单
#市价买入,双向持仓要加上params={“positionSide”:”long”}
market_buy=binance.create_market_buy_order(symbol=”BTC/USDC:USDC”,amount=0.002)
#市价卖出
market_sell=binance.create_market_sell_order(symbol=”BTC/USDC:USDC”,amount=0.002)
返回:
{‘info’: {‘orderId’: ‘12956203731’, ‘symbol’: ‘BTCUSDC’, ‘status’: ‘FILLED’, ‘clientOrderId’: ‘x-cvBPrNm959b4606a8022b59bb0e0a9’, ‘price’: ‘0.0’, ‘avgPrice’: ‘84595.0000’, ‘origQty’: ‘0.002’, ‘executedQty’: ‘0.002’, ‘cumQty’: ‘0.002’, ‘cumQuote’: ‘169.1900’, ‘timeInForce’: ‘GTC’, ‘type’: ‘MARKET’, ‘reduceOnly’: False, ‘closePosition’: False, ‘side’: ‘SELL’, ‘positionSide’: ‘BOTH’, ‘stopPrice’: ‘0.0’, ‘workingType’: ‘CONTRACT_PRICE’, ‘priceProtect’: False, ‘origType’: ‘MARKET’, ‘priceMatch’: ‘NONE’, ‘selfTradePreventionMode’: ‘EXPIRE_MAKER’, ‘goodTillDate’: ‘0’, ‘updateTime’: ‘1744950029606’}, ‘id’: ‘12956203731’, ‘clientOrderId’: ‘x-cvBPrNm959b4606a8022b59bb0e0a9’, ‘timestamp’: 1744950029606, ‘datetime’: ‘2025-04-18T04:20:29.606Z’, ‘lastTradeTimestamp’: 1744950029606, ‘lastUpdateTimestamp’: 1744950029606, ‘symbol’: ‘BTC/USDC:USDC’, ‘type’: ‘market’, ‘timeInForce’: ‘GTC’, ‘postOnly’: False, ‘reduceOnly’: False, ‘side’: ‘sell’, ‘price’: 84595.0, ‘triggerPrice’: None, ‘amount’: 0.002, ‘cost’: 169.19, ‘average’: 84595.0, ‘filled’: 0.002, ‘remaining’: 0.0, ‘status’: ‘closed’, ‘fee’: None, ‘trades’: [], ‘fees’: [], ‘stopPrice’: None, ‘takeProfitPrice’: None, ‘stopLossPrice’: None}
==========================================================================
#取消订单
cancel=binance.cancel_order(id=12955637201,symbol=”BTC/USDC:USDC”)
print(cancel)
返回:
{‘info’: {‘orderId’: ‘12955637201’, ‘symbol’: ‘BTCUSDC’, ‘status’: ‘CANCELED’, ‘clientOrderId’: ‘x-cvBPrNm96ae057d02156316563a81a’, ‘price’: ‘84773.0’, ‘avgPrice’: ‘0.00’, ‘origQty’: ‘0.002’, ‘executedQty’: ‘0.000’, ‘cumQty’: ‘0.000’, ‘cumQuote’: ‘0.0000’, ‘timeInForce’: ‘GTC’, ‘type’: ‘LIMIT’, ‘reduceOnly’: False, ‘closePosition’: False, ‘side’: ‘SELL’, ‘positionSide’: ‘BOTH’, ‘stopPrice’: ‘0.0’, ‘workingType’: ‘CONTRACT_PRICE’, ‘priceProtect’: False, ‘origType’: ‘LIMIT’, ‘priceMatch’: ‘NONE’, ‘selfTradePreventionMode’: ‘EXPIRE_MAKER’, ‘goodTillDate’: ‘0’, ‘updateTime’: ‘1744949955997’}, ‘id’: ‘12955637201’, ‘clientOrderId’: ‘x-cvBPrNm96ae057d02156316563a81a’, ‘timestamp’: 1744949955997, ‘datetime’: ‘2025-04-18T04:19:15.997Z’, ‘lastTradeTimestamp’: None, ‘lastUpdateTimestamp’: 1744949955997, ‘symbol’: ‘BTC/USDC:USDC’, ‘type’: ‘limit’, ‘timeInForce’: ‘GTC’, ‘postOnly’: False, ‘reduceOnly’: False, ‘side’: ‘sell’, ‘price’: 84773.0, ‘triggerPrice’: None, ‘amount’: 0.002, ‘cost’: 0.0, ‘average’: None, ‘filled’: 0.0, ‘remaining’: 0.002, ‘status’: ‘canceled’, ‘fee’: None, ‘trades’: [], ‘fees’: [], ‘stopPrice’: None, ‘takeProfitPrice’: None, ‘stopLossPrice’: None}
==========================================================================
#查询当前某交易对的持仓
ask_chichang=binance.fetch_positions(symbols=[“BTC/USDC:USDC”])
print(ask_chichang)
返回:
[{‘info’: {‘symbol’: ‘BTCUSDC’, ‘positionSide’: ‘LONG’, ‘positionAmt’: ‘0.004’, ‘entryPrice’: ‘84568.05’, ‘breakEvenPrice’: ‘84568.05’, ‘markPrice’: ‘84687.96451179’, ‘unRealizedProfit’: ‘0.47965804’, ‘liquidationPrice’: ‘83347.00571536’, ‘isolatedMargin’: ‘0’, ‘notional’: ‘338.75185804’, ‘marginAsset’: ‘USDC’, ‘isolatedWallet’: ‘0’, ‘initialMargin’: ‘3.38751858’, ‘maintMargin’: ‘1.35500743’, ‘positionInitialMargin’: ‘3.38751858’, ‘openOrderInitialMargin’: ‘0’, ‘adl’: ‘3’, ‘bidNotional’: ‘0’, ‘askNotional’: ‘0’, ‘updateTime’: ‘1744950309865’}, ‘id’: None, ‘symbol’: ‘BTC/USDC:USDC’, ‘contracts’: 0.004, ‘contractSize’: 1.0, ‘unrealizedPnl’: 0.47965804, ‘leverage’: None, ‘liquidationPrice’: 83347.00571536, ‘collateral’: 6.21772923, ‘notional’: 338.75185804, ‘markPrice’: 84687.96451179, ‘entryPrice’: 84568.05, ‘timestamp’: 1744950309865, ‘initialMargin’: 3.38751858, ‘initialMarginPercentage’: 0.00999999, ‘maintenanceMargin’: 1.35500743216, ‘maintenanceMarginPercentage’: 0.004, ‘marginRatio’: 0.2179, ‘datetime’: ‘2025-04-18T04:25:09.865Z’, ‘marginMode’: ‘cross’, ‘marginType’: ‘cross’, ‘side’: ‘long’, ‘hedged’: True, ‘percentage’: 14.15, ‘stopLossPrice’: None, ‘takeProfitPrice’: None}]
==========================================================================
#查询当前的订单委托
ask_openorder=binance.fetch_open_orders(symbol=”BTC/USDC:USDC”)
print(ask_openorder)
返回:
[{‘info’: {‘orderId’: ‘12956655116’, ‘symbol’: ‘BTCUSDC’, ‘status’: ‘NEW’, ‘clientOrderId’: ‘android_DSiUbMlCR2YdgBJSQlui’, ‘price’: ‘84787.2’, ‘avgPrice’: ‘0’, ‘origQty’: ‘0.004’, ‘executedQty’: ‘0’, ‘cumQuote’: ‘0.0000’, ‘timeInForce’: ‘GTC’, ‘type’: ‘LIMIT’, ‘reduceOnly’: True, ‘closePosition’: False, ‘side’: ‘SELL’, ‘positionSide’: ‘LONG’, ‘stopPrice’: ‘0’, ‘workingType’: ‘CONTRACT_PRICE’, ‘priceProtect’: False, ‘origType’: ‘LIMIT’, ‘priceMatch’: ‘NONE’, ‘selfTradePreventionMode’: ‘EXPIRE_MAKER’, ‘goodTillDate’: ‘0’, ‘time’: ‘1744950820324’, ‘updateTime’: ‘1744950820324’}, ‘id’: ‘12956655116’, ‘clientOrderId’: ‘android_DSiUbMlCR2YdgBJSQlui’, ‘timestamp’: 1744950820324, ‘datetime’: ‘2025-04-18T04:33:40.324Z’, ‘lastTradeTimestamp’: None, ‘lastUpdateTimestamp’: 1744950820324, ‘symbol’: ‘BTC/USDC:USDC’, ‘type’: ‘limit’, ‘timeInForce’: ‘GTC’, ‘postOnly’: False, ‘reduceOnly’: True, ‘side’: ‘sell’, ‘price’: 84787.2, ‘triggerPrice’: None, ‘amount’: 0.004, ‘cost’: 0.0, ‘average’: None, ‘filled’: 0.0, ‘remaining’: 0.004, ‘status’: ‘open’, ‘fee’: None, ‘trades’: [], ‘fees’: [], ‘stopPrice’: None, ‘takeProfitPrice’: None, ‘stopLossPrice’: None}]
==========================================================================