Esempio n. 1
0
 def __init__(self, credentials, coins):
     self.credentials = credentials
     self.coins = coins
     self.exchanges = {}
     self.last_market_update = 0
     for i, exch in enumerate(self.credentials):
         self.exchanges[exch] = {}
         processed = False
         if (exch == "cryptsy"):
             self.exchanges[exch]["connection"] = PyCryptsy(
                 str(self.credentials[exch]["pubkey"]),
                 str(self.credentials[exch]["privkey"]))
             processed = True
         if (exch == "bittrex"):
             self.exchanges[exch]["connection"] = Bittrex(
                 str(self.credentials[exch]["pubkey"]),
                 str(self.credentials[exch]["privkey"]))
             processed = True
         if (exch == "coins-e"):
             self.exchanges[exch]["connection"] = PyCoinsE(
                 str(self.credentials[exch]["pubkey"]),
                 str(self.credentials[exch]["privkey"]))
             processed = True
         if (exch == "c-cex"):
             self.exchanges[exch]["connection"] = PyCCEX(
                 str(self.credentials[exch]["key"]))
             processed = True
         if (processed == False):
             raise ValueError("unknown exchange")
     self.update_markets()
Esempio n. 2
0
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
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)
    return
Esempio n. 4
0
    def __init__(self, bankroll, source, dest, levels, rate):
        '''
        :param bankroll: Starting bankroll in dest currency
        :param source: Currency to trade in
        :param dest: Currency to trade with
        :param levels: Number of levels of Martingale (e.g. number of times to double previous bet)
        :param rate: Percentage of current price to place bets at, expressed as a rate
        '''
        self.bankroll = float(bankroll)
        self.source = source
        self.dest = dest
        self.balance = {
            self.source: 0,
            self.dest: self.bankroll
        }
        self.fees = 0
        self.levels = int(levels)
        self.current_level = 1

        '''Always bid at a consistent rate below the current price, e.g. .95 or .9'''
        self.bid_rate = float(rate)
        '''Don't be greedy'''
        self.ask_rate = 1 + (1 - self.bid_rate)/2

        '''If we haven't placed a buy yet and the price is going up, we need to reset the bid price. The reset
        ratio is the spread between our bid and the current price. If the reset ratio is exceeded, reset the buy order
        to a higher price.
        '''
        self.reset_ratio = self.bid_rate - (1 - self.bid_rate)/2

        '''Store the order ids'''
        self.buy_order_id = None
        self.sell_order_id = None

        self.api = PyCryptsy(config.cryptsy_public_key, config.cryptsy_private_key)

        '''Catch CTRL-C and cancel open orders'''
        signal.signal(signal.SIGINT, self.signal_handler)

        '''Get the logger and prefix each message with currency pair'''
        self.adapter = CurrencyPairAdapter(logger, {'source': self.source, 'dest': self.dest})

        self.adapter.info("Initialized rates - Bid rate: {0}, Ask rate: {1}, Reset ratio: {2}".format(
            self.bid_rate,
            self.ask_rate,
            self.reset_ratio
        ))
Esempio n. 5
0
 def __init__(self, daemons, credentials):
     self.daemons = daemons
     self.out = {}
     self.api = {}
     for i, exch in enumerate(credentials):
         if (exch == "cryptsy"):
             self.api[exch] = PyCryptsy(str(credentials[exch]["pubkey"]),
                                        str(credentials[exch]["privkey"]))
         elif (exch == "bittrex"):
             self.api[exch] = Bittrex.Bittrex(
                 str(credentials[exch]["pubkey"]),
                 str(credentials[exch]["privkey"]))
         elif (exch == "c-cex"):
             self.api[exch] = PyCCEX(str(credentials[exch]["key"]))
         elif (exch == "cryptopia"):
             self.api[exch] = PyCryptopia()
         elif (exch == "poloniex"):
             self.api[exch] = poloniex(str(credentials[exch]["key"]),
                                       str(credentials[exch]["secret"]))
         elif (exch == "bleutrade"):
             self.api[exch] = bleuBot(str(credentials[exch]["key"]),
                                      str(credentials[exch]["secret"]))
         else:
             raise ValueError("unknown exchange")
Esempio n. 6
0
def GetMarkets(cfg):
    #return simplejson.loads(open("cryptsy.json").read()) # read from file for testing
    cryptsy = PyCryptsy(cfg.get("Cryptsy", "key"),
                        cfg.get("Cryptsy", "secret"))
    return cryptsy.Query("getmarkets", {})
Esempio n. 7
0
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

from PyCryptsy import PyCryptsy

api=PyCryptsy('public_key_goes_here', 'private_key_goes_here')

# currencies to trade

src="YAC"
dest="BTC"

# trade multiplier (set to 1 to trade at lowest buy price)

multiplier=1.01

# get target price

target=api.GetBuyPrice(src, dest)*multiplier

# get available balance
Esempio n. 8
0
FEE = 1.02  # fee for every trade (2%)
Diff = 1.02  # 2 % arbitrage to execute
curr = ["xpm", "ltc", "ftc", "ppc",
        "nmc"]  #currencies to trade if arbitrage is found
exc = ["crypto", "vircu", "btc-e",
       "coins-e"]  #exchanges to trade on for the function calls
# ["btc-e", "vircu", "cryptsy", "coins-e"]
amount1 = 1  #the number of altcoins to be traded vs. btc in each trade

# BTC-e login data:
btce = btc_e_api.API(
    'XJP018WC-35J8SO7G-Z7QH8BDU-JEVRV5VA-G23W3ZSN',
    'caf818fa22084b672a0d53e05fc6f0e903e1e242976034f8aa2666f5c502b497')

#Vircurex Login Data:
vircurex = Account('peanutpower', '745p2V8v5c5J21u')

#Crypto-trade Login Data:
cryp = crypto('67FF99C7-69D1-A090-C3C9-12AB9BD94E14',
              'c27b6251614b4baeebc115358f79697636fa27b6')

#Cryptsy Login Data:
cryptsy = PyCryptsy(
    'db34131d6a8f0bbc19028f322cd22a6b986dde69',
    '79d5bf670a684b3bbbc109f6f64d4ed48c84b1b426546c30a5bcac43d7d8687c2c2d6b96f13b2c2f'
)

#coins-e Login Data:
PUBLIC_KEY = '14def7bc47f9858551b34f7cda5a17d64fe76112c21f53838a03f2f3'
PRIVATE_KEY = 'f0896ce593aa2ed4232dff8abc0581f69fd77bd6eaf8360cf682b462b89cbd31'
Esempio n. 9
0
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

import sys
sys.path.insert(0, './PyCryptsy/')
from PyCryptsy import PyCryptsy
from decimal import *
import ConfigParser
import pprint
import time

Config = ConfigParser.ConfigParser()
Config.read('./coinswitch.conf')

api=PyCryptsy(Config.get("Cryptsy", "key"), Config.get("Cryptsy", "secret"))
getcontext().prec=8

while True:
  balance=Decimal(api.Query("getinfo", {})["return"]["balances_available"]["BTC"])
  print "balance: "+str(balance)+" BTC"
  if (balance>0.01):
    print "withdrawal triggered"
    pprint.pprint(api.Query("makewithdrawal", {"address": Config.get("Cryptsy", "addr"), "amount": balance}))
  time.sleep(float(Config.get("Misc", "interval")))
Esempio n. 10
0
class Martingale(object):
    '''This class implements an adaptation of the Martingale betting method for gambling with crypto coins.
    http://en.wikipedia.org/wiki/Martingale_(betting_system)
    '''

    delay = 10 # Number of seconds to delay between price checks

    def __init__(self, bankroll, source, dest, levels, rate):
        '''
        :param bankroll: Starting bankroll in dest currency
        :param source: Currency to trade in
        :param dest: Currency to trade with
        :param levels: Number of levels of Martingale (e.g. number of times to double previous bet)
        :param rate: Percentage of current price to place bets at, expressed as a rate
        '''
        self.bankroll = float(bankroll)
        self.source = source
        self.dest = dest
        self.balance = {
            self.source: 0,
            self.dest: self.bankroll
        }
        self.fees = 0
        self.levels = int(levels)
        self.current_level = 1

        '''Always bid at a consistent rate below the current price, e.g. .95 or .9'''
        self.bid_rate = float(rate)
        '''Don't be greedy'''
        self.ask_rate = 1 + (1 - self.bid_rate)/2

        '''If we haven't placed a buy yet and the price is going up, we need to reset the bid price. The reset
        ratio is the spread between our bid and the current price. If the reset ratio is exceeded, reset the buy order
        to a higher price.
        '''
        self.reset_ratio = self.bid_rate - (1 - self.bid_rate)/2

        '''Store the order ids'''
        self.buy_order_id = None
        self.sell_order_id = None

        self.api = PyCryptsy(config.cryptsy_public_key, config.cryptsy_private_key)

        '''Catch CTRL-C and cancel open orders'''
        signal.signal(signal.SIGINT, self.signal_handler)

        '''Get the logger and prefix each message with currency pair'''
        self.adapter = CurrencyPairAdapter(logger, {'source': self.source, 'dest': self.dest})

        self.adapter.info("Initialized rates - Bid rate: {0}, Ask rate: {1}, Reset ratio: {2}".format(
            self.bid_rate,
            self.ask_rate,
            self.reset_ratio
        ))

    def run(self):
        '''Run Martingale indefinitely'''
        buy_prices = []
        self.adapter.info("Starting loop for {l} levels of Martingale".format(
            l=self.levels
        ))
        while True:
            if self.current_level <= self.levels:
                self.buy_order_id = self.place_buy_order()
            trades = self.wait_for_trades()
            if not trades:
                self.reset()
                buy_prices = []
                continue

            buy_prices.append(self.current_level*self.process_buy(trades['return']))

            self.sell_order_id = self.place_sell_order(buy_prices)
            self.current_level += 1

    def reset(self):
        '''When a sell has executed, or when a sell order has not yet been placed and the price is increasing,
        reset all the things and start the loop over again'''
        self.adapter.info("Cancelling active buy order and resetting")
        if self.buy_order_id:
            self.api.cancel_order(self.buy_order_id)
        self.buy_order_id = None
        self.sell_order_id = None
        self.current_level = 1
        return None

    def process_buy(self, trades):
        """
        :param trades: List of trades associated with a given buy order
        :returns: The highest price of all the buys (could be variable in some cases)
        """
        source_totals, dest_totals, fees, trade_prices = zip(*[(
                                                               float(trade['quantity']),
                                                               float(trade['total']),
                                                               float(trade['fee']),
                                                               float(trade['tradeprice']))
                                                               for trade in trades])
        self.balance[self.source] += sum(source_totals)
        self.balance[self.dest] -= sum(dest_totals)
        self.fees += sum(fees)
        self.buy_order_id = None

        self.adapter.info("Bought {quantity}{source} for {total}{dest}".format(
            quantity=str(sum(source_totals)),
            source=self.source,
            total=str(sum(dest_totals)),
            dest=self.dest
        ))
        self.log_balance()
        return max(trade_prices)

    def process_sell(self, trades):
        """
        :param trades: List of trades associated with a given sell order
        """
        source_totals, dest_totals, fees = zip(*[(
                                                 float(trade['quantity']),
                                                 float(trade['total']),
                                                 float(trade['fee']))
                                               for trade in trades])
        self.balance[self.source] -= sum(source_totals)
        self.balance[self.dest] += sum(dest_totals)
        self.fees += sum(fees)
        self.bankroll = self.balance[self.dest]

        self.adapter.info("Sold {quantity}{source} for {total}{dest}".format(
            quantity=str(sum(source_totals)),
            source=self.source,
            total=str(sum(dest_totals)),
            dest=self.dest
        ))

        self.log_balance()
        return None

    def wait_for_trades(self):
        '''Watch the list of orders and return when either a sell or a buy is exercised
        :returns: A list of trades, or None if no trades were executed'''
        while True:
            buy_order = None
            sell_order = None
            time.sleep(self.delay)
            if self.sell_order_id:
                '''If a sell order already exists, get that order.'''
                sell_order = self.get_order(self.sell_order_id)
                '''If no order is returned, the order must have executed, so get the trades associated with that sell'''
                if sell_order is None:
                    trades = self.get_trades(str(self.sell_order_id))
                    try:
                        self.process_sell(trades['return'])
                    except TypeError:
                        raise "Trades had a problem: {0}".format(trades)
                    return None
            if self.current_level <= self.levels:
                buy_order = self.get_order(self.buy_order_id)
                if buy_order is None:
                    return self.get_trades(str(self.buy_order_id))

            cp = self.current_price()
            if buy_order and not self.sell_order_id:
                """We are in level 1 with an active buy order and no sell order. If the price goes above
                the reset ratio, reset """
                bid_to_current_ratio = round(float(buy_order["price"]) / cp, 8)
                if bid_to_current_ratio < self.reset_ratio:
                    return None

                self.log_first_level(cp, buy_order['price'], bid_to_current_ratio)
            elif self.sell_order_id and not buy_order:
                """We are in the last level with an active sell order and no buy order. We are in
                 a holding pattern until a sell executes"""
                self.log_last_level(cp, sell_order['price'])
            elif self.sell_order_id and self.buy_order_id:
                """We have an active buy order and an active sell order."""
                bid_to_current_ratio = round(float(buy_order["price"]) / cp, 8)
                self.log_mid_level(cp, buy_order['price'], sell_order['price'], bid_to_current_ratio)
            else:
                """We should never have neither an active buy nor an active sell"""
                self.adapter.critical("No active bids or asks!")
                raise Exception("Cannot proceed without an active buy or sell order.")

    def get_order(self, order_id):
        '''Get a specific order
        '''
        orders = None
        retries = 5
        for i in range(retries):
            time.sleep(self.delay)
            orders = self.api.get_my_orders(self.source, self.dest)
            self.adapter.debug("Orders: {0}".format(orders))
            if orders is None or int(orders['success']) == 0:
                self.adapter.debug("Orders not found. Retrying ({0}/{1})".format(i+1, retries))
            else:
                break
        try:
            _order = next((order for order in orders['return'] if order["orderid"] == str(order_id)), None)
        except TypeError:
            raise Exception("orders has a problem. orders: {0}".format(str(orders)))
        return _order

    def get_trades(self, order_id):
        '''Get all trades associated with an order id
        :param order_id: Which order id the trades were executed against
        :type order_id: str
        :returns: A list of trades
        '''
        trades = None
        retries = 3
        for i in range(retries):
            '''Wait a while to make sure Cryptsy processes all the trades
            Do it in a loop 'cause Cryptsy fails all the time '''
            time.sleep(12*self.delay)
            trades = self.api.get_my_trades(self.source, self.dest, order_id)
            if trades is None or len(trades['return']) == 0:
                self.adapter.debug("Trades not found. Retrying ({0}/{1})".format(i+1, retries))
            else:
                break
        if not trades:
            self.adapter.critical("Oh noes! Order {order} was not found in the list of orders or trades!".format(
                order=order_id
            ))
            raise Exception("Missing order.")
        return trades

    def place_sell_order(self, buy_prices):
        '''Create a sell order
        :param buy_prices: A list of prices of the buys, used to calculate the sale prices
        :returns: An order id
        '''

        if self.sell_order_id:
            '''If there is an existing sell order, we need to cancel it to free up the balance for a new
            order. '''
            self.api.cancel_order(self.sell_order_id)
        '''Sleep since Cryptsy is slow and terrible'''
        time.sleep(12*self.delay)
        # The ask price needs to account for all previous buys and still make a profit of
        # self.ask_rate.
        ask_price = round(sum(buy_prices)/(2**self.current_level - 1) * self.ask_rate, 8)
        quantity = self.balance[self.source]
        self.adapter.info("Creating sell order of {quantity} {source} at {price} {dest}".format(
            source=self.source,
            dest=self.dest,
            quantity=str(quantity),
            price=str(ask_price),
        ))
        _create_order = self.api.create_sell_order
        return self.create_order(
            _create_order,
            self.source,
            self.dest,
            quantity,
            ask_price
        )

    def place_buy_order(self):
        '''Create a buy order
        '''
        bid_price = self.current_price() * self.bid_rate

        # spend is the amount of bankroll to spend on this buy order
        # It is a geometric sequence of the form bankroll * 1/(2^levels - 1)
        spend = round(self.bankroll * self.current_level * (float(1) / (2**self.levels - 1)), 8)
        if spend > self.balance[self.dest]:
            self.adapter.warning("Not enough left in balance for calculated spend! Using full balance. "
                        "({0} Balance: {1}, Spend: {2})".format(self.dest, self.balance[self.dest], spend))
            spend = self.balance[self.dest]

        # Total quantity to buy
        quantity = round(spend / bid_price, 8)
        self.adapter.info("Creating buy order of {quantity} {source} at price of {price} {dest} each".format(
            source=self.source,
            dest=self.dest,
            quantity=str(quantity),
            price=str(bid_price),
        ))
        _create_order = self.api.create_buy_order
        return self.create_order(
            _create_order,
            self.source,
            self.dest,
            quantity,
            bid_price
        )

    def create_order(self, _create_order, *args):
        '''
        :param _create_order: A method to call to create an order
        :param *args: The args to pass to the method passed in _create_order
        :return:  The order ID (Cryptsy API specific)
        '''
        order = _create_order(*args)
        if not order or not order['success'] or 'orderid' not in order:
            raise Exception("Tried to place buy order but orderid not returned! order: {0}".format(order))
        else:
            self.adapter.debug("Created order {id}".format(
                id=str(order['orderid']),
            ))
            return order['orderid']


    def current_price(self):
        '''Check current price.
        '''
        cp = None
        '''This loop is a hack to work around API failures'''
        for i in range(5):
            cp = self.api.get_buy_price(self.source, self.dest)
            if not cp:
                time.sleep(self.delay)
            else:
                break

        if not cp:
            raise Exception("Unable to obtain current price from API")
        else:
            return cp

    def log_first_level(self, cp, buy_price, ratio):
        self.adapter.info("CP: {cp}, BP: {bp}, Ratio: {current_ratio}".format(
            cp=str(cp),
            bp=str(buy_price),
            current_ratio=str(ratio)
        ))

    def log_mid_level(self, cp, buy_price, sell_price, ratio):
        self.adapter.info("CP: {cp}, BP: {bp}, SP: {sp}, Buy-to-Current Ratio: {current_ratio}".format(
            cp=str(cp),
            bp=str(buy_price),
            sp=str(sell_price),
            current_ratio=str(ratio)
        ))

    def log_last_level(self, cp, sell_price):
        self.adapter.info("CP: {cp}, SP: {sp}".format(
            cp=str(cp),
            sp=str(sell_price)
        ))

    def log_balance(self):
        self.adapter.info("Balance: {src_balance}{source} {dest_balance}{dest}".format(
            src_balance=str(self.balance[self.source]),
            dest_balance=str(self.balance[self.dest]),
            source=self.source,
            dest=self.dest,
        ))
        self.adapter.info("Bankroll: {0}".format(self.bankroll))
        self.adapter.info("Total fees: %f" % round(self.fees, 8))

    def signal_handler(self, signal, frame):
        '''Clean up buy orders if the martingale is sent a SIGINT
        Do not clean up sell orders since those are placed at an appropriate price to ensure
        profit of self.ask_rate
        '''
        self.adapter.critical('Caught interrupt. Cleaning up open orders.')
        if self.buy_order_id:
            self.api.cancel_order(self.buy_order_id)
        sys.exit(0)
Esempio n. 11
0
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

import time as t
import logging

from PyCryptsy import PyCryptsy

public_key = 'TODO'
private_key = 'TODO'

api = PyCryptsy(public_key, private_key)

# Don't trade these currencies
non_traded_currencies = ('BTC', 'LTC')

# currencies to trade

#src_currencies = ['NVC', 'MNC', 'WDC', 'DGC', 'LKY', 'ARG', 'PXC', 'NRB']
dest_currency = "BTC"

# trade multiplier (set to 1 to trade at lowest buy price)
multiplier = 1
percent_to_sell = 1.0


def setup_logging():