Pages:
Author

Topic: [ANN] CryptoSwitcher - Automatically mine the best coin. - page 3. (Read 95412 times)

legendary
Activity: 1400
Merit: 1000
BitBar and BBQCoin added to Cryptoswitcher. SolidCoin removed.

Maybe you'd be interested in supporting this site: http://www.coinwarz.com/cryptocurrency

these lines can help you...   I addedd support to coinwarz

cryptoSwitcher.py:

(replace YOUR_COINWARZ_API_KEY with your api key)

Code:
  
from bs4 import BeautifulSoup
import urllib2
import time
import subprocess
import numpy as np
import sys
# Ugly hack so git submodule init is adequate.
sys.path.insert(0, './btce-api/')
import btceapi
sys.path.insert(0, './pyvircurex/')
import vircurex as vircurexapi
sys.path.insert(0, './PyCryptsy/')
from PyCryptsy import PyCryptsy

import ConfigParser

import simplejson
import socket

# -----------
# Hopefully nothing below this needs editing.
# -----------

class Coin:
    def __init__(self, name):
        self.ratio=0 # assume totally unprofitable unless otherwise shown to be the case.
        self.willingToMine = False
        self.miningNow = False
        self.merged = False
        self.willingToSell = False
        self.command = '' # the command that is run when we want to mine this coin.
        self.name = name
        self.cnt = 0
        self.median = 0
        self.m = 0
        self.h = 0
        self.fee = 0
        self.source = '--'
        self.price = 0.0
        self.diff = 9999999999.9 # start off with ridiculously high diff so we dont mine the wrong coin
        self.reward = 0
        self.algo = ""

coins = {}
coins['alf'] =  Coin('AlphaCoin')
coins['bet'] =  Coin('Betacoin')
coins['uno'] =  Coin('Unobtanium')
coins['amc'] =  Coin('AmericanCoin')
coins['anc'] =  Coin('Anoncoin')
coins['arg'] =  Coin('Argentum')
coins['asc'] =  Coin('Asiccoin')
coins['bfc'] =  Coin('ButterflyCoin')
coins['bqc'] =  Coin('BBQCoin')
coins['btb'] =  Coin('Bitbar')
coins['btc'] =  Coin('Bitcoin')
coins['bte'] =  Coin('Bytecoin')
coins['btg'] =  Coin('Bitgem')
coins['cap'] =  Coin('Bottlecap')
coins['cgb'] =  Coin('CryptogenicBullion')
coins['cnc'] =  Coin('CHNCoin')
coins['crc'] =  Coin('Craftcoin')
coins['dbl'] =  Coin('Doubloons')
coins['dgc'] =  Coin('DigitalCoin')
coins['emd'] =  Coin('Emerald')
coins['elc'] =  Coin('Elacoin')
coins['ezc'] =  Coin('EZCoin')
coins['frc'] =  Coin('Freicoin')
coins['frk'] =  Coin('Franko')
coins['fst'] =  Coin('Fastcoin')
coins['ftc'] =  Coin('Feathercoin')
coins['gdc'] =  Coin('Grandcoin')
coins['gld'] =  Coin('GLDCoin')
coins['hbn'] =  Coin('Hobonickel')
coins['hyc'] =  Coin('Hypercoin')
coins['kgc'] =  Coin('Krugercoin')
coins['jkc'] =  Coin('Junkcoin')
coins['lbw'] =  Coin('Lebowski')
coins['lky'] =  Coin('Luckycoin')
coins['ltc'] =  Coin('Litecoin')
coins['mec'] =  Coin('Megacoin')
coins['mem'] =  Coin('Memecoin')
coins['mnc'] =  Coin('Mincoin')
coins['nbl'] =  Coin('Nibble')
coins['nrb'] =  Coin('NoirBits')
coins['nvc'] =  Coin('NovaCoin')
coins['ppc'] =  Coin('PPCoin')
coins['pwc'] =  Coin('Powercoin')
coins['pxc'] =  Coin('Phenixcoin')
coins['ryc'] =  Coin('RoyalCoin')
coins['spt'] =  Coin('Spot')
coins['sbc'] =  Coin('StableCoin')
coins['tgc'] =  Coin('TigerCoin')
coins['trc'] =  Coin('TerraCoin')
coins['wdc'] =  Coin('Worldcoin')
coins['yac'] =  Coin('YaCoin')
coins['zet'] =  Coin('Zetacoin')
# Merged
coins['dvc'] = Coin('Devcoin')
coins['dvc'].merged = True
coins['ixc'] = Coin('IXCoin')
coins['ixc'].merged = True
coins['i0c'] =  Coin('I0Coin')
coins['i0c'].merged = True
coins['nmc'] =  Coin('NameCoin')
coins['nmc'].merged = True
# Kind of an alternate coin...
coins['vanity'] = Coin('Vanity Mining')

# Read in config file
Config = ConfigParser.ConfigParser()
Config.read('./cryptoSwitcher.config')

# Enable the coins you want to mine here.
for key in coins:
    try:
        coins[key].willingToMine = Config.getboolean('MineCoins','mine'+key)
    except:
        continue

# You should have scripts that stop all other forms of mining, set
# your clocks and environment variables appropriately, and start
# mining the appropriate coin. I have these called 'litecoin.sh',
# 'bitcoin.sh' etc., but edit and/or replace these as you see fit.

# Any coins you aren't mining you can just leave blank.
for key in coins:
    try:
        coins[key].command = Config.get('Scripts',key+'script')
    except:
        continue

# read source list
try:
    source = [x.strip() for x in Config.get('Data-Source','source').split(',')]
except:
    try:
        source = [x.strip() for x in Config.get('Misc','source').split(',')]
        print "warning: you are using an old config file structure. please update using the config sample file."
    except:
        sys.exit("ERROR: Cannot read source from config file.")



# read source list
try:
    source_cryptoswitcher = [x.strip() for x in Config.get('Data-Source','source_cryptoswitcher').split(',')]
except:
    source_cryptoswitcher = ''
    print "warning: couldnt read source_cryptoswitcher from config file. Leaving blank."

# read hashrates
try:
    hashrate_sha256 = int(Config.get('Data-Source','hashrate_sha256'))
    hashrate_scrypt = int(Config.get('Data-Source','hashrate_scrypt'))
except:
    hashrate_sha256 = 1000
    hashrate_scrypt = 1
    print "warning: couldnt read hashrates from config file. Setting to 1:1000."

# get idle time between two profitability check cycles
try:
    idletime = int(Config.get('Misc','idletime'))
except:
    idletime = 5
    print "warning: couldnt read idletime from config file. Setting to 5 min."

# get the coinfees
for key in coins:
    try:
        coins[key].fee = float(Config.get('Fees','fee'+key))
    except:
        continue


# And now some information to calculate Vanity Address mining profitability
try:
    gkeypersec = float(Config.get('Misc','gkeypersec')) #Gigakeys per second you can test
    ghashpersec = float(Config.get('Misc','ghashpersec')) #Gigahash per second you can output doing normal BTC mining.
except:
    print "warning: couldnt read gkeypersec and ghashpersec from config file."

# If you want to sell your coins on BTCE ASAP, then there's a bit more setup for you
try:
    enableBTCE = Config.getboolean('Sell','enableBTCE')
    enableVircurex = Config.getboolean('Sell','enableVircurex')
    enableCryptsy = Config.getboolean("Sell", "enableCryptsy")
    vircurexSecret = Config.get('Sell','vircurexSecret')
    vircurexUsername = Config.get('Sell','vircurexUsername')
    cryptsyPubkey = Config.get("Sell", "cryptsyPublicKey")
    cryptsyPrivkey = Config.get("Sell", "cryptsyPrivateKey")
except:
    enableBTCE = False
    enableVircurex = False
    enableCryptsy = False
    print "warning: couldnt read sell information from config file. Disabling auto sell."

# And flag which coins you want to sell as they come in. These coins will only
# sell for BTC, not for USD or any other cryptocoin.
for key in coins:
    try:
        coins[key].willingToSell = Config.getboolean('Sell','sell'+key)
    except:
        continue

#Trade multiplier. i.e. Don't sell for the highest current bid if this is
#larger than 1, but make a new ask at highest_bid * tradeMultiplier.

tradeMultiplier = 1
try:
    tradeMultiplier = float(Config.get('Misc','tradeMultiplier'))
except:
    pass

tradeMultiplierCheck = False
try:
    tradeMultiplierCheck = Config.getboolean ('Misc', 'tradeMultiplierCheck')
except:
    pass

def sellCoinBTCE(coin, tradeapi):
    r = tradeapi.getInfo()
    try:
        balance = getattr(r, 'balance_'+coin)
    except:
        # probably a coin that BTCE doesn't have an exchange for, so just return
        return
    if balance > 0.1:
        # i.e. if we're selling and we have some to sell that's larger than the minimum order...
        asks, bids = btceapi.getDepth(coin + '_btc')
        price = bids[0][0]*tradeMultiplier
        if price > asks[0][0] and tradeMultiplierCheck == True:
            price = asks[0][0] - 0.00000001
        tr = tradeapi.trade(coin + '_btc', 'sell', price, balance)
        # If tradeMultiplier is 1, then this sells at the highest price someone
        # currently has a bid lodged for.  It's possible that this won't
        # totally deplete our reserves, but any unsold immediately will be left
        # on the book, and will probably sell shortly.
        # A higher trade multiplier than 1 will not sell right away, but will
        # leave an order on the book.

def sellCoinVircurex(coin):
    pair = vircurexapi.Pair(coin+'_btc')
    try:
        bid = pair.highest_bid
        ask = pair.lowest_ask
    except:
        # probably a coin that Vircurex doesn't have an exchange for, so just return
        return
    account = vircurexapi.Account(vircurexUsername, vircurexSecret)
    balance = account.balance(coin.upper())
    if balance >= 0.1:
        price = bid * tradeMultiplier
        if price > ask and tradeMultiplierCheck == True:
            price = ask - 0.00000001
        order = account.sell(coin.upper(),balance, 'BTC', price)
        account.release_order(order['orderid'])

def sellCoinCryptsy(coin):
    acct = PyCryptsy(cryptsyPubkey, cryptsyPrivkey)
    bal = acct.GetAvailableBalance(coin)
    price = acct.GetBuyPrice(coin, "BTC")*tradeMultiplier
    sell = acct.GetSellPrice(coin, "BTC")
    if price > sell and tradeMultiplierCheck == True:
        price = sell - 0.00000001
    if price > 0:
        acct.CreateSellOrder(coin, "BTC", bal, price)
    else:
        #Try to get price from a coin/LTC market:
        priceltc = acct.GetBuyPrice(coin, "LTC")*tradeMultiplier
        if priceltc > 0:
            acct.CreateSellOrder(coin, "LTC", bal, priceltc)
    return

if enableBTCE:
    key_file = './key'
    handler = btceapi.KeyHandler(key_file)
    key = handler.keys.keys()[0]
    secret, nonce =  handler.keys[handler.keys.keys()[0]]
    authedAPI = btceapi.TradeAPI(key, secret, nonce)


# create http handler
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'CryptoSwitcher')]

# disable extended status output (=> coin price and difficulty) by default. only
# enable it, if at least one coins profitability is calculated by cryptoswitcher
extout = False

# main loop
cnt_all = 0
while True:
    # print header
    print "\n\n\n<<< Round %d >>>" % (cnt_all+1)
    print "time:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

    # get data from sources
    prestr = "getting data... "

    for x in source:
        # coinchoose
        if x=='coinchoose' or x=='cryptoswitcher':
            try:
                fullstr = prestr + "coinchoose"
                print fullstr + (79-len(fullstr))*" " + "\r",
                req = urllib2.Request("http://www.coinchoose.com/api.php")
                opener_cc = urllib2.build_opener()
                opener_cc.addheaders = [('User-agent', 'CryptoSwitcher')]
                f = opener_cc.open(req, timeout = 5)
                data_cc = simplejson.load(f)
                #print data_cc
            except:
                pass


        elif x=='coinwarz':
            try:
                fullstr = prestr + "coinwarz"
                print fullstr + (79-len(fullstr))*" " + "\r",
                req = urllib2.Request("http://www.coinwarz.com/v1/api/profitability/?apikey=YOUR_COINWARZ_API_KEY&algo=all")
                opener_cz = urllib2.build_opener()
                opener_cz.addheaders = [('User-agent', 'CryptoSwitcher')]
                f = opener_cz.open(req, timeout = 5)
                data_cz = simplejson.load(f)
                #print data_cc
            except:
                pass


        # dustcoin
        elif x=='dustcoin':
            try:
                fullstr = prestr + "dustcoin"
                print fullstr + (79-len(fullstr))*" " + "\r",
                usock = urllib2.urlopen('http://dustcoin.com/mining', timeout = 5)
                data = usock.read()
                usock.close()
                soup = BeautifulSoup(data)
                table_dustcoin = soup.findAll('tr',{ "class":"coin" })
            except:
                pass

        # coinotron
        elif x=='coinotron':
            try:
                fullstr = prestr + "coinotron"
                print fullstr + (79-len(fullstr))*" " + "\r",
                usock = urllib2.urlopen('https://coinotron.com/coinotron/AccountServlet?action=home', timeout = 5)
                data = usock.read()
                usock.close()
                soup = BeautifulSoup(data)
                table_coinotron = soup.findAll('tr')
            except:
                pass


    for x in source_cryptoswitcher:
        # cryptsy
        if x=='cryptsy':
            try:
                fullstr = prestr + "cryptsy"
                print fullstr + (79-len(fullstr))*" " + "\r",
                req = urllib2.Request("http://pubapi.cryptsy.com/api.php?method=orderdata")
                opener_cyp = urllib2.build_opener()
                opener_cyp.addheaders = [('User-agent', 'CryptoSwitcher')]
                f = opener_cyp.open(req, timeout = 5)
                data_cyp = simplejson.load(f)
            except:
                pass



    # assign data to coins
    # loop through coins
    for abbreviation, c in coins.items():
        # only get profitability for coins which we are interested in.
        # this saves network traffic and running time
        if c.willingToMine==False:
            continue

        success = 0
        # loop trough source list. try first entry first.
        for x in source:
            if x=='coinchoose':
                try:
                    for item in data_cc:
                        if item['symbol'].lower()==abbreviation:
                            print abbreviation
                            coins[item['symbol'].lower()].ratio = float(item['adjustedratio'])
                            coins[item['symbol'].lower()].source = 'cc'
                            success = 1
                            break
                except:
                    print "eccezione********"
                    continue




            elif x=='coinwarz':
                try:
                    ciao = data_cz["Data"]
                    ids = [item['CoinTag'] for item in ciao]
                    ids = [s.encode('utf-8') for s in ids]
                    for item in ciao:
                        if item['CoinTag'].lower()==abbreviation:
                         coins[item['CoinTag'].lower()].ratio = float(item['ProfitRatio'])
                  
                         coins[item['CoinTag'].lower()].source = 'cz'


                    success = 1
                    break
                except:
                    print "eccezione********"
   continue





            elif x=='dustcoin':
                try:
                    i=0
                    for coinrow in table_dustcoin:
                        coinName, profit = coinrow.find('strong',text=True).text, coinrow.find('td',{"id":"profit"+str(i)}).text.replace('%','')
                        # make sure the profit we read is floating value, if not, continue loop and keep old profit value until next check
                        try:
                            profit = float(profit)
                        except:
                            continue
                        # calculate profitabilty
                        if coinName == coins[abbreviation].name:
                            coins[abbreviation].ratio = float(profit)
                            coins[abbreviation].source = 'dc'
                            success = 1
                            break
                        i+=1
                except:
                    continue

            elif x=='coinotron':
                try:
                    i = 0
                    for coinrow in table_coinotron:
                        coinName = coinrow.findNext('td').contents[0]
                        profit = coinrow.findNext('td').findNext('td').findNext('td').findNext('td').findNext('td').findNext('td').findNext('td').findNext('td').contents[0]
                        # when all coins where read, leave loop
                        if i == 5: break
                        i+=1
                        # convert profitability to percent
                        profit = float(profit)*100
                        # calculate profitabilty
                        if coinName.lower()==abbreviation:
                            coins[abbreviation].ratio = float(profit)
                            coins[abbreviation].source = 'ct'
                            success = 1
                            break
                        i+=1
                except:
                    continue

            # lets calulate profitability ourself
            elif x=='cryptoswitcher':
                # get difficulty and block rewards
                # source for difficulty data depends on coin
                try:
                    # if this is the first time we come here, update btc as well.
                    # otherwise we are unable to calculate the profitabilty.
                    fullstr = prestr + "difficulty of " + coins[abbreviation].name
                    print fullstr + (79-len(fullstr))*" " + "\r",
                    if coins['btc'].reward == 0:
                        for item in data_cc:
                            if item['symbol'].lower()=='btc':
                                coins['btc'].diff = float(item['difficulty'])
                                coins['btc'].reward = float(item['reward'])
                                break

                    # get difficulty values from coinchoose by default
                    for item in data_cc:
                        if item['symbol'].lower()==abbreviation:
                            coins[item['symbol'].lower()].diff = float(item['difficulty'])
                            coins[item['symbol'].lower()].reward = float(item['reward'])
                            coins[item['symbol'].lower()].algo = item['algo']
                            break

                    # if we dont have a difficulty source for our coin, continue loop and get profitabilty from
                    # other sources
                    if item['symbol'].lower()!=abbreviation:
                        continue

                    # for trc: use a different source for difficulty
                    if abbreviation == 'trc':
                        req = urllib2.Request("http://cryptocoinexplorer.com:3750/chain/Terracoin/q/getdifficulty")
                        f = opener.open(req, timeout = 5)
                        coins['trc'].diff = simplejson.load(f)

                    # for btc: we dont need to calculate
                    if abbreviation=='btc':
                        coins['btc'].ratio=100.0
                        coins['btc'].source = '--'
                        coins['btc'].algo = "SHA-256"
                        coins['btc'].price = 1.0
                        success = 1
                        break

                except:
                    continue


                # calculate highest buy value
                # use only data sources defined in source_cryptoswitcher
                coins[abbreviation].price = 0.0
                for y in source_cryptoswitcher:

                    # if coin profitability couldnt be processed manually in the
                    # last round, then they are probably not traded on the chosen
                    # markets. so the coin is removed from manual processing.
                    if coins[abbreviation].source != '--' and coins[abbreviation].source != 'cs':
                        continue

                    # btc-e
                    if y=='btce':
                        try:
                            fullstr = prestr + "price of " + coins[abbreviation].name + " at BTC-E"
                            print fullstr + (79-len(fullstr))*" " + "\r",
                            req = urllib2.Request("https://btc-e.com/api/2/" + abbreviation + "_btc/ticker")
                            f = opener.open(req, timeout = 5)
                            output = simplejson.load(f)
                            if coins[abbreviation].price < float(output['ticker']['sell']):
                                coins[abbreviation].price = float(output['ticker']['sell'])
                        except:
                            continue

                    # bter
                    elif y=='bter':
                        try:
                            fullstr = prestr + "price of " + coins[abbreviation].name + " at Bter"
                            print fullstr + (79-len(fullstr))*" " + "\r",
                            req = urllib2.Request("https://bter.com/api/1/ticker/" + abbreviation + "_btc")
                            f = opener.open(req, timeout = 5)
                            output = simplejson.load(f)
                            if coins[abbreviation].price < float(output['buy']):
                                coins[abbreviation].price = float(output['buy'])
                        except:
                            continue

                    # vircurex
                    elif y=='vircurex':
                        try:
                            fullstr = prestr + "price of " + coins[abbreviation].name + " at Vircurex"
                            print fullstr + (79-len(fullstr))*" " + "\r",
                            req = urllib2.Request("https://vircurex.com/api/get_highest_bid.json?base=" + abbreviation + "&alt=btc")
                            f = opener.open(req, timeout = 5)
                            output = simplejson.load(f)
                            if coins[abbreviation].price < float(output['value']):
                                coins[abbreviation].price = float(output['value'])
                        except:
                            continue

                    # cryptsy
                    elif y=='cryptsy':
                        try:
                            fullstr = prestr + "price of " + coins[abbreviation].name + " at Cryptsy"
                            print fullstr + (79-len(fullstr))*" " + "\r",
                            for item in data_cyp['return']:
                                if item.lower()==abbreviation:
                                    if data_cyp['return'][item]['secondarycode']=='BTC':
                                        if coins[abbreviation].price < float(data_cyp['return'][item]['buyorders'][0]['price']):
                                            coins[abbreviation].price = float(data_cyp['return'][item]['buyorders'][0]['price'])
                                    success = 1
                                    break
                        except:
                            continue

                # calculate profitability
                if coins[abbreviation].price!=0.0:
                    try:
                        if coins[abbreviation].algo == 'scrypt':
                            coins[abbreviation].ratio = (coins[abbreviation].reward/coins[abbreviation].diff)/(coins['btc'].reward/coins['btc'].diff)*coins[abbreviation].price*100/(hashrate_sha256/hashrate_scrypt)
                        else:
                            coins[abbreviation].ratio = (coins[abbreviation].reward/coins[abbreviation].diff)/(coins['btc'].reward/coins['btc'].diff)*coins[abbreviation].price*100
                        coins[abbreviation].source = 'cs'
                        success = 1

                        # at least one coins profitability was calculated by cryptoswitcher
                        # => enable extended status output
                        extout = True
                        break
                    except:
                        continue

            if success==1:
                break


    # Now work out how profitable btc mining really is, if we're doing any merged mining
    if coins['nmc'].willingToMine:
        coins['btc'].ratio +=coins['nmc'].ratio
    if coins['dvc'].willingToMine:
        coins['btc'].ratio +=coins['dvc'].ratio
    if coins['ixc'].willingToMine:
        coins['btc'].ratio +=coins['ixc'].ratio

    fullstr = prestr + "done"
    print fullstr + (79-len(fullstr))*" " + "\r"


    # Now get data for vanity mining
    if coins['vanity'].willingToMine:
        vanityDataValid = True
        try:
            usock = urllib2.urlopen('http://www.fizzisist.com/mining-value/api/bitcoin-value',timeout=1)
            btcperghash = usock.read()
            usock.close()
            btcperghash = float(btcperghash)
        except (urllib2.URLError, ValueError, socket.timeout) as  e:
            print "There was an error: ,", e
            vanityDataValid = False

        try:
            usock = urllib2.urlopen('http://www.fizzisist.com/mining-value/api/vanitypool-value',timeout=1)
            btcpergkey = usock.read()
            btcpergkey = float(btcpergkey)
            usock.close()
        except (urllib2.URLError, ValueError, socket.timeout) as  e:
            print "There was an error: ,", e
            vanityDataValid = False

        if vanityDataValid:
            # Now put vanity mining in terms of BTC mining.
            vanitybtcsec = gkeypersec * btcpergkey
            miningbtcsec = ghashpersec * btcperghash
            vanityprof = vanitybtcsec / miningbtcsec * 100
            coins['vanity'].ratio = vanityprof
            # print 'Vanity Mining', vanityprof

    # Now find the best profit coin
    bestcoin = 'btc'
    bestprof = 0
    print "comparing profitabilty..."
    print "-"*36
    for abbreviation, c in coins.items():
        if c.willingToMine:
            print "%11s: %3d  (fee: %2d, src: %s)" % (coins[abbreviation].name, c.ratio, coins[abbreviation].fee, coins[abbreviation].source),
            if extout == True:
                if coins[abbreviation].source == "cs" or abbreviation == "btc":
                    print "(pr: %.5f, di[%s]: %.2f)" % (coins[abbreviation].price, coins[abbreviation].algo, coins[abbreviation].diff),
                else:
                    # if diff is valid print it
                    if coins[abbreviation].reward != 0:
                        print "(pr:  -NA-  , di[%s]: %.2f)" % (coins[abbreviation].algo, coins[abbreviation].diff),
                    else:
                        print "(pr:  -NA-  , di[%s]:  -NA-  )" % (coins[abbreviation].algo),
            print ""

        if c.ratio-coins[abbreviation].fee > bestprof and c.willingToMine:
            bestcoin = abbreviation
            bestprof=c.ratio-coins[abbreviation].fee
    print "-"*36
    print "=> Best: %d, mining %s" % (bestprof, coins[bestcoin].name)
    coins[bestcoin].median = ((coins[bestcoin].median * coins[bestcoin].cnt) + coins[bestcoin].ratio-coins[bestcoin].fee) / (coins[bestcoin].cnt+1)
    coins[bestcoin].cnt = coins[bestcoin].cnt+1


    if coins[bestcoin].miningNow == False:
        # i.e. if we're not already mining the best coin
        print '=> Switching to %s (running %s)' % (coins[bestcoin].name, coins[bestcoin].command)
        for abbreviation, c in coins.items():
            c.miningNow = False
        coins[bestcoin].miningNow = True
        subprocess.Popen(coins[bestcoin].command)

    # Sell some coins if that's what we're into
    for abbreviation, c in coins.items():
        if c.willingToSell and (c.miningNow or c.merged) and enableBTCE:
            # i.e. if we're willing to sell it AND it's still worth more than BTC -
            # with pool payout delays and wild exchange swings, while it might be
            # profitable to have mined it, we didn't sell it quickly enough. This
            # keeps hold of the coin until you've made a decision.
            sellCoinBTCE(abbreviation, authedAPI)
        # elif c.willingToSell and c.miningNow and enableVircurex:
        if c.willingToSell and enableVircurex and (c.miningNow or c.merged):
            sellCoinVircurex(abbreviation)
        if c.willingToSell and enableCryptsy and (c.miningNow or c.merged):
            sellCoinCryptsy(abbreviation)

    # ...and now save the keyfile in case the script is aborted.
    if enableBTCE:
        handler.setNextNonce(key,time.time()) #Thanks, jsorchik
        handler.save(key_file)

    # create status output strings
    sname = "#        "
    smedian = "# Median:"
    stime = "# Time:  "
    median_all = 0
    cnt_all = 0
    for abbreviation, c in coins.items():
        if c.willingToMine and (not c.merged):
            coins[abbreviation].h, coins[abbreviation].m = divmod(coins[abbreviation].cnt*idletime, 60)
            if coins[abbreviation].h < 10:
                sname += "%5s  " % (abbreviation.upper())
                smedian += "%5d |" % (coins[abbreviation].median)
                stime += "%2d:%02d |" % (coins[abbreviation].h, coins[abbreviation].m)
            elif coins[abbreviation].h < 100:
                sname += "%6s  " % (abbreviation.upper())
                smedian += "%6d |" % (coins[abbreviation].median)
                stime += "%3d:%02d |" % (coins[abbreviation].h, coins[abbreviation].m)
            else:
                sname += "%7s  " % (abbreviation.upper())
                smedian += "%7d |" % (coins[abbreviation].median)
                stime += "%4d:%02d |" % (coins[abbreviation].h, coins[abbreviation].m)
            if coins[abbreviation].cnt > 0:
                median_all = ((median_all * cnt_all) + (coins[abbreviation].median*coins[abbreviation].cnt)) / (cnt_all+coins[abbreviation].cnt)
                cnt_all += coins[abbreviation].cnt

    # remove last chars
    sname = sname[:-2]
    smedian = smedian[:-2]
    stime = stime[:-2]

    smedian_all = '# Total Median:%5d' % (median_all)
    stime_all = '# Total Time:%4d:%02d' % (divmod(cnt_all*idletime, 60))

#    # fill strings to screen width and add "#" to the end
#    sname = "%s%s%s" % (sname, " "*(79-len(sname)), "#")
#    smedian = "%s%s%s" % (smedian, " "*(79-len(smedian)), "#")
#    stime = "%s%s%s" % (stime, " "*(79-len(stime)), "#")
#    smedian_all = "%s%s%s" % (smedian_all, " "*(79-len(smedian_all)), "#")
#    stime_all = "%s%s%s" % (stime_all, " "*(79-len(stime_all)), "#")

    # output status strings
#    print "\n", "#"*80+sname+smedian+stime+smedian_all+stime_all+"#"*80
    print "\n", sname
    print smedian
    print stime
    print smedian_all
    print stime_all, "\n"

    # sleep
    print 'Going to sleep...'
    i=0
    while i        print "Seconds remaining:", (idletime*60-i), " ", "\r",
        time.sleep(1)
        i+=1




cryptoSwitcher.config

Code:


# -------------------------------------------------#
# Cryptocurrency mining switcher config file       #
# TipJar (BTC): 1NhathL6LpcgofDnHELSS6Hej6kU9xrVgp #
# Author: area                                     #
# -------------------------------------------------#


################################################################################
[MineCoins]

# Enable the coins you want to mine here.
mineALF = False
mineAMC = False
mineANC = False
mineARG = False
mineASC = False
mineBFC = False
mineBQC = False
mineBET = True
mineBTB = False
mineBTC = False
mineBTE = False
mineBTG = False
mineCAP = False
mineCGB = False
mineCNC = False
mineCRC = False
mineDGC = False
mineDEM = True
mineEMD = False
mineELC = False
mineEZC = False
mineFRC = False
mineFRK = False
mineFST = False
mineFTC = False
mineGDC = False
mineHBN = False
mineHYC = False
mineKGC = False
mineLBW = False
mineLKY = False
mineLTC = False
mineMEM = False
mineMNC = False
mineNBL = False
mineNRB = False
mineNVC = False
minePPC = False
minePXC = False
mineSPT = False
mineSBC = False
mineTGC = True
mineTRC = False
mineWDC = False
mineZET = False
mineUNO = True

# Listed against LTC only (currently unusable by CS)
mineDBL = False
mineGLD = False
mineJKC = False
mineRYC = False

# No data available from sources
minePWC = False
mineMEC = False
mineYAC = False

# BTC Merged mining coins. Will be added to Bitcoin profitibilty when enabled.
mineDVC = True
mineIXC = True
mineI0C = False
mineNMC = True

# Enable to mine vanity addresses.
mineVANITY = False


################################################################################
[Scripts]

# You should have scripts that stop all other forms of mining, set all necesary
#  environment variables, and start mining the appropriate coin.

# Examples included are 'litecoin.sh.sample' and 'bitcoin.sh.sample'.
# Any coins you aren't mining you can just leave blank.
# For Windows you can use bat-files, eg "BTCscript = bitcoin.bat".
ALFscript =
AMCscript =
ANCscript =
ARGscript =
ASCscript =
BETscript = ./betacoin.sh
BFCscript =
BQCscript =
BTBscript =
BTCscript = ./bitcoin.sh
BTEscript =
BTGscript =
CAPscript =
CGBscript =
CNCscript =
CRCscript =
DBLscript =
DGCscript =
DEMscript = ./dem.sh
EMDscript =
ELCscript =
EZCscript =
FRCscript =
FRKscript =
FSTscript =
FTCscript =
GDCscript =
GLDscript =
HBNscript =
HYCscript =
KGCscript =
JKCscript =
LBWscript =
LKYscript =
LTCscript = ./litecoin.sh
MECscript =
MEMscript =
MNCscript =
NBLscript =
NRBscript =
NVCscript =
PPCscript =
PWCscript =
PXCscript =
RYCscript =
SPTscript =
SBCscript =
TGCscript = ./tigercoin.sh
TRCscript =
WDCscript =
YACscript =
ZETscript =
UNOscript = ./uno.sh

VANITYscript =

################################################################################
[Fees]

# Set specific fees for every coin (in percent).
# The fee simply adds to the profitability before calculating the most profitable coin.
# Negative values are also allowed, they increase the profitability.
feeALF = 0
feeAMC = 0
feeANC = 0
feeARG = 0
feeASC = 0
feeBET = 0
feeBFC = 0
feeBQC = 0
feeBTB = 0
feeBTC = 1.5
feeBTE = 0
feeBTG = 0
feeCAP = 0
feeCGB = 0
feeCNC = 0
feeCRC = 0
feeDBL = 0
feeDEM = 0
feeDGC = 0
feeEMD = 0
feeELC = 0
feeEZC = 0
feeFRC = 0
feeFRK = 0
feeFST = 0
feeFTC = 0
feeGDC = 0
feeGLD = 0
feeHBN = 0
feeHYC = 0
feeKGC = 0
feeJKC = 0
feeLBW = 0
feeLKY = 0
feeLTC = 2
feeMEC = 0
feeMEM = 0
feeMNC = 0
feeNBL = 0
feeNRB = 0
feeNVC = 0
feePPC = 0
feePWC = 0
feePXC = 0
feeRYC = 0
feeSPT = 0
feeSBC = 0
feeTGC = 0
feeTRC = 0
feeWDC = 0
feeYAC = 0
feeZET = 0
feeUNO = 0

################################################################################
[Data-Source]

# Source list for determining mining profitability.
# The first entry in the source list has the highest priority and is used first.
# If the site is down or a certain coin is not found the next source is used.
# Available sources: cryptoswitcher, coinotron, coinchoose, dustcoin
source=coinwarz, coinotron, coinchoose, dustcoin
#source=coinwarz

# If using CryptoSwitcher as a source, list markets to source prices from.
# Difficulty is acquired from coinchoose and cryptocoinexplorer.
# Available sources: btce, bter, vircurex, cryptsy
source_cryptoswitcher=btce, bter, vircurex, cryptsy

# Hashrates used in calculations when using CryptoSwitcher as a source.
# Measured in hashes per second. Can be acquired by testmining with cgminer.
# sha256 is used by Bitcoin etc. while scrypt is used by Litecoin etc.
hashrate_sha256=1350000
hashrate_scrypt=1450


################################################################################
[Misc]

# Idle Time (in minutes) between two checks of coin profitability.
idletime = 5

# Gigahash per second you can output doing normal BTC mining.
ghashpersec = 0.7

# Gigakeys per second you can output doing vanity address mining.
gkeypersec = 0.05

# Trade multiplier - if not 1, sells not at the highest bid, but at this
#  multiple of it.  
tradeMultiplier = 1.01

# make sure our sell order is the lowest if tradeMultiplier > 1
tradeMultiplierCheck = False

################################################################################
[Sell]

# If you want to sell your coins ASAP after mining, enable an exchange here.
# This will automatically sell flagged coins for BTC ONLY.

# BTC-e
enableBTCE = False
# You'll need to configure your API key, secret, and a nonce in "key.sample".
# Rename this file to "key".

# VirCurEx
enableVircurex = False
vircurexUsername = VCEUSERNAME
vircurexSecret = APISECRET

# Cryptsy
enableCryptsy = False
cryptsyPublicKey = YOUR_CRYPTSY_API_PUBLIC_KEY
cryptsyPrivateKey = YOUR_CRYPTSY_API_PRIVATE_KEY

# Enable the coins you want to sell here.
sellALF = False
sellAMC = False
sellANC = False
sellARG = False
sellASC = False
sellBET = False
sellBFC = False
sellBQC = False
sellBTB = False
sellBTE = False
sellBTG = False
sellCAP = False
sellCGB = False
sellCNC = False
sellCRC = False
sellDBL = False
sellDGC = False
sellEMD = False
sellELC = False
sellEZC = False
sellFRC = False
sellFRK = False
sellFST = False
sellFTC = False
sellGDC = False
sellGLD = False
sellHBN = False
sellHYC = False
sellKGC = False
sellJKC = False
sellLBW = False
sellLKY = False
sellLTC = False
sellMEC = False
sellMEM = False
sellMNC = False
sellNBL = False
sellNRB = False
sellNVC = False
sellPPC = False
sellPWC = False
sellPXC = False
sellRYC = False
sellSPT = False
sellSBC = False
sellTGC = False
sellTRC = False
sellWDC = False
sellYAC = False
sellUNO = False
sellZET = False
member
Activity: 70
Merit: 10
nov
sr. member
Activity: 433
Merit: 251
Independent crypto developer
Do you think auto switching of the coin mining pool method is more profitable or is it just a theory?
And real values are different? Like frequent change of exchange rate, long time to get full hash rate efficiency in just switched pool, other problems, etc.?
Delay caused in transferring of the coins to exchange, etc.? Could that finally cause lower earnings finally?

What are your experiences?
nov
sr. member
Activity: 433
Merit: 251
Independent crypto developer
Looks like nice idea!

It could be interesting if somebody could add this functionality to minepeon raspberry pi mining distro.
https://bitcointalk.org/index.php?topic=137934.0;topicseen
newbie
Activity: 10
Merit: 0
Hi. Noob here.
I downloaded this program 2 weeks ago, played with it, and set it up to mine the various SHA-256 coins in the list.
But within those two weeks, coins have disappeared (like BFC), and new coins have popped up (OSC and the new UNO to name a few).

Could someone please help me understand how make this program look at CoinWarz site and the CoinEx.pw site, first, before looking at the other exchanges already in this program?
Also, how do I implement new coins? For instance OSC and the new UNO coins are only listed on the COINEX exchange (and coinwarz site) and I want to use them with the CryptoSwitcher program.

Do I use these in the code?
https://coinex.pw/api/v1/trade_pairs
https://coinex.pw/api/v1/ticker

Thank you for your help.
hero member
Activity: 651
Merit: 501
My PGP Key: 92C7689C
A couple of days or so ago, I merged some pull requests that had been sitting around a while.  I also included a PHP script that uses the cgminer API to switch pools.  Others have posted about using just one cgminer.conf with every pool and issuing a switchpool call.  My script takes a pool URL, miner name, and password, adds them to the current list of pools, and (optionally) removes all of the other pools.  In your pool-switching shell script, you then call my script once for each pool you want to use for a coin, with the "clear" parameter included on the first call. This allows you to have multiple pools configured for a coin as a backup.
member
Activity: 88
Merit: 10

It was working but not good at all, sometimes it switch good sometimes it start another instance of cgminer without shutdown one that is running and than everything for some reason stop.
Also I did not like fact that every time on switch GPU's are turned off and than turned on, so I come out with solution that now works perfect for me.
I made just one instance of cgminer with just one config file, in which are pools for all coins, because I mine just scrypt based coins it works, settings are the same.
In .sh that switcher start I put just this:
Code:
echo "switchpool|1" | nc 127.0.0.1 80
where number in "switchpool|1" represent ID of pool in cgminer configuration.
So now it mining and switching good, even without stoping GPU's!

I got CryptoSwitcher up and running on Linux great last night. It's really awesome with your suggestion to just load all of your pools in the config file and then just have each script run the switchpool command through cgminer's API. Right now I only have 1 Linux box and my main miner runs on Windows 7. I use CGWatcher to profit switch but I hate that it has to close and reopen a cgminer instance each time. I personally think it leads to instability. I got CryptoSwitcher running on Windows, but I can't get the same switchpool command to work. I downloaded a copy of netcat, but when I run the command, I get this error:

STATUS=E,When=1379746858,Code=14,Msg=Invalid command,Description=cgminer 3.2.1|

I have --api-listen, --api-port and --api-allow set in the cgminer config file. netcat is obviously talking to cgminer since it's getting an error response from it. Any suggestions?

Thanks to everyone!
I personally dont have any of the problems mentioned above. Once i had 2 cgminers running, but then i changed some stuff and now everything is running great, i have 7 block erupters running on a linux host and 2 block erupters on a windows host; Both of them running fine,
I even noticed a small increase of income, but i guess thats what its supposed to do...??
But, again, i'm not using any gpu or cpu anymore so i can not speak for basic hardware.
full member
Activity: 163
Merit: 100

It was working but not good at all, sometimes it switch good sometimes it start another instance of cgminer without shutdown one that is running and than everything for some reason stop.
Also I did not like fact that every time on switch GPU's are turned off and than turned on, so I come out with solution that now works perfect for me.
I made just one instance of cgminer with just one config file, in which are pools for all coins, because I mine just scrypt based coins it works, settings are the same.
In .sh that switcher start I put just this:
Code:
echo "switchpool|1" | nc 127.0.0.1 80
where number in "switchpool|1" represent ID of pool in cgminer configuration.
So now it mining and switching good, even without stoping GPU's!

I got CryptoSwitcher up and running on Linux great last night. It's really awesome with your suggestion to just load all of your pools in the config file and then just have each script run the switchpool command through cgminer's API. Right now I only have 1 Linux box and my main miner runs on Windows 7. I use CGWatcher to profit switch but I hate that it has to close and reopen a cgminer instance each time. I personally think it leads to instability. I got CryptoSwitcher running on Windows, but I can't get the same switchpool command to work. I downloaded a copy of netcat, but when I run the command, I get this error:

STATUS=E,When=1379746858,Code=14,Msg=Invalid command,Description=cgminer 3.2.1|

I have --api-listen, --api-port and --api-allow set in the cgminer config file. netcat is obviously talking to cgminer since it's getting an error response from it. Any suggestions?

Thanks to everyone!
member
Activity: 88
Merit: 10
For anyone who's interested.

I've added some coins and included batch file samples the for coins i use.
I have also modified the batch file for windows, makes it easier to implement on existing installs.
Take a look at the bitcoin example to see what i mean --> https://github.com/MasterX1582/CryptoSwitcher/blob/master/bitcoin.bat.sample

The coins i have added are Asiccoin, ButterflyCoin and TigerCoin.

Have fun mining with it!
sr. member
Activity: 290
Merit: 250

So looking at the script.

If I have 2 exchanges enabled... it will attempt to sell the balance of my current coin on them both.

Obv doesn't complete if I have no balance

sr. member
Activity: 290
Merit: 250
I made just one instance of cgminer with just one config file, in which are pools for all coins, because I mine just scrypt based coins it works, settings are the same.
In .sh that switcher start I put just this:
Code:
echo "switchpool|1" | nc 127.0.0.1 80
where number in "switchpool|1" represent ID of pool in cgminer configuration.
So now it mining and switching good, even without stoping GPU's!

That's a brilliant idea, Thanks!
sr. member
Activity: 490
Merit: 250


I'm an avalon ASIC owner (recieved my 20chip miner very late) so I thought I'd give cryptoswitcher a try. Got the clock speed set nice 'n high too.  Will post my results.  SebastianJu, I would change my data source to coinchoose rather than dustcoin.  I have found that dustcoin's numbers to be off *somehow* too.  Can't quite put my finger on it though.  It will be interesting to see how coinchoose stacks up against an ASIC.  Your choice of pools can have a pretty big effect as well.

Would be nice to see tigercoin/butterflycoin support.  I'll mine anything if its mathmatically calculated, has quick confirms, and can be auto-sold at cryptsy for btc.  Can anyone edit the github?  I should see how my python skills are and edit github.

My hashrate will get much higher than it would mining btc briefly every few minutes.
legendary
Activity: 1124
Merit: 1013
ParalleCoin's ruler from the shadow
I am testing this tool on Centos, it start ok, .sh of best profitable coin start, but it wont switch automaticly to best profitable coin.
I have set idletime = 3 and watching but it did not change coin anyhow.
Where am I wrong?

edit

I was wrong on many steps Smiley

First my centos did not have nc and screen and .sh script did not start well.
Second cgminer API was configured to port 80, because I use Anubis to watch my rigs.
At the end I figure out to make switcher start cgminer in other, new window instead of screen command, so I made this start script:
Code:
#!/bin/bash
echo "{\"command\":\"quit\"}" | nc 127.0.0.1 80
export GPU_MAX_ALLOC_PERCENT=100
export GPU_USE_SYNC_OBJECTS=1
export DISPLAY=:0
cd /cg
gnome-terminal -e "./cgminer -c /conf/ftc.conf"

At last CryptoSwitcher work for me now on one rig.
I will install it on the second rig and try to write down everything that it is done so I can post it here if some one have similar problems.

Cheers! Smiley

edit again Smiley
It was working but not good at all, sometimes it switch good sometimes it start another instance of cgminer without shutdown one that is running and than everything for some reason stop.
Also I did not like fact that every time on switch GPU's are turned off and than turned on, so I come out with solution that now works perfect for me.
I made just one instance of cgminer with just one config file, in which are pools for all coins, because I mine just scrypt based coins it works, settings are the same.
In .sh that switcher start I put just this:
Code:
echo "switchpool|1" | nc 127.0.0.1 80
where number in "switchpool|1" represent ID of pool in cgminer configuration.
So now it mining and switching good, even without stoping GPU's!
legendary
Activity: 1124
Merit: 1013
ParalleCoin's ruler from the shadow
Great tool area Smiley

This could be useful to use with it  Crypto-currency directory
legendary
Activity: 2674
Merit: 1083
Legendary Escrow Service - Tip Jar in Profile
Is cryptoswitcher still rewarding for ASIC-User? I see a big list of scrypt coins but only one coint better than bitcoin and this coin lost half of its advantage the last day. So would it be worth the effort for me yet? I now mine at bitparking.com and get 2% more in total because of merged mining.

I've only had my Jalapeños on it since this morning, but it's already reporting a median ~150% return for the Zetacoin mining it's done.

Hm. I tried mining zetacoins the last 24 hours too. http://www.alloscomp.com/bitcoin/calculator told me with mining bitcoins i should have made 0.34BTC. I received 28953 Zetacoins. Even at 0.000008BTC exchange price this would translate to 0.23BTC only. So i dont see anywhere near the 150% that zetacoin often stands at dustcoin.

The pool states nearly the hashrate cgminer states. And only 0.6% invalid. But cgminer shows me 13% Rejected shares. Now what to trust? I mean even when the pool counts rejected shares too it would mean i effectively mine with less hashpower than normal since the calculations on coinchoose are based on clean hashing without errors.

Im not sure whats wrong but i think cryptoswitcher and its depending websites make an error by not including a factor of some kind

Im back at bitcoin mining for the moment.
hero member
Activity: 651
Merit: 501
My PGP Key: 92C7689C
Is cryptoswitcher still rewarding for ASIC-User? I see a big list of scrypt coins but only one coint better than bitcoin and this coin lost half of its advantage the last day. So would it be worth the effort for me yet? I now mine at bitparking.com and get 2% more in total because of merged mining.

I've only had my Jalapeños on it since this morning, but it's already reporting a median ~150% return for the Zetacoin mining it's done.
legendary
Activity: 2674
Merit: 1083
Legendary Escrow Service - Tip Jar in Profile
So there is no pool for sha256 yet? Only possibility would be using cryptoswitcher. But is it rewarding at all for sha256?

Freicoin and Zetacoin have blipped above Bitcoin recently, sometimes by a considerable margin.  I have a couple of Jalapeños mining through CryptoSwitcher.

I watched zetacoin too... but i saw it lost its better position in hours up to the level of bitcoin mining. Thats why im wondering if its worth the effort...
hero member
Activity: 651
Merit: 501
My PGP Key: 92C7689C
So there is no pool for sha256 yet? Only possibility would be using cryptoswitcher. But is it rewarding at all for sha256?

Freicoin and Zetacoin have blipped above Bitcoin recently, sometimes by a considerable margin.  I have a couple of Jalapeños mining through CryptoSwitcher.
legendary
Activity: 2674
Merit: 1083
Legendary Escrow Service - Tip Jar in Profile
So there is no pool for sha256 yet? Only possibility would be using cryptoswitcher. But is it rewarding at all for sha256?
hero member
Activity: 505
Merit: 500
Does it matter the color of money to you ?
Pages:
Jump to: