def create_brokers(mode, pairs, exchangeNames):
    # returns an array of Broker objects
    brokers = []
    for name in exchangeNames:
        if (name == 'VIRCUREX'):
            xchg = Vircurex(config.VIRCUREX_USER, config.VIRCUREX_SECURITY_WORD)
        elif (name == 'BTCE'):
            xchg = BTCE(config.BTCE_KEYFILE)
        elif (name == 'BTER'):
            xchg = BTER(config.BTER_KEYFILE)
        elif (name == 'COINS-E'):
            xchg = CoinsE(config.COINS_E_API_KEY, config.COINS_E_SECRET)
        elif (name == 'CRYPTSY'):
            xchg = Cryptsy(config.CRYPTSY_API_KEY, config.CRYPTSY_SECRET)
        elif (name == 'CRYPTO-TRADE'):
            xchg = CryptoTrade(config.CRYPTOTRADE_API_KEY, config.CRYPTOTRADE_SECRET)
        elif (name == 'COINEX'):
            xchg = CoinEx(config.COINEX_API_KEY, config.COINEX_SECRET)
        else:
            print('Exchange ' + name + ' not supported!')
            continue
        print('%s initialized' % (xchg.name))

        broker = Broker(mode, xchg)
        if mode == 'BACKTEST':
#            broker.balances = config.PAPER_BALANCE
            broker.balances = broker.xchg.get_all_balances() # use real starting balances.
        brokers.append(broker)
    return brokers
Example #2
0
def getcoins(sc):
	from Cryptsy import Cryptsy
	from pprint import pprint
	import time
	import sys
	
	from config import pub,priv,targetcoin,targetcoinlabel,mytime,targetamount,targetprice
	coin_currency_id=0
	print "keys..."
	c = Cryptsy(pub, priv)
	
	print "api check..."
	if c.currency(3)['data']['name'] != 'BitCoin':
		sys.exit('api changed!')
	
	print "check bal..."
	if c.balance(3)['data']['available'].values()[0] < .02:
		sys.exit('get more BTC!')
	
	for item in c.markets()['data']:
		if item['label'] == targetcoinlabel:
			coin_currency_id= item['coin_currency_id']
	if coin_currency_id == 0:
		sys.exit("Cant get coin_currency_id from targetcoinlabel in config!")
	print "get price..."
	price=c.currency_markets(coin_currency_id)['data']['markets'][0]['last_trade']['price'] *.0025 + c.currency_markets(coin_currency_id)['data']['markets'][0]['last_trade']['price']
	print "Price: %s." % price
	price = str(price)
	#if price >= 3.0e-5:
	#	sys.exit("Price too high!")
	
	marketid=str(c.currency_markets(coin_currency_id)['data']['markets'][0]['id'])
	print "Marketid: %s" % marketid		
	
	if price <= targetprice:
		print "BUY!"
		c.order_create(marketid,targetamount,'buy',price)
	sc.enter(int(mytime), 1, getcoins, (sc,))
Example #3
0
    def configAll(self):
        self.parser.read(self.file)

        # API keys
        self.publickey = self.parser.get('API', 'public')
        self.privatekey = self.parser.get('API', 'private')

        # Check if keys are valid        
        self.cryptsy = Cryptsy(self.publickey, self.privatekey)

        if self.cryptsy.getInfo()['success'] != '1':
            raise Exception('Cryptsy key pairs are invalid.')

        # Settings
        self.configSettings()

        # Trading
        self.configTrading()

        # Signals
        self.configSignals()
        
        # Markets
        self.configMarkets()
from Cryptsy import Cryptsy
from pprint import pprint
import time
import json
import pdb
import copy

originCurrencyCode = 'BTC'
originCurrencyAmount = 0.001
originCurrency = None
currencyMarketId = None



c = Cryptsy("fefa680f20ccea932758caa72b5fd91a4d26b31f", "06525df00812cd6af6503a4856e048e7d5921118a3c591d3798b0152d99fa32843c57594841a7cc3")
# ohlc = c.market_ohlc(133, start=0, stop=time.time(), interval="minute", limit=60)
listMarkets = c.markets()
listCurrencies = c.currencies()

tradeRoute = []


# pprint(listCurrencies[data])
for currency in listCurrencies['data']:
	if currency['code'] == originCurrencyCode:
		originCurrency = currency




Example #5
0
import subprocess
import sys
import time
import traceback
from operator import itemgetter
import Helper
from Cryptsy import Cryptsy

"""
This is the main entry of the script.
"""
if __name__ == '__main__':
    config = Helper.Config()
    #log = Helper.Log()
    #printing = Helper.Printing()
    cryptsy = Cryptsy(config.publickey, config.privatekey)
    markets = cryptsy.getMarkets()

    """
    list = []
    for i in markets['return']:
        element = []
        element.append(int(i['marketid']))
        element.append(str(i['label']))
        list.append(element)

    final = sorted(list, key=itemgetter(0))
    for i in final:
        #print "%s" % (i[1])
        #print "self.pairs['%s'] = self.parser.getboolean('Markets', '%s')" % (i[1], i[1])
        print "%i %s" % (i[0], i[1])
Example #6
0
class Config(object):
    def __init__(self, file='settings.ini'):
        self.file = file
        self.parser = SafeConfigParser()
        self.configAll()

    # Method: configAll
    # Description: Configure and store all user settings based on settings.ini values
    def configAll(self):
        self.parser.read(self.file)

        # API keys
        self.publickey = self.parser.get('API', 'public')
        self.privatekey = self.parser.get('API', 'private')

        # Check if keys are valid        
        self.cryptsy = Cryptsy(self.publickey, self.privatekey)

        if self.cryptsy.getInfo()['success'] != '1':
            raise Exception('Cryptsy key pairs are invalid.')

        # Settings
        self.configSettings()

        # Trading
        self.configTrading()

        # Signals
        self.configSignals()
        
        # Markets
        self.configMarkets()

    # Method: configSettings
    # Description: Configure and store settings only based on settings.ini values
    def configSettings(self):
        self.parser.read(self.file)
        self.showTicker = self.parser.getboolean('Settings', 'showTicker')
        self.verbose = self.parser.getboolean('Settings', 'verbose')
        self.loopSleep = self.parser.getint('Settings', 'loopSleep')
        self.saveGraph = self.parser.getboolean('Settings', 'saveGraph')
        self.graphDPI = self.parser.getint('Settings', 'graphDPI')

    # Method: configTrading
    # Description: Configure and store trading only based on settings.ini values
    def configTrading(self):
        self.parser.read(self.file)
        self.simMode = self.parser.getboolean('Trading','simMode')
        self.min_volatility = self.parser.getfloat('Trading', 'min_volatility')
        self.volatility_sleep = self.parser.getint('Trading', 'volatility_sleep')
        self.longOn = self.parser.get('Trading','longOn')
        self.orderType = self.parser.get('Trading','orderType')
        self.fokTimeout = self.parser.getint('Trading', 'fokTimeout')
        self.fee = self.parser.getfloat('Trading', 'fee')

    # Method: configSignals
    # Description: Configure and store signals only based on settings.ini values
    def configSignals(self):
        self.parser.read(self.file)
        self.signalType = self.parser.get('Signals','signalType')
        if self.signalType == 'single':
            self.single = self.parser.get('Signals','single')
        elif self.signalType == 'dual':
            self.fast = self.parser.getint('Signals','fast')
            self.slow = self.parser.getint('Signals','slow')
        elif self.signalType == 'ribbon':
            self.ribbonStart = self.parser.get('Signals','ribbonStart')
            self.numRibbon = self.parser.get('Signals','numRibbon')
            self.ribbonSpacing = self.parser.get('Signals','ribbonSpacing')
        self.priceBand= self.parser.getboolean('Signals','priceBand')

    # Method: configMarkets
    # Description: Configure and store markets based on settings.ini values
    def configMarkets(self):
        self.parser.read(self.file)
        self.request= self.cryptsy.getMarkets()
        self.markets= {}

        # Check to see if there are new or removed markets.
        # If not, configure settings.
        self.marketsCryptsy = []
        for label in self.request['return']:
            self.marketsCryptsy.append(str(label['label']).upper())
        self.marketsSettings = [x[0].upper() for x in self.parser.items('Markets')]
        self.marketDiffC = list(set(self.marketsCryptsy) - set(self.marketsSettings))
        self.marketDiffS = list(set(self.marketsSettings) - set(self.marketsCryptsy))
        if (len(self.marketDiffC + self.marketDiffS) == 0):
            for market in self.marketsCryptsy:
                self.markets[market] = self.parser.getboolean('Markets', market)
        else:
            if (len(self.marketDiffC) > 0):
                print "ERROR: New Cryptsy market(s) found. Add %s to settings.ini." % self.marketDiffC
            if (len(self.marketDiffS) > 0):
                print "ERROR: Cryptsy market(s) removed. Remove %s from settings.ini." % self.marketDiffS
            raise Exception("Cryptsy markets sync with settings.ini markets mismatch.")
Example #7
0
# Import the Cryptsy API package
from Cryptsy import Cryptsy
from pprint import pprint
import time

import warnings
warnings.filterwarnings("ignore");

### Create an instance of Cryptsy API to use
pub_key = '11027f50bbb088e2957581f28203cc7e9e76713f';
pri_key = '55b85d72673804a47662a4ff92bba0fd5516d4be797e6eedc5c4f4215dab6136695aebd1dfb4d9fb';
Cryptsy_Handle = Cryptsy( pub_key , pri_key );

# Number of data points. 1 data point = 1 minute of data
sell_fee = 0#0.25 / 100;
buy_fee = 0#0.25 / 100;

### List of all market ID's to check
ID_list = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '17', '21', '22', '23', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '36', '38', '39', '40', '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', '78', '80', '81', '82', '83', '84', '85', '86', '87', '88', '90', '91', '92', '93', '94', '95', '96', '98', '100', '101', '102', '106', '107', '108', '109', '111', '114', '115', '116', '117', '119', '120', '121', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '138', '139', '140', '141', '142', '143', '144', '145', '147', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '166', '167', '169', '170', '171', '173', '175', '176', '177', '178', '179', '180', '182', '183', '184', '185', '186', '188', '189', '190', '191', '192', '193', '194', '195', '197', '198', '199', '200', '201', '202', '203', '204', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '223', '224', '225', '227', '228', '229', '230', '231', '232', '233', '234', '235', '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', '288', '289', '290', '291', '292', '293', '294', '295', '296', '297', '298', '299', '300', '301', '302', '303', '304', '305', '306', '307', '308', '309', '310', '311', '312', '313', '314', '315', '316', '322', '323', '324', '326', '327', '329', '330', '331', '332', '333', '334', '335', '336', '338', '340', '343', '344', '345', '346', '347', '348', '349', '350', '351', '352', '354', '355', '356', '357', '361', '363', '364', '365', '368', '370', '371', '376', '380', '381', '382', '383', '386', '389', '390', '391', '395', '396', '397', '398', '399', '401', '402', '404', '405', '410', '412', '417', '420', '424', '429', '431', '432', '435', '436', '440', '442', '443', '444', '445', '446', '448', '449', '450', '451', '452', '453', '454', '455', '456', '457', '458', '459', '460', '461', '462', '463', '465', '466', '467', '468', '469', '470', '471', '472', '473', '474', '476', '478', '479', '480', '481', '482', '483', '484', '485', '486', '487', '488', '489', '490', '491', '492', '493', '494', '495', '496', '497', '498', '499'];

Table = ['ID' , 'Market' , 'BESR' , '% profit' , 'volume' ];
print( str(Table[0]) + '%20s' % str(Table[1]) + '\t\t' + '%20s' % str(Table[2]) + '\t\t' + '%20s' % str(Table[3]) + '\t\t' '%20s' % str(Table[4]) )

# Scan through all ID's that are of interest
count = 5;
for x in ID_list:
#for x in ['167']:
    # Check to see if the market actually exists
    ECK = Cryptsy_Handle.market(x);
    vol = ECK.values()[0];
    vol = vol.values()[6];
Example #8
0
def execute(direction, current_trendExist, APIKey, Secret):
    cr = Cryptsy(APIKey, Secret)
    method = "singleorderdata"
    #orderIds= ""
    if (current_trendExist == "newTrend" and direction == "Up"):
        action = "Buy"
        btcBalance = float(cr.getInfo()['return']['balances_available']['BTC'])
        while (btcBalance > .01):
            ret = ""
            while (ret == ""):
                try:
                    ret = urllib2.urlopen(
                        urllib2.Request(
                            'http://pubapi.cryptsy.com/api.php?method=' +
                            method + '&marketid=' + str(marketid)))
                except:
                    continue

            topTrade = json.loads(
                ret.read())['return']['DOGE']['sellorders'][1]
            tradePrice = float(topTrade['price'])
            amount = min((btcBalance) * .99, float(topTrade['total']))
            amount = amount / tradePrice
            orderid = cr.createOrder(marketid, "Buy", amount, tradePrice)
            #orderIds = orderIds + "-" + orderid
            btcBalance = float(
                cr.getInfo()['return']['balances_available']['BTC'])
        pause(5)
        if (cr.myOrders(marketid)['return'] != []):
            cr.cancelAllOrders()
            pause(10)
            print "Cancled Orders: Redoing excecute stage"
            execute(direction, current_trendExist, APIKey, Secret)
        sendText(action)

    else:
        action = "Hold"
        dogeBalance = float(
            cr.getInfo()['return']['balances_available']['DOGE'])
        while (dogeBalance > 3000):
            action = "Sell"
            ret = ""
            while (ret == ""):
                try:
                    ret = urllib2.urlopen(
                        urllib2.Request(
                            'http://pubapi.cryptsy.com/api.php?method=' +
                            method + '&marketid=' + str(marketid)))
                except:
                    continue

            topTrade = json.loads(ret.read())['return']['DOGE']['buyorders'][1]
            amount = min(dogeBalance * .99, float(topTrade['quantity']))
            orderid = cr.createOrder(marketid, "Sell", amount,
                                     topTrade['price'])
            #orderIds = orderIds + "-" + orderid
            dogeBalance = float(
                cr.getInfo()['return']['balances_available']['DOGE'])
            pause(2)
            sendText(action)
        pause(5)
        if (cr.myOrders(marketid)['return'] != []):
            cr.cancelAllOrders()
            pause(10)
            print "Cancled Orders: Redoing excecute stage"
            execute(direction, current_trendExist, APIKey, Secret)

    return action  #+ ": " + orderIds
Example #9
0
import subprocess
import sys
import time
import traceback
from operator import itemgetter
import Helper
from Cryptsy import Cryptsy
"""
This is the main entry of the script.
"""
if __name__ == '__main__':
    config = Helper.Config()
    #log = Helper.Log()
    #printing = Helper.Printing()
    cryptsy = Cryptsy(config.publickey, config.privatekey)
    markets = cryptsy.getMarkets()
    """
    list = []
    for i in markets['return']:
        element = []
        element.append(int(i['marketid']))
        element.append(str(i['label']))
        list.append(element)

    final = sorted(list, key=itemgetter(0))
    for i in final:
        #print "%s" % (i[1])
        #print "self.pairs['%s'] = self.parser.getboolean('Markets', '%s')" % (i[1], i[1])
        print "%i %s" % (i[0], i[1])
    """
Example #10
0
from Cryptsy import Cryptsy
from pprint import pprint
import time
import warnings
warnings.filterwarnings("ignore");

# Create a handle to the Cryptsy API
pub_key = "11027f50bbb088e2957581f28203cc7e9e76713f";
pri_key = "55b85d72673804a47662a4ff92bba0fd5516d4be797e6eedc5c4f4215dab6136695aebd1dfb4d9fb";
Cryptsy_Handle = Cryptsy( pub_key , pri_key );

# 
minimum_difference = 0.00000001;

#   ID      Market
#
#   167     DGB/BTC
#

#   ID      Balance
#
#   124     DGB
#

market_ID = 167;     # Market ID of the market we want to play
limit = 0.1;            # The maximum amount (in BTC) we allow to be in the market at a given time
x = 1;

# Start a ledger for all transactions
Transaction_Ledger = [ [ 'Transaction_ID' , 'Amount' , 'Price' , 'Total' , 'Type' ] ];
while (x == 1):
Example #11
0
def execute(direction, current_trendExist, APIKey, Secret):
	cr = Cryptsy(APIKey, Secret)
	method = "singleorderdata"
	#orderIds= ""
	if (current_trendExist == "newTrend" and direction == "Up"):
		action = "Buy"
		btcBalance = float(cr.getInfo()['return']['balances_available']['BTC'])
		while(btcBalance > .01):
			ret = ""
			while(ret == ""):
				try:
					ret = urllib2.urlopen(urllib2.Request('http://pubapi.cryptsy.com/api.php?method=' + method + '&marketid=' + str(marketid)))
				except:
					continue

			topTrade = json.loads(ret.read())['return']['DOGE']['sellorders'][1]
			tradePrice = float(topTrade['price'])
			amount = min((btcBalance)*.99, float(topTrade['total']))
			amount = amount/tradePrice
			orderid = cr.createOrder(marketid, "Buy", amount, tradePrice)
			#orderIds = orderIds + "-" + orderid
			btcBalance = float(cr.getInfo()['return']['balances_available']['BTC'])
		pause(5)
		if (cr.myOrders(marketid)['return']!=[]):
			cr.cancelAllOrders()
			pause(10)
			print "Cancled Orders: Redoing excecute stage"
			execute(direction, current_trendExist, APIKey, Secret)
		sendText(action)

	else:
		action = "Hold"
		dogeBalance = float(cr.getInfo()['return']['balances_available']['DOGE'])
		while(dogeBalance > 3000):
			action = "Sell"
			ret = ""
			while(ret == ""):
				try:
					ret = urllib2.urlopen(urllib2.Request('http://pubapi.cryptsy.com/api.php?method=' + method + '&marketid=' + str(marketid)))
				except:
					continue

			topTrade = json.loads(ret.read())['return']['DOGE']['buyorders'][1]
			amount = min(dogeBalance*.99, float(topTrade['quantity']))
			orderid = cr.createOrder(marketid, "Sell", amount, topTrade['price'])
			#orderIds = orderIds + "-" + orderid
			dogeBalance = float(cr.getInfo()['return']['balances_available']['DOGE'])
			pause(2)
			sendText(action)
		pause(5)
		if (cr.myOrders(marketid)['return']!=[]):
			cr.cancelAllOrders()
			pause(10)
			print "Cancled Orders: Redoing excecute stage"
			execute(direction, current_trendExist, APIKey, Secret)
		

	return action #+ ": " + orderIds