-
Notifications
You must be signed in to change notification settings - Fork 7
/
trademybit-switcher.py
267 lines (218 loc) · 9.18 KB
/
trademybit-switcher.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import ConfigParser
import csv
import datetime
import logging
import os.path
import socket
import subprocess
import sys
import time
from trademybitapi import TradeMyBitAPI
from pycgminer import CgminerAPI
class Algo:
def __init__(self, name):
self.command = '' # the command that is run when we want to mine this coin.
self.name = name
self.cnt = 0
class TradeMyBitSwitcher(object):
def __init__(self):
# Define supported algo
self.algos = {}
self.algos['scrypt'] = Algo('Scrypt')
self.algos['nscrypt'] = Algo('N-Scrypt')
self.profitability_log = None
self.__load_config()
self.api = TradeMyBitAPI(self.api_key, 'https://pool.trademybit.com/api/')
self.cgminer = CgminerAPI(self.cgminer_host, self.cgminer_port)
# We track state in a variable
self.current_algo = None
def main(self):
try:
# cnt_all = 0
# main loop
print '-' * 72
while True:
# print header
# self.logger.info("<<< Round %d >>>" % (cnt_all+1))
# get data from sources
self.logger.debug("Fetching data...")
bestalgo = self.best_algo()
self.logger.debug("=> Best: %s | Currently mining: %s" % (bestalgo, self.current_algo))
if bestalgo != self.current_algo and bestalgo != None:
# i.e. if we're not already mining the best algo
self.switch_algo(bestalgo)
elif self.current_algo == None:
# No miner running and profitability is similar, run the first algo
self.logger.warning('No miner running')
self.switch_algo(self.algos.keys()[0])
# sleep
self.logger.debug('Going to sleep for %dmin...' % self.idletime)
i = 0
while i < self.idletime*60:
time.sleep(1)
i += 1
except KeyboardInterrupt:
self.logger.warn('Caught KeyboardInterrupt, terminating...')
self.cleanup()
def cleanup(self):
"""Cleanup our mess"""
if self.profitability_log:
self.profitability_file.close()
sys.exit()
def best_algo(self):
"""Retrieves the "bestalgo" from TMB api"""
try:
data = self.api.bestalgo()
# parse json data into variables
algo1 = data[0]["algo"]
score1 = float(data[0]["score"])
algo2 = data[1]["algo"]
score2 = float(data[1]["score"])
self.logger.debug("%s : %f | %s: %f" % (algo1, score1, algo2, score2))
# return result
if (score2 - score1) / score1 > self.profitability_threshold:
best = algo2
elif (score1 - score2) / score2 > self.profitability_threshold:
best = algo1
else:
best = None
if self.profitability_log:
self.profitability_log.writerow({'date': datetime.datetime.now(), algo1: score1, algo2: score2})
self.profitability_file.flush()
return best
except (socket.error, KeyError):
self.logger.warning('Cannot connect to TMB API...')
return None
# # Return scrypt/nscrypt based on the version of the miner running
# # Temporarly disabled to support sgminer since we can't reliably determine
# # if sgminer is mining nfactor 10 or 11
# def current_algo(self):
# try:
# data = self.cgminer.version()
# version = data['STATUS'][0]['Description']
# if version.startswith('vertminer'): # vertminer 0.5.4pre1
# return 'nscrypt'
# elif version.startswith('cgminer'): # cgminer 3.7.2
# return 'scrypt'
# else:
# return None
# except:
# self.logger.warning('Cannot connect to miner API...')
# return None
def switch_algo(self, algo):
"""Tells the current miner to exit and start the other one"""
self.logger.info('=> Switching to %s (running %s)' % (algo, self.algos[algo].command))
self.current_algo = algo
try:
self.cgminer.quit()
time.sleep(self.switchtime) # Wait for it to quit / Or check the process id?
except socket.error:
pass # Cgminer not running
try:
subprocess.Popen(self.algos[algo].command)
except OSError:
self.logger.critical('Cannot execute [%s]!' % self.algos[algo].command)
self.logger.critical('Make sure your miner startup scripts are executable before continuing.')
sys.exit()
def __prepare_logger(self, logging_config={}):
"""Configure the logger"""
logfile = logging_config.get('logfile')
# Set console log level based on the config
if bool(logging_config.get('verbose')):
log_level = logging.DEBUG
else:
log_level = logging.INFO
# Prepare logger
self.logger = logging.getLogger()
self.logger.setLevel(logging.DEBUG)
## Console logging
# create console handler
stream_handler = logging.StreamHandler()
stream_handler.setLevel(log_level)
# create formatter and add it to the handler
formatter = logging.Formatter('%(asctime)s :: %(message)s', "%Y-%m-%d %H:%M:%S")
stream_handler.setFormatter(formatter)
# add the handler to the logger
self.logger.addHandler(stream_handler)
## File logging
if logfile:
print "Logging to %s" % logfile
# create file handler
file_handler = logging.FileHandler(logfile, 'a')
file_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s :: %(levelname)8s :: %(message)s', "%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
self.logger.addHandler(file_handler)
csv_file = logging_config.get('profitability_log')
if csv_file:
self.__prepare_profitability_log(csv_file)
def __prepare_profitability_log(self, csv_file):
# Check if file is already present to know if we need to write the headers
write_header = not(os.path.isfile(csv_file))
self.profitability_file = open(csv_file, 'ab')
self.profitability_log = csv.DictWriter(self.profitability_file, ['date', 'scrypt', 'nscrypt'])
if write_header:
self.profitability_log.writeheader()
def __load_config(self):
config_file = 'tmb-switcher.conf'
# Check if the config file is present
if not(os.path.isfile(config_file)):
print "ERROR: Configuration file not found!"
print "Make sure the tmb-switcher.conf file is present!"
sys.exit()
# Load the config file
config = ConfigParser.ConfigParser()
config.read(config_file)
# Read the logging settings and setup the logger
logging_config = dict(config.items('Logging'))
self.__prepare_logger(logging_config)
# Read the settings or use default values
try:
self.api_key = config.get('TradeMyBit', 'apikey')
except:
self.logger.critical("Could not read apikey from config file")
sys.exit()
try:
self.idletime = config.getint('Misc','idletime')
except:
self.logger.warning("Could not read idletime from config file. Defaulting to 5 min")
self.idletime = 5
try:
self.switchtime = config.getint('Misc', 'switchtime')
except:
self.logger.warning("Could not read switchtime from config file. Defaulting to 1s")
self.switchtime = 1
try:
self.profitability_threshold = config.getfloat('Misc','profitability_threshold')
except:
self.logger.warning("Could not read profitability_threshold from config file. Defaulting to 10%")
self.profitability_threshold = 0.1
try:
self.cgminer_host = config.get('cgminer', 'host')
except:
self.logger.warning("Could not read cgminer host from config file. Defaulting to 127.0.0.1")
self.cgminer_host = '127.0.0.1'
try:
self.cgminer_port = config.getint('cgminer', 'port')
except:
self.logger.warning("Could not read cgminer port from config file. Defaulting to 4028")
self.cgminer_host = 4028
for key in self.algos:
try:
script = config.get('Scripts', key)
if os.path.isfile(script):
self.algos[key].command = script
else:
self.logger.critical('Script for %s not found!' % key)
self.cleanup()
except ConfigParser.NoOptionError :
self.logger.warning('Script for %s not configured!' % key)
continue
def main():
switcher = TradeMyBitSwitcher()
switcher.main()
if __name__ == '__main__':
main()