166 lines
6.8 KiB
Python
166 lines
6.8 KiB
Python
|
||
import time
|
||
import pandas as pd
|
||
import ccxt
|
||
from datetime import timedelta
|
||
# import pandas_ta
|
||
import talib
|
||
|
||
# ====================================================================================================
|
||
# =====格式设置
|
||
# ====================================================================================================
|
||
pd.set_option('display.max_rows', 1000)
|
||
pd.set_option('expand_frame_repr', False) # 当列太多时不换行
|
||
# 设置命令行输出时的列对齐功能
|
||
pd.set_option('display.unicode.ambiguous_as_wide', True)
|
||
pd.set_option('display.unicode.east_asian_width', True)
|
||
|
||
# ====================================================================================================
|
||
# =====创建ccxt交易所
|
||
# ====================================================================================================
|
||
BINANCE_CONFIG = {
|
||
'apiKey': '',
|
||
'secret': '',
|
||
'proxies': {'http': '127.0.0.1:7890', 'https': '127.0.0.1:7890'}
|
||
}
|
||
exchange = ccxt.binance(BINANCE_CONFIG)
|
||
|
||
|
||
|
||
while True:
|
||
# list = ['DOGEUSDT', 'ETHUSDT', 'BTCUSDT']
|
||
#
|
||
# # for symbol in list:
|
||
symbol = 'ETHUSDT'
|
||
time_interval = '1m' # 其他可以尝试的值:'1m', '5m', '15m', '30m', '1h', '2h', '1d', '1w', '1M', '1y',并不是每个交易所都支持
|
||
bar_num = 1000 # 获取K线的数量
|
||
params = {'symbol': symbol, # 交易币对
|
||
'interval': time_interval, # 时间间隔
|
||
'limit': bar_num} # 数据条数
|
||
|
||
# ====================================================================================================
|
||
# =====获取K线数据
|
||
# ====================================================================================================
|
||
response = exchange.fapiPublicGetKlines(params=params)
|
||
k_lines = pd.DataFrame(response)
|
||
# print(k_lines)
|
||
|
||
# =====整理K线数据
|
||
df = pd.DataFrame(response, dtype=float) # 将数据转换为dataframe
|
||
df.rename(columns={0: 'MTS', 1: 'Open', 2: 'High',
|
||
3: 'Low', 4: 'Close', 5: 'Volume'}, inplace=True) # 重命名
|
||
df['candle_begin_time'] = pd.to_datetime(df['MTS'], unit='ms') # 整理时间
|
||
df['candle_begin_time_GMT8'] = df['candle_begin_time'] + timedelta(hours=8) # 北京时间
|
||
df = df[['candle_begin_time_GMT8', 'Open', 'High', 'Low', 'Close', 'Volume']] # 整理列的顺序
|
||
|
||
# ====================================================================================================
|
||
# =====获取币对的最新价格
|
||
# ====================================================================================================
|
||
data = exchange.fapiPublicGetTickerPrice(params={'symbol': "ETHUSDT"})
|
||
price_ETH = data['price']
|
||
|
||
# ====================================================================================================
|
||
# =====通过pandas-ta计算指标并加入相关指标计算列
|
||
# ====================================================================================================
|
||
## 计算均线
|
||
# df.ta.sma(length=5, append=True, col_names="SMA_5") # pandas-ta 计算SM5指标
|
||
df['MA5'] = talib.MA(df['Close'], timeperiod=5) # ta-lib计算MA5指标
|
||
|
||
# # 计算14日相对强弱指数(RSI)
|
||
# df.ta.rsi(length=14, append=True, col_names="RSI_14") # pandas-ta计算RSI指标
|
||
df['RSI_14'] = talib.RSI(df['Close'], timeperiod=14) # ta-lib计算RSI指标
|
||
|
||
# # 计算MACD(12/26/9周期)
|
||
# df.ta.macd(fast=12, slow=26, signal=9, append=True) # 默认列名:MACD_12_26_9, MACDs_12_26_9, MACDh_12_26_9 [2,7](@ref)
|
||
|
||
# # 计算布林带(20日,2倍标准差)
|
||
# df.ta.bbands(length=20, std=2, append=True)
|
||
# pandas-ta计算布林带指标
|
||
# 默认列名:BBL_20_2.0, BBM_20_2.0, BBU_20_2.0
|
||
|
||
## ta-lib 计算布林带指标
|
||
upper_band, middle_band, lower_band = talib.BBANDS(
|
||
df['Close'],
|
||
timeperiod=20,
|
||
nbdevup=2,
|
||
nbdevdn=2,
|
||
matype=0 # SMA
|
||
)
|
||
df['BB_Upper'] = upper_band
|
||
df['BB_Middle'] = middle_band
|
||
df['BB_Lower'] = lower_band
|
||
|
||
## 计算ADX指标
|
||
# df.ta.adx(length=20, append=True) # pandas-ta计算adx
|
||
df['ADX_14'] = talib.ADX(df['High'], df['Low'], df['Close'], timeperiod=14) # ta-lib计算ADX指标
|
||
|
||
## 计算ATR指标
|
||
# df.ta.atr(length=16, append=True) # pandas-ta计算atr,默认参数14,length也可以调整
|
||
df['ATR_14'] = talib.ATR(df['High'], df['Low'], df['Close'], timeperiod=14)
|
||
|
||
print(df)
|
||
# df.to_csv('Ta4.csv')
|
||
|
||
# ====================================================================================================
|
||
# =====设置下单条件并执行
|
||
# ====================================================================================================
|
||
# if float(price_ETH) > float(df['Close'].iloc[-2]):
|
||
# print('价格上升')
|
||
# else:
|
||
# print('价格下降')
|
||
#
|
||
# print(price_ETH)
|
||
# print(df['Close'].iloc[-2])
|
||
# print(df['RSI_14'].iloc[-2] > 30)
|
||
|
||
# 以上为dataframe取数格式的测试,目前使用还不太熟练
|
||
|
||
## 调整杠杆倍率
|
||
# params = {'symbol': 'ETHUSDT', # 交易币对
|
||
# 'leverage': 10,
|
||
# 'timestamp': int(time.time() * 1000)}
|
||
# leverage = exchange.fapiPrivatePostLeverage(params=params)
|
||
# print('调整开仓杠杆\n', leverage, '\n')
|
||
|
||
## 下单操作
|
||
num = 0
|
||
max_num = 3
|
||
# 使用变量来控制下单次数
|
||
|
||
params = {'side': 'BUY',
|
||
'symbol': 'ETHUSDT', # 交易币对
|
||
'type': 'LIMIT',
|
||
# 'price': price_ETH,
|
||
'price': df['Close'].iloc[-1],
|
||
# 下单价格,在限价单的时候
|
||
# 启用,将type换成LIMIT
|
||
# 此处用变量取代了课程中的数值。以后下单的价格可能需要复杂计算再储存在变量中,做测试。
|
||
'quantity': 0.01, # 下单数量
|
||
'timestamp': int(time.time() * 1000),
|
||
'timeInForce': 'GTC'} # https://academy.binance.com/zh/articles/understanding-the-different-order-types
|
||
|
||
|
||
|
||
|
||
if df['RSI_14'].iloc[-2] > 30 and df['RSI_14'].iloc[-1] < 30:
|
||
print('向下穿越rsi30,执行买入')
|
||
response = exchange.fapiPrivatePostOrder(params=params)
|
||
order_info = pd.DataFrame(response, index=['symbol'])
|
||
order_id = order_info['orderId'].iloc[0]
|
||
print('下单\n', order_info, '\n')
|
||
num += 1
|
||
# 此后这里还可以多个条件,组合多个指标的值
|
||
# RSI的使用作为一个参考
|
||
# 通过现有数据(开高收低量),已经可以计算出不少指标了。
|
||
|
||
else:
|
||
print('不符合交易条件,监控中')
|
||
time.sleep(30)
|
||
|
||
if num >= max_num:
|
||
break
|
||
|
||
## 这是我在办公室电脑上敲的注释
|
||
## 测试能否通过iCloud同步成功,在家也可已经iCloud对同一个项目进行编辑。
|
||
|