· 9 years ago · Jan 22, 2017, 12:34 AM
1################################################################################
2# API interaction for YOBIT.NET, very simple beginning to start from,
3# Just sample code, you will need a "config file" with your keys and a
4# nonce value, (start with 1). Generate your keys from the YOBIT.NET site
5# This also does NOT trade for you right now, but does show how to use the API
6#
7# YOBIT.NET nick: dotoo1337
8# if you like this....feel free to donate!
9# BTC ADDR: 1CsEcj2Rp4uT88bWabQP1Z4WwzjSmDs8Zh
10################################################################################
11
12# usage: python yobit_api.py -c <config filename> -t <text output file>
13################################################################################
14# Pack the request to the site
15################################################################################
16import hashlib
17import urllib
18import json
19import hmac
20import httplib
21import optparse
22import sys
23import os
24from collections import namedtuple
25
26import datetime
27import signal
28
29global run
30run=False
31
32global last_ltc_btc
33last_ltc_btc=0
34global last_btc_usd
35last_btc_usd=0
36global last_nmc_btc
37last_nmc_btc=0
38global last_ppc_btc
39last_ppc_btc=0
40
41global last_ltc_btc_buy
42last_ltc_btc_buy=0
43global last_btc_usd_buy
44last_btc_usd_buy=0
45global last_nmc_btc_buy
46last_nmc_btc_buy=0
47global last_ppc_btc_buy
48last_ppc_btc_buy=0
49
50now=datetime.datetime.now()
51global pnl
52pnl = os.getcwd()+'/pnl_'+now.strftime("%Y-%m-%d_%H%M%S")+"_results.txt"
53global pl
54pl = open(pnl, 'a+')
55
56def signal_handler(signal, frame):
57 global run
58 print 'Caught signal!'
59 pl.close()
60 sys.exit(0)
61 run = False
62
63################################################################################
64# Global defines, (gross, but testing)
65################################################################################
66nonce=0
67BTC_api_key=''
68BTC_trade_key=''
69BTC_secret_key=''
70sign=0
71headers = {"Content-type":"application/x-www-form-urlencoded",
72 "Key": BTC_api_key,
73 "Sign":sign}
74trade_headers = {"Content-type":"application/x-www-form-urlencoded",
75 "Key": BTC_trade_key,
76 "Sign":sign}
77
78conf=namedtuple('conf','api_key secret_key')
79
80methods={"g":"getInfo",
81 "b":"buy",
82 "a":"ActiveOrders",
83 "t":"TradeHistory",
84 "s":"sell"}
85
86params = {"method":'',
87 "nonce":0}
88
89################################################################################
90# Pack the request to the TRADE API
91################################################################################
92def pack_trade(method, params):
93 global nonce
94 nonce += 1
95
96 global headers
97 global sign
98
99 print 'Nonce: %d' % nonce
100 print 'Method: %s' % method
101
102 params["method"] = method
103 params["nonce"] = nonce
104 print params
105 params=urllib.urlencode(params)
106
107 headers["Key"]=BTC_trade_key
108 H=hmac.new(BTC_trade_secret_key, digestmod=hashlib.sha512)
109 H.update(params)
110
111 sign=H.hexdigest()
112 headers["Sign"]=sign
113 print headers
114
115 send_req(params, headers)
116################################################################################
117# Pack the request to the TRADE API
118################################################################################
119def pack_req(method, params):
120 global nonce
121 nonce += 1
122
123 global headers
124 global sign
125
126 print 'Nonce: %d' % nonce
127 print 'Method: %s' % method
128
129 params["method"] = method
130 params["nonce"] = nonce
131 print params
132 params=urllib.urlencode(params)
133
134 headers["Key"]=BTC_api_key
135 H=hmac.new(BTC_secret_key, digestmod=hashlib.sha512)
136 H.update(params)
137
138 sign=H.hexdigest()
139 headers["Sign"]=sign
140 print headers
141
142 send_req(params, headers)
143################################################################################
144# Pack the request to the PUBLIC API
145################################################################################
146'''def pack_public_req(method, pair):
147
148 print 'Method: %s' % method
149
150 params=urllib.urlencode(params)
151
152 send_req(params, headers)'''
153################################################################################
154# Send the request
155################################################################################
156def send_req(params, headers):
157 conn = httplib.HTTPSConnection("yobit.net")
158 conn.request("POST","/tapi",params,headers)
159 response = conn.getresponse()
160 print response.status, response.reason
161 print json.load(response)
162 conn.close()
163
164def get_ticker(pair):
165 conn = httplib.HTTPSConnection("yobit.net")
166 conn.request("POST","/api/3/ticker/"+pair,pair)
167 response = conn.getresponse()
168 print response.status, response.reason
169 pass_on = json.load(response)
170 #print json.load(response)
171 #print pass_on
172 conn.close()
173 #print json.dumps(pass_on, indent=4)
174 key=pass_on[pair].keys()
175 val=pass_on[pair].values()
176 if val[0] > val[3]:
177 direction = 'UP %lf' % (val[0]-val[3])
178 percent_diff = (1-(float(val[3])/float(val[0])))
179 if percent_diff > 0.00001:#0.1 testing with small changes
180 pl.write(str(now.strftime("%Y-%m-%d_%H:%M:%S")+'%s INCREASED: %f------->SELL!\n' % (pair, percent_diff)))
181
182 elif val[3] > val[0]:
183 direction = 'DOWN %lf' % (val[3]-val[0])
184 percent_diff = (1-(float(val[0])/float(val[3])))
185 if percent_diff > 0.00001:#0.2: testing...
186 pl.write(str(now.strftime("%Y-%m-%d_%H:%M:%S")+'%s DECREASED: %f------->BUY!\n' % (pair, percent_diff)))
187 else:
188 direction = 'STALE'
189
190 print 'NAME: %s PRICE: %lf DIRECTION: %s' % (pair, float(val[0]), direction)
191 #parse_pair(pair, pass_on)
192
193def parse_pair(x, response):
194 return{
195 'btc_usd':response,
196 'anal_btc':json.load(response),
197 'trump_btc':json.load(response),
198 'jane_btc':json.load(response),
199 }.get(x, 0)
200################################################################################
201# Main
202################################################################################
203def main():
204 signal.signal(signal.SIGINT, signal_handler)
205 #pnl = os.getcwd()+'/pnl_'+now.strftime("%Y-%m-%d_%H%M%S")+"_results.txt"
206 #pl = open(pnl, 'a+')
207
208 parser = optparse.OptionParser("Usage: "+ sys.argv[0] +\
209 " -c <config filename> -t <text file to save>")
210 parser.add_option('-c', dest='config', type='string', help='Please specify config file')
211 parser.add_option('-t', dest='outName', type='string', help='Please specify text file to save to')
212 (options, args) = parser.parse_args()
213 config = options.config
214 outName = options.outName
215
216 if config == None or outName == None:
217 print parser.usage
218 exit(0)
219 else:
220 config_file = open(config, "r+")
221 conf = namedtuple('conf','api_key secret_key')
222
223 config_file.seek(0)
224 global BTC_api_key
225 BTC_api_key = (config_file.readline()).strip()
226 print BTC_api_key
227
228 global BTC_secret_key
229 BTC_secret_key = (config_file.readline()).strip()
230 print BTC_secret_key
231
232 global BTC_trade_key
233 BTC_trade_key = (config_file.readline()).strip()
234 print BTC_trade_key
235
236 global BTC_trade_secret_key
237 BTC_trade_secret_key = (config_file.readline()).strip()
238 print BTC_trade_secret_key
239
240 global nonce
241 nonce = int(config_file.readline())
242
243 print 'API KEY: %s' % BTC_api_key
244 print 'SECRET KEY: %s' % BTC_secret_key
245 print 'TRADE KEY: %s' % BTC_trade_key
246 print 'TRADE SECRET KEY: %s' % BTC_trade_secret_key
247 print 'NONCE: %d' % nonce
248
249 get_ticker('anal_btc')
250
251 pack_req(methods["g"], params)
252 pack_trade(methods["a"], params)
253 pack_trade(methods["t"], params)
254
255 global run
256 run = True
257 while run is True: #set to false upon ^+C signal catch
258 get_ticker('btc_usd')
259 get_ticker('anal_btc')
260 get_ticker('trump_btc')
261 get_ticker('jane_btc')
262
263
264 print 'Current nonce value: %d' % nonce
265
266 config_file.seek(0)
267 #this is gross but only happens on close
268 config_file.readline()
269 config_file.readline()
270 config_file.readline()
271
272 config_file.write(str(nonce))
273 config_file.close()
274
275if __name__ == '__main__':
276 main()
277################################################################################
278# EOF
279################################################################################