def get_the_money_you_shall_spend(depth,target_coin,target_amount): ''' :param depth: :param target_coin: :param target_amount: :return: ''' cp1=CP.CurrencyPair() currency_pair=depth.currency_pair base_currency=cp1.get_base_currency(currency_pair) money_we_shall_spend=0 current_amount=0 if target_coin.name==base_currency: # we just buy it for ask in depth.asks: amount=ask.amount price=ask.price if current_amount+amount>=target_amount: money_we_shall_spend+=price*(target_amount-current_amount) break else: money_we_shall_spend+=amount*price current_amount+=amount else: for bid in depth.bids: amount=bid.amount price=bid.price amount_in_this_level=price*amount if current_amount+amount_in_this_level<target_amount: money_we_shall_spend+=amount target_amount+=current_amount else: money_we_shall_spend+=(target_amount-current_amount)/price break return money_we_shall_spend
def determine_best_currency_pairs(self, top_n=10): ''' we should consider the trading volume, which has a weight of 20%, of the last 600 trades we should consider the depth gap, which has a weight of 20%, of the last 10 seconds snapshot we should consider the :param top_n: :return: ''' # get all currency pair trading vol of last 600 trades using ticker method: from packages import currency_pair as cp all_currency_pairs = self.get_all_currency_pairs() # get the ratio of ref1 to usdt cp1 = cp.CurrencyPair() referencial_currencies = cp1.get_referencial_currencies("okex") prices_of_referencial_currencies = {} for currency in referencial_currencies: if currency != "usdt": ticker = self.ticker(currency + "_usdt") price = ticker.last prices_of_referencial_currencies[ticker.currency_pair] = price currency_pair_trading_vol_list = {} for currency_pair in all_currency_pairs: trades = self.trades(currency_pair) buy_volume_in_past_2_minute = 0 sell_volume_in_past_2_minute = 0 total_volume_in_past_2_minute = 0 for trade in trades.trades: trade_type = trade.trade_type timestamp = trade.timestamp if int(time.time()) - timestamp <= 120: if trade_type == 1: buy_volume_in_past_2_minute += trade.amount else: sell_volume_in_past_2_minute += trade.amount total_volume_in_past_2_minute += trade.amount # print(buy_volume_in_past_600_trades,sell_volume_in_past_600_trades) max_vol = max(sell_volume_in_past_2_minute, buy_volume_in_past_2_minute) min_vol = min(sell_volume_in_past_2_minute, buy_volume_in_past_2_minute) if total_volume_in_past_2_minute != 0 and min_vol / max_vol > 0.5 and min_vol / max_vol < 2: ratio_of_referencial_currency_to_usdt = 1 referencial_currency = cp1.get_referencial_currency( currency_pair) ratio_of_currency_to_referencial_currency = trades.trades[ -1].price if referencial_currency != "usdt": ratio_of_referencial_currency_to_usdt = prices_of_referencial_currencies[ referencial_currency + '_usdt'] turn_vol = total_volume_in_past_2_minute * ratio_of_currency_to_referencial_currency * ratio_of_referencial_currency_to_usdt currency_pair_trading_vol_list[currency_pair] = turn_vol currency_pair_trading_vol_list = sorted( currency_pair_trading_vol_list.items(), key=lambda x: x[1], reverse=True) a = 1
def get_the_quantity_of_coin_you_can_buy(depth,buy_target,coin): cp1=CP.CurrencyPair() currency_pair=depth.currency_pair base_currency=cp1.get_base_currency(currency_pair) quantity_of_coin=copy.copy(coin.quantity) referencial_currency=cp1.get_referencial_currency(currency_pair) total_amount_we_can_buy=0 if buy_target==base_currency: # means we just buy buy_target is OK for ask in depth.asks: total_money_they_ask=ask.price*ask.amount if quantity_of_coin>=total_money_they_ask: amount_we_can_buy=ask.amount quantity_of_coin-=total_money_they_ask else: amount_we_can_buy=quantity_of_coin/ask.price quantity_of_coin=0 total_amount_we_can_buy+=amount_we_can_buy if quantity_of_coin==0: break else: # means that we should sell the for bid in depth.bids: total_money_they_bid=bid.price*bid.amount total_coins_they_bid=bid.amount if quantity_of_coin>=total_coins_they_bid: amount_we_can_buy=bid.amount*bid.price quantity_of_coin-=total_money_they_bid else: amount_we_can_buy=quantity_of_coin*bid.price quantity_of_coin=0 total_amount_we_can_buy+=amount_we_can_buy if quantity_of_coin==0: break return total_amount_we_can_buy*(1-FEE1)
def get_all_currency_pairs(self): from packages import currency_pair currencies = self.get_all_currencies() references = currency_pair.CurrencyPair().get_referencial_currencies( "okex") currency_pairs = [] for reference in references: for currency in currencies: if str(currency).lower() != str(reference).lower(): currency_pairs.append(str(currency) + "_" + str(reference)) return currency_pairs
def get_currency_pair_order(self, top_n=10, ordered_by="trading volume"): ''' this method returns a list of currency pairs ordered by trading volume :param top_n: how many currency pairs you want to list :param ordered_by: either of 'trading volume', 'market cap', 'price', etc. :return: a list of currency pairs ordered by trading volume ''' # get all the currency pairs: from packages import currency_pair as cp all_currency_pairs = self.get_all_currency_pairs() # get the ratio of ref1 to usdt cp1 = cp.CurrencyPair() referencial_currencies = cp1.get_referencial_currencies("okex") prices_of_referencial_currencies = {} for currency in referencial_currencies: if currency != "usdt": ticker = self.ticker(currency + "_usdt") price = ticker.last prices_of_referencial_currencies[ticker.currency_pair] = price tickers = [] turn_volumes = {} for currency_pair in all_currency_pairs: referencial_currency = cp1.get_referencial_currency( str(currency_pair)) time.sleep(0.1) ticker = self.ticker(currency_pair) if referencial_currency != "usdt": if ticker.message == "True" or "'操作成功'": turn_volume = ( ticker.high + ticker.low ) * ticker.vol * prices_of_referencial_currencies[ referencial_currency + "_usdt"] / 2 turn_volumes[ticker.currency_pair] = turn_volume else: if ticker.message == "True" or "'操作成功'": turn_volume = (ticker.high + ticker.low) * ticker.vol * 1 / 2 turn_volumes[ticker.currency_pair] = turn_volume turn_volumes = sorted(turn_volumes.items(), key=lambda x: x[1], reverse=True) return turn_volumes[:top_n - 1]
def if_price_changed(): pass if len(sys.argv) > 2: currency_pair = sys.argv[2] account_name = sys.argv[1] else: currency_pair = 'btc_usdt' account_name = 'c008' account = account.Account(account_name) okex1 = okex.OKEx(account) cp1 = CP.CurrencyPair() coin = cp1.get_base_currency(currency_pair) reference = cp1.get_referencial_currency(currency_pair) def main(arg): MUL_CONSTANT = 1 previous_bid = 0 previous_ask = 99999 my_info = okex1.balances() ask_order = None bid_order = None account.set_balance(my_info)
import time import requests import json from packages import liquid as LIQUID from packages import kraken as KRAKEN from packages import account as ACCOUNT from packages import currency_pair as CURRENCYPAIR from packages import universal as UNIVERSAL # pgmanager from packages import db as DB import CONSTANTS pgmanager = DB.PGManager(**CONSTANTS.DB_CONNECT_ARGS_LOCAL) currency_pair = CURRENCYPAIR.CurrencyPair() def get_rows(sql): return pgmanager.select(sql) def combine_trades_by_timestamp(rows): trades = [] current_timestamp = rows[0][3] current_price = rows[0][5] current_amount = rows[0][6] current_trade_type = rows[0][4] rows_len = len(rows) cnt = 1 trade = UNIVERSAL.TradeInfo(current_timestamp, current_price, current_amount, current_trade_type)
from packages import okex as OKEX from packages import currency_pair as CP okex=OKEX.Okex(None) cp=CP.CurrencyPair('btc','usdt') trades=okex.trades(currency_pair=cp) a=1
from packages import binance as B from packages import currency_pair as CP from packages import account as ACC import time account = ACC.Account( 'gBAyXDQx4SWJ1FKI5cG4xaYJVwTNnMWUVcrvHjNVAKjxmt0JrpLpowQ85Kg49Ak9', 'EZaHgc67HCNeniUGiLbTBHZJyYsq5MyVPuwOugXUSeTz1mKma1wWaPm3yTeAN7En') binance = B.Binance(account) trades = binance.trades(CP.CurrencyPair()) starting_timestamp = 0 ending_timestamp = time.time() while starting_timestamp < ending_timestamp: pass a = 1
'c6d6a4b051b36e373bb47eede7c1675d05d12cfa0') digifinex = DIGIFINEX.DigiFinex(account) color = CL.Colored() coins = [] coin0 = CN.Coin('btc', 1, 0.01) coin1 = CN.Coin('cny', 1, 900) coin2 = CN.Coin('usdt', 1, 128) coins.append(coin0) coins.append(coin1) coins.append(coin2) btc = coin0 cny = coin1 usdt = coin2 pairs = [ CP.CurrencyPair('btc', 'cny'), CP.CurrencyPair('btc', 'usdt'), CP.CurrencyPair('usdt', 'cny'), ] money_reserved = {'btc': 0.01, 'cny': 900, 'usdt': 128} # ----------------------------------------------------------------------------------------- # assume we have c0 c1 c2, each of which has a quantity q0 q1 q2 # we should re-buy c0,c1,c2 in different market/pair at possible low price: # the c0 we can buy at different markets are: # you can only buy c0 by selling c2 in pairs[2] or selling c1 in pairs[0]: # so the quantities of c0 you can buy are: # f(depths[2],buy='c0',q2)---->in pairs[2] # f(depths[0],buy='c0',q1)---->in pairs[0] # the quantities of c1 you can buy are::
''' # coding=utf-8 from packages import account as AC, currency_pair from OKEx import okex from apscheduler.schedulers.blocking import BlockingScheduler import time # CONSTANTS: FEE0 = -0.001 FEE1 = 0.002 market = "OKEx" account = AC.Account("c008") okex1 = okex.OKEx(account) currency_pair_of_bch_usdt = currency_pair.CurrencyPair( 'bch', 'usdt').get_currency_pair() currency_pair = 'bch_btc' def determine_table_name(): localtime = time.localtime() table_name = "depth_OKEx_" + str(localtime[1]).rjust(2, "0") + str( localtime[2]).rjust(2, "0") return table_name # 初始化apikey,secretkey,url # print(account.api_key,account.secret_key,account.name) # currency_pair1=currency_pair.CurrencyPair() # currency_pair1=currency_pair1.get_currency_pair()
from packages import currency_pair as CURRENCYPAIR from packages import universal as UNIVERSAL # pgmanager from packages import db as DB import CONSTANTS pgmanager = DB.PGManager(**CONSTANTS.DB_CONNECT_ARGS_LOCAL) account = ACCOUNT.Account( '26q2SGG+j42h3PlrA2g2IWfynAQ+YsIAKWrQ6ms2es5GTSQjnTXbuguB', 'LkpL2am9qfRWA6f3ZPAJqytCHrNk9m9XdQlu5bx95PFzvHh1/e+heb2gKgsSrQ3mfQXUiRQksmqvUEsDgKmIFQ==' ) kraken = KRAKEN.Kraken(account) currency_pair = CURRENCYPAIR.CurrencyPair('btc', 'usdt') currency_pair = CURRENCYPAIR.CurrencyPair('btc', 'eur') _name_map = 'XXBT' + 'Z' + currency_pair.reference.upper() table_name = 'trades_' + currency_pair.base + '_' + currency_pair.reference + '_kraken' # balance=kraken.balances() # orderInfo=kraken.submit_order(0,currency_pair,15550.1,0.02) # cancleOrderResult=kraken.cancel_order(currency_pair,'OCOEAM-QIU63-DSPAU3') tradeVolume = kraken.trades_volume() # currency_pair_infos=kraken.get_currency_pairs_info() fees = KRAKEN.Kraken.get_fees(volume=tradeVolume) # ticker=kraken.ticker(currency_pair) starting_timestamp = int((time.time() - 3600 * 240) * 10**9) ending_timestamp = int((time.time() - 100) * 10**9) cnt = 0
from packages import account as ACCOUNT from packages import currency_pair as CURRENCYPAIR from packages import universal as UNIVERSAL # pgmanager from packages import db as DB import CONSTANTS pgmanager = DB.PGManager(**CONSTANTS.DB_CONNECT_ARGS_LOCAL) account = ACCOUNT.Account( '26q2SGG+j42h3PlrA2g2IWfynAQ+YsIAKWrQ6ms2es5GTSQjnTXbuguB', 'LkpL2am9qfRWA6f3ZPAJqytCHrNk9m9XdQlu5bx95PFzvHh1/e+heb2gKgsSrQ3mfQXUiRQksmqvUEsDgKmIFQ==' ) kraken = KRAKEN.Kraken(account) currency_pair = CURRENCYPAIR.CurrencyPair('btc', 'usd') # currency_pair=CURRENCYPAIR.CurrencyPair('btc','eur') _name_map = 'XXBT' + 'Z' + currency_pair.reference.upper() table_name = 'trades_' + currency_pair.base + '_' + currency_pair.reference + '_kraken' # balance=kraken.balances() # orderInfo=kraken.submit_order(0,currency_pair,15550.1,0.02) # cancleOrderResult=kraken.cancel_order(currency_pair,'OCOEAM-QIU63-DSPAU3') tradeVolume = kraken.trades_volume() # currency_pair_infos=kraken.get_currency_pairs_info() fees = KRAKEN.Kraken.get_fees(volume=tradeVolume) # ticker=kraken.ticker(currency_pair) starting_timestamp = int((time.time() - 3600 * 240) * 10**9) ending_timestamp = int((time.time() - 100) * 10**9) cnt = 0
问题分析: 0. k线的构成要素: OHLC+Volume+顶部成交量+底部成交量+可触及的高点、低点 1. 按照什么生成k线序列? 1.1 按照等时间间隔,例如1分钟生成一根k线 1.2 按照成交量,例如每100btc成交量生成一根k线,或者每100000美元生成一根k线 1.3 按照笔数(存疑),例如每1000笔交易生成一根k线 1.4 按照波动区间生成k线 2. ''' from packages import universal as UNIVERSAL from packages import currency_pair as CP from packages import data as DATA from packages import plot as PLOT currency_pair = CP.CurrencyPair() trades = DATA.Data.from_db( 'select * from trades_for_kraken order by timestamp') # 测试根据成交量生成k线 # klines=UNIVERSAL.Klines.from_trades(currency_pair,trades,aggregated_by='volume',distance=100) # 测试根据等价格间隔生成k线 # counter=0 # map={} # for i in range(0,1): # distance=80+i*10 # klines=UNIVERSAL.Klines.from_trades(currency_pair,trades,aggregated_by='equal_price',distance=distance) # counter=len(klines.klines) # map[str(distance)]=counter
def swap(depth, currency1, amount1, action='buy'): ''' the params mean that YOU DO ACTION ON CURRENCY1 FOR AMOUNT1 参数的意思是: 你实施action在currency1上面,例如,action是buy,则买入currency1 this function returns a dict {target_currency:target_currency, target_amount:target_amount} :param depth: :param currency1: :param amount1: :param action: :return: ''' cp1 = CP.CurrencyPair() currency_pair = depth.currency_pair target_currency = currency_pair.subtract(currency1) target_amount = 0 # if currency1 == currency_pair.base: current_amount = 0 # if action == 'buy': for ask in depth.asks: amount = ask.amount price = ask.price if current_amount + amount >= amount1: target_amount += price * (amount1 - current_amount) break else: target_amount += amount * price current_amount += amount else: for bid in depth.bids: amount = bid.amount price = bid.price if current_amount + amount >= amount1: target_amount += price * (amount1 - current_amount) break else: target_amount += amount * price current_amount += amount if currency1 == currency_pair.reference: current_expense = 0 if action == 'sell': for ask in depth.asks: amount = ask.amount price = ask.price if current_expense + amount * price >= amount1: target_amount += (amount1 - current_expense) / price break else: current_expense += amount * price target_amount += amount else: for bid in depth.bids: amount = bid.amount price = bid.price if current_expense + amount * price >= amount1: target_amount += (amount1 - current_expense) / price break else: current_expense += amount * price target_amount += amount return {'target_currency': target_currency, 'target_amount': target_amount}
import sys sys.path.append("..") from packages import digifinex as DIGIFINEX from packages import account as ACCOUNT from packages import currency_pair as CURRENCYPAIR from packages import universal as UNIVERSAL import time from threading import Thread account = ACCOUNT.Account('15d12cfa0a69be', 'c6d6a4b051b36e373bb47eede7c1675d05d12cfa0') digifinex = DIGIFINEX.DigiFinex(account) currency_pair = CURRENCYPAIR.CurrencyPair('ltc', 'usdt') # global variables are defined here: CURRENCY_PAIR_INFOS = None PRICE_PRECISION = {} CHANGING_UNIT = None MINIMUM_AMOUNT = None INITIAL_FUNDS = None FEES = {'maker': 0, 'taker': 0.002} depths = [] balance = None my_pending_orders = None def initialize(): # 0. read exchange-based constants global CURRENCY_PAIR_INFOS global PRICE_PRECISION
aex=AEX.AEX(account,USER_ID) # get all tradable currency pairs: currency_pairses=CP.CurrencyPair.find_triangle_arbitragable_currency_pairs('aex',account,USER_ID) # get all distinctive currency pair: distinctive_currency_pairs=[] for currency_pairs in currency_pairses: for currency_pair in currency_pairs: if not distinctive_currency_pairs.__contains__(currency_pair): distinctive_currency_pairs.append(currency_pair) # get relative prices of all currency pairs: initial_funds={} tickers = {} tickers['cny'] = aex.ticker(CP.CurrencyPair('all', 'cny'), True) tickers['usdt'] = aex.ticker(CP.CurrencyPair('all', 'usdt'), True) # reformat tickers _tickers = {} for key1 in tickers.keys(): for key2 in tickers[key1]: if key1 + '_' + key2 == 'usdt_tusd' or key1 + '_' + key2 == 'usdt_pax': continue _tickers[key2 + '_' + key1] = tickers[key1][key2]['ticker'] tickers = _tickers initial_funds['cny']=100 # inquire the relative price of currency N to cny for currency_pair in distinctive_currency_pairs: currencies=[currency_pair.base,currency_pair.reference] for currency in currencies: if currency!='cny':
from OKEx import okex import time import threading from packages import aex as AEX # CONSTANTS,所有的外部参数、数值常量、字符串全都在这里定义---------------------------------------- FEE={ 'buy':0, 'sell':0 } FEE0 = 0 FEE1 = 0 market = "AEX" account = AC.Account('426817f2228d6d8f485dff7b8a9aee71','41ebfb59508cd77031a25228758755dc10f566c18b19f13c52e39ca4c69d775f') aex=AEX.AEX(account,472702) # okex1 = okex.OKEx(account) currency_pair_of_bch_usdt = currency_pair.CurrencyPair('bch', 'usdt').get_currency_pair() currency_pair = 'bch_btc' color = CL.Colored() coins = [] coin0 = CN.Coin('btc', 1, 0.01) coin1 = CN.Coin('cny', 1, 900) coin2 = CN.Coin('usdt', 1, 128) coins.append(coin0) coins.append(coin1) coins.append(coin2) btc = coin0 cny = coin1 usdt = coin2 pairs = [ CP.CurrencyPair('btc','cny'),
import sys sys.path.append("..") from packages import itbit as IB from packages import account as ACCOUNT from packages import currency_pair as CP account = ACCOUNT.Account('577e4a03-540f9610-f686d434-qz5c4v5b6n', 'dd7b02f5-c286e9d4-f2cc78c3-bfab3') ib = IB.Itbit(account) currency_pair = CP.CurrencyPair('btc', 'usd') depth = ib.depth(currency_pair) a = 1
# for currency_pair in distinctive_currency_pairs: # depth = aex.depth(currency_pair) # depths[currency_pair] = depth # # for tradable_currency_pairs in currency_pairses: # depth = [depths[tradable_currency_pairs[0]], depths[tradable_currency_pairs[1]], # depths[tradable_currency_pairs[2]]] # # strategy = TRI.TriangleArbitrage(account, 'digifinex', tradable_currency_pairs, initial_funds=initial_funds) # print('Now:\t'+str(tradable_currency_pairs[0].toString())+'\t'+str(tradable_currency_pairs[1].toString())+'\t'+str(tradable_currency_pairs[2].toString())) # strategy.find_arbitrage_points(depth) # print('\n\n') # time.sleep(3) # except Exception as e: # print(e) # a=1 # a=1 currency_pair = CP.CurrencyPair('btc', 'cny') # ticker=aex.ticker(currency_pair) # depth=aex.depth(currency_pair) trades = aex.trades(currency_pair) # balance=aex.balances() # orderInfo=aex.submit_order(2,currency_pair,100000,0.01) # cancleOrderResult=aex.cancel_order(currency_pair,'29207338') # orderList=aex.order_list(currency_pair) tradeList = aex.trade_list(currency_pair) a = 1