Ejemplo n.º 1
0
 def test_deposit_fee(self):
     self.deposit.fee = Money.loads("BTC 0.1")
     old_balance = self.target_exchange.balance['BTC']
     self.deposit.complete()
     new_balance = self.target_exchange.balance['BTC']
     balance_delta = new_balance - old_balance
     balance_delta.should.equal(Money.loads("BTC 0.9"))
Ejemplo n.º 2
0
 def test_withdrawal_fee(self):
     self.withdrawal.fee = Money.loads("BTC 0.1")
     old_balance = self.source_exchange.balance['BTC']
     self.withdrawal.complete()
     new_balance = self.source_exchange.balance['BTC']
     balance_delta = new_balance - old_balance
     balance_delta.should.equal(Money.loads("BTC -1.1"))
Ejemplo n.º 3
0
    def test_reverse_position_change(self):
        old_position = self.order.position
        empty_data = {'btc_total': Money.loads("BTC 0"),
            'fiat_total': Money.loads("USD 0"),
            'time_created': 1431712831,
            'trades': [],
            'type': u'ASK'}

        self.order.was_partially_eaten(empty_data)
        delta = self.order.position_change(old_position)
        delta['USD'].should.equal(Money(77, "USD"))
        delta['BTC'].should.equal(Money("-0.75", "BTC"))
Ejemplo n.º 4
0
def withdraw_fiat(exchange_name, target_exchange_name, amount_str, deposit_amount_str, transaction_details):
    db = session.get_a_trading_db_mysql_session()
    try:
        exchange_data = make_exchange_data_from_key(exchange_name, db)
        target_exchange_data = make_exchange_data_from_key(target_exchange_name, db)
        amount = Money.loads(amount_str)
        if deposit_amount_str:
            deposit_amount = Money.loads(deposit_amount_str)
            exchange_data.record_fiat_withdrawal(target_exchange_data, amount, deposit_amount=deposit_amount, transaction_details=transaction_details)
        else:
            exchange_data.record_fiat_withdrawal(target_exchange_data, amount, transaction_details=transaction_details)
            
        session.commit_mysql_session(db)
        logger.info(tc.colored("Recorded %s withdrawal from %s" % (amount, exchange_name), "green"))
    finally:
        db.remove()
Ejemplo n.º 5
0
 def test_deposit_completed_cancel(self):
     self.deposit.fee = Money.loads("BTC 0.1")
     old_balance = self.source_exchange.balance['BTC']
     self.deposit.complete()
     self.deposit.cancel()
     new_balance = self.target_exchange.balance['BTC']
     new_balance.should.equal(old_balance)
Ejemplo n.º 6
0
def get_balance_time_series_from_audits(audits):
    fiat_balances = []
    btc_balances = []
    
    for audit in audits:
        timestamp = int(Delorean(audit.time_created, "UTC").epoch) * 1000

        # load the fiat and btc balances from the audit data
        data = json.loads(audit.data)

        try:
            # Old data format from before Jan 28, 2015
            raw_fiat = data['exchange_balance']['fiat_available']
            raw_btc = data['exchange_balance']['btc_available']
            fiat = Money.loads(raw_fiat).to("USD")
            btc = Money.loads(raw_btc)

        except KeyError:
            # New data format from after Jan 28, 2015
            try:
                balance_data = data['balance_data']
            except KeyError:
                continue

            # convert to Money objects
            for currency, balance_str in balance_data.iteritems():
                balance_data[currency] = Money.loads(balance_str)

            balance = Balance(balance_data)
            fiat = balance.fiat().to('USD')
            btc = balance['BTC']

        fiat_datapoint = [
            timestamp,
            str(fiat.amount),
        ]

        fiat_balances.append(fiat_datapoint)

        btc_datapoint = [
            timestamp,
            str(btc.amount),
        ]

        btc_balances.append(btc_datapoint)

    return fiat_balances, btc_balances
Ejemplo n.º 7
0
def get_drift_from_audits(audits):
    drift_by_currency = Balance()

    for audit in audits:
        if 'drift' in audit.data:
            data = json.loads(audit.data)

            for currency, str_amount in data['drift'].iteritems():
                drift_by_currency += Money.loads(str_amount)

    return drift_by_currency
Ejemplo n.º 8
0
def withdraw(exchange_name, target_exchange_name, amount_str):
    db = session.get_a_trading_db_mysql_session()
    try:
        exchange_data = make_exchange_data_from_key(exchange_name, db)
        target_exchange_data = make_exchange_data_from_key(target_exchange_name, db)
        target_exchange = make_exchange_from_key(target_exchange_name)
        amount = Money.loads(amount_str)
        
        addr = target_exchange.current_deposit_address
        exchange_data.record_withdrawal(target_exchange_data, amount, addr)
        session.commit_mysql_session(db)
        logger.info(tc.colored("Recorded %s withdrawal from %s" % (amount, exchange_name), "green"))
    finally:
        db.remove()
Ejemplo n.º 9
0
def parse_configurable_value(value):
    """
    Simple function to parse a setting specified either in a .conf file or from the
    command line.
    """
    if value is None:
        return None
    if type(value) is bool:
        return value
    elif value == 'yes':
        return True
    elif value == 'no':
        return False
    else:
        try:
            return Money.loads(value)
        except ValueError:
            try:
                return Decimal(value)
            except InvalidOperation:
                pass

        return value
Ejemplo n.º 10
0
from gryphon.execution.lib.heartbeat import heartbeat
from gryphon.lib import assets
from gryphon.lib import session
from gryphon.lib.exchange.exchange_factory import ALL_EXCHANGE_KEYS
import gryphon.lib.gryphonfury.positions as positions
import gryphon.lib.gryphonfury.revenue as revenue_lib
from gryphon.lib.logger import get_logger
from gryphon.lib.models.datum import Datum
from gryphon.lib.models.order import Order
from gryphon.lib.models.trade import Trade
from gryphon.lib.money import Money

logger = get_logger(__name__)

DAILY_PROFIT_THRESHOLD = Money.loads('USD -500')
OPEN_PL_THRESHOLD = Money.loads('USD -200')
TICK_SLEEP = 30
FV_MOVEMENT_MINIMUM = 0.10
LARGE_EXCHANGES = [
    'bitfinex', 'bitstamp', 'coinbase', 'itbit', 'kraken', 'okcoin'
]
INTER_EXCHANGE_SPREAD_THRESHOLD = 5
PREDICTIVE_VOLUME_REDIS_KEY = 'ML_PREDICTION'

OVERWATCH_HEARTBEAT_KEY = 'OVERWATCH_%s'


def watch():
    db = session.get_a_trading_db_mysql_session()
    r = session.get_a_redis_connection()
Ejemplo n.º 11
0
    def get_trades_info_from_ledger(self, trade_ids, order_open_timestamp, order_close_timestamp):
        """
        Check the ledger entries to get accurate numbers for how much our balance was
        changed.

        The ledger is Kraken's only real source of truth, the trades/order endpoints
        lie to us.
        """

        # We add a 0.1s buffer to make sure we get entries right on the boundary
        # timestamps.
        ledger_start = order_open_timestamp - Decimal('0.1')
        # We add a 1s buffer because it takes Kraken a bit of time to write to the
        # ledger.
        ledger_end = order_close_timestamp + Decimal('1')

        entries = self.get_ledger_entries(
            start=ledger_start,
            end=ledger_end,
        )

        trades_info = {}

        for trade_id in trade_ids:
            trades_info[trade_id] = {
                'btc': Money.loads('BTC 0'),
                'btc_fee': Money.loads('BTC 0'),
                'fiat': Money(0, self.currency),
                'fiat_fee': Money(0, self.currency),
            }

        for ledger_id, entry in entries.iteritems():
            trade_id = entry['refid']

            if trade_id not in trade_ids:
                continue

            amount = Decimal(entry['amount'])

            if entry['type'] == 'credit':
                # Credit ledger entries show up when we dip into our line of credit.
                # They have opposite signs, and need to be included along side the
                # trade ledger entries to get accurate trade amounts.
                amount = -amount
            elif entry['type'] == 'trade':
                pass
            else:
                raise exceptions.ExchangeAPIErrorException(
                    self,
                    'Unexpected ledger entry type "%s"' % entry['type'],
                )

            currency = self.convert_from_kraken_currency(entry['asset'])

            if currency == 'BTC':
                trades_info[trade_id]['btc'] += Money(amount, 'BTC')
                trades_info[trade_id]['btc_fee'] += Money(entry['fee'], 'BTC')
            else:
                trades_info[trade_id]['fiat'] += Money(amount, currency)
                trades_info[trade_id]['fiat_fee'] += Money(entry['fee'], currency)

            # There are multiple ledger entries per trade, but they should all be going
            #through at the same time, so we can just take the timestamp of the last
            # one.
            trades_info[trade_id]['time'] = entry['time']

        return trades_info