Example #1
0
def test_coinbasepro_market_buy_insufficient_funds():
    with open('config-coinbasepro.json') as config_file:
        config = json.load(config_file)

    account = TradingAccount(config)
    resp = account.buy('BTC', 'GBP', 20000)
    assert str(resp) == 'None'
def test_orders_columns():
    account = TradingAccount()
    account.buy('BTC', 'GBP', 1000, 30000)
    actual = account.getOrders().columns.to_list()
    expected = ['market', 'action', 'type', 'size', 'value', 'status', 'price']
    assert len(actual) == len(expected)
    assert all([a == b for a, b in zip(actual, expected)])
Example #3
0
def test_dummy_balances():
    account = TradingAccount()
    actual = account.getBalance().columns.to_list()
    if len(actual) == 0:
        pytest.skip('No balances to perform test')
    assert type(actual) is list
    expected = ['currency', 'balance', 'hold', 'available']
    assert len(actual) == len(expected)
    assert all([a == b for a, b in zip(actual, expected)])
    assert account.getExchange() == 'coinbasepro'
    assert account.getMode() == 'test'
Example #4
0
def test_binance_market_balance():
    try:
        with open('config-binance.json') as config_file:
            config = json.load(config_file)

        account = TradingAccount(config)
        actual = account.getBalance('BTC')
        assert type(actual) is float
        assert account.getExchange() == 'binance'
        assert account.getMode() == 'live'

    except IOError:
        pytest.skip('config-binance.json does not exist to perform test')
Example #5
0
def test_coinbasepro_instantiates_without_error():
    config = {
        "api_url": "https://api.pro.coinbase.com",
        "api_key": "00000000000000000000000000000000",
        "api_secret":
        "0000/0000000000/0000000000000000000000000000000000000000000000000000000000/00000000000==",
        "api_pass": "******"
    }

    account = TradingAccount(config)
    assert type(account) is TradingAccount
    assert account.getExchange() == 'coinbasepro'
    assert account.getMode() == 'live'
Example #6
0
def test_binance_market_buy_insufficient_funds():
    try:
        with open('config-binance.json') as config_file:
            config = json.load(config_file)

        account = TradingAccount(config)
        with pytest.raises(Exception) as execinfo:
            account.buy('DOGE', 'BTC', 1000000, 0.000025)
        assert str(
            execinfo.value
        ) == 'APIError(code=-2010): Account has insufficient balance for requested action.'

    except IOError:
        pytest.skip('config-binance.json does not exist to perform test')
Example #7
0
def test_binance_not_load():
    config = {
        "api_url":
        "https://api.binance.com",
        "api_key":
        "0000000000000000000000000000000000000000000000000000000000000000",
        "api_secret":
        "0000000000000000000000000000000000000000000000000000000000000000"
    }

    account = TradingAccount(config)
    assert type(account) is TradingAccount
    assert account.getExchange() == 'coinbasepro'
    assert account.getMode() == 'test'
Example #8
0
def test_binance_instantiates_without_error():
    config = {
        "exchange":
        "binance",
        "api_url":
        "https://api.binance.com",
        "api_key":
        "0000000000000000000000000000000000000000000000000000000000000000",
        "api_secret":
        "0000000000000000000000000000000000000000000000000000000000000000"
    }

    account = TradingAccount(config)
    assert type(account) is TradingAccount
    assert account.getExchange() == 'binance'
    assert account.getMode() == 'live'
Example #9
0
def test_coinbasepro_api_secret_error():
    config = {
        "api_url": "https://api.pro.coinbase.com",
        "api_key": "00000000000000000000000000000000",
        "api_secret": "error",
        "api_pass": "******"
    }

    with pytest.raises(TypeError) as execinfo:
        TradingAccount(config)
    assert str(execinfo.value) == 'Coinbase Pro API secret is invalid'
Example #10
0
def test_binance_balances():
    try:
        with open('config-binance.json') as config_file:
            config = json.load(config_file)

        account = TradingAccount(config)
        assert type(account) is TradingAccount
        assert account.getExchange() == 'binance'
        assert account.getMode() == 'live'

        actual = account.getBalance().columns.to_list()
        if len(actual) == 0:
            pytest.skip('No orders to perform test')
        assert type(actual) is list
        expected = ['currency', 'balance', 'hold', 'available']
        assert len(actual) == len(expected)
        assert all([a == b for a, b in zip(actual, expected)])

    except IOError:
        pytest.skip('config-binance.json does not exist to perform test')
Example #11
0
def test_coinbasepro_api_url_error():
    config = {
        "api_url": "error",
        "api_key": "00000000000000000000000000000000",
        "api_secret":
        "0000/0000000000/0000000000000000000000000000000000000000000000000000000000/00000000000==",
        "api_pass": "******"
    }

    with pytest.raises(ValueError) as execinfo:
        TradingAccount(config)
    assert str(execinfo.value) == 'Coinbase Pro API URL is invalid'
Example #12
0
def test_binance_api_secret_error():
    config = {
        "exchange": "binance",
        "api_url": "https://api.binance.com",
        "api_key":
        "0000000000000000000000000000000000000000000000000000000000000000",
        "api_secret": "error"
    }

    with pytest.raises(TypeError) as execinfo:
        TradingAccount(config)
    assert str(execinfo.value) == 'Binance API secret is invalid'
Example #13
0
def test_coinbasepro_all_orders():
    try:
        with open('config-coinbasepro.json') as config_file:
            config = json.load(config_file)

        account = TradingAccount(config)
        assert type(account) is TradingAccount
        assert account.getExchange() == 'coinbasepro'
        assert account.getMode() == 'live'

        actual = account.getOrders().columns.to_list()
        if len(actual) == 0:
            pytest.skip('No orders to perform test')
        expected = [
            'created_at', 'market', 'action', 'type', 'size', 'value',
            'status', 'price'
        ]
        assert len(actual) == len(expected)
        assert all([a == b for a, b in zip(actual, expected)])

    except IOError:
        pytest.skip('config-coinbasepro.json does not exist to perform test')
Example #14
0
def test_binance_api_url_error():
    config = {
        "exchange":
        "binance",
        "api_url":
        "error",
        "api_key":
        "0000000000000000000000000000000000000000000000000000000000000000",
        "api_secret":
        "0000000000000000000000000000000000000000000000000000000000000000"
    }

    with pytest.raises(ValueError) as execinfo:
        TradingAccount(config)
    assert str(execinfo.value) == 'Binance API URL is invalid'
Example #15
0
def test_dummy_orders():
    account = TradingAccount()
    account.buy('BTC', 'GBP', 1000, 30000)
    actual = account.getOrders().columns.to_list()
    if len(actual) == 0:
        pytest.skip('No orders to perform test')
    expected = [
        'created_at', 'market', 'action', 'type', 'size', 'value', 'status',
        'price'
    ]
    assert len(actual) == len(expected)
    assert all([a == b for a, b in zip(actual, expected)])
    assert account.getExchange() == 'coinbasepro'
    assert account.getMode() == 'test'
Example #16
0
from models.PyCryptoBot import PyCryptoBot
from models.TradingAccount import TradingAccount

# Coinbase Pro orders
app = PyCryptoBot(exchange='coinbasepro')
app.setLive(1)
account = TradingAccount(app)
#orders = account.getOrders()
orders = account.getOrders(app.getMarket(), '', 'done')
print(orders)

# Binance Live orders
app = PyCryptoBot(exchange='binance')
app.setLive(1)
account = TradingAccount(app)
#orders = account.getOrders('DOGEBTC')
orders = account.getOrders('DOGEBTC', '', 'done')
print(orders)
Example #17
0
def test_orders_returns_dict():
    account = TradingAccount()
    assert type(account.getOrders()) is pd.DataFrame
Example #18
0
def test_unspecified_balance_returns_dict():
    account = TradingAccount()
    assert type(account.getBalance()) is pd.DataFrame
Example #19
0
def test_successful_buy_and_sell():
    account = TradingAccount()
    account.buy('BTC', 'GBP', 1000, 30000)
    account.sell('BTC', 'GBP', 0.0331, 35000)
    assert type(account.getBalance('GBP')) is float
    assert account.getBalance('GBP') == 1152.7
Example #20
0
def test_sell_insufficient_funds():
    account = TradingAccount()
    account.buy('BTC', 'GBP', 1000, 30000)
    with pytest.raises(Exception) as execinfo:
        account.sell('BTC', 'GBP', 1, 35000)
    assert str(execinfo.value) == 'Insufficient funds.'
Example #21
0
def test_buy_sufficient_funds():
    account = TradingAccount()
    account.buy('BTC', 'GBP', 1000, 30000)
    assert type(account.getBalance('GBP')) is float
    assert account.getBalance('GBP') == 0
Example #22
0
buy_count = 0
sell_count = 0
buy_sum = 0
sell_sum = 0
failsafe = False

config = {}
account = None
# if live trading is enabled
if is_live == 1:
    # open the config.json file
    with open('config.json') as config_file:
        # store the configuration in dictionary
        config = json.load(config_file)
    # connect your Coinbase Pro live account
    account = TradingAccount(config)

    # if the bot is restarted between a buy and sell it will sell first
    if (market.startswith('BTC-')
            and account.getBalance(cryptoMarket) > 0.001):
        last_action = 'BUY'
    elif (market.startswith('BCH-')
          and account.getBalance(cryptoMarket) > 0.01):
        last_action = 'BUY'
    elif (market.startswith('ETH-')
          and account.getBalance(cryptoMarket) > 0.01):
        last_action = 'BUY'
    elif (market.startswith('LTC-')
          and account.getBalance(cryptoMarket) > 0.1):
        last_action = 'BUY'
    elif (market.startswith('XLM-') and account.getBalance(cryptoMarket) > 35):
Example #23
0
from models.TradingAccount import TradingAccount
from views.TradingGraphs import TradingGraphs
"""Parameters for the test, get from experiments/experimnets.csv"""

market = 'BTC-GBP'
cryptoMarket, fiatMarket = market.split('-', 2)
granularity = 3600
#startDate = ''
startDate = '2020-11-20T23:12:07.720258'
#endDate = ''
endDate = '2020-12-03T11:12:07.720258'
openingBalance = 1000
amountPerTrade = 100

# instantiate a non-live trade account
account = TradingAccount()

# instantiate a CoinbassePro object with desired criteria
coinbasepro = CoinbasePro(market, granularity, startDate, endDate)

# adds buy and sell signals to Pandas DataFrame
coinbasepro.addEMABuySignals()
coinbasepro.addMACDBuySignals()

# stores the Pandas Dataframe in df
df = coinbasepro.getDataFrame()

# defines the buy and sell signals and consolidates into df_signals
buysignals = ((df.ema12gtema26co == True) & (df.macdgtsignal == True) &
              (df.obv_pc > 0.1)) | ((df.ema12gtema26 == True) &
                                    (df.macdgtsignal == True) &
Example #24
0
from datetime import datetime, timedelta
from models.PyCryptoBot import PyCryptoBot, truncate as _truncate
from models.AppState import AppState
from models.Trading import TechnicalAnalysis
from models.TradingAccount import TradingAccount
from models.Stats import Stats
from models.helper.MarginHelper import calculate_margin
from views.TradingGraphs import TradingGraphs
from models.Strategy import Strategy
from models.helper.LogHelper import Logger

# minimal traceback
sys.tracebacklimit = 1

app = PyCryptoBot()
account = TradingAccount(app)
Stats(app, account).show()
technical_analysis = None
state = AppState(app, account)
state.initLastAction()

s = sched.scheduler(time.time, time.sleep)


def executeJob(sc=None,
               app: PyCryptoBot = None,
               state: AppState = None,
               trading_data=pd.DataFrame()):
    """Trading bot job which runs at a scheduled interval"""

    global technical_analysis
Example #25
0
import json
from models.TradingAccount import TradingAccount

with open('config.json') as config_file:
    config = json.load(config_file)

account = TradingAccount(config)
print(account.getBalance())
print(account.getBalance('BTC'))
#print (account.getOrders('BTC-GBP', '', 'done'))
Example #26
0
buy_state = ''
eri_text = ''
last_buy = 0
iterations = 0
buy_count = 0
sell_count = 0
buy_sum = 0
sell_sum = 0
fib_high = 0
fib_low = 0

config = {}
account = None
# if live trading is enabled
if app.isLive() == 1:
    account = TradingAccount(app)

    if account.getBalance(app.getBaseCurrency()) < account.getBalance(app.getQuoteCurrency()):
        last_action = 'SELL'
    elif account.getBalance(app.getBaseCurrency()) > account.getBalance(app.getQuoteCurrency()):
        last_action = 'BUY'

    if app.getExchange() == 'binance':
        if last_action == 'SELL'and account.getBalance(app.getQuoteCurrency()) < 0.001:
            raise Exception('Insufficient available funds to place sell order: ' + str(account.getBalance(app.getQuoteCurrency())) + ' < 0.1 ' + app.getQuoteCurrency() + "\nNote: A manual limit order places a hold on available funds.")
        elif last_action == 'BUY'and account.getBalance(app.getBaseCurrency()) < 0.001:
            raise Exception('Insufficient available funds to place buy order: ' + str(account.getBalance(app.getBaseCurrency())) + ' < 0.1 ' + app.getBaseCurrency() + "\nNote: A manual limit order places a hold on available funds.")
 
    elif app.getExchange() == 'coinbasepro':
        if last_action == 'SELL'and account.getBalance(app.getQuoteCurrency()) < 50:
            raise Exception('Insufficient available funds to place buy order: ' + str(account.getBalance(app.getQuoteCurrency())) + ' < 50 ' + app.getQuoteCurrency() + "\nNote: A manual limit order places a hold on available funds.")
"""Trading Account object model examples"""

import json
from models.TradingAccount import TradingAccount

with open('config.json') as config_file:
    config = json.load(config_file)

# live trading account - your account data!
'''
account = TradingAccount(config)
print (account.getBalance('GBP'))
print (account.getOrders('BTC-GBP'))
'''

# test trading account - dummy data

account = TradingAccount()
print(account.getBalance('GBP'))
print(account.getBalance('BTC'))
account = TradingAccount()
account.buy('BTC', 'GBP', 250, 30000)
print(account.getBalance())
account.sell('BTC', 'GBP', 0.0082, 35000)
print(account.getBalance())
account.buy('ETH', 'GBP', 250, 30000)
print(account.getBalance())
account.sell('ETH', 'GBP', 0.0082, 35000)
print(account.getOrders())
print(account.getOrders('BTC-GBP'))
print(account.getOrders('ETH-GBP'))
Example #28
0
def test_orders_filtering():
    account = TradingAccount()
    account.buy('BTC', 'GBP', 250, 30000)
    assert len(account.getOrders()) == 1
    account.sell('BTC', 'GBP', 0.0082, 35000)
    assert len(account.getOrders()) == 2
    account.buy('ETH', 'GBP', 250, 30000)
    assert len(account.getOrders()) == 3
    account.sell('ETH', 'GBP', 0.0082, 35000)
    assert len(account.getOrders()) == 4
    assert len(account.getOrders('BTC-GBP')) == 2
Example #29
0
def test_default_initial_balance():
    account = TradingAccount()
    assert type(account.getBalance('GBP')) is float
    assert account.getBalance('GBP') == 1000
Example #30
0
buy_state = ''
eri_text = ''
last_buy = 0
iterations = 0
buy_count = 0
sell_count = 0
buy_sum = 0
sell_sum = 0
fib_high = 0
fib_low = 0

config = {}
account = None
# if live trading is enabled
if app.isLive() == 1:
    account = TradingAccount(app)

    if account.getBalance(app.getBaseCurrency()) < account.getBalance(
            app.getQuoteCurrency()):
        last_action = 'SELL'
    elif account.getBalance(app.getBaseCurrency()) > account.getBalance(
            app.getQuoteCurrency()):
        last_action = 'BUY'

    if app.getExchange() == 'binance':
        if last_action == 'SELL' and account.getBalance(
                app.getQuoteCurrency()) < 0.001:
            raise Exception(
                'Insufficient available funds to place sell order: ' +
                str(account.getBalance(app.getQuoteCurrency())) + ' < 0.1 ' +
                app.getQuoteCurrency() +