Ejemplo n.º 1
0
    def _createExchangeObject(self, exchange):
        ''' Depricated ... now instantiating class using "eval" in __init__'''
        if exchange == "Binance":
            exchange = ccxt.binance()
        elif exchange == "Bitfinex":
            exchange = ccxt.bitfinex2()
        elif exchange == "Bitmex":
            exchange = ccxt.bitmex()
        elif exchange == "BitStamp":
            exchange = ccxt.binance()
        elif exchange == "Bittrex":
            exchange = ccxt.binance()
        elif exchange == "Bithumb":
            exchange = ccxt.bithumb()
        elif exchange == "CCTX":
            exchange = ccxt.cctx()
        elif exchange == "GDAX":
            exchange = ccxt.gdax()
        elif exchange == "HitBC":
            exchange = ccxt.hitbc()
        elif exchange == "Huobipro":
            exchange = ccxt.huobipro()
        elif exchange == "Kraken":
            exchange = ccxt.kraken()
        elif exchange == "OKEx":
            exchange = ccxt.okex()
        else:
            raise "Exception ExchangeCCXT::_createExchangeObject - ccxt Exchange not valid"

        return exchange
Ejemplo n.º 2
0
 def __init__(self, exchange, symbol=u'BTC/USD', logfile='full.log'):
     if exchange in self.known_exchanges:
         if exchange == 'bfx':
             self.exchange = ccxt.bitfinex2({
                 'rateLimit': 10000,
                 'enableRateLimit': True
             })
         if exchange == 'bitmex':
             self.exchange = ccxt.bitmex({
                 'rateLimit': 10000,
                 'enableRateLimit': True
             })
         self.symbol = symbol
     self.logger = logging.getLogger(__name__ + '.ExchgData')
     self.logger.setLevel(logging.DEBUG)
     sh = logging.StreamHandler()
     dh = logging.FileHandler(logfile)
     sh.setLevel(logging.INFO)
     dh.setLevel(logging.DEBUG)
     fm = logging.Formatter(
         '[%(asctime)s][%(levelname)s][%(name)s] %(message)s')
     dh.setFormatter(fm)
     sh.setFormatter(fm)
     self.logger.addHandler(sh)
     self.logger.addHandler(dh)
     self.logger.info("Logger initialized")
Ejemplo n.º 3
0
 def __init__(self, time_interval='15m', setProxy=True):
     print('__init__')
     self.setProxy = setProxy
     self.URL = 'https://api.bitfinex.com/v1'
     self.bitfinex2 = ccxt.bitfinex2()  # 创建交易所,此处为bitfinex v2 协议
     self.bitfinex1 = ccxt.bitfinex()  # 创建交易所,此处为bitfinex v1 协议
     self.time_interval = time_interval
     self.proxies = {
             "http": "socks5h://127.0.0.1:1080",
             "https": "socks5h://127.0.0.1:1080"
         }
     if self.setProxy:
         self.bitfinex2.proxies = self.proxies
         self.bitfinex1.proxies = self.proxies
Ejemplo n.º 4
0
def get_bitfinex_static(file):
    bitfinex = ccxt.bitfinex2()
    fee = bitfinex.fees
    taker_fee, maker_fee = fee['trading']['taker'], fee['trading']['maker']

    with open(file, 'a') as csvFile:
        csvwriter = csv.writer(csvFile)
        for i in bitfinex.fetch_markets():
            if i['symbol'] in ['BTC/USDT', 'ETH/USDT', 'BCH/USDT']:
                uid = i['symbol'].replace('/', '_') + '-bitfinex'
                csvwriter.writerow([uid, 'Bitfinex', i['id'], '', '1', i['limits']['amount']['min'],
                                    i['limits']['amount']['max'], i['limits']['price']['min'],
                                    i['limits']['price']['max'], i['precision']['amount'],
                                    i['precision']['price'], taker_fee * 10000, maker_fee * 10000,
                                    0, 0, 'cryptocurrency'])
Ejemplo n.º 5
0
 def initialize(self):
     for exchange_name in self.exchanges.keys():
         if exchange_name == EXCHANGE_BITFINEX:
             self.exchanges[exchange_name]["client"] = ccxt.bitfinex2({
                 'apiKey':
                 self.exchanges[EXCHANGE_BITFINEX]["api_key"],
                 'secret':
                 self.exchanges[EXCHANGE_BITFINEX]["api_secret"],
                 'enableRateLimit':
                 True
             })
             self.exchanges[exchange_name]["client_"] = ccxt.bitfinex({
                 'apiKey':
                 self.exchanges[EXCHANGE_BITFINEX]["api_key"],
                 'secret':
                 self.exchanges[EXCHANGE_BITFINEX]["api_secret"],
                 'enableRateLimit':
                 True
             })
         elif exchange_name == EXCHANGE_BINANCE:
             self.exchanges[exchange_name]["client"] = ccxt.binance({
                 'apiKey':
                 self.exchanges[EXCHANGE_BINANCE]["api_key"],
                 'secret':
                 self.exchanges[EXCHANGE_BINANCE]["api_secret"],
                 'enableRateLimit':
                 True,
                 'options': {
                     'adjustForTimeDifference': True
                 }
             })
         elif exchange_name == EXCHANGE_KRAKEN:
             self.exchanges[exchange_name]["client"] = ccxt.kraken({
                 'apiKey':
                 self.exchanges[EXCHANGE_KRAKEN]["api_key"],
                 'secret':
                 self.exchanges[EXCHANGE_KRAKEN]["api_secret"],
                 'enableRateLimit':
                 True
             })
         elif exchange_name == EXCHANGE_OANDA:
             self.exchanges[exchange_name]["client"] = oanda.oanda(self.exchanges[EXCHANGE_OANDA]["account_id"], \
                                                                   self.exchanges[EXCHANGE_OANDA]["account_token"])
         else:
             print("Please configure a valid Exchange.")
             sys.exit(1)
Ejemplo n.º 6
0
 def init_ccxt(self):
     self.binance = ccxt.binance({
         'apiKey': secrets.BINANCE_KEY,
         'secret': secrets.BINANCE_SECRET,
         'timeout': 30000,
         'enableRateLimit': True,
     })
     self.bittrex = ccxt.bittrex({
         'apiKey': secrets.BITTREX_KEY,
         'secret': secrets.BITTREX_SECRET,
         'timeout': 30000,
         'enableRateLimit': True,
     })
     self.bitfinex = ccxt.bitfinex2({
         'apiKey': secrets.BITFINEX_KEY,
         'secret': secrets.BITFINEX_SECRET,
         'timeout': 30000,
         'enableRateLimit': True,
     })
Ejemplo n.º 7
0
def fetch_exchange_data(exchange_name):
    bitstamp = ccxt.bitstamp()
    bitmex = ccxt.bitmex()
    bitfinex = ccxt.bitfinex2()
    bittrex = ccxt.bittrex()
    okcoin = ccxt.okcoinusd()
    kraken = ccxt.kraken()
    binance = ccxt.binance()
    coss = ccxt.coss()
    kucoin = ccxt.kucoin2()
    poloniex = ccxt.poloniex()
    # theocean = ccxt.theocean()
    upbit = ccxt.upbit()
    dict_of_exchanges = {
        'kraken': kraken,
        'bitmex': bitmex,
        'bittrex': bittrex,
        'bitstamp': bitstamp,
        'bitfinex': bitfinex,
        'okcoin': okcoin,
        'binance': binance,
        'coss': coss,
        'kucoin': kucoin,
        'poloniex': poloniex,
        # 'theocean': theocean,
        'upbit': upbit
    }
    try:
        return dict(
            dict_of_exchanges[exchange_name].fetch_order_book('BTC/USD'))
        # return dict(dict_of_exchanges[exchange_name].fetch_order_book('XRP/USD'))
        # return dict(dict_of_exchanges[exchange_name].fetch_order_book('LTC/USD'))
        # add BitcoinCash
        # return dict(dict_of_exchanges[exchange_name].fetch_order_book('ETH/USD'))
    except Exception as ex:
        print('%s - erro: %s' % (exchange_name, ex))
        return {}
Ejemplo n.º 8
0
def getBitfinexOhlcv(symbol='BTC/USD', timeframe='1m', since=None, limit=500):
    ohlcv = getOhlcv(ccxt.bitfinex2(), symbol, timeframe, since, limit)
    return ohlcv
Ejemplo n.º 9
0
    4. 根据目前仓位、买卖信息,结束本次循环,或者进行交易
    5. 交易
"""

# =====ccxt初始化=====
# proxies = {
#     'http': 'socks5://127.0.0.1:1080',
#     'https': 'socks5://127.0.0.1:1080'
# }
proxies = {
    'http': 'http://127.0.0.1:1080',
    'https': 'https://127.0.0.1:1080'
}
apiKey = ''  # 此处加上自己的apikey和secret,都需要开通交易权限
secret = ''
bfx2 = ccxt.bitfinex2()  # 创建交易所,此处为okex交易所
bfx2.apiKey = apiKey
bfx2.secret = secret
# bfx2.proxies = proxies
bfx2.userAgent = bfx2.userAgents['chrome']
bfx2.load_markets()
bfx = ccxt.bitfinex()
bfx.apiKey = apiKey
bfx.secret = secret
# bfx.proxies = proxies
bfx.userAgent = bfx.userAgents['chrome']
bfx.load_markets()

# =====交易品种=====
symbol = 'EOS/USDT'  # 交易品种
base_coin = symbol.split('/')[-1]
Ejemplo n.º 10
0
import ccxt
import numpy as np
import pandas as pd
import time
import json

bitmex = ccxt.bitmex()
bithumb = ccxt.bithumb()
okex = ccxt.okex()
binance = ccxt.binance()
huobi = huobi = ccxt.huobipro()
bitforex = ccxt.bitforex()
bittrex = ccxt.bittrex()
kraken = ccxt.kraken()
gdax = ccxt.gdax()
bitfinex = ccxt.bitfinex2()

exchange_names = ['bithumb']
exchanges = [bithumb]

bithumb.load_markets()


def load_pairs():
    pairs = {}
    for index, exchange in enumerate(exchange_names):
        pairs[exchange] = list(exchanges[index].load_markets().keys())
    return pairs


pairs = load_pairs()
Ejemplo n.º 11
0
for i in USDPairs:
    Pairs['USD'].append(i)

for i in BTCPairs:
    Pairs['BTC'].append(i)

for i in ETHPairs:
    Pairs['ETH'].append(i)

for q in quotes:
    for b in Pairs[q]:
        tableName = b + q
        symbol = b + '/' + q
        print(symbol)
        Db.createNewTable(tableName, fileName)
        timestamp = Db.getMaxTimestamp(tableName, fileName)
        if timestamp is None:
            Ex.DbMake(exchange=ccxt.bitfinex2(),
                      symbol=symbol,
                      timeframe='1m',
                      fileName=fileName,
                      waiting=2.95)
        else:
            Ex.DbMake(exchange=ccxt.bitfinex2(),
                      symbol=symbol,
                      timeframe='1m',
                      startTimestamp=timestamp * 1000,
                      fileName=fileName,
                      waiting=2.95)
Ejemplo n.º 12
0
# Time: 9/5/2018 11:24 PM
# Author: Guanlin Chen
from datetime import datetime, timedelta
import pandas as pd
from time import sleep
import ccxt
from Code.Trade import next_run_time, place_order, get_bitfinex_candle_data, auto_send_email, fetch_position, send_dingding_msg, fetch_margin_balance
from Code.Signals import signal_bolling

pd.set_option('display.max_rows', 1000)
pd.set_option('expand_frame_repr', False)  # do not wrap

# ===== Parameters
time_interval = '30m'  # run time interval
exchange = ccxt.bitfinex()
exchange2 = ccxt.bitfinex2()  # bitfinex has two different API
exchange.apiKey = 'your key'
exchange.secret = 'your secret'
exchange2.apiKey = 'your key'
exchange2.secret = 'your secret'

symbol = 'EOS/USDT'  # should comply with exchange
symbol_for_position = 'eosusd'
base_coin = symbol.split('/')[-1]
trade_coin = symbol.split('/')[0]
leverage = 2
para = [300, 3.4]  # strats parameter
email = 'your email'
# ===== Main Code
while True:
    # ===monitoring email content
Ejemplo n.º 13
0
    def public_executions_asc(self, instrument: str, start: datetime,
                              stop: datetime, **params):
        """
        https://api.bitfinex.com/v2/trades/Symbol/hist
        Path Params
        Symbol        string        required
            The symbol you want information about.
        Query Params
        limit        int32
            Number of records
        start        int32
            Millisecond start time
        end        int32
            Millisecond end time
        sort        int32
            if = 1 it sorts results returned with old > new

        // on trading pairs (ex. tBTCUSD)
        [
          [
            ID,
            MTS,
            AMOUNT,
            PRICE
          ]
        ]
        // on funding currencies (ex. fUSD)
        [
          [
            ID,
            MTS,
            AMOUNT,
            RATE,
            PERIOD
          ]
        ]
        """
        """
            params = dict(symbol=symbol, limit=limit)
            if timestamp:
                params.update(end=timestamp)
            res = v2api.publicGetTradesSymbolHist(params)
"""
        api = ccxt.bitfinex2()
        rps_limit = 60 / 60
        if os.environ.get('https_proxy'):
            rps_limit *= 5
        fn = RateLimiter(rps_limit, getattr(api, 'publicGetTradesSymbolHist'))
        limit = self.LIMIT
        params = dict(symbol='t{}'.format(self.instruments[instrument]['id']),
                      limit=limit,
                      sort=1)
        cache = OrderedDict()
        start = int(start.timestamp() * 1000)
        stop = int(stop.timestamp() * 1000)
        mts = start
        while mts < stop:
            try:
                params.update(start=mts)
                res = fn(params)
                processed_n = 0
                for data in res:
                    _id, mts, amount, price = data
                    if start <= mts < stop:
                        processed_n += 1
                        if _id not in cache:
                            cache[_id] = True
                            if len(cache) > self.CACHE_LIMIT:
                                cache.popitem(last=False)
                        yield dict(time=self.utc_from_timestamp(mts / 1000),
                                   id=_id,
                                   price=price,
                                   qty=abs(amount),
                                   data=data)
                if len(res) < limit:
                    break
                if not processed_n:
                    self.error('no processed item {}'.format(params))
                    break
            except DDoSProtection:
                self.warning('DDoSProtection. sleep {}.'.format(
                    self.RATE_LIMIT_INTERVAL))
                time.sleep(self.RATE_LIMIT_INTERVAL)
            except ExchangeNotAvailable as e:
                self.warning(str(e))
Ejemplo n.º 14
0
def BifinexData(symbol='BTC/USD', timeframe='1m', startTimestamp=''):
    ohlcv = getAllData(ccxt.bitfinex2(), symbol, timeframe, startTimestamp, 3)
    return ohlcv
Ejemplo n.º 15
0
# os.system('python ../program/test/test.py')
# os.popen("python ../program/test/test.py")
# os.popen("kill -9 $(ps -aux|grep test.py|awk '{print $2}')")

proxies = {
    'http': 'socks5://127.0.0.1:1080',
    'https': 'socks5://127.0.0.1:1080'
}
apiKey = ''  # 此处加上自己的apikey和secret,都需要开通交易权限
secret = ''
bfx = ccxt.bitfinex()  # 创建交易所,此处为okex交易所
bfx.apiKey = apiKey
bfx.secret = secret
bfx.load_markets()
# bfx.proxies = proxies
bfx2 = ccxt.bitfinex2()
bfx2.apiKey = apiKey
bfx2.secret = secret
bfx2.load_markets()
# bfx2.proxies = proxies

# 策略脚本进程
proc = None


# 获取bfx的账户余额
def get_bfx_balance():
    exchange_balance = bfx.fetch_balance(params={'type': 'exchange'})
    margin_balance = bfx.fetch_balance(params={'type': 'trading'})

    exchange_msg = 'Exchange账户\n总余额:'
Ejemplo n.º 16
0
    },  # 注意,此处只是案例,每个币的参数是不一样的。
}
# =====account_info这个dict变量,存储各个账户信息,包括:该账户的api、secret,该账户准备交易的币种,每个币种分配的仓位等。
account_info = {
    # 第一个账号
    '账号': {
        # 该账户的api、secret'
        # bfx交易所有两个版本的api,第一代和第二代,能用2的时候尽量用2,下单操作用1
        'exchange':
        ccxt.bitfinex({
            'apiKey': '4MHDdkaXcwZid3yr',
            'secret': 'Aj649NHnbeeDa8Wx',
        }),
        'exchange2':
        ccxt.bitfinex2({
            'apiKey': '4MHDdkaXcwZid3yrO',
            'secret': 'Aj649NHnbeeDa8Wxa',
        }),
        'dingding_id':
        '',
        # 该账户交易的币种,以及每个币种分配的仓位等。
        'symbol_info':
        pd.DataFrame({
            'btc/usd': {
                '分配仓位': 0.2
            },
            'eth/usd': {
                '分配仓位': 0.2
            },
            'ltc/usd': {
                '分配仓位': 0.2
            },
Ejemplo n.º 17
0
 def bitfinex_v2_ccxt_object(apiKey, apiSecret):
     ccxt_object = ccxt.bitfinex2()
     ccxt_object.enableRateLimit = True
     ccxt_object.rateLimit = 10000
     return CCXTObjectFactory._config_ccxt_object(ccxt_object, apiKey,
                                                  apiSecret)
Ejemplo n.º 18
0
import ccxt

exchanges = [
    ccxt._1broker(),
    ccxt._1btcxe(),
    ccxt.acx(),
    ccxt.allcoin(),
    ccxt.anxpro(),
    ccxt.bibox(),
    ccxt.binance(),
    ccxt.bit2c(),
    ccxt.bitbank(),
    ccxt.bitbay(),
    ccxt.bitfinex(),
    ccxt.bitfinex2(),
    ccxt.bitflyer(),
    ccxt.bithumb(),
    ccxt.bitkk(),
    ccxt.bitlish(),
    ccxt.bitmarket(),
    ccxt.bitmex(),
    ccxt.bitso(),
    ccxt.bitstamp(),
    ccxt.bitstamp1(),
    ccxt.bittrex(),
    ccxt.bitz(),
    ccxt.bl3p(),
    ccxt.bleutrade(),
    ccxt.braziliex(),
    ccxt.btcbox(),
    ccxt.btcchina(),
              CANCELED,
              INSUFFICIENT MARGIN was: PARTIALLY FILLED @ PRICE(AMOUNT),
              CANCELED was: PARTIALLY FILLED @ PRICE(AMOUNT)

"""

#价格类型映射 这里有三种价格类型
priceTypeMap = {}
priceTypeMap[constant.PRICETYPE_LIMITPRICE] = 'LIMIT'
priceTypeMap[constant.PRICETYPE_MARKETPRICE] = 'MARKET'
priceTypeMap[constant.PRICETYPE_FOK] = 'FILL-OR-KILL'

# 使用ccxt 对交易细节进行控制
import ccxt

bitfinex = ccxt.bitfinex2()  #因为bitfinex 在ccxt之中显示这里使用bitfinex2

# import pdb;pdb.set_trace()


############################################################################################
class BitfinexGateay(VtGateway):  #网关接口定义类函数
    """Bitfinex接口"""

    # ----------------------------------------------------------------------
    def __init__(self, eventEngine, gatewayName=''):
        """Constructor"""

        super(BitfinexGateay, self).__init__(eventEngine, gatewayName)
        self.api = GatewayApi(self)  # vnapi 类继承函数
Ejemplo n.º 20
0
    2. 获取实时数据
    3. 根据最新数据计算买卖信号 
    4. 根据目前仓位、买卖信息,结束本次循环,或者进行交易
    5. 交易
"""

# =====参数
time_interval = '5m'  # 间隔运行时间,不能低于5min

proxies = {
    'http': 'socks5://127.0.0.1:1080',
    'https': 'socks5://127.0.0.1:1080'
}
apiKey = ''  # 此处加上自己的apikey和secret,都需要开通交易权限
secret = ''
exchange = ccxt.bitfinex2()  # 创建交易所,此处为okex交易所
exchange.apiKey = apiKey
exchange.secret = secret
exchange.proxies = proxies
exchange_v1 = ccxt.bitfinex()
exchange_v1.apiKey = apiKey
exchange_v1.secret = secret
exchange_v1.proxies = proxies
symbol = 'EOS/BTC'  # 交易品种
base_coin = symbol.split('/')[-1]
trade_coin = symbol.split('/')[0]

para = [210, 2]  # 策略参数

# 微信
wechat = Send_Message()