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'
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')
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')
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): last_action = 'BUY' elif (account.getBalance(fiatMarket) > 30): last_action = 'SELL'
# if the last transation was a buy retrieve open amount addBalance = 0 df_orders = account.getOrders() if len(df_orders) > 0 and df_orders.iloc[[-1]]['action'].values[0] == 'buy': # last trade is still open, add to closing balance addBalance = df_orders.iloc[[-1]]['value'].values[0] # displays the transactions from the simulation print('') print(df_orders) def truncate(f, n): return math.floor(f * 10**n) / 10**n # if the last transaction was a buy add the open amount to the closing balance result = truncate( round((account.getBalance(cryptoMarket) + addBalance) - openingBalance, 2), 2) print('') print("Opening balance:", truncate(openingBalance, 2)) print("Closing balance:", truncate(round(account.getBalance(cryptoMarket) + addBalance, 2), 2)) print(" Result:", result) print('') # renders the DataFrame for analysis tradinggraphs = TradingGraphs(coinbasepro) tradinggraphs.renderBuySellSignalEMA1226MACD()
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'))
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.") elif last_action == 'BUY'and account.getBalance(app.getBaseCurrency()) < 0.001: raise Exception('Insufficient available funds to place sell order: ' + str(account.getBalance(app.getBaseCurrency())) + ' < 0.1 ' + app.getBaseCurrency() + "\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'))
x_since_buy = 0 x_since_sell = 0 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 (account.getBalance(fiatMarket) == 0 and account.getBalance(cryptoMarket) > 0): last_action = 'BUY' def truncate(f, n): return math.floor(f * 10**n) / 10**n def compare(val1, val2, label=''): if val1 > val2: if label == '': return str(truncate(val1, 2)) + ' > ' + str(truncate(val2, 2)) else: return label + ': ' + str(truncate(val1, 2)) + ' > ' + str( truncate(val2, 2))
def test_unspecified_balance_returns_dict(): account = TradingAccount() assert type(account.getBalance()) is pd.DataFrame
def test_dummy_market_balance(): account = TradingAccount() actual = account.getBalance('GBP') assert type(actual) is float assert account.getExchange() == 'coinbasepro' assert account.getMode() == 'test'
from models.PyCryptoBot import PyCryptoBot from models.TradingAccount import TradingAccount app = PyCryptoBot(exchange='dummy') account = TradingAccount(app) #print (account.getBalance()) #account.depositBaseCurrency(0.5) #print (account.getBalance()) account.depositQuoteCurrency(1000) print(account.getBalance(), "\n") #account.withdrawBaseCurrency(0.5) #print (account.getBalance()) #account.withdrawQuoteCurrency(500) #print (account.getBalance()) account.marketBuy(app.getMarket(), 100, 100, 20000) print(account.getBalance(), "\n") account.marketSell(app.getMarket(), account.getBalance(app.getBaseCurrency()), 100, 20000) print(account.getBalance(), "\n") print(account.getOrders())
from models.PyCryptoBot import PyCryptoBot from models.TradingAccount import TradingAccount app = PyCryptoBot(exchange='dummy') account = TradingAccount(app) print (account.getBalance()) ''' TODO: re-implement this account.depositQuoteCurrency(1000) print (account.getBalance()) account.marketBuy(app.getMarket(), 100, 100, 20000) account.marketSell(app.getMarket()', 0.004975, 100, 30000) account.marketBuy(app.getMarket(), 100, 100, 31000) account.marketSell(app.getMarket(), 100, 3000) '''
from models.PyCryptoBot import PyCryptoBot from models.TradingAccount import TradingAccount from models.AppState import AppState app = PyCryptoBot() account = TradingAccount(app) state = AppState(app, account) print(account.getBalance(app.getBaseCurrency()), account.getBalance(app.getQuoteCurrency())) print(state.last_action) state.initLastAction(app, account, state) print(state.last_action)
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
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
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." )
def test_default_initial_balance(): account = TradingAccount() assert type(account.getBalance('GBP')) is float assert account.getBalance('GBP') == 1000
def runExperiment(id, market='BTC-GBP', granularity=3600, mostRecent=True): """Run an experiment Parameters ---------- market : str A valid market/product from the Coinbase Pro exchange. (Default: 'BTC-GBP') granularity : int A valid market interval {60, 300, 900, 3600, 21600, 86400} (Default: 86400 - 1 day) """ if not isinstance(id, int): raise TypeError('ID not numeric.') if id < 0: raise TypeError('ID is invalid.') p = re.compile(r"^[A-Z]{3,4}\-[A-Z]{3,4}$") if not p.match(market): raise TypeError('Coinbase Pro market required.') cryptoMarket, fiatMarket = market.split('-', 2) if not isinstance(granularity, int): raise TypeError('Granularity integer required.') if not granularity in [60, 300, 900, 3600, 21600, 86400]: raise TypeError( 'Granularity options: 60, 300, 900, 3600, 21600, 86400.') if not isinstance(mostRecent, bool): raise TypeError('Most recent is a boolean.') print('Experiment #' + str(id) + "\n") endDate = datetime.now() - timedelta(hours=random.randint( 0, 8760 * 3)) # 3 years in hours startDate = endDate - timedelta(hours=300) if mostRecent == True: startDate = '' endDate = '' print('Start date:', (datetime.now() - timedelta(hours=300)).isoformat()) print(' End date:', datetime.now().isoformat()) print('') else: startDate = str(startDate.isoformat()) endDate = str(endDate.isoformat()) print('Start date:', startDate) print(' End date:', endDate) print('') # 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)) | ((df.ema12gtema26 == True) & (df.ema12gtema26 == True) & (df.macdgtsignal == True) & (df.obv_pc >= 2)) sellsignals = (((df.ema12ltema26co == True) & (df.macdltsignal == True)) | ((df.ema12gtema26 == True) & ((df.macdltsignal == True) & (df.obv_pc < 0)))) df_signals = df[(buysignals) | (sellsignals)] diff = 0 action = '' last_action = '' last_close = 0 total_diff = 0 events = [] # iterate through the DataFrame buy and sell signals for index, row in df_signals.iterrows(): df_orders = account.getOrders() # determine if the df_signal is a buy or sell, just a high level check if row['ema12gtema26'] == True and row['macdgtsignal'] == True: action = 'buy' elif row['ema12ltema26co'] == True and row['macdltsignal'] == True: # ignore sell if close is lower than previous buy if len(df_orders) > 0 and df_orders.iloc[[ -1 ]]['action'].values[0] == 'buy' and row['close'] > df_orders.iloc[[ -1 ]]['price'].values[0]: action = 'sell' if action != '' and action != last_action and not ( last_action == '' and action == 'sell'): if last_action != '': if action == 'sell': diff = row['close'] - last_close else: diff = 0.00 if action == 'buy': account.buy(cryptoMarket, fiatMarket, 100, row['close']) elif action == 'sell': account.sell(cryptoMarket, fiatMarket, df_orders.iloc[[-1]]['size'].values[0], row['close']) data_dict = { 'market': market, 'granularity': granularity, 'start': startDate, 'end': endDate, 'action': action, 'index': str(index), 'close': row['close'], 'sma200': row['sma200'], 'ema12': row['ema12'], 'ema26': row['ema26'], 'macd': row['macd'], 'signal': row['signal'], 'ema12gtema26co': row['ema12gtema26co'], 'macdgtsignal': row['macdgtsignal'], 'ema12ltema26co': row['ema12ltema26co'], 'macdltsignal': row['macdltsignal'], 'obv_pc': row['obv_pc'], 'diff': diff } events.append(data_dict) last_action = action last_close = row['close'] total_diff = total_diff + diff # displays the events from the simulation events_df = pd.DataFrame(events) print(events_df) # if the last transation was a buy retrieve open amount addBalance = 0 df_orders = account.getOrders() if len(df_orders) > 0 and df_orders.iloc[[-1 ]]['action'].values[0] == 'buy': # last trade is still open, add to closing balance addBalance = df_orders.iloc[[-1]]['value'].values[0] # displays the orders from the simulation print('') print(df_orders) def truncate(f, n): return math.floor(f * 10**n) / 10**n # if the last transaction was a buy add the open amount to the closing balance result = truncate( round((account.getBalance(fiatMarket) + addBalance) - 1000, 2), 2) print('') print("Opening balance:", 1000) print("Closing balance:", truncate(round(account.getBalance(fiatMarket) + addBalance, 2), 2)) print(" Result:", result) print('') # saves the rendered diagram for the DataFrame (without displaying) tradinggraphs = TradingGraphs(coinbasepro) tradinggraphs.renderBuySellSignalEMA1226MACD( 'experiments/experiment' + str(id) + '_' + str(result) + '.png', True) result_dict = { 'market': market, 'granularity': granularity, 'start': startDate, 'end': endDate, 'open': 1000, 'close': '{:.2f}'.format(round(account.getBalance(fiatMarket) + addBalance, 2)), 'result': result } return result_dict