1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
| import json import math import time import traceback from datetime import timedelta
import ccxt import pandas as pd from tqdm import tqdm
from common.utils import retry_wrapper
exchange = ccxt.binance() exchange.https_proxy = 'http://127.0.0.1:7890/' exchange.timeout = 3000
def fetch_account_balance(enable_retry=False): account_data = retry_wrapper( exchange.fapiPrivateV2GetAccount, func_name='fapiPrivateV2GetAccount', enable_retry=enable_retry, ) assets = pd.DataFrame(account_data['assets']) return float(assets[assets['asset'] == 'USDT']['walletBalance'])
def fetch_positions(enable_retry=False): position_data = retry_wrapper( exchange.fapiPrivateV2GetPositionRisk, func_name='fapiPrivateV2GetPositionRisk', enable_retry=enable_retry, )
df = pd.DataFrame(position_data) columns = { 'positionAmt': '当前持仓量', 'entryPrice': '持仓均价', 'markPrice': '当前价格', 'unRealizedProfit': '持仓收益', }
df.rename(columns=columns, inplace=True) df = df.astype({ '当前持仓量': float, '持仓均价': float, '当前价格': float, '持仓收益': float, }) df = df[df['当前持仓量'] != 0] df.set_index('symbol', inplace=True)
df = df[['当前持仓量', '持仓均价', '当前价格', '持仓收益']]
return df
def fetch_candle_data(symbol, end_time, time_interval, limit, enable_retry=False): start_time_dt = end_time - pd.to_timedelta(time_interval) * limit params = { 'symbol': symbol, 'interval': time_interval, 'limit': limit, 'startTime': int(start_time_dt.timestamp() * 1000) } try: kline_data = retry_wrapper( exchange.fapiPublicGetKlines, params, func_name='fapiPublicGetKlines', enable_retry=enable_retry, ) except Exception as e: print(traceback.format_exc()) return pd.DataFrame()
df = pd.DataFrame(kline_data).astype(float) columns = { 0: 'candle_begin_time', 1: 'open', 2: 'high', 3: 'low', 4: 'close', 5: 'volume', 6: 'close_time', 7: 'quote_volume', 8: 'trade_num', 9: 'taker_buy_base_asset_volume', 10: 'taker_buy_quote_asset_volume', 11: 'ignore', } df.rename(columns=columns, inplace=True) df['symbol'] = symbol df.sort_values(by=['candle_begin_time'], inplace=True) df.drop_duplicates(subset=['candle_begin_time'], keep='last', inplace=True) df.reset_index(drop=True, inplace=True)
return df
def fetch_all_candle_data(symbol_list, run_time, time_interval, limit, enable_retry=False): symbol_candle_data = {} for symbol in tqdm(symbol_list): df = fetch_candle_data(symbol, run_time, time_interval, limit, enable_retry) if df.empty: continue
utc_offset = int(time.localtime().tm_gmtoff / 60 / 60) df['candle_begin_time'] = pd.to_datetime(df['candle_begin_time'], unit='ms') + timedelta(hours=utc_offset)
df = df[df['candle_begin_time'] < run_time]
symbol_candle_data[symbol] = df
return symbol_candle_data
def fetch_ticker_price(enable_retry=False): ticker_data = retry_wrapper( exchange.fapiPublicGetTickerPrice, func_name='fapiPublicGetTickerPrice', enable_retry=enable_retry, ) tickers = pd.DataFrame(ticker_data).astype({'price': float, 'time': float}) tickers.set_index('symbol', inplace=True)
return tickers['price']
def load_market(): exchange_data = retry_wrapper( exchange.fapiPublicGetExchangeInfo, func_name='fapiPublicGetExchangeInfo', )
symbol_dict_list = exchange_data['symbols'] df_list = [] for symbol_info in symbol_dict_list: symbol = symbol_info['symbol'] df_data = { 'symbol': symbol, 'onboardDate': int(symbol_info['onboardDate']), 'status': symbol_info['status'], 'quoteAsset': symbol_info['quoteAsset'], 'contractType': symbol_info['contractType'], }
for _filter in symbol_info['filters']: if _filter['filterType'] == 'PRICE_FILTER': df_data['pricePrecision'] = int(math.log(float(_filter['tickSize']), 0.1)) if _filter['filterType'] == 'LOT_SIZE': df_data['minQuantity'] = int(math.log(float(_filter['minQty']), 0.1)) if _filter['filterType'] == 'MIN_NOTIONAL': df_data['minNotional'] = float(_filter['notional'])
df_list.append(df_data)
df = pd.DataFrame(df_list) df.set_index('symbol', inplace=True)
return df
def place_order(symbol_order, symbol_market_info, enable_retry=False, enab order_params = [] symbol_ticker_price = fetch_ticker_price(enable_retry)
for symbol, row in symbol_order.iterrows(): min_qty = symbol_market_info.at[symbol, 'minQuantity'] min_notional = symbol_market_info.at[symbol, 'minNotional'] price_precision = symbol_market_info.at[symbol, 'pricePrecision']
if pd.isna(min_qty) or pd.isna(min_notional) or pd.isna(price_precision) : raise Exception('当前币种没有最小下单精度或者最小价格精度,币种信息异常')
quantity = row['实际下单量'] quantity = round(quantity, min_qty) if quantity > 0: side = 'BUY' price = symbol_ticker_price[symbol] * 1.015 else: side = 'SELL' price = symbol_ticker_price[symbol] * 0.985 quantity = abs(quantity) price = round(price, price_precision) reduce_only = (row['交易模式'] == '清仓')
if quantity * price < min_notional: if not reduce_only: print(symbol, '交易金额小于最小下单金额,跳过该笔交易') print('下单量: ', quantity, '价格: ', price, '最小下单金额: ', min_notional) continue
params = dict() params['symbol'] = symbol params['type'] = 'LIMIT' params['timeInForce'] = 'GTC' params['newClientOrderId'] = str(time.time()) params['side'] = side params['price'] = str(price) params['quantity'] = str(quantity) params['reduceOnly'] = str(reduce_only) order_params.append(params)
print('每个币种的下单参数: ', order_params) order_results = []
if not enable_place_order: return order_params, order_params
for i in range(0, len(order_params), 5): order_params = order_params[i:i+5] try: result = retry_wrapper( exchange.fapiPrivatePostBatchOrders, params={'batchOrders': json.dumps(order_params)}, func_name='fapiPrivatePostBatchOrders', enable_retry=enable_retry, ) print('批量下单完成,批量下单结果: ', result) order_results += result except Exception as e: print(e) continue
return order_params, order_results
|