forked from shallwe/btcchina_agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
287 lines (247 loc) · 8.81 KB
/
main.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
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#coding: utf-8
from datetime import datetime, timedelta
import time
import api
bc = api.BTCChina()
PRICE_LENGTH = 30
SINGLE_THRESHOLD_CHANGE = 0.002
MULTI_THRESHOLD_CHANGE = 0.01
LITTLE_CHANGE_RATE = 0.05#每次出货进货的量
MEDIUM_CHANGE_RATE = 0.1#每次出货进货的量
HIGH_CHANGE_RATE = 0.2#每次出货进货的量
DETECT_GAP = 5
btc_balance = {}
cny_balance = {}
current_value = 0 #当前价值
price_history = [] #价格历史
history_change = [] #历史上的变动
current_price = 0
current_value = 0
initial_value = 0 #最初价钱
initial_time = datetime.now()
last_update_time = initial_time
def log(txt, level='info'):
f = file('log.txt', 'a+')
content = '%s:%s' % (str(datetime.now()), txt)
if level != 'info':
print content
f.write(content + "\n")
f.close()
def update_balance():
global btc_balance, cny_balance
try:
account_info = bc.get_account_info()
except:
account_info = None
if account_info:
btc_balance = account_info['balance']['btc']
btc_balance['amount'] = float(btc_balance['amount'])
cny_balance = account_info['balance']['cny']
cny_balance['amount'] = float(cny_balance['amount'])
def calculate_value():
if current_price:
return btc_balance['amount'] * current_price + cny_balance['amount']
else:
return cny_balance['amount']
def legal_number(num):
return "%.4f" % num
def buy(percent, price):
btc_amount = cny_balance['amount'] * percent / price
log("[buy]%f,%f" % (btc_amount, price), 'warning')
try:
bc.buy(legal_number(price), legal_number(btc_amount))
except:
pass
return
def sell(percent, price):
btc_amount = btc_balance['amount'] * percent
log("[sell]%f,%f" % (btc_amount, price), 'warning')
if btc_amount:
try:
bc.sell(legal_number(price), legal_number(btc_amount))
except:
pass
def cancel_current_orders():
try:
orders = bc.get_orders()
except:
orders = {'order':[]}
now = time.time()
for order in orders['order']:
if now - order['date'] > 300:
_id = order['id']
log("cancel order:%s" % _id)
bc.cancel(_id)
def get_price_from_depth():
depth = bc.get_market_depth()
total = 0
amount = 0
for order in depth['market_depth']['ask']:
total += order['price'] * order['amount']
amount += order['amount']
price = total / amount
log(price)
return price
def append_price(price):
global price_history
if len(price_history) < PRICE_LENGTH:
price_history.append(price)
else:
price_history = price_history[1:]
price_history.append(price)
def append_change_history(change):
global history_change
if len(history_change) < 20:
history_change.append(change)
else:
history_change = history_change[1:]
history_change.append(change)
def multi_change():
result = 1
for change in history_change:
result *= change
return result
def is_decreasing():
if len(price_history) > PRICE_LENGTH / 5:
total = 0
count = PRICE_LENGTH/10
for i in xrange(count):
total += price_history[i]
old_price = total / count
if current_price < old_price:
if (-1 * calculate_delta_rate(old_price, current_price)) > SINGLE_THRESHOLD_CHANGE:
return True
return False
def is_increasing():
if len(price_history) > PRICE_LENGTH / 5:
total = 0
count = PRICE_LENGTH/10
for i in xrange(count):
total += price_history[i]
old_price = total / count
if current_price > old_price:
if calculate_delta_rate(old_price, current_price) > SINGLE_THRESHOLD_CHANGE:
return True
return False
def calculate_delta_rate(old_val, new_val):
delta = new_val - old_val
return delta / old_val
def buy_decrease():
global current_price, last_update_time, current_value
while True:
try:
current_price = get_price_from_depth()
except:
log('get price fail', 'warning')
time.sleep(10)
continue
append_price(current_price)
if is_decreasing():
log("[decrease]buy", 'warning')
update_balance()
buy(LITTLE_CHANGE_RATE, current_price)
elif is_increasing():
log("[increase]sell", 'warning')
update_balance()
sell(LITTLE_CHANGE_RATE, current_price)
else:
log("nothing", 'warning')
if datetime.now() - last_update_time > timedelta(hours=0.5):
cancel_current_orders()
update_balance()
current_value = calculate_value()
log("[effect]current the rate is %f" % calculate_delta_rate(initial_value, current_value), 'warning')
last_update_time = datetime.now()
time.sleep(10)
def buy_increase():
global current_price, last_update_time, current_value
while True:
try:
current_price = get_price_from_depth()
except:
time.sleep(10)
continue
append_price(current_price)
if is_decreasing():
log("[decrease]sell", 'warning')
update_balance()
sell(LITTLE_CHANGE_RATE, current_price)
elif is_increasing():
log("[increase]buy", 'warning')
update_balance()
buy(LITTLE_CHANGE_RATE, current_price)
else:
log("nothing", 'warning')
if datetime.now() - last_update_time > timedelta(hours=0.5):
cancel_current_orders()
update_balance()
current_value = calculate_value()
log("[effect]current the rate is %f" % calculate_delta_rate(initial_value, current_value), 'warning')
last_update_time = datetime.now()
time.sleep(5)
def calculate_averate(arr):
total = 0
for i in arr:
total += i
return total / len(arr)
def triple_step_buy_increase():
global current_price, last_update_time, current_value
count = 0
price_list = []
old_price = 0
while True:
try:
current_price = get_price_from_depth()
except:
log("get price failed")
time.sleep(DETECT_GAP)
continue
price_list.append(current_price)
count += 1
if count % 5 == 0:
avg_price = calculate_averate(price_list)
price_list = []
log("average_price: %.4f" % avg_price)
if old_price != 0:
change_rate = avg_price / old_price
append_change_history(change_rate)
total_change = multi_change()
print "change:%f, multichange:%f" % (change_rate, total_change)
if change_rate > 1 + SINGLE_THRESHOLD_CHANGE or change_rate < 1 - SINGLE_THRESHOLD_CHANGE or \
total_change > 1 + MULTI_THRESHOLD_CHANGE or total_change < 1 - MULTI_THRESHOLD_CHANGE:
update_balance()
if change_rate > 1 + SINGLE_THRESHOLD_CHANGE:
if total_change > 1 + MULTI_THRESHOLD_CHANGE:
buy(LITTLE_CHANGE_RATE, current_price)
elif total_change < 1 - MULTI_THRESHOLD_CHANGE:
buy(HIGH_CHANGE_RATE, current_price)
else:
buy(MEDIUM_CHANGE_RATE, current_price)
elif change_rate < 1 - SINGLE_THRESHOLD_CHANGE:
if total_change > 1 + MULTI_THRESHOLD_CHANGE:
sell(HIGH_CHANGE_RATE, current_price)
elif total_change < 1 - MULTI_THRESHOLD_CHANGE:
sell(LITTLE_CHANGE_RATE, current_price)
else:
sell(MEDIUM_CHANGE_RATE, current_price)
else:
if total_change > 1 + MULTI_THRESHOLD_CHANGE:
sell(LITTLE_CHANGE_RATE, current_price)
elif total_change < 1 - MULTI_THRESHOLD_CHANGE:
buy(LITTLE_CHANGE_RATE, current_price)
else:
log("nothing todo")
old_price = avg_price
if datetime.now() - last_update_time > timedelta(hours=0.5):
cancel_current_orders()
update_balance()
current_value = calculate_value()
log("[effect]current the rate is %f" % calculate_delta_rate(initial_value, current_value), 'warning')
last_update_time = datetime.now()
time.sleep(10)
if __name__ == "__main__":
update_balance()
current_price = get_price_from_depth()
initial_value = calculate_value()
log("[begin]now the value is %f" % initial_value, 'warning')
triple_step_buy_increase()