Exemple #1
0
def Main():

	exchange = Binance()
	# symbols = exchange.GetTradingSymbols(quoteAssets=["BTC", "USDT", "ETH"])
	symbols = exchange.GetTradingSymbols(quoteAssets=["BTC"])

	strategy_evaluators = [
		StrategyEvaluator(strategy_function=strategies_dict['bollinger_simple']),
		# StrategyEvaluator(strategy_function=Strategies.maStrategy),
		# StrategyEvaluator(strategy_function=strategies_dict['ichimoku_bullish']),
		# StrategyEvaluator(strategy_function=strategies_dict['ma_crossover'])
	]

	print(opening_text)
	
	answer = input()
	while answer not in ['b', 'e', 'q']:
		print(opening_text)
		answer = input()

	if answer == 'e':
		EvaluateStrategies(symbols=symbols, interval='1h', strategy_evaluators=strategy_evaluators)
	if answer == 'b':
		BacktestStrategies(symbols=symbols, interval='1h', plot=False, strategy_evaluators=strategy_evaluators)
	if answer == 'q':
		print("\nBYE!\n")
Exemple #2
0
def Main():
    """"""
    exchange = Binance(filename='credentials.txt')
    symbol = 'LTCUSDT'
    df = exchange.GetSymbolKlines(symbol, '5m', 1000)
    lines = FindTrends(df, distance_factor=0.01, n=20)
    PlotData(df, trends=lines, plot_title=symbol + " trends")
def Main():
    exchange = Binance()
    symbols = exchange.get_trade_symbols(quoteAssets=['BTC'])

    strategy_evaluators = [
        EvaluateStrategy(strategy_function=Strategies.bollStrategy),
        EvaluateStrategy(strategy_function=Strategies.maStrategy),
        EvaluateStrategy(strategy_function=Strategies.ichimokuBull)
    ]

    print(starting_message)
    answer = input()
    while answer not in ['b', 'q', 'e']:
        print(starting_message)
        answer = input()
    if answer == 'e':
        evalStrategies(symbols=symbols,
                       interval='1h',
                       strategy_evaluators=strategy_evaluators)
    if answer == 'b':
        BackTestStrategies(symbols=symbols,
                           interval='1h',
                           plot=False,
                           strategy_evaluators=strategy_evaluators)
    if answer == 'q':
        print('\nExiting now...\n')
Exemple #4
0
def Main():

    exchange = Binance()
    symbols = exchange.GetTradingSymbols(quoteAssets=["ETH"])

    strategy_evaluators = [
        StrategyEvaluator(strategy_function=Strategies.bollStrategy),
        StrategyEvaluator(strategy_function=Strategies.maStrategy),
        StrategyEvaluator(strategy_function=Strategies.ichimokuBullish)
    ]

    print(opening_text)

    answer = input()
    while answer not in ['b', 'e', 'q']:
        print(opening_text)
        answer = input()

    if answer == 'e':
        EvaluateStrategies(symbols=symbols,
                           interval='5m',
                           strategy_evaluators=strategy_evaluators)
    if answer == 'b':
        BacktestStrategies(symbols=symbols,
                           interval='5m',
                           plot=True,
                           strategy_evaluators=strategy_evaluators)
    if answer == 'q':
        print("\nBYE!\n")
Exemple #5
0
    def __init__(self):
        self.start_value = 0
        self.coinbase = Coinbase()
        self.binance = Binance()
        self.polo = poloniex()
        self.Threshold = 0.0021

        self.num_trades = 0

        self.order_volume = {'btc': 0.5, 'eth': 1, 'usd': 1000, 'xrp': 100}
        self.start_value = 0
Exemple #6
0
def Main():
    exchange = Binance()
    symbols = exchange.GetTradingSymbols(quoteAssets=["ETH"])

    strategy_evaluators = [
        StrategyEvaluator(strategy_function=Strategies.bollStrategy),
        StrategyEvaluator(strategy_function=Strategies.maStrategy),
        StrategyEvaluator(strategy_function=Strategies.ichimokuBullish)
    ]
    opening_text = "\nWelcome to Tudor's Crypto Trading Bot. \n \
	Press 'b' (ENTER) to backtest all strategies \n \
	Press 'e' (ENTER) to execute the strategies on all coins \n \
	Press 'q' (ENTER) to quit. "

    print(opening_text)
    '''
    answer = input()
	while answer not in ['b', 'e', 'q']:
		print(opening_text)
		answer = input()

	if answer == 'e':
		EvaluateStrategies(symbols=symbols, interval='5m', strategy_evaluators=strategy_evaluators)
	if answer == 'b':
		BacktestStrategies(symbols=symbols, interval='5m', plot=True, strategy_evaluators=strategy_evaluators)
	if answer == 'q':
		print("\nBYE!\n")
    '''
    answer = input()
    symbol = 'ETCBTC'
    interval = '1h'

    model = TradingModel(symbol=symbol, timeframe=interval)

    if answer == 'buy':
        order_result = model.exchange.PlaceOrder(model.symbol,
                                                 "BUY",
                                                 "MARKET",
                                                 quantity=0.02,
                                                 test=False)
    elif answer == 'sell':
        order_result = model.exchange.PlaceOrder(model.symbol,
                                                 "SELL",
                                                 "MARKET",
                                                 quantity=0.01,
                                                 test=False)

        if "code" in order_result:
            print("\nERROR.")
            print(order_result)
        else:
            print("\nSUCCESS.")
            print(order_result)
Exemple #7
0
def main():
    print("Starting...")
    exchange = Binance()

    evaluators = [
        Evaluator(strategy=Strategies.boll_strategy),
        Evaluator(strategy=Strategies.ma_strategy),
        Evaluator(strategy=Strategies.ichimoku_bullish)
    ]

    print(QUOTE_PROMPT)
    user_in = input().lower()
    while user_in not in ['1', '2', '3', 'quit']:
        print("\nInvalid entry.")
        print(QUOTE_PROMPT)
        user_in = input().lower()
    if user_in == '1':
        print("Selected BTC.\n")
        quote = "BTC"
    elif user_in == '2':
        print("Selected BUSD.\n")
        quote = "BUSD"
    elif user_in == '3':
        print("Selected USDT.\n")
        quote = "USDT"
    elif user_in == 'quit':
        sys.exit(0)

    symbols = exchange.get_trading_symbols(quote_assets=[quote])

    print(MAIN_PROMPT)
    user_in = input().lower()
    while user_in not in ['b', 'e', 'quit']:
        print("\nInvalid entry.")
        print(MAIN_PROMPT)
        user_in = input().lower()

    if user_in == 'e':
        print("Evaluating...", flush=True)
        evaluate_strategies(symbols=symbols,
                            interval='5m',
                            evaluators=evaluators)
    elif user_in == 'b':
        print("Backtesting...", flush=True)
        backtest_strategies(symbols=symbols,
                            interval='5m',
                            plot=True,
                            evaluators=evaluators)
    elif user_in == 'quit':
        sys.exit(0)
    def __init__(self, symbol, timeframe: str = '4h'):
        self.symbol = symbol
        self.exchange = Binance()
        self.df = self.exchange.get_symbol_data(symbol, timeframe)
        self.last_price = self.df['close'][len(self.df['close']) - 1]

        try:
            self.df['short_sma'] = sma(self.df['close'].tolist(), 10)
            self.df['long_sma'] = sma(self.df['close'].tolist(), 30)
            self.df['low_boll'] = lbb(self.df['close'].tolist(), 14)
        except Exception as e:
            print(' Exception when trying to computer indicators on: ' +
                  self.symbol)
            print(e)
            return None
Exemple #9
0
	def __init__(self, symbol):
		self.symbol = symbol
		self.exchange = Binance()
		self.df = self.exchange.GetSymbolData(symbol, '4h')
		self.last_price = self.df['close'][len(self.df['close'])-1]
		self.buy_signals = []

		try:
			self.df['fast_sma'] = sma(self.df['close'].tolist(), 10)
			self.df['slow_sma'] = sma(self.df['close'].tolist(), 30)
			self.df['low_boll'] = lbb(self.df['close'].tolist(), 14)
		except Exception as e:
			print(" Exception raised when trying to compute indicators on "+self.symbol)
			print(e)
			return None
Exemple #10
0
    def __init__(self, symbol, timeframe='4h'):
        self.symbol = symbol
        self.timeframe = timeframe
        self.exchange = Binance()
        self.df = self.exchange.GetSymbolData(symbol, timeframe)
        self.last_price = self.df['close'][len(self.df['close']) - 1]

        try:
            self.df['fast_sma'] = sma(self.df['close'].tolist(), 10)
            self.df['slow_sma'] = sma(self.df['close'].tolist(), 30)
            self.df['low_boll'] = lbb(self.df['close'].tolist(), 14)
        except Exception as e:
            print(
                "Exception occurred when attempting to compute indicators on "
                + self.symbol)
            print(e)
            return None
Exemple #11
0
def Main():

	exchange = Binance()
	symbols = exchange.GetTradingSymbols()
	for symbol in symbols:

		print(symbol)
		model = TradingModel(symbol)
		plot = False
		
		# if model.maStrategy(len(model.df['close'])-1):
		# 	print(" MA Strategy match on "+symbol)
		# 	plot = True

		if model.bollStrategy(len(model.df['close'])-1):
			print(" Boll Strategy match on "+symbol)
			plot = True

		if plot:
			model.plotData()
Exemple #12
0
    def __getBalances(self):
        balances = {}

        error = None

        if self.exchange:
            key, secret, passphrase = ('', '', '')

            if self.exchange.key:
                key = self.exchange.key.encode('utf-8')

            if self.exchange.secret:
                secret = self.exchange.secret.encode('utf-8')

            if self.exchange.passphrase:
                passphrase = self.exchange.passphrase.encode('utf-8')

            api = None

            if self.exchange.exchange.name == Config.BINANCE:
                api = Binance(key, secret)
            elif self.exchange.exchange.name == Config.BITTREX:
                api = Bittrex(key, secret)
            elif self.exchange.exchange.name == Config.COINBASE:
                api = Coinbase(key, secret)
            elif self.exchange.exchange.name == Config.LIQUI:
                api = Liqui(key, secret)
            elif self.exchange.exchange.name == Config.POLONIEX:
                api = Poloniex(key, secret)
            elif self.exchange.exchange.name == Config.GDAX:
                api = GDAX(key, secret, passphrase)

            if api:
                try:
                    new_balances = api.getBalances()
                    for key in new_balances:
                        if key in balances:
                            balances[key] += new_balances[key]
                        else:
                            balances[key] = new_balances[key]
                except ExchangeException as e:
                    error = e.message
            else:
                error = "Exchange %s is not defined!" % (
                    self.exchange.exchange.name)

        return (balances, error)
Exemple #13
0
def Main():
    exchange = Binance()
    symbols = exchange.GetTradingSymbols(quoteAssets=['ETH'])

    strategy_evaluators = [
        EvaluateStrategy(strategy_function=strategies_dict['bollinger_simple']),
        #EvaluateStrategy(strategy_function=strategies_dict.maStrategy),
        EvaluateStrategy(strategy_function=strategies_dict['ichimoku_bullish']),
        EvaluateStrategy(strategy_function=strategies_dict['ma_crossover'])
    ]
    
    print(starting_message)
    
    answer = input()
    while answer not in ['b', 'q', 'e']:
        print(starting_message)
        answer = input()
    if answer == 'e':
        evalStrategies(symbols=symbols, interval='1h', strategy_evaluators=strategy_evaluators)
    if answer == 'b':
        #Change plot=True to make graphs of each symbol to trade
        BackTestStrategies(symbols=symbols, interval='1h', plot=False, strategy_evaluators=strategy_evaluators)
    if answer == 'q':
        print('\nExiting now...\n')
Exemple #14
0
def Main():

    sp = yaspin()
    exchange = Binance(filename='credentials.txt')
    database = BotDatabase("database.db")
    prog = BotRunner(sp, exchange, database)

    i = input("Execute or Quit? (e or q)\n")
    bot_symbol_datas = []
    while i not in ['q']:
        if i == 'e':
            i = input("Create a new bot? (y or n)\n")
            if i == 'y':

                # symbols = ['ETHBTC', 'NEOBTC', 'EOSETH', 'BNBETH', 'BTCUSDT', \
                # 'ETHUSDT', 'WTCBTC', 'KNCETH', 'IOTABTC', 'LINKBTC', 'ENGBTC', \
                # 'DNTBTC', 'BTGBTC', 'XRPBTC', 'ENJBTC', 'BNBUSDT', 'XMRBTC', 'BATBTC', \
                # 'NEOUSDT', 'LTCUSDT', 'WAVESBTC', 'IOSTBTC', 'QTUMUSDT', 'XEMBTC', \
                # 'ADAUSDT', 'XRPUSDT', 'EOSUSDT', 'THETABTC', 'IOTAUSDT', 'XLMUSDT', \
                # 'ONTUSDT', 'TRXUSDT', 'ETCUSDT', 'ICXUSDT', 'VETUSDT', 'POLYBTC', \
                # 'LINKUSDT', 'WAVESUSDT', 'BTTUSDT', 'FETBTC', 'BATUSDT', 'XMRUSDT', \
                # 'IOSTUSDT', 'MATICBTC', 'ATOMUSDT', 'ALGOBTC', 'ALGOUSDT', 'DUSKBTC', \
                # 'TOMOBTC', 'XTZBTC', 'HBARBTC', 'HBARUSDT', 'FTTBTC', 'FTTUSDT', \
                # 'OGNBTC', 'OGNUSDT', 'BEARUSDT', 'ETHBULLUSDT', 'ETHBEARUSDT', \
                # 'WRXBTC', 'WRXUSDT', 'LTOBTC', 'EOSBEARUSDT', 'XRPBULLUSDT', \
                # 'XRPBEARUSDT', 'AIONUSDT', 'COTIBTC']

                symbols = ['ETHBTC', 'XPRBTC', 'BCHBTC', 'LTCBTC', 'BTCUSDT', \
                            'ETHUSDT', 'BNBBTC', 'EOSBTC', 'XTZBTC', 'ADABTC', 'LINKBTC', \
                            'XLMBTC', 'XMRBTC', 'XRPBTC', 'XPRBNB', 'BNBUSDT', 'BCHBNB', 'LTCBNB', \
                            'EOSBNB', 'EOSBNB', 'XTZBNB', 'ADABNB', 'XLMBNB', 'XMRBNB', \
                            'BCHUSDT', 'XRPUSDT', 'LTCUSDT', 'EOSUSDT', 'XTZUSDT', 'ADAUSDT',]

                bot, symbol_datas_dict = prog.CreateBot(
                    strategy_name='ma_crossover',
                    trade_allocation=0.001,
                    symbols=symbols)
                bot_symbol_datas.append((bot, symbol_datas_dict))

            else:
                bot_symbol_datas = prog.GetAllBotsFromDb()

            prog.StartExecution(bot_symbol_datas)

        i = input("Execute or Quit? (e or q)")
Exemple #15
0
def Main():

    sp = yaspin(
        Spinners.growHorizontal)  # horizontal growing bar during botRunning
    exchange = Binance(credentials='credentials.txt'
                       )  # access to the exchange (adapted for Binance only)
    database = BotDatabase("database.db")  # access to the local database
    prog = BotRunner(sp, exchange, database)  # initializing the tradingBot

    i = input("Execute or Quit? (e or q)\n")  # Execute the tradingBot ?
    while i not in ['q']:
        if i == 'e':
            i = input("Create a new bot? (y or n)\n"
                      )  # We can create a new bot or recover the last one
            if i == 'y':  # Creating a brand new bot (usualy with new parameters)
                bot_symbol_datas = [
                ]  # Defining a list about to receive all data from symbols, strategy and allocation
                symbols = ['BTCUSDT', 'LTCUSDT', 'BNBUSDT', 'QTUMUSDT', \
                'ADAUSDT', 'XRPUSDT', 'EOSUSDT', 'XLMUSDT', 'ONTUSDT', \
                'TRXUSDT', 'VETUSDT', 'LINKUSDT', 'ETHUSDT', 'BATUSDT', \
                'XMRUSDT', 'ATOMUSDT', 'ALGOUSDT']   # List of symbols we want to trade

                bot, symbol_datas_dict = prog.CreateBot(  # Creating a new bot
                    name='TestingBot',  # Name of the bot
                    strategy_name='ma_crossover',  # Name of the strategy
                    interval='1m',  # Interval of trading process
                    trade_allocation=0.1,  # Allocation allowed for this bot (%)
                    profit_target=1.012,
                    test=True,  # we can run the bot in test mode
                    symbols=symbols
                )  # This function creates a bot based on some settings ans saves it to the DB
                bot_symbol_datas.append(
                    (bot, symbol_datas_dict)
                )  # adding this new bot to a variable used here in the script
            else:
                bot_symbol_datas = prog.GetAllBotsFromDb(
                )  # adding this saved bot to a variable used here in the script

            prog.StartExecution(
                bot_symbol_datas)  # Starting the bot with parameters given

        i = input("Execute or Quit? (e or q)")
Exemple #16
0
def execute_trades(binance, predict_dummy):
    balance = binance.fetchBalance()
    BTC_balance = round(balance['BTC']['free'], 4)
    USDT_balance = round(balance['USDT']['free'], 4)
    print("Account Balance BTC ", BTC_balance)
    print("Account Balance USDT ", USDT_balance)
    symbol = 'BTCUSDT'
    interval = '1h'
    exchange = Binance()
    model = TradingModel(symbol=symbol, timeframe=interval)

    if predict_dummy:
        USDT_quantity = min(5, USDT_balance)
        print("Model predicts BUY, we are buying ", USDT_quantity)
        if USDT_quantity == 0:
            sys.exit("USDT balance in account not sufficient")
        order_result = model.exchange.PlaceOrder(model.symbol,
                                                 "BUY",
                                                 "MARKET",
                                                 quantity=10,
                                                 test=False)
    else:
        BTC_quantity = min(.001, BTC_balance)
        print("Model predicts SELL, we are selling ", BTC_quantity)
        if BTC_quantity == 0:
            sys.exit("BTC balance in account not sufficient")
        order_result = model.exchange.PlaceOrder(model.symbol,
                                                 "SELL",
                                                 "MARKET",
                                                 quantity=10,
                                                 test=False)

    if "code" in order_result:
        print("\nERROR.")
        print(order_result)
    else:
        print("\nSUCCESS.")
        print(order_result)

    with open('trade_history.txt', 'a') as outfile:
        json.dump(order_result, outfile)
Exemple #17
0
def get_users_info():
    from config import get_users
    users = get_users()

    exchange_dict = {}
    telegram_id_dict = {}

    for user in users:
        API_KEY = users[user]['API_KEY']
        SECRET_KEY = users[user]['SECRET_KEY']
        PASSPHRASE = users[user]['PASSPHRASE']
        if users[user]['exchange'].lower() == 'binance':
            exchange = Binance(API_KEY, SECRET_KEY)
            exchange_dict[user] = exchange
        elif users[user]['exchange'].lower() == 'coinbase':
            exchange = CoinbasePro(API_KEY, SECRET_KEY, PASSPHRASE)
            exchange_dict[user] = exchange

        telegram_id = users[user]['telegram_id']
        telegram_id_dict[user] = telegram_id

    return users, exchange_dict, telegram_id_dict
Exemple #18
0
def Main():
    #log file.. when bot is running in paper mode log trades
    lf = open('tradelog.txt', 'w')
    lf.write("welcoem to trade bot's log file")
    print(opening_text)
    answer = input()
    if answer == 'e':
        exchange = Binance()
        symbols = [
            "BNBETH"
        ]  #, "BTCUSDT", "BNBBTC", "LTCBTC", "BANDBTC", "ETHBTC"]    #exchange.GetTradingSymbols(quoteAssets=["ETH"])

        strategy_evaluators = [
            #StrategyEvaluator(strategy_function=Strategies.bollStrategy),
            #StrategyEvaluator(strategy_function=Strategies.maStrategy),
            StrategyEvaluator(strategy_function=Strategies.ichimokuBullish)
        ]
        #loop 20 times a second
        while True:
            try:
                t1 = time.monotonic()
                print(str(t1), flush=True)
                #BacktestStrategies(symbols=symbols, interval='5m', plot=True, strategy_evaluators=strategy_evaluators)
                EvaluateStrategies(symbols=symbols,
                                   interval='5m',
                                   strategy_evaluators=strategy_evaluators)
                t2 = time.monotonic()
                if (t2 - t1) < 0.05:
                    time.sleep(0.05)
            except KeyboardInterrupt:
                print("key board interrupt by user")
                return
    elif answer == 'q':
        sys.exit("user quit program")

    lf.close()
Exemple #19
0
class TradingModel:
	
	def __init__(self, symbol):
		self.symbol = symbol
		self.exchange = Binance()
		self.df = self.exchange.GetSymbolData(symbol, '4h')
		self.last_price = self.df['close'][len(self.df['close'])-1]
		self.buy_signals = []

		try:
			self.df['fast_sma'] = sma(self.df['close'].tolist(), 10)
			self.df['slow_sma'] = sma(self.df['close'].tolist(), 30)
			self.df['low_boll'] = lbb(self.df['close'].tolist(), 14)
		except Exception as e:
			print(" Exception raised when trying to compute indicators on "+self.symbol)
			print(e)
			return None

	def strategy(self):	
		
		'''If Price is 3% below Slow Moving Average, then Buy
		Put selling order for 2% above buying price'''

		df = self.df

		buy_signals = []

		for i in range(1, len(df['close'])):
			if df['slow_sma'][i] > df['low'][i] and (df['slow_sma'][i] - df['low'][i]) > 0.03 * df['low'][i]:
				buy_signals.append([df['time'][i], df['low'][i]])

		self.plotData(buy_signals = buy_signals)

	def plotData(self, buy_signals = False):
		df = self.df

		# plot candlestick chart
		candle = go.Candlestick(
			x = df['time'],
			open = df['open'],
			close = df['close'],
			high = df['high'],
			low = df['low'],
			name = "Candlesticks")

		# plot MAs
		fsma = go.Scatter(
			x = df['time'],
			y = df['fast_sma'],
			name = "Fast SMA",
			line = dict(color = ('rgba(102, 207, 255, 50)')))

		ssma = go.Scatter(
			x = df['time'],
			y = df['slow_sma'],
			name = "Slow SMA",
			line = dict(color = ('rgba(255, 207, 102, 50)')))

		lowbb = go.Scatter(
			x = df['time'],
			y = df['low_boll'],
			name = "Lower Bollinger Band",
			line = dict(color = ('rgba(255, 102, 207, 50)')))

		data = [candle, ssma, fsma, lowbb]

		if buy_signals:
			buys = go.Scatter(
					x = [item[0] for item in buy_signals],
					y = [item[1] for item in buy_signals],
					name = "Buy Signals",
					mode = "markers",
				)

			sells = go.Scatter(
					x = [item[0] for item in buy_signals],
					y = [item[1]*1.05 for item in buy_signals],
					name = "Sell Signals",
					mode = "markers",
				)

			data = [candle, ssma, fsma, buys, sells]


		# style and display
		layout = go.Layout(title = self.symbol)
		fig = go.Figure(data = data, layout = layout)

		plot(fig, filename=self.symbol+'.html')


	def maStrategy(self, i:int):
		''' If price is 10% below the Slow MA, return True'''

		df = self.df
		buy_price = 0.8 * df['slow_sma'][i]
		if buy_price >= df['close'][i]:
			self.buy_signals.append([df['time'][i], df['close'][i], df['close'][i] * 1.045])
			return True

		return False

	def bollStrategy(self, i:int):
		''' If price is 5% below the Lower Bollinger Band, return True'''

		df = self.df
		buy_price = 0.98 * df['low_boll'][i]
		if buy_price >= df['close'][i]:
			self.buy_signals.append([df['time'][i], df['close'][i], df['close'][i] * 1.045])
			return True

		return False
Exemple #20
0
from Poloniex import poloniex
import sys


class C:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


b = Binance()
p = poloniex()
engine = Engine()

while True:
    polo_price = float(p.getLastTradingPrice('BTC_XRP'))
    binance_price = float(b.client.get_all_tickers()[88]['price'])
    percent_difference = (polo_price - binance_price) / min(
        polo_price, binance_price)

    pd = str(percent_difference)
    if (percent_difference) > engine.Threshold:
        pd = C.OKBLUE + str(percent_difference) + C.ENDC
    elif abs(percent_difference) > engine.Threshold:
        pd = C.OKGREEN + str(percent_difference) + C.ENDC
Exemple #21
0
import pandas as pd
import sys
sys.path.append('../')
from Binance import Binance
import logging.config
import logging.handlers
import logging
import os

# this logging configuration is sketchy
binance = logging.getLogger(__name__)
logging.config.fileConfig('logging.ini')

# create Binance object
bn = Binance()

# set keys
bn.setSecretKey(
    'NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j')
bn.setAPIKey(
    'vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A')

# getTicker
print "---------------- getTicker --------------"
print "---------------- tickerType = 24hr --------------"
print "################################# POSITIVE TESTS (returns 1 or r) ###################"
queryParams = {'symbol': 'SALTBTC'}
print "****test valid symbol for tickerType = 24hr"
test = bn.getTicker('24hr', queryParams)
print
Exemple #22
0
class TradingModel:
	
	# We can now remove the code where we're computing the indicators from this class,
	# As we will be computing them in the Strategies class (on a per-need basis)

	def __init__(self, symbol, timeframe:str='4h'):
		self.symbol = symbol
		self.timeframe = timeframe
		self.exchange = Binance()
		self.df = self.exchange.GetSymbolKlines(symbol, timeframe, 10000)
		self.last_price = self.df['close'][len(self.df['close'])-1]

	# We'll look directly in the dataframe to see what indicators we're plotting

	def plotData(self, buy_signals = False, sell_signals = False, plot_title:str="",
	indicators=[
		dict(col_name="fast_ema", color="indianred", name="FAST EMA"), 
		dict(col_name="50_ema", color="indianred", name="50 EMA"), 
		dict(col_name="200_ema", color="indianred", name="200 EMA")]):
		df = self.df

		# plot candlestick chart
		candle = go.Candlestick(
			x = df['time'],
			open = df['open'],
			close = df['close'],
			high = df['high'],
			low = df['low'],
			name = "Candlesticks")

		data = [candle]

		for item in indicators:
			if df.__contains__(item['col_name']):
				fsma = go.Scatter(
					x = df['time'],
					y = df[item['col_name']],
					name = item['name'],
					line = dict(color = (item['color'])))
				data.append(fsma)

		# if df.__contains__('50_ema'):
		# 	fsma = go.Scatter(
		# 		x = df['time'],
		# 		y = df['50_ema'],
		# 		name = "50 EMA",
		# 		line = dict(color = ('rgba(102, 207, 255, 50)')))
		# 	data.append(fsma)

		# if df.__contains__('200_ema'):
		# 	fsma = go.Scatter(
		# 		x = df['time'],
		# 		y = df['200_ema'],
		# 		name = "200 EMA",
		# 		line = dict(color = ('rgba(102, 207, 255, 50)')))
		# 	data.append(fsma)

		if df.__contains__('fast_sma'):
			fsma = go.Scatter(
				x = df['time'],
				y = df['fast_sma'],
				name = "Fast SMA",
				line = dict(color = ('rgba(102, 207, 255, 50)')))
			data.append(fsma)

		if df.__contains__('slow_sma'):
			ssma = go.Scatter(
				x = df['time'],
				y = df['slow_sma'],
				name = "Slow SMA",
				line = dict(color = ('rgba(255, 207, 102, 50)')))
			data.append(ssma)

		if df.__contains__('low_boll'):
			lowbb = go.Scatter(
				x = df['time'],
				y = df['low_boll'],
				name = "Lower Bollinger Band",
				line = dict(color = ('rgba(255, 102, 207, 50)')))
			data.append(lowbb)

		# Now, Let's also plot the Ichimoku Indicators

		if df.__contains__('tenkansen'):
			trace = go.Scatter(
				x = df['time'],
				y = df['tenkansen'],
				name = "Tenkansen",
				line = dict(color = ('rgba(40, 40, 141, 100)')))
			data.append(trace)
		
		if df.__contains__('kijunsen'):
			trace = go.Scatter(
				x = df['time'],
				y = df['kijunsen'],
				name = "Kijunsen",
				line = dict(color = ('rgba(140, 40, 40, 100)')))
			data.append(trace)

		if df.__contains__('senkou_a'):
			trace = go.Scatter(
				x = df['time'],
				y = df['senkou_a'],
				name = "Senkou A",
				line = dict(color = ('rgba(160, 240, 160, 100)')))
			data.append(trace)
	
		# As you saw in the chart earlier, the portion between Senkou A and B
		# is filled, either with red or with green. Here, We'll only be using red
		# I haven't found a proper way to change the colors of the fill based on
		# who is on top (Senkou A or B). If you have a way, please put it into the
		# comments, or bettew yet, write it in the code on github (make a pull request)!!

		if df.__contains__('senkou_b'):
			trace = go.Scatter(
				x = df['time'],
				y = df['senkou_b'],
				name = "Senkou B",
				fill = "tonexty",
				line = dict(color = ('rgba(240, 160, 160, 50)')))
			data.append(trace)

		if buy_signals:
			buys = go.Scatter(
					x = [item[0] for item in buy_signals],
					y = [item[1] for item in buy_signals],
					name = "Buy Signals",
					mode = "markers",
					marker_size = 20
				)
			data.append(buys)

		if sell_signals:
			sells = go.Scatter(
				x = [item[0] for item in sell_signals],
				y = [item[1] for item in sell_signals],
				name = "Sell Signals",
				mode = "markers",
				marker_size = 20
			)
			data.append(sells)

		# style and display
		# let's customize our layout a little bit:
		layout = go.Layout(
			title=plot_title,
			xaxis = {
				"title" : self.symbol,
				"rangeslider" : {"visible": False},
				"type" : "date"
			},
			yaxis = {
				"fixedrange" : False,
			})
			
		fig = go.Figure(data = data, layout = layout)

		plot(fig, filename='graphs/'+plot_title+'.html')
Exemple #23
0
	def __init__(self, symbol, timeframe:str='4h'):
		self.symbol = symbol
		self.timeframe = timeframe
		self.exchange = Binance()
		self.df = self.exchange.GetSymbolKlines(symbol, timeframe, 10000)
		self.last_price = self.df['close'][len(self.df['close'])-1]
class TradingModel:
    def __init__(self, symbol, timeframe: str = '4h'):
        self.symbol = symbol
        self.timeframe = timeframe
        self.exchange = Binance()
        self.df = self.exchange.GetSymbolKlines(symbol, timeframe, 10000)
        self.last_price = self.df['close'][len(self.df['close']) - 1]

#%%

    def plotData(self,
                 buy_signals=False,
                 sell_signals=False,
                 plot_title: str = "",
                 indicators=[
                     dict(col_name="fast_ema",
                          color="indianred",
                          name="FAST EMA"),
                     dict(col_name="50_ema", color="indianred", name="50 EMA"),
                     dict(col_name="200_ema",
                          color="indianred",
                          name="200 EMA")
                 ]):
        df = self.df

        # plot candlestick chart
        candle = go.Candlestick(x=df['time'],
                                open=df['open'],
                                close=df['close'],
                                high=df['high'],
                                low=df['low'],
                                name="Candlesticks")

        data = [candle]

        for item in indicators:
            if df.__contains__(item['col_name']):
                fsma = go.Scatter(x=df['time'],
                                  y=df[item['col_name']],
                                  name=item['name'],
                                  line=dict(color=(item['color'])))
                data.append(fsma)

        if df.__contains__('fast_sma'):
            fsma = go.Scatter(x=df['time'],
                              y=df['fast_sma'],
                              name="Fast SMA",
                              line=dict(color=('rgba(102, 207, 255, 50)')))
            data.append(fsma)

        if df.__contains__('slow_sma'):
            ssma = go.Scatter(x=df['time'],
                              y=df['slow_sma'],
                              name="Slow SMA",
                              line=dict(color=('rgba(255, 207, 102, 50)')))
            data.append(ssma)

        if df.__contains__('low_boll'):
            lowbb = go.Scatter(x=df['time'],
                               y=df['low_boll'],
                               name="Lower Bollinger Band",
                               line=dict(color=('rgba(255, 102, 207, 50)')))
            data.append(lowbb)

        if df.__contains__('tenkansen'):
            trace = go.Scatter(x=df['time'],
                               y=df['tenkansen'],
                               name="Tenkansen",
                               line=dict(color=('rgba(40, 40, 141, 100)')))
            data.append(trace)

        if df.__contains__('kijunsen'):
            trace = go.Scatter(x=df['time'],
                               y=df['kijunsen'],
                               name="Kijunsen",
                               line=dict(color=('rgba(140, 40, 40, 100)')))
            data.append(trace)

        if df.__contains__('senkou_a'):
            trace = go.Scatter(x=df['time'],
                               y=df['senkou_a'],
                               name="Senkou A",
                               line=dict(color=('rgba(160, 240, 160, 100)')))
            data.append(trace)

        if df.__contains__('senkou_b'):
            trace = go.Scatter(x=df['time'],
                               y=df['senkou_b'],
                               name="Senkou B",
                               fill="tonexty",
                               line=dict(color=('rgba(240, 160, 160, 50)')))
            data.append(trace)

        if buy_signals:
            buys = go.Scatter(x=[item[0] for item in buy_signals],
                              y=[item[1] for item in buy_signals],
                              name="Buy Signals",
                              mode="markers",
                              marker_size=20)
            data.append(buys)

        if sell_signals:
            sells = go.Scatter(x=[item[0] for item in sell_signals],
                               y=[item[1] for item in sell_signals],
                               name="Sell Signals",
                               mode="markers",
                               marker_size=20)
            data.append(sells)

        layout = go.Layout(title=plot_title,
                           xaxis={
                               "title": self.symbol,
                               "rangeslider": {
                                   "visible": False
                               },
                               "type": "date"
                           },
                           yaxis={
                               "fixedrange": False,
                           })

        fig = go.Figure(data=data, layout=layout)

        plot(fig, filename='graphs/' + plot_title + '.html')
Exemple #25
0

order_amount = 0.00091
nominal_btc_price = 11800

if __name__ == '__main__':
    binance_data = Array('d', 4)
    p1 = Process(target=binance, args=(0, binance_data))
    p1.start()

    btcturk_data = Array('d', 4)
    p2 = Process(target=btcturk, args=(0, btcturk_data))
    p2.start()

    with open(f'{str(date.today())}_log.txt', 'w+') as log_file:
        binance = Binance(log_file, nominal_btc_price)
        btcturk = Btcturk(log_file, nominal_btc_price)
        initial_total_usd_worth = binance.total_usd_worth + btcturk.total_usd_worth
        log_print(f'Initial total USD worth: {initial_total_usd_worth:0.2f}')

        while True:
            # Safety checks
            if len(btcturk.get_open_orders('BTCUSDT')['data']['bids']) < 2 and \
                    len(btcturk.get_open_orders('BTCUSDT')['data']['asks']) < 2 and \
                    len(binance.get_open_orders('BTCUSDT')) < 2:

                opp = check_for_opp(binance_data, binance, btcturk_data,
                                    btcturk)

                # Check if opp is profitable enough dependent on direction
                if (opp['max_bid_exchange'].btc_free_balance >= opp['min_ask_exchange'].btc_free_balance
class TradeModel:
    def __init__(self, symbol, timeframe: str = '4h'):
        self.symbol = symbol
        self.timeframe = timeframe
        self.exchange = Binance()
        self.df = self.exchange.GetSymbolKlines(symbol, timeframe)
        self.last_price = self.df['close'][len(self.df['close']) - 1]

    #For indicators, check if they are in the df to see what to plot
    #Eventually want the function to just be able to get an indicator array of inputs,
    #Plot
    def plot_data(self,
                  buy_signals=False,
                  sell_signals=False,
                  plot_title: str = "",
                  indicators=[
                      dict(col_name='short_sma',
                           color='indianred',
                           name='SHORT EMA'),
                      dict(col_name='50_ema', color='blue', name='50 EMA'),
                      dict(col_name='200_ema',
                           color='indianred',
                           name='200 EMA')
                  ]):
        df = self.df

        #Plotting candlesticks
        candle = pgo.Candlestick(x=df['time'],
                                 open=df['open'],
                                 close=df['close'],
                                 high=df['high'],
                                 low=df['low'],
                                 name='Candlesticks')

        data = [candle]

        for item in indicators:
            if df.__contains__(item['col_name']):
                ssma = pgo.Scatter(x=df['time'],
                                   y=df[item['col_name']],
                                   name=item['name'],
                                   line=dict(color=(item['color'])))
                data.append(ssma)

        indicators
        if df.__contains__('50_ema'):
            #Adding MAs
            ssma = pgo.Scatter(x=df['time'],
                               y=df['50_ema'],
                               name='50 EMA',
                               line=dict(color=('rgba(102,207,255,50)')))
            data.append(ssma)

        if df.__contains__('200_ema'):
            #Adding MAs
            ssma = pgo.Scatter(x=df['time'],
                               y=df['200_ema'],
                               name='200 EMA',
                               line=dict(color=('rgba(102,207,255,50)')))
            data.append(ssma)

        if df.__contains__('short_sma'):
            #Adding MAs
            ssma = pgo.Scatter(x=df['time'],
                               y=df['short_sma'],
                               name='Short SMA',
                               line=dict(color=('rgba(102,207,255,50)')))
            data.append(ssma)

        if df.__contains__('long_sma'):
            lsma = pgo.Scatter(x=df['time'],
                               y=df['long_sma'],
                               name='LONG SMA',
                               line=dict(color=('rgba(255,207,102,50)')))
            data.append(lsma)

        if df.__contains__('low_boll'):
            lowbb = pgo.Scatter(x=df['time'],
                                y=df['low_boll'],
                                name='Lower Bollinger Band',
                                line=dict(color=('rgba(255,102,207,50)')))
            data.append(lowbb)

        #Ichimoku Cloud Indicator
        #Tekansen
        if df.__contains__('tenkansen'):
            trace = pgo.Scatter(x=df['time'],
                                y=df['tenkansen'],
                                name='Tenkansen',
                                line=dict(color=('rgba(40,40,141,100)')))
            data.append(trace)
        #Kijunsen
        if df.__contains__('kijunsen'):
            trace = pgo.Scatter(x=df['time'],
                                y=df['kijunsen'],
                                name='Kijunsen',
                                line=dict(color=('rgba(140,40,40,100)')))
            data.append(trace)
        #senkou A
        if df.__contains__('senkou_a'):
            trace = pgo.Scatter(x=df['time'],
                                y=df['senkou_a'],
                                name='Senkou A',
                                line=dict(color=('rgba(160,240,156,100)')))
            data.append(trace)
        #Senkou B
        #Gap between senkou_a and senkou_b must be filled, usually with red or green.
        #Need to implement way to change colour of fill depending on if A or B is on top
        if df.__contains__('senkou_b'):
            trace = pgo.Scatter(x=df['time'],
                                y=df['senkou_b'],
                                name='Senkou B',
                                fill='tonexty',
                                line=dict(color=('rgba(240,160,160,50)')))
            data.append(trace)

        #plots buy signals if parameter is passed
        if buy_signals:
            buys = pgo.Scatter(
                #x is time, y is price
                x=[i[0] for i in buy_signals],
                y=[i[1] for i in buy_signals],
                name="Buy Signals",
                mode="markers",  #for dots not line
                marker_size=20)
            data.append(buys)

        if sell_signals:
            #Add sell signals, use 5% over buy price to start
            sells = pgo.Scatter(
                x=[i[0] for i in sell_signals],
                y=[i[1] for i in sell_signals],
                name="SELL SIGNALS",
                mode="markers",  #for dots not line
                marker_size=20)
            data.append(sells)

        #Styling, will open in an html page
        layout = pgo.Layout(title=plot_title,
                            xaxis={
                                'title': self.symbol,
                                'rangeslider': {
                                    'visible': False
                                },
                                'type': 'date'
                            },
                            yaxis={
                                'fixedrange': False,
                            })

        fig = pgo.Figure(data=data, layout=layout)
        plot(fig, filename='graphs/' + plot_title + '.html')
Exemple #27
0
class TradingModel:
    def __init__(self, symbol, timeframe='4h'):
        self.symbol = symbol
        self.timeframe = timeframe
        self.exchange = Binance()
        self.df = self.exchange.GetSymbolData(symbol, timeframe)
        self.last_price = self.df['close'][len(self.df['close']) - 1]

        try:
            self.df['fast_sma'] = sma(self.df['close'].tolist(), 10)
            self.df['slow_sma'] = sma(self.df['close'].tolist(), 30)
            self.df['low_boll'] = lbb(self.df['close'].tolist(), 14)
        except Exception as e:
            print(
                "Exception occurred when attempting to compute indicators on "
                + self.symbol)
            print(e)
            return None

    def plotData(self,
                 buy_signals=False,
                 sell_signals=False,
                 plot_title="",
                 indicators=[]):
        df = self.df
        # Plot candlestick chart
        candle = go.Candlestick(x=df['time'],
                                open=df['open'],
                                close=df['close'],
                                high=df['high'],
                                low=df['low'],
                                name="Candlesticks")
        data = [candle]
        # Plot MAs
        if indicators.__contains__('fast_sma'):
            fsma = go.Scatter(x=df['time'],
                              y=df['fast_sma'],
                              name="Fast SMA",
                              line=dict(color='rgba(102, 207, 255, 50)'))
            data.append(fsma)

        if indicators.__contains__('slow_sma'):
            ssma = go.Scatter(x=df['time'],
                              y=df['slow_sma'],
                              name="Slow SMA",
                              line=dict(color='rgba(255, 207, 102, 50)'))
            data.append(ssma)

        if indicators.__contains__('low_boll'):
            lowbb = go.Scatter(x=df['time'],
                               y=df['low_boll'],
                               name="Lower Bollinger Band",
                               line=dict(color='rgba(255, 102, 207, 50)'))
            data.append(lowbb)

        if buy_signals:
            buys = go.Scatter(x=[item[0] for item in buy_signals],
                              y=[item[1] for item in buy_signals],
                              name="Buy Signals",
                              mode="markers")
            data.append(buys)

        if sell_signals:
            sells = go.Scatter(x=[item[0] for item in sell_signals],
                               y=[item[1] for item in sell_signals],
                               name="Sell Signals",
                               mode="markers")
            data.append(sells)

        # Style and UI
        layout = go.Layout(title=plot_title)
        fig = go.Figure(data=data, layout=layout)

        plot(fig, filename='graphs/' + plot_title + '.html')
import pandas as pd
import sys
sys.path.append('../')
from Binance import Binance
import logging.config
import logging.handlers
import logging
import os

# this logging configuration is sketchy
binance = logging.getLogger(__name__)
logging.config.fileConfig('logging.ini')

# create Binance object
bn = Binance()

# set keys
bn.setSecretKey(
    'NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j')
bn.setAPIKey(
    'vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A')

# getSigtnature
print "---------------- getSignature --------------"
totalParams = bytes(
    "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559"
).encode('utf-8')
secretKey = bytes(
    "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j").encode(
        'utf-8')
Exemple #29
0
import pandas as pd
import sys
sys.path.append('../')
from Binance import Binance
import logging.config
import logging.handlers
import logging
import os

# this logging configuration is sketchy
binance = logging.getLogger(__name__)
logging.config.fileConfig('logging.ini')

# create Binance object
bn = Binance()

# set keys
bn.setSecretKey(
    'NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j')
bn.setAPIKey(
    'vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A')

# getAggTrades
print "---------------- getAggTrades --------------"
print "################################# POSITIVE TESTS (returns 1 or r) ###################"
queryParams = {'symbol': 'ETHBTC'}
print "****test valid symbol"
test = bn.getAggTrades(queryParams)
print
queryParams = {'symbol': 'SALTBTC', 'fromId': 1766960}
    config = ConfigParser.ConfigParser()
    config.read("config.ini")
    return config.get('KEYS', key)


queryParams = {}
queryParams['symbol'] = (raw_input("Name of Symbol: ")).upper()
queryParams['limit'] = int(
    raw_input("Number of Rows: "
              ))  # note cast to int here, otherwise python makes this a string

# this logging configuration is sketchy
binance = logging.getLogger(__name__)
logging.config.fileConfig('logging.ini')

# create Binance object
bn = Binance()

# set keys
bn.setSecretKey(readConfig('secret'))
bn.setAPIKey(readConfig('apikey'))

print "MY ORDER HISTORY OF " + queryParams['symbol']
# fetch order list into a pandas dataframe, add human readable date/time, and print out a few columns of interest
df = pd.DataFrame(bn.getAllOrders(queryParams))
df['date'] = df['time'].apply(
    lambda x: (time.strftime('%Y-%m-%d', (time.localtime(x / 1000)))))
df['time'] = df['time'].apply(
    lambda x: (time.strftime('%H:%M:%S', (time.localtime(x / 1000)))))
print df.loc[:, ['orderId', 'date', 'time', 'side', 'price', 'origQty']]