|
import os |
|
import pandas as pd |
|
import requests |
|
import math |
|
import datetime |
|
import pytz |
|
import time |
|
import schedule |
|
from binance.client import Client |
|
from pymongo import MongoClient |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api_key = "266950dec031270d32fed06a552c2698cf662f0e32c4788acf25646bba7ef2c6" |
|
api_secret = "1a2b9793419db20e99a307be8ac04fec7a43bd77d46b71b161456105161b164d" |
|
|
|
client = Client(api_key, api_secret, testnet=True, |
|
base_endpoint='https://testnet.binancefuture.com/fapi') |
|
|
|
|
|
dbclient = MongoClient( |
|
"mongodb://wth000:wth000@43.159.47.250:27017/dbname?authSource=wth000") |
|
db = dbclient["wth000"] |
|
name = "COIN" |
|
collection_write = db[f'order期货{name}'] |
|
|
|
symbols = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT', 'TRXUSDT'] |
|
symbol_dict = client.futures_exchange_info() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def buy(symbols): |
|
balances = client.futures_account_balance() |
|
for balance in balances: |
|
if balance['asset'] == 'USDT': |
|
usdt_balance = balance['balance'] |
|
print('USDT余额:', usdt_balance) |
|
|
|
error_count = 0 |
|
for symbol in symbols: |
|
try: |
|
|
|
for symbol_info in symbol_dict['symbols']: |
|
if symbol_info['symbol'] == f'{str(symbol)}': |
|
symbol_info = symbol_info |
|
break |
|
print(symbol_info) |
|
|
|
price_precision = symbol_info['filters'][0]['minPrice'] |
|
price_precision = abs(int(math.log10(float(price_precision)))) |
|
print(f"{symbol}价格精度: {price_precision}") |
|
precision = symbol_info['filters'][1]['minQty'] |
|
precision = abs(int(math.log10(float(precision)))) |
|
print(f"{symbol}数量精度: {precision}") |
|
tickSize = float(symbol_info['filters'][0]['tickSize']) |
|
print(f"{symbol}价格步长: {tickSize}") |
|
stepSize = float(symbol_info['filters'][1]['minQty']) |
|
print(f"{symbol}数量步长: {stepSize}") |
|
|
|
depth = client.futures_order_book(symbol=symbol, limit=5) |
|
buy_ask_price_1 = float(depth['asks'][0][0]) |
|
buy_bid_price_1 = float(depth['bids'][0][0]) |
|
print(depth) |
|
|
|
target_price = (buy_ask_price_1+buy_bid_price_1)/2 |
|
buy_limit_price = round( |
|
buy_ask_price_1 - pow(0.1, price_precision), price_precision) |
|
sell_limit_price = round( |
|
buy_bid_price_1 + pow(0.1, price_precision), price_precision) |
|
print('最优卖价', sell_limit_price, '最优买价', buy_limit_price) |
|
|
|
|
|
if 1-buy_bid_price_1/target_price >= 0.001 or buy_ask_price_1/target_price-1 <= 0.001: |
|
|
|
symbol = symbol |
|
quantity = round( |
|
round(12/buy_limit_price/stepSize) * stepSize, precision) |
|
order = client.futures_create_order( |
|
symbol=symbol, |
|
side=Client.SIDE_BUY, |
|
type=Client.ORDER_TYPE_LIMIT, |
|
quantity=float(quantity), |
|
price=float(buy_limit_price), |
|
timeInForce="GTC", |
|
leverage=1, |
|
isIsolated=False |
|
) |
|
print("下单信息:", order) |
|
collection_write.insert_one({ |
|
'orderId': int(order['orderId']), |
|
'symbol': symbol, |
|
'time': int(time.time()), |
|
'quantity': float(order['origQty']), |
|
'buy_quantity': None, |
|
'buy_price': float(order['price']), |
|
'sell_time': None, |
|
'sell_quantity': None, |
|
'sell_price': None, |
|
'status': 'pending', |
|
'precision': int(precision), |
|
'price_precision': int(price_precision), |
|
'tickSize': float(tickSize), |
|
'stepSize': float(stepSize), |
|
}) |
|
except Exception as e: |
|
|
|
error_count += 1 |
|
print(f"发生bug: {e}") |
|
continue |
|
|
|
print(f"共出现{error_count}次异常") |
|
|
|
time.sleep(1) |
|
|
|
for order in collection_write.find({'status': 'pending'}): |
|
symbol = order['symbol'] |
|
order_id = order['orderId'] |
|
try: |
|
|
|
result = client.futures_cancel_order( |
|
symbol=symbol, orderId=order_id) |
|
print(f'撤销订单{order_id}成功:{result}') |
|
except Exception as e: |
|
print(f'撤销订单{order_id}失败{e}') |
|
|
|
time.sleep(1) |
|
|
|
|
|
def sell(symbols): |
|
|
|
try: |
|
for symbol in symbols: |
|
|
|
open_orders = client.futures_get_open_orders(symbol=symbol) |
|
|
|
for order in open_orders: |
|
order_id = order['orderId'] |
|
buy_price = float(order['price']) |
|
buy_quantity = float(order['executedQty']) |
|
|
|
collection_write.update_one( |
|
{'orderId': order_id}, |
|
{'$set': { |
|
'status': order['status'], |
|
'buy_price': float(buy_price), |
|
'buy_quantity': float(buy_quantity) |
|
}} |
|
) |
|
print('历史成交订单更新', order) |
|
|
|
start_time = int((datetime.datetime.now() - |
|
datetime.timedelta(hours=1)).timestamp() * 1000) |
|
all_orders = client.futures_get_all_orders( |
|
symbol=symbol, startTime=start_time) |
|
|
|
for order in all_orders: |
|
order_id = order['orderId'] |
|
buy_price = float(order['price']) |
|
buy_quantity = float(order['executedQty']) |
|
|
|
collection_write.update_one( |
|
{'orderId': order_id}, |
|
{'$set': { |
|
'status': order['status'], |
|
'buy_price': float(buy_price), |
|
'buy_quantity': float(buy_quantity) |
|
}} |
|
) |
|
print('历史成交订单更新', order) |
|
except Exception as e: |
|
print(f"发生异常:{e}") |
|
try: |
|
|
|
orders = list(collection_write.find()) |
|
for order in orders: |
|
symbol = order['symbol'] |
|
|
|
for symbol_info in symbol_dict['symbols']: |
|
if symbol_info['symbol'] == f'{str(symbol)}': |
|
symbol_info = symbol_info |
|
break |
|
print(symbol_info) |
|
|
|
price_precision = symbol_info['filters'][0]['minPrice'] |
|
price_precision = abs(int(math.log10(float(price_precision)))) |
|
print(f"{symbol}价格精度: {price_precision}") |
|
precision = symbol_info['filters'][1]['minQty'] |
|
precision = abs(int(math.log10(float(precision)))) |
|
print(f"{symbol}数量精度: {precision}") |
|
tickSize = float(symbol_info['filters'][0]['tickSize']) |
|
print(f"{symbol}价格步长: {tickSize}") |
|
stepSize = float(symbol_info['filters'][1]['minQty']) |
|
print(f"{symbol}数量步长: {stepSize}") |
|
|
|
depth = client.futures_order_book(symbol=symbol, limit=5) |
|
sell_ask_price_1 = float(depth['asks'][0][0]) |
|
sell_bid_price_1 = float(depth['bids'][0][0]) |
|
print(depth) |
|
|
|
target_price = (sell_ask_price_1+sell_bid_price_1)/2 |
|
buy_limit_price = round( |
|
sell_ask_price_1 - pow(0.1, price_precision), price_precision) |
|
sell_limit_price = round( |
|
sell_bid_price_1 + pow(0.1, price_precision), price_precision) |
|
print('最优卖价', sell_limit_price, '最优买价', buy_limit_price) |
|
|
|
|
|
if 1-sell_bid_price_1/target_price >= 0.001 or sell_ask_price_1/target_price-1 <= 0.001: |
|
|
|
|
|
sell_time = order['time'] |
|
|
|
|
|
if 1-sell_bid_price_1/target_price >= 0.001 or sell_ask_price_1/target_price-1 <= 0.001: |
|
|
|
if (order['status'] != 'end') & (order['buy_quantity'] != 0) & (order['buy_quantity'] != order['sell_quantity']): |
|
|
|
|
|
sell_time = order['time'] |
|
|
|
if int(time.time()) >= sell_time: |
|
|
|
sell_order = client.futures_create_order( |
|
symbol=order['symbol'], |
|
side=Client.SIDE_SELL, |
|
type=Client.ORDER_TYPE_LIMIT, |
|
quantity=float(order['buy_quantity']), |
|
price=sell_bid_price_1, |
|
timeInForce="GTC", |
|
leverage=1, |
|
isIsolated=False |
|
) |
|
print("卖出信息:", sell_order) |
|
|
|
if sell_order['status'] == 'FILLED': |
|
print(order, '卖出成功') |
|
collection_write.update_one( |
|
{'orderId': order_id}, |
|
{'$set': { |
|
'status': 'end', |
|
'sell_quantity': float(sell_order['price']), |
|
'sell_price': float(sell_order['price']), |
|
}} |
|
) |
|
else: |
|
print(order, '卖出失败') |
|
except Exception as e: |
|
print(f"发生异常:{e}") |
|
|
|
|
|
def clearn(): |
|
limit = 10000 |
|
if collection_write.count_documents({}) >= limit: |
|
oldest_data = collection_write.find().sort([('日期', 1)]).limit( |
|
collection_write.count_documents({})-limit) |
|
ids_to_delete = [data['_id'] for data in oldest_data] |
|
collection_write.delete_many({'_id': {'$in': ids_to_delete}}) |
|
print('数据清理成功') |
|
|
|
|
|
while True: |
|
buy(symbols) |
|
time.sleep(60) |
|
sell(symbols) |
|
time.sleep(60) |
|
clearn() |
|
time.sleep(3600) |