def __init__(self, manager): Exchange.__init__(self, manager) self.name = 'chbtc' self.tick_url = 'http://api.chbtc.com/data/ticker' self.depth_url = 'http://api.chbtc.com/data/depth' self.trade_url = 'http://api.chbtc.com/data/getTrades' self.tick_query = '''INSERT IGNORE INTO bitcoin_ticker (exchange, ticker, requested, received, bid, ask, low, high, last, vol) VALUES ('{}', '{}', {}, {}, {}, {}, {}, {}, {}, {})'''
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 __init__(self): Exchange.__init__(self) self.name = 'Bitfinex' self.trading_fee = 0.0015 self.transfer_fee = 0 self.logger = logging.getLogger('BitBot.Bitfinex')
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 on_enter_Exchange(self, event): # TODO: обработать биржу print('Желаете торговать на бирже (y/n)? ==> ') exchange = Exchange() while exchange.state != 'End': exchange.step() self.is_crisis = True
def __init__(self): """ """ self.config = Util.read_config() self.exchange = Exchange("binance", self.config["binance_api_key"], self.config["binance_api_secret"])
def __init__(self, manager): Exchange.__init__(self, manager) self.name = 'okcoin' self.tick_url = 'https://www.okcoin.com/api/ticker.do?symbol={}' self.depth_url = 'https://www.okcoin.com/api/depth.do?symbol={}' self.trade_url = 'https://www.okcoin.com/api/trades.do?symbol={}' self.tick_query = '''INSERT IGNORE INTO bitcoin_ticker (exchange, ticker, requested, received, bid, ask, low, high, last, vol) VALUES ('{}', '{}', {}, {}, {}, {}, {}, {}, {}, {})'''
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 __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 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!")
class BitfinexExchange(): def __init__(self): self.exchange = ccxt.bitfinex() # 创建交易所,此处为okex交易所 self.exchange.apiKey = apikey.bitfinex_apiKey_ro # 此处加上自己的apikey和secret,都需要开通交易权限 self.exchange.secret = apikey.bitfinex_secret_ro self.source_exchange = Exchange(self.exchange) def fetch_ticker(self, symbol): return self.source_exchange.fetch_ticker(symbol) def fetch_trades(self, symbol, since, limit): trades = self.source_exchange.fetch_trades(symbol, since=since, limit=limit) for t in trades: t['symbol'] = t['symbol'] t['price'] = t['info']['price'] t['amount'] = t['info']['amount'] t['side'] = t['info']['type'] return trades def fetch_last_price(self, symbol): ticker = self.source_exchange.fetch_ticker(symbol) return float(ticker['info']['last_price']) def fetch_order_book(self, symbol, limit): return self.source_exchange.fetch_order_book(symbol, limit)
class BestAsset: def __init__(self, period): self.period = period self.statistics = Statistics(default="USDT") self.exchange = Exchange(default="USDT") self.currentAssetSymbol = None def best_asset(self): try: ticker_range = ["BTC", "ETH", "NEO", "BNB", "LTC", "BCH"] best_asset_symbol = self.statistics.get_best_asset( self.period, ticker_range) if best_asset_symbol != self.currentAssetSymbol: # Print on console best asset print("Best Asset: %s" % best_asset_symbol) # Sell all assets self.exchange.sell_all_assets() # Buy best asset self.exchange.buy_asset(best_asset_symbol) # Set new current asset self.currentAssetSymbol = best_asset_symbol except Exception as e: print(e) pass def run(self): print("Strategy Best Asset %s" % self.period.value) while True: self.best_asset() time.sleep(10) # Sleep 10 seconds
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 __init__(self): Exchange.__init__(self, "KRAKEN") self.conn = Connection() self.api = API() self.price_decimals = dict() self.lot_decimals = dict() self.api.load_key('kraken.keys') self.pair_name_map = {} with open('kraken_info.json') as f: self.tickers = json.loads(f.read())['result'].items() self.symbols = [ 'USD', 'BTC', 'ETH', 'LTC', 'BCH', 'XMR', 'XRP', 'XLM', 'ADA', 'ATOM' ] for pair, info in self.tickers: if '.' in pair: # some duplicate entries have a period, unsure why continue token = symbol_from_kraken(info['base']) currency = symbol_from_kraken(info['quote']) if token in self.symbols and currency in self.symbols: uniform_ticker = "%s-%s" % (token, currency) self.pair_name_map[uniform_ticker] = pair self.fees[uniform_ticker] = FEES[self.name].taker self.price_decimals[uniform_ticker] = info['pair_decimals'] self.lot_decimals[uniform_ticker] = info['lot_decimals']
def __init__(self, manager): Exchange.__init__(self, manager) self.name = 'bitstamp' self.tick_url = 'https://www.bitstamp.net/api/ticker/' self.depth_url = 'https://www.bitstamp.net/api/order_book/' self.trade_url = 'http://www.bitstamp.net/api/transactions?time=minute' self.tick_interval = 2 self.depth_interval = 20
def __init__(self, manager): Exchange.__init__(self, manager) self.trade_interval = 10 self.depth_interval = 10 self.name = 'btcchina' self.tick_url = 'https://data.btcchina.com/data/ticker?market={}' self.depth_url = 'https://data.btcchina.com/data/orderbook?market={}' self.trade_url = 'http://data.btcchina.com/data/historydata?market={}' self.tick_query = '''INSERT IGNORE INTO bitcoin_ticker (exchange, ticker, requested, received, bid, ask, low, high, last, vol) VALUES ('{}', '{}', {}, {}, {}, {}, {}, {}, {}, {})'''
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")
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 __init__(self, manager): Exchange.__init__(self, manager) self.name = 'mtgox' self.tick_url = 'http://data.mtgox.com/api/1/{}/ticker' self.depth_url = 'http://data.mtgox.com/api/2/{}/money/depth/fetch' self.trade_url = 'https://data.mtgox.com/api/2/{}/money/trades' self.depth_query = '''INSERT IGNORE INTO {} (ticker, requested, received, timestamp, bid, ask, bids, asks) VALUES ('{}', {}, {}, {}, {}, {}, '{}', '{}')''' self.depth_interval = 15
def __init__(self, manager): Exchange.__init__(self, manager) self.depth_interval = 10 self.name = 'bitfinex' self.tick_url = 'https://api.bitfinex.com/v1/ticker/{}' self.depth_url = 'https://api.bitfinex.com/v1/book/{}' self.trade_url = 'https://api.bitfinex.com/v1/trades/{}' self.tick_query= '''INSERT IGNORE INTO bitcoin_ticker (exchange, ticker, requested, received, timestamp, bid, ask, last) VALUES ('{}', '{}', {}, {}, {}, {}, {}, {})''' self.last_trade_query = '''SELECT MAX(timestamp) FROM {} WHERE ticker = '{}' '''
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 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, manager): Exchange.__init__(self, manager) self.name = 'fxbtc' self.depth_interval = 15 self.tick_interval = 2 self.tick_url = 'https://data.fxbtc.com/api?op=query_ticker&symbol={}' self.depth_url = 'https://data.fxbtc.com/api?op=query_depth&symbol={}' self.trade_url = 'https://data.fxbtc.com/api?op=query_history_trades&symbol={}' self.tick_query = '''INSERT IGNORE INTO bitcoin_ticker (exchange, ticker, requested, received, bid, ask, low, high, last, vol)
def x_get_candlesticks(self, timeframe="1h", size="5m", dateOffset="now()"): self.timeframe = timeframe self.cssize = size points = self.influxdb.raw_query( """select LAST(basevolume) as basevolume, LAST(volume) as volume, FIRST(last) as open, LAST(last) as closed, MAX(last) as high, MIN(last) as low FROM "market_summary" WHERE marketname='{0}' and time < {1} and time > {1} - {2} group by time({3})""" .format(self.market, dateOffset, timeframe, size)).get_points() cs = self.clear_candlesticks() psize = 0 for point in points: psize += 1 cs["low"].extend([point["low"]]) cs["high"].extend([point["high"]]) cs["closed"].extend([point["closed"]]) cs["open"].extend([point["open"]]) cs["volume"].extend([point["volume"]]) cs["basevolume"].extend([point["basevolume"]]) cs["time"].extend([point["time"]]) if psize == 0: raise Exception("no market data for {} at {}".format( self.market, dateOffset)) def fix_gaps(lst): for idx, val in enumerate(lst): if val == None: if idx > 0: lst[idx] = lst[idx - 1] if idx == 0: lst[idx] = 0 fix_gaps(cs["low"]) fix_gaps(cs["high"]) fix_gaps(cs["closed"]) fix_gaps(cs["open"]) fix_gaps(cs["volume"]) fix_gaps(cs["basevolume"]) fix_gaps(cs["time"]) self.cs = { "low": numpy.array(cs["low"]), "high": numpy.array(cs["high"]), "closed": numpy.array(cs["closed"]), "volume": numpy.array(cs["volume"]), "basevolume": numpy.array(cs["basevolume"]), "open": numpy.array(cs["open"]), "time": cs["time"] } Exchange.getInstance().set_market_value(self.market, self.cs["closed"][-1]) return self.cs
def __init__(self): Exchange.__init__(self, 'BITFLYER') with open('bitflyer.keys') as secrets_file: secrets = json.load(secrets_file) self.api = API(str(secrets['key']), str(secrets['secret']), timeout=5) self.symbols = ['USD', 'BTC'] self.fees['BTC-USD'] = FEES[self.name].taker
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)
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())
class BestAssetTest: 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 best_asset(self): try: ticker_range = ["BTC", "ETH", "NEO", "BNB", "LTC", "BCH"] best_asset_symbol = self.statistics.get_best_asset( self.period, ticker_range) if best_asset_symbol != self.current_asset_symbol: if self.current_asset_symbol is not None: current_price = self.exchange.get_asset_price( self.current_asset_symbol) print(current_price) percentage = (float(current_price) - float( self.buyPrice)) / float(self.buyPrice) * 100 print( "Selling asset %s at %s with percentage %s" % (self.current_asset_symbol, current_price, percentage)) file_name = "output_%s.csv" % self.period.value file = open(file_name, 'a') try: writer = csv.writer(file) writer.writerow( (self.current_asset_symbol, self.buyPrice, current_price, percentage)) finally: file.close() if best_asset_symbol is not None: self.buyPrice = self.exchange.get_asset_price( best_asset_symbol) print("Buying asset %s at %s" % (best_asset_symbol, self.buyPrice)) # Set new current asset self.current_asset_symbol = best_asset_symbol except Exception as e: print(e) pass def run(self): print("[TEST] Strategy Best Asset %s" % self.period.value) while True: self.best_asset() time.sleep(10) # Sleep 10 seconds
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
async def exchange_amount(message: types.Message): try: float(message.text) except: await message.reply( 'The entered value must be numeric, please try again', reply=False) else: Exchange.put_numeric(message.text) await message.reply('To exchange select the base currency', reply=False, reply_markup=keyboard2)
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 __init__(self, api_key, api_secret): # 取引所インスタンスへAPIキー・SECRETをセット self.exchange = Exchange(api_key=api_key, api_secret=api_secret) self.exchange.product_code = 'FX_BTC_JPY' self.exchange.minute_to_expire = 1 # タスクの設定及びイベントループの開始 loop = asyncio.get_event_loop() tasks = asyncio.gather( self.exchange.subscribe(self.realtime), self.trade(), ) loop.run_until_complete(tasks)
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_all_share_index_realistic(self): # More realistic case, spread of stock values stocks = { "100": self.stock_100, "105": self.stock_105, "110": self.stock_110, "200": self.stock_200 } exchange = Exchange("TESTEX", stocks) all_share_index = exchange.calculate_all_share_index() self.assertAlmostEqual(all_share_index, 123.283, places=3) # note rounding.
def index(): title = "Download CSV HMRC Exchange Rates" view_base = 'index/' x = Exchange() years = range(x.earliest_year, x.latest_year + 1) currencies = x.available_currencies() return render_template(view_base + 'main.html', title=title, years=years, currencies=currencies)
def __init__(self): self.exchange = Exchange(exchange_id=config.API_DETAILS['EXCHANGE_ID'], api_key=config.API_DETAILS['API_KEY'], api_secret=config.API_DETAILS['API_SECRET']) self.order_id = "" self.market = config.OPTIONS["SYMBOL"] self.type = "sell" self.starting_price = float(config.OPTIONS["STARTING_PRICE"]) self.percentage = float(config.OPTIONS["PERCENTAGE"]) self.interval = 1 self.running = False self.stoploss = self.initialize_stop() self.amount = self.exchange.get_balance(self.market.split("/")[0])
def __init__(self): Exchange.__init__(self, 'ITBIT') with open('itbit.keys') as secrets_file: secrets = json.load(secrets_file) self.api = itBitApiConnection(secrets['key'], secrets['secret'], secrets['userId']) self.symbols = ['USD', 'BTC', 'ETH'] self.fees['BTC-USD'] = FEES[self.name].taker self.fees['ETH-USD'] = FEES[self.name].taker wallets = self.api.get_all_wallets().json() assert (len(wallets) == 1) self.wallet_id = self.api.get_all_wallets().json()[0]['id']
def __init__(self): Exchange.__init__(self, 'GDAX') with open('gdax.keys') as secrets_file: secrets = json.load(secrets_file) self.api = gdax.AuthenticatedClient(secrets['key'], secrets['secret'], secrets['passphrase']) self.symbols = ['USD', 'BTC', 'ETH', 'LTC', 'BCH'] for ticker in PAIRS: if ticker.startswith('LTC') or ticker.startswith('ETH'): self.fees[ticker] = Decimal('0.003') else: self.fees[ticker] = FEES[self.name].taker
class Backtest: 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 run(self): """ Simulate the transaction with the price data "Close"; -- Get the price of current tick by broker; -- Calculate with the strategy at current tick. """ # Initialize the strategy to get sma1 and sma2. self._strategy.init() self.sma1 = self._strategy.sma1 self.sma2 = self._strategy.sma2 # specify the start and end point of the simulation process. start = self._slow + 1 end = len(self._broker.values) # Increase the tick by one at each iteration. for i in range(start, end): # Update the value of tick and get current price. self._broker.next(i) # Execute the strategy. self._strategy.next(i) # Record computing results in a dictionary. self._results['Commission:'] = self._commission self._results['SMA1 window size:'] = self._fast self._results['SMA2 window size:'] = self._slow self._results['Initial value:'] = self._broker.initial_cash self._results['Final value:'] = self._broker.market_value self._results['Transaction frequency:'] = self._strategy.count self._results[ 'Profit:'] = self._broker.market_value - self._broker.initial_cash return self._results def print_results(self): for k, v in self._results.items(): print(' ', k, v)
def main() -> None: """ Create an exchange and a trading bot with a strategy. Run the strategy once on a particular symbol. """ # create the exchange and connect to it exchange = Exchange() exchange.connect() # create the trading strategy trading_strategy = MinMaxTradingStrategy(min_price=31000, max_price=34000) # create the trading bot and run the bot once bot = TradingBot(exchange, trading_strategy) bot.run("BTC/USD")
def test_market_maker_price(self): # scenario: check that marker maker prices are based on order book prices exchange = Exchange() # given an order book with a buy order with price 10.0 exchange.current_client = 99 exchange.submit_order(Order('buy',100,10.0)) # and the market maker is a client of the exchange exchange.add_client(MarketMaker()) # when do_trading is called exchange.do_trading() # the order book contains a buy order with price 10.0 - MARGIN/2 # and the original buy at 10.0 self.assertEqual(exchange.buy_order_book(), [Order('buy',100,10.0), Order('buy',100,10.0 * (1 - MarketMaker.MARGIN/2))]) # and a sell order with price 10 + MARGIN/2 self.assertEqual(exchange.sell_order_book(), [Order('sell',100,10.0 * (1 + MarketMaker.MARGIN/2))])
def __init__(self): self.ex = Exchange() self.positions = self.ex.position[ "symbols"] # format = [{"symbol": "DD", "position": N}, ] self.company_info = {} self.value = self.ex.position["cash"] for entry in self.positions: self.company_info[entry["symbol"]] = { "position": int(entry["position"]), "total": 0 }
def __init__(self): Exchange.__init__(self) self.name = 'Btce' self.trading_fee = 0.002 self.transfer_fee = 0.001 self.nonce = 1 self.logger = logging.getLogger('BitBot.BTCE') #Find the correct nonce parameter print 'Computing correct nonce parameter' params = { 'method' : 'getInfo', 'nonce' : self.nonce } params = urllib.urlencode(params) H = hmac.new(keys.BTCE_API_SECRET_KEY, digestmod=hashlib.sha512) H.update(params) sign = H.hexdigest() headers = { 'Content-type' : 'application/x-www-form-urlencoded', 'Key' : keys.BTCE_API_KEY, 'Sign' : sign } req = urllib2.Request(BTCE.private_url, params, headers) res = urllib2.urlopen(req) res = json.load(res) error = res['error'] error = error.split(' ') for word in error: if 'key' in word: n = word.replace('key', '') n = n.replace(':', '') n = n.replace(',', '') self.nonce = int(n)
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 __init__(self): Exchange.__init__(self) self.cbx_extern = CampBX(keys.CAMPBX_LOGIN, keys.CAMPBX_PASS) self.cbx_extern.debug_mode(True) self.name = "CampBX"
def __init__(self, manager): Exchange.__init__(self, manager) self.name = '796' self.tick_query = '''INSERT IGNORE INTO bitcoin_ticker (exchange, ticker, requested, received, bid, ask, low, high, last, vol) VALUES ('{}', '{}', {}, {}, {}, {}, {}, {}, {}, {})''' self.depth_interval = 10
from exchange import Exchange if __name__ == '__main__': app = Exchange() app.run("127.0.0.1", 8888) """ app = Exchange() router = app.Router() router.post("/login", loginRouter) router.get("/Submit", submitRouter) app.use(router) app.staticDir(__name__) app.use(CSRFMiddle, "middleware") app.run("127.0.0.1", 8888) """
#!/usr/bin/python import gc from exchange import Exchange import logging from settings import ENDPOINT_LIST, EVENT_ENDPOINT, BALANCE_TO, LOG_LEVEL if __name__ == '__main__': logging.basicConfig( level=LOG_LEVEL, format='%(asctime)-15s %(levelname)s %(message)s') x = Exchange(ENDPOINT_LIST , EVENT_ENDPOINT, BALANCE_TO) x.start()
def __init__(self, manager): Exchange.__init__(self, manager) self.name = 'huobi' self.btc_url = 'http://market.huobi.com/staticmarket/detail.html' self.ltc_url = 'http://market.huobi.com/staticmarket/detail_ltc.html' self.tick_query = '''INSERT IGNORE INTO bitcoin_ticker (exchange, ticker, requested, received, bid, ask, low, high, last, vol) VALUES ('{}', '{}', {}, {}, {}, {}, {}, {}, {}, {})'''
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)
class Bot: def __init__(self): self.ex = Exchange() self.positions = self.ex.position[ "symbols"] # format = [{"symbol": "DD", "position": N}, ] self.company_info = {} self.value = self.ex.position["cash"] for entry in self.positions: self.company_info[entry["symbol"]] = { "position": int(entry["position"]), "total": 0 } def buy_to_even(self): for k, ex in self.company_info.items(): if ex["position"] < 0 and self.determine_fp_confidence(ex) > 50: fair_price = self.determine_fair_price(ex) buy_price = int(fair_price - 5) number = abs(ex["position"]) expected_cost = number * buy_price self.ex.trade("BUY", k, buy_price, number) self.company_info[k]["position"] = 0 self.value -= expected_cost def buy_below_fp(self, limit=100000): for k, ex in self.company_info.items(): fair_price = self.determine_fair_price(ex) buy_price = int(fair_price - 10) number = randint(1, 10) expected_cost = number * buy_price if abs(self.value - expected_cost) < limit: print("buy", k, "for", buy_price) self.ex.trade("BUY", k, buy_price, number) self.company_info[k]["position"] += number self.company_info[k]["total"] += self.value -= buy_price def determine_fp_confidence(self, company_dict): if "sell" not in company_dict or "buy" not in company_dict: return -1 return len(company_dict["sell"]) + len(company_dict["buy"]) def determine_fair_price(self, company_dict): # total_buy_price = sum(o[0] * o[1] for o in company_dict["buy"]) # total_buy_shares = sum(o[1] for o in company_dict["buy"]) # total_sell_price = sum(o[0] * o[1] for o in company_dict["sell"]) # total_sell_shares = sum(o[1] for o in company_dict["sell"] if "sell" not in company_dict or "buy" not in company_dict: return -1 min_sell = min(o[0] for o in company_dict["sell"]) max_buy = max((o[0] for o in company_dict["buy"]), default=0) return (max_buy + min_sell) / 2 def sell_everything(self): for k, dic in self.company_info.items(): fair_price = int(self.determine_fair_price(dic)) if dic["position"] > 0 and fair_price != -1: self.ex.trade("SELL", k, fair_price, dic["position"]) self.company_info[k]["position"] = 0 def run(self): loop_counter = 0 while True: line = self.ex.get_next() if "type" in line and line["type"] == "book": sym = line["symbol"] if sym not in self.company_info or "buy" not in self.company_info[sym]: self.company_info[sym]["buy"] = [] self.company_info[sym]["sell"] = [] self.company_info[sym]["buy"] += line["buy"] self.company_info[sym]["sell"] += line["sell"] else: print(line) if loop_counter % 10 == 0: # self.buy_to_even() self.buy_below_fp() # self.sell_everything() loop_counter += 1 time.sleep(0.1)
def __init__(self): Exchange.__init__(self, exchange='exchange-001', type='fanout') self.bind()
def __init__(self, manager): Exchange.__init__(self, manager) self.name = 'btce' self.tick_url = 'https://btc-e.com/api/2/{}/ticker' self.depth_url = 'http://btc-e.com/api/2/{}/depth' self.trade_url = 'http://btc-e.com/api/2/{}/trades'
def __init__(self): Exchange.__init__(self, exchange='exchange_001', type='direct') self.routing = sys.argv[1] self.bind()
import time from exchange import Exchange from config import config def queue_callback(message, is_redelivered): print '================================================' print '================================================' print 'message received' print '================================================' print message time.sleep(config['PROCESS_EXEC_TIME']) response = {} response['success'] = config['PROCESS_EXEC_RETURN'] return response if __name__ == '__main__': exConfig = {} exConfig['DEFAULT_EXCHANGE'] = 'test.exchange' requeueOnFailure = config['REQUEUE_ON_FAILURE'] exchange = Exchange(config['URL'], config['LISTEN_QUEUE'], queue_callback, requeueOnFailure, config) exchange.run()