-
Notifications
You must be signed in to change notification settings - Fork 0
/
bolling_quant.py
175 lines (156 loc) · 6.85 KB
/
bolling_quant.py
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
#! /usr/bin/python
# -*- codeing = utf-8 -*-
# @Time : 2021-09-09 14:06
# @Author : yjh
# @File : bolling_quant.py
# @Software : PyCharm
import ccxt
import datetime
import time
import s_mail
from Trader import *
import pandas as pd
pd.set_option('display.width', 5000)
pd.set_option("max_colwidth",1000)
pd.set_option('display.max_columns',None)
pd.set_option('display.max_rows',None)
# ==参数设置
time_interval = '1m'
# 我的api
exchange = ccxt.binance(
{
"apiKey": "rfbx9FOyzsrpeDzGD8nMo7H1hxYWm8P2OFn2ugnLLzcLjjOfTkZ6YoGt1dlrPk9N",
"secret": "wLjRHkDEwp4FgEISNI2zuYwZlJK4GhRPc3wT3ZEqtuYarmMVlbBrFtTBwWhVKKN0"
}
)
# symbol和pair最好一致
symbol = 'ETH/USDT'
pair = 'ETHUSDT' # 合约的交易对(ccxt隐式中用)
contractType = 'PERPETUAL'
base_coin = symbol.split('/')[-1]
trade_coin = symbol.split('/')[0]
buy_amount = 0.01 # 以交易币种计算
"""
合约类型:
PERPETUAL 永续合约
CURRENT_MONTH 当月交割合约
NEXT_MONTH 次月交割合约
CURRENT_QUARTER 当季交割合约
NEXT_QUARTER 次季交割合约
"""
para = [158,2] # 布林策略参数
# == 主函数
def main():
while True:
# 邮件内容
email_message = ''
# # 从服务器上获取账户数据(现货)
# balance = exchange.fetch_balance()['total']
# base_coin_amount = float(balance[base_coin])
# trade_coin_amount = float(balance[trade_coin])
# print("当前资产\n",base_coin,base_coin_amount,trade_coin,trade_coin_amount)
################================================================================##################
# 获取合约账户(U本位)
base_coin_amount = get_contractAccount_balance(exchange,base_coin)
trade_coin_amount =get_perpetualContract_position(exchange,pair) # 这个函数会取出负值说明是空仓
print("当前资产\n", base_coin, base_coin_amount, trade_coin, trade_coin_amount)
email_message += str("当前资产:\n"+ base_coin+ str(base_coin_amount)+ trade_coin+ str(trade_coin_amount)+"\n")
################===============================================================###################
# sleep到运行时间
run_time = next_run_time(time_interval)
# sleep 直到靠近下次运行时间
time.sleep(max(0,(run_time-datetime.datetime.now()).seconds))
while True:
if run_time > datetime.datetime.now():
continue
else:
break
# # 获取最新数据(现货)
# while True:
# df = get_binance_candle_data(exchange,symbol,time_interval)
# _temp = df[df['candle_begin_time_GMT8'] == (run_time - datetime.timedelta(minutes=int(time_interval.strip('m'))))]
# if _temp.empty:
# print("数据不包含最新数据,重新获取")
# continue
# else:
# break
# 获取最新u本位永续合约数据
while True:
df = get_binance_contract_candadle(exchange,pair,contractType,interval=time_interval,limit=1000)
_temp = df[df['candle_begin_time_GMT8'] == (run_time - datetime.timedelta(minutes=int(time_interval.strip('m'))))]
if _temp.empty:
print("数据不包含最新数据,重新获取")
continue
else:
break
# ==产生交易信号
df = df[df['candle_begin_time_GMT8'] < pd.to_datetime(run_time)]
df = signal_bolling(df,para=para)
signal = df.iloc[-1]['signal']
print("交易信号",signal)
email_message += ("交易信号"+str(signal)+'\n')
signal = 1
# 越线信号(一根K线同时上穿或下穿两个轨道)
df2 = df[df['signal'].notnull()][['signal']]
if df2.iloc[-1]['signal']+df2.iloc[-2]['signal']==0:
signal2 = True
else:
signal2 = False
# print(df)
#==== 识别信号下单
if signal2 :
if trade_coin_amount <0:
price = get_price(exchange, 'BUY', pair)
price *= 1.01
price = round(price,2)
_2trade = abs(trade_coin_amount) * 2
orders_info = place_order(exchange, pair, 'BUY', 'LIMIT', price, quantity=(_2trade))
print(orders_info)
email_message += str(orders_info)+"\n 平仓并做多,价格为:"+str(price)
# 多两倍数量的多单平仓加做多
elif trade_coin_amount > 0:
price = get_price(exchange, 'SELL', pair)
price *= 0.99
price = round(price,2)
_2trade = trade_coin_amount *2
orders_info = place_order(exchange, pair, 'SELL', 'LIMIT', price, quantity=(_2trade))
print(orders_info)
email_message += str(orders_info)+"\n 平仓并做空,价格为:"+str(price)
else:
# 空单平仓
if signal == 0 and trade_coin_amount < 0:
price = get_price(exchange,'BUY',pair)
price *= 1.01
price = round(price,2)
orders_info = place_order(exchange,pair,'BUY','LIMIT',price,quantity=abs(trade_coin_amount))
print(orders_info)
email_message += str(orders_info)+"\n 空单平仓,价格为:"+str(price)
# 多单平仓
if signal == 0 and trade_coin_amount > 0:
price = get_price(exchange,'SELL',pair)
price *= 0.99
price = round(price,2)
orders_info = place_order(exchange,pair,'SELL','LIMIT',price,quantity=trade_coin_amount)
print(orders_info)
email_message += str(orders_info)+"\n 多单平仓,价格为:"+str(price)
# 开多仓
if signal == 1 and trade_coin_amount == 0:
price = get_price(exchange, 'BUY', pair)
price *= 0.1
price = round(price,2)
orders_info = place_order(exchange, pair, 'BUY', 'LIMIT', price, quantity=buy_amount)
print(orders_info)
email_message += str(orders_info)+"\n 做多,价格为:"+str(price)
# 开空仓
if signal == -1 and trade_coin_amount == 0:
price = get_price(exchange, 'SELL', pair)
price *= 0.99
price = round(price,2)
orders_info = place_order(exchange, pair, 'SELL', 'LIMIT', price, quantity=buy_amount)
print(orders_info)
email_message += str(orders_info)+"\n 做空,价格为:"+str(price)
print("\n")
email_message += "\n"
s_mail.send_mail(email_message)
if __name__ == '__main__':
main()