· 6 years ago · Feb 07, 2020, 03:38 AM
1import Binance_Api as ba
2import pandas as pd
3import ta
4import json
5import decimal
6import time
7
8api_key='7lgMXGnu0D03QCqsUi9lReaHwiTsRjdUIHYvCgSUMKOQ0yurY0AdPUCmE9p6FoYy'
9headers={'X-MBX-APIKEY':api_key}
10secret_key='F3qWSi9lRlsqKdS66EObYpEUHxOwA0SCSzxCM83EqxYcUkDrzOP4DXbaMq7DZSw7'
11
12'''So far program is looking good need to make sure that float values arent being cut off
13short and find a way to refresh data values for positions that im in'''
14
15
16'''Next step is to deal with the errors that are popping up price flter and fixing code so
17all prces are able to be traded are next priority once that is complete code needs to
18be able to automatically exit we will then attempt to connect to a google sheets
19doc so that we can track our trades entry criteria may need to be revised so that
20we dont enter positions that are already extremely passed the expo moving avg'''
21
22decimal.getcontext().prec=11
23
24btc_pairs_list=[]
25closing_prices={}
26symbol_ta={}
27df_list=[]
28tradeable_symbols=[]
29ask_prices={}
30bb_list=[]
31width_dict={}
32intrade_symbols={}
33
34#getting btc balance for my account
35#account_balance=ba.get_balances('BTC',secret_key,headers)
36btc_pairs=ba.get_pairs('BTC',btc_pairs_list)
37
38#sig=ba.get_signature(secret_key,params)
39def gather_data(pairs):
40 print('were starting')
41 for pairs in btc_pairs:
42 df= ba.get_klines(pairs)
43 asset_close_price=df['close']
44 #turns the close column into a float so that it can be ran through calculations
45 closing_prices['{}'.format(pairs)]=pd.to_numeric(asset_close_price)
46
47 for closes in closing_prices.values():
48 #mayneed error handling for the bands theys seem to act oddly sometimes the program tries to
49 #treat closes as a list
50 #put in type to see if it would help the memormy be able to rember that it isnt a list
51 type(closes)
52 hband= ta.bollinger_hband(closes)
53 lband= ta.bollinger_lband(closes)
54 moving_avg=ta.bollinger_mavg(closes)
55
56 bb_width=(hband-lband)/moving_avg
57 expo_mavg=closes.ewm(span=12,adjust=False).mean()
58
59 #turning the series into a dataframe
60 ta_df=pd.concat([hband,lband,bb_width,expo_mavg],axis=1,
61 keys=['hband','lband','bb_width','expo_mavg'])
62
63 df_list.append(ta_df)
64
65 print('made list')
66 #making a dictionary using two lists helps overcome the problem of incorrect dfs
67 #being saves as values
68 zip_obj=zip(btc_pairs_list,df_list)
69 symbol_ta=dict(zip_obj)
70
71 for key in symbol_ta.keys():
72 ask_price=ba.get_ask_price(key)
73 asset=symbol_ta['{}'.format(key)]
74 if ask_price > asset['expo_mavg'][-1]and asset['bb_width'][-1]>0.005:
75 tradeable_symbols.append(key)
76
77 for item in tradeable_symbols:
78 bb_rank=symbol_ta['{}'.format(item)]['bb_width'][-1]
79 bb_list.append(bb_rank)
80
81#gather_data(btc_pairs)
82def bol_list(symbols,bols):
83#the lines below dont run in the loop function that breaks the code
84 width_zip=zip(tradeable_symbols,bb_list)
85 width_dict=dict(width_zip)
86
87 #this turns width dict into a list of symbols sorted by greatest bb_width
88 width_list=sorted(width_dict,key=width_dict.get,reverse=True)
89 return width_list
90
91#need to find a way for my program to know how many digits to put on a number
92def enter_trade(data_list):
93# account_balance=ba.get_cookies('BTC',secret_key,headers)
94 for symbol in data_list:
95 account_balance=ba.get_cookies('BTC',secret_key,headers)
96# account_balance=account_balance
97 # account_balance=decimal.Decimal(1.0)
98 pricing=ba.get_ask_price(symbol)
99 # decimal_places=pricing.as_tuple().exponent
100 price_digits=len(str(pricing))
101
102
103 #calculates a stock price that insures we only resk 2% per trade
104 stop_loss=str((pricing)-(pricing)*decimal.Decimal(0.02))
105 stop_price=str((pricing)-(pricing)*decimal.Decimal(0.03))
106
107 #this fixes the problem where sometimes my program putstoo many digits on the stop prices
108 if price_digits < len(stop_loss):
109 stop_loss=stop_loss[:-1]
110
111 if price_digits < len(stop_price):
112 stop_price=stop_price[:-1]
113
114 if account_balance < 0.02:
115 quantity=int(account_balance/pricing)
116 quantity=str(quantity)
117 else:
118 nums=account_balance/3
119 quantity=int(nums/pricing)
120 quantity=str(quantity)
121
122 if account_balance >= 0.003:
123 print(symbol)
124 print(quantity)
125 print(pricing)
126 print(stop_loss)
127 timestamp=str(ba.create_timestamp())
128 buy_params=ba.test_order('{}'.format(symbol),'BUY','LIMIT',quantity,'FOK',str(pricing),
129 timestamp)
130 sig=ba.get_signature(secret_key,buy_params)
131 buy_order=ba.create_call('new_order',buy_params,sig,headers=headers)
132
133 order_info=json.loads(buy_order.text)
134 print(order_info)
135
136 if 'code' in order_info:
137 pass
138
139 elif order_info['status']=='EXPIRED':
140 pass
141
142 elif order_info['fills'][0]['commissionAsset']=='BNB'and order_info['symbol']=='BNB':
143 quantity=decimal.Decimal(quantity)-decimal.Decimal(order_info['fills'][0]['commission'])
144 quantity=str(quantity)
145
146 elif order_info['fills'][0]['commissionAsset']=='BNB':
147 quantity=quantity
148
149 elif 'commissionAsset'in order_info['fills'][0]:
150 quantity=decimal.Decimal(quantity)-decimal.Decimal(order_info['fills'][0]['commission'])
151 quantity=str(quantity)
152 print(quantity)
153 if len(order_info['fills'])>1:
154 commission=decimal.Decimal(0)
155 for number in order_info['fills']:
156 commission+=decimal.Decimal(number['commission'])[0:len(order_info['fills'])]
157 quantity=decimal.Decimal(quantity)-commission
158 quantity=str(quantity)
159# print(order_info['fills'][0]['commissionAsset'])
160# print(order_info['symbol'])
161 # the if statement checks to see if the api returns a dictionary
162 if isinstance(order_info,dict):
163 decimal.getcontext().prec=4
164 decimal.getcontext().rounding='ROUND_DOWN'
165# trade_amount=decimal.Decimal(ba.get_balances(symbol,secret_key,headers))
166# quantity=order_info["executedQty"]
167 #sub quantity for trade amount thats the code that was working
168 stop_loss_params=ba.test_order('{}'.format(symbol),'SELL','STOP_LOSS_LIMIT',quantity,
169 'GTC',stop_price,stop_loss,timestamp)
170 sig2=ba.get_signature(secret_key,stop_loss_params)
171 stop_order=ba.create_call('new_order',stop_loss_params,sig2,headers=headers)
172 stop_order_call=json.loads(stop_order.text)
173 print(stop_order_call)
174
175 # this if statement is to try to figure out if the code key is in a dictionary
176 if 'code' in stop_order_call:
177 error_code= stop_order_call.get('code')
178 if error_code==-1013:
179
180 bid_price=ba.get_bid_price(symbol)
181 timestamp=str(ba.create_timestamp())
182
183 error_sell_params=ba.test_order('{}'.format(symbol),'SELL','LIMIT',quantity,'FOK',str(bid_price),
184 timestamp)
185 sig=ba.get_signature(secret_key,error_sell_params)
186 sell_order=ba.create_call('new_order',error_sell_params,sig,headers=headers)
187
188 else:
189 print('code 1013 was not in this symbol')
190
191 if stop_order_call.get('code')==None or stop_order_call.get('symbol')==symbol:
192 intrade_symbols.update({symbol:stop_loss})
193 print (account_balance)
194 else:
195 break
196#enter_trade(width_list)
197
198
199def trade_loop(symbol_dict):
200 print(type(symbol_dict))
201 if symbol_dict==False:
202 print('starting')
203 gather_data(btc_pairs)
204 enter_trade(bol_list)
205
206 while True:
207# find out whats printing in this spot
208# thught maybe it doesnt run because you have no function to check for type none??
209 for trades in symbol_dict.keys():
210 print(type(trades))
211 price=ba.get_bid_price(trades)
212 pricing=ba.get_ask_price(trades)
213 global trade_amount
214 trade_amount=decimal.Decimal(ba.get_balances(trades,secret_key,headers))
215
216 current_stop=decimal.Decimal(symbol_dict['{}'.format(trades)])
217 print(current_stop)
218 if price >=decimal.Decimal(1.02) * current_stop:
219
220 timestamp=str(ba.create_timestamp())
221
222 #creating trailing stop losses
223 cancel_stop_params=ba.cancel_order(trades,timestamp)
224 sig=ba.get_signature(secret_key,cancel_stop_params)
225 delete_order=ba.create_call('cancel_order',cancel_stop_params,sig,headers=headers)
226 print(delete_order)
227
228
229 stop_loss=str((pricing)-(pricing)*decimal.Decimal(0.02))
230 stop_price=str((pricing)-(pricing)*decimal.Decimal(0.03))
231
232 trade_amount=trade_amount
233 print(trade_amount)
234 decimal.getcontext().prec=4
235
236 quantity=str(trade_amount)
237
238 stop_loss_params=ba.test_order('{}'.format(trades),'SELL','STOP_LOSS_LIMIT',quantity,
239 'GTC',stop_price,stop_loss,timestamp)
240 sig2=ba.get_signature(secret_key,stop_loss_params)
241 stop_order=ba.create_call('new_order',stop_loss_params,sig2,headers=headers)
242 stop_order_call=json.loads(stop_order.text)
243 print(stop_order_call)
244
245 del symbol_dict[trades]
246 symbol_dict.update({trades:stop_loss})
247
248 else:
249 trade_amount=trade_amount
250 if ba.dollar_asset_value('BTC',trades)*trade_amount<decimal.Decimal('10'):
251 del symbol_dict[trades]
252 print(trade_amount)
253 time.sleep(60)
254
255trade_loop(intrade_symbols)