def open(self): print("opening local websocket") self.snapshots = {"bitfinex": []} self.subscribed = False #becomes true when snapshots are recieved from both exchanges self.coinbase = Exchange(self, "wss://ws-feed-public.sandbox.gdax.com", "coinbase") self.bitfinex = Exchange(self, "wss://api.bitfinex.com/ws", "bitfinex")
async def tasks_main(): #yapf:disable exchange = await Endpoints().send_to('myfoo',Exchange("poko",{'foo': 'bar','pon': {'puu': 'poo'}})) exchange = await Endpoints().send_to('myfoo',Exchange("poko",{'foo': 'bar','pon': {'puu': 'poo'}})) gathering_exchange = await Endpoints().send_to('gathering', Exchange('boo')) #yapf:enable if exchange: print(exchange.get_body()) if gathering_exchange: #expect: boo bon boo poyo print('gathered:', gathering_exchange.get_body())
def main(strategies, test): exchange = Exchange(test) print ("Connected to exchange") trading_bot = Trading_Bot(exchange, strategies) print ("Bot initialized") trading_bot.trade() print ("Bot finished Trading")
def __init__(self, period): self.period = period self.statistics = Statistics(default="USDT") self.exchange = Exchange(default="USDT") self.current_asset_symbol = None self.buyPrice = 0
def __init__(self, global_model, T, T_max, t_max=1000, states_to_prime=1000, summary_writer=None, data=DATA): self.previous = None # for testing if input is the same self.t = tf.Variable(initial_value=1, trainable=False) self.T = T self.T_max = T_max self.t_max = t_max self.global_model = global_model # Redundant self.deep_model = not global_model.naive self.naive = global_model.naive self.states_to_prime = states_to_prime #self.model = Model(**global_model.get_params()) # build model based on global model params # For now, just interface with main model self.model = self.global_model self.summary_writer = summary_writer # Each worker has an exchange; can be reset to any state self.exchange = Exchange(data, time_interval=1, game_length=self.t_max, naive_price_history=self.model.input_size, naive_inputs=self.model.inputs_per_time_step)
def Main(): config = readConfig() exchange = Exchange(config) pairs = config['exchange']['pair_list'] exchange.ValidatePairs(pairs) store = Store() telegram = Telegram(config) while True: for pair in pairs: print(f"Get {pair} {timeframe}") df = exchange.fetchOHLCV(pair, timeframe, f"{size} hours ago") if not df.empty: df_old = store.load_data(pair,timeframe) df = calculate_gainer(df) if not df_old.empty: df_old.append(df) else: df_old = df store.store_data(pair=pair,timeframe=timeframe,data=df_old) print(f"Returned {pair} {df.size} lines") else: print(f"Returned {pair} Empty!")
def profileFunction(): cur = 'ETH' priceStep = 10 ex = Exchange(debug=True, startTime=1554681601, hours=12, stepTime=priceStep) # Price stat variables to feed our neural network. avgTime = 600 # 600 second (10 minute) moving average. movAvg = None prePrices = [] maxPrePrices = int(avgTime / priceStep) while True: # Get a new price list. ex.updatePrices() curPrice = ex.getPriceUSD('ETH') if curPrice == None: break prePrices.append(curPrice) if len(prePrices) > maxPrePrices: prePrices.pop(0) if len(prePrices) == maxPrePrices: movAvg = helpers.expMovingAvg(prePrices, .5) print('Done.')
def handler_exchanges_after_call(self, probability, messages_queue_fast): exchange_name = self.status.split("_")[1] mess = Message(self) if probability == self.player.skill_book and self.player.book.get_quantity( ) == 0: mess.set_text(message_book_empty) return mess.get_message() tiredness = self.player.is_tired() if tiredness[0]: if tiredness[1] is None: mess.set_text(message_tired_2) return mess.get_message() mess.set_text(message_tired_1.format(tiredness[1])) return mess.get_message() mess_timer = Message(self) mess_timer.set_text("✅ Ты готов к заключению новых сделок!") messages_queue_fast.add_message(mess_timer.get_message(), self.player.rest_time) if probability == self.player.skill_book: self.player.book.make_call() keyboard = VkKeyboard(one_time=False) keyboard.add_button(button_exchange_random, color=VkKeyboardColor.DEFAULT) keyboard.add_line() keyboard.add_button(button_exchange_book.format( self.player.book.get_quantity()), color=VkKeyboardColor.DEFAULT) keyboard.add_line() keyboard.add_button(button_exchange_buy_book, color=VkKeyboardColor.POSITIVE) keyboard.add_line() keyboard.add_button(button_go_back, color=VkKeyboardColor.PRIMARY) keyboard.add_button(button_go_to_menu, color=VkKeyboardColor.PRIMARY) mess.set_keyboard(keyboard) if success(probability): exchange = Exchange(exchange_name) message_success, commission, exp = exchange.new_deal(self.player) mess.set_text(message_success) self.player.money += commission message_level = self.player.level.add_exp(exp) mess.add_text(message_level) self.player.update_last_time_deal('success') return mess.get_message() else: mess.set_text(message_lost) self.player.update_last_time_deal('lost') return mess.get_message()
def __init__(self): """ """ self.config = Util.read_config() self.exchange = Exchange("binance", self.config["binance_api_key"], self.config["binance_api_secret"])
def main(script): exchange = Exchange() pairs = [] for k in exchange.get_markets(): if k['symbol'] is not None: pairs.append(k['symbol']) for pair in pairs: #print(pair) result = db.get_last_row_timestamp(pair) if result is None: last_row_timestamp = BINANCE_OPEN_DATE else: last_row_dt = result[1] last_row_dt = last_row_dt + datetime.timedelta(minutes=1) #print('Last row datetime = {}'.format(last_row_dt)) last_row_timestamp = int(time.mktime( last_row_dt.timetuple())) * 1000 try: data = exchange.get_ticker_history(pair, '1m', last_row_timestamp) except Exception as e: logger.error(e) df = parse_ticker_dataframe(data) db.write_market_data(df, pair)
def test_market_maker_trade_completed(self): # This test is too complicated! exchange = Exchange() exchange.add_client(MarketMaker()) exchange.do_trading() # Should be two orders at this point self.assertEqual(len(exchange.order_book()), 2) exchange.submit_order(Order('buy',100,exchange.OPEN_DEFAULT_PRICE * (1 + MarketMaker.MARGIN))) self.assertEqual(len(exchange.order_book()), 3) trades = exchange.match_orders() self.assertEqual(len(trades), 1) exchange.do_trading() # price should have gone up price, volume = exchange.last_trade() self.assertEqual(price, exchange.OPEN_DEFAULT_PRICE * (1 + MarketMaker.MARGIN/2)) # old mm orders should have been removed # new mm offers should be based on new price # check order prices and volumes self.assertEqual(len(exchange.order_book()), 2) expected_offer = price * (1 + MarketMaker.MARGIN/2) expected_bid = price * (1 - MarketMaker.MARGIN/2) self.assertEqual(exchange.buy_order_book()[0].price, expected_bid) self.assertEqual(exchange.sell_order_book()[0].price, expected_offer) self.assertEqual(exchange.buy_order_book()[0].quantity, MarketMaker.ORDER_QUANTITY) self.assertEqual(exchange.sell_order_book()[0].quantity, MarketMaker.ORDER_QUANTITY)
def test_exchange_constructor(): """Test the exchange class constructor with simple cases.""" binance = Exchange("binance") assert (binance is not None), "Binance was not constructed" assert (binance.wallet["USD"] == 0),\ "Binance should have wallet['USD'] == 0" assert (binance.name == "binance"), "Binance.name should equal 'binance'"
def test_trainer(self): batch_size = 3 length = 5 descriptors = torch.FloatTensor(self.config.nclasses, self.config.descriptor_dim).normal_() sender = Sender(self.config) sender.eval() receiver = Receiver(self.config) receiver.eval() exchange_model = ExchangeModel(self.config) baseline_sender = Baseline(self.config, 'sender') baseline_receiver = Baseline(self.config, 'receiver') exchange = Exchange(exchange_model, sender, receiver, baseline_sender, baseline_receiver, descriptors) trainer = Trainer(exchange) image = torch.FloatTensor(batch_size, self.config.image_in).normal_() target_dist = F.softmax(torch.FloatTensor( batch_size, self.config.nclasses).normal_(), dim=1) target = target_dist.argmax(dim=1) trainer_loss = trainer.run_step(image, target) self.assertEqual(trainer_loss.sender_message_loss.numel(), 1) self.assertEqual(trainer_loss.receiver_message_loss.numel(), 1) self.assertEqual(trainer_loss.stop_loss.numel(), 1) self.assertEqual(trainer_loss.baseline_loss_sender.numel(), 1) self.assertEqual(trainer_loss.baseline_loss_receiver.numel(), 1) self.assertEqual(trainer_loss.xent_loss.numel(), 1)
def test_composer(self): (Composer({ 'id': 'test_composer', 'from': ['source_1', 'source_2', 'source_3'], 'compose': lambda exchanges: ' and '.join( [exchange.get_body() for exchange in exchanges]), 'wait_for_all': True, }).assert_('test_composer_1', self.assertEqual, body(), 'foo and bar and wao')) #yapf: disable (To(composer('test_composer', 'source_1'))).send_to_sync(Exchange('foo')) (To(composer('test_composer', 'source_2'))).send_to_sync(Exchange('bar')) (To(composer('test_composer', 'source_3'))).send_to_sync(Exchange('wao'))
def session(self): exgs = self.wccxt.getallexchanges() df = pd.DataFrame() for exg in exgs: exchange = Exchange(exg) order_book = exchange.fetch_order_book() df.append(order_book) order_bookdf = pd.DataFrame(order_book) print("aa")
def __init__(self, agents, update_when_receiving=False): self.agents = agents self.last_market_price = 0.5 self.market_price = 0.5 self.best_belief = 0.5 self.idx_agent_receiving_evidence = -1 #This is always set to the last agent to receive evidence self.god = Agent() self.exchange = Exchange() self.update_when_receiving = update_when_receiving #Whlie receiving evidence, does the agent update belief based on change in market price?
def test_run(): exchange = Exchange() exchange.add_client(MarketMaker()) exchange.add_client(SimpleAlgo(order_gen)) for i in range(100): print 'Round: ', i exchange.do_trading() trades = exchange.match_orders() print exchange.last_trade()
def test_trade_placed_each_time_algo_is_called(self): # Given an algo object exchange = Exchange() algo = SimpleAlgo(order_gen) exchange.add_client(algo) # When it is executed exchange.do_trading() # A trade is added to the order book self.assertEqual(len(exchange.order_book()), 1)
def initialiseExchanges(self): """ Initialise exchanges, returns list of exchange objects """ for i in range(NUM_OF_EXCHANGES): self.exchanges[i] = Exchange( i, NUM_OF_COMPETITORS ) # NUM_OF_COMPETITORS may be changed to list of competitor objects that are participating self.exchangeOrderQs[i] = queue.Queue()
def test_exchange_deposit(): """Test the exchange class deposit funciton with simple cases.""" binance = Exchange("binance") binance.deposit("USD", 10) assert (binance.wallet["USD"] == 10),\ "Deposit of 10 should raise value to 10" binance.deposit("BTC", 5) assert (binance.wallet["BTC"] == 5), "Deposit of new currency should work." binance.deposit("USD", 1) assert (binance.wallet["USD"] == 11), "Multiple deposits should work."
def setUp(self): self.stock_100 = quick_mock_stock(100) self.stock_105 = quick_mock_stock(105) self.stock_110 = quick_mock_stock(110) self.stock_200 = quick_mock_stock(200) # basic stocks and exchange combo for tests self.basic_stocks = {"100": self.stock_100, "105": self.stock_105} self.basic_exchange = Exchange("TESTEX", self.basic_stocks)
def update_table(connection, table_name='currency_rate'): """ updating whole table :param table_name: :param connection: :return: """ exch = Exchange() for code, rate in exch.all_rates.items(): update_record(connection, code, rate, table_name)
def __init__(self, name, addr, balance, base_cur, desired_cur): self.name = name self.exchange = Exchange(name, addr, balance) self.book = OrderBook(base_cur, desired_cur) self.exchange.book = self.book self.graph = Graph(self.exchange) self.traders = {} self.html = '' self.display_graph = False self.clearing_price = np.random.uniform(20, 50) self.first_time = True
def test_cache(self): from cachetools import LRUCache (RouteId('test_cache_request') .process(set_header('process_flag', True)) .process(set_body('response'))) #yapf: disable route = (Any().to(cache({ 'to': To(direct('test_cache_request')), 'keys': [header('key')], 'cache_object': LRUCache(maxsize=1000) })))#yapf: disable ex1 = route.send_to_sync(Exchange(header={'key': 'foo'})) self.assertEqual(ex1.get_body(), 'response') self.assertEqual(ex1.get_header('process_flag'), True) ex2 = route.send_to_sync(Exchange(header={'key': 'foo'})) self.assertEqual(ex2.get_body(), 'response') self.assertEqual(ex2.get_header('process_flag'), None) ex3 = route.send_to_sync(Exchange(header={'key': 'bar'})) self.assertEqual(ex3.get_body(), 'response') self.assertEqual(ex3.get_header('process_flag'), True)
def test_direct(self): (RouteId('test_direct') .process(set_body('test_direct_success'))) #yapf: disable ((Any() .assert_('test_direct_0', self.assertEqual, body(), 'boo') .to(direct('test_direct')) .assert_('test_direct_1', self.assertEqual, body(), 'test_direct_success')) ).send_to_sync(Exchange('boo')) #yapf: disable (RouteId('test_direct_blank')) ((Any() .to(direct('test_direct_blank')) .assert_('test_direct_blank_1', self.assertEqual, body(), 'bar')) ).send_to_sync(Exchange('bar')) #yapf: disable (RouteId('test_direct_nest_first').to(direct('test_direct_nest_second'))) #yapf: disable (RouteId('test_direct_nest_second').to(direct('test_direct_nest_third'))) #yapf: disable (RouteId('test_direct_nest_third').process(set_body('nest_success'))) #yapf: disable ((Any().to(direct('test_direct_nest_first')) .assert_('test_direct_nest_0', self.assertEqual, body(), 'nest_success')) ).send_to_sync() #yapf: disable
def test_no_current_orders(self): exchange = Exchange() exchange.add_client(MarketMaker()) exchange.do_trading() # check order prices and volumes self.assertEqual(len(exchange.order_book()), 2) expected_offer = exchange.OPEN_DEFAULT_PRICE * (1 + MarketMaker.MARGIN/2) expected_bid = exchange.OPEN_DEFAULT_PRICE * (1 - MarketMaker.MARGIN/2) self.assertEqual(exchange.buy_order_book()[0].price, expected_bid) self.assertEqual(exchange.sell_order_book()[0].price, expected_offer) self.assertEqual(exchange.buy_order_book()[0].quantity, MarketMaker.ORDER_QUANTITY) self.assertEqual(exchange.sell_order_book()[0].quantity, MarketMaker.ORDER_QUANTITY)
def insert_all_records(connection, table_name='currency_rate'): """ creating all record in currency rate table :param connection: :param table_name: :return: """ exch = Exchange() for code, rate in exch.all_rates.items(): pars = (code, rate) insert_record(connection, pars, table_name)
def execute(self): """ :rtype: object """ keys = Util.get_api_params() self.__set_params() self.market = Exchange(self.market_name, keys[self.market_name]["apiKey"], keys[self.market_name]["apiSecret"]) print(self.__call_market_function())
def __init__(self, data, cash=10000, commission=0.0005, fast=30, slow=90): self.sma1 = [] self.sma2 = [] self._data = data self._cash = cash self._commission = commission self._fast = fast self._slow = slow self._results = {} # Define and initialize objects of Exchange and SmaCross. self._broker = Exchange(data, cash, commission) self._strategy = SmaCross(self._broker, data, fast, slow) self.values = self._broker.values
def test_exchange_trade(): """Test the exchange class trade funciton with simple cases.""" binance = Exchange("binance") binance.deposit("USD", 10) assert (binance.trade("USD", "USD", 1, 1)), "This is a valid trade." assert (binance.wallet["USD"] == 10), "Trade shouldn't have changed value" assert (not binance.trade("USD", "USD", 11, 11)), "Amount too large." assert (binance.trade("USD", "BTC", 5, 1)),\ "Should be able to trade to new." assert (binance.wallet["USD"] == 5), "Trades should reduce fromCurrency." assert (binance.wallet["BTC"] == 1), "Trades should increase toCurrency." assert (binance.trade("BTC", "USD", 1, 1)), "Should be able to trade back." assert (binance.wallet["BTC"] == 0), "Should go to zero."