Ejemplo n.º 1
0
    def create_gateway_obj(self, exchange, setting):
        """
        创建gateway对象
        :param exchange: 交易所
        :param setting: 配置信息
        :return: 交易所对象
        """
        if "BITMEX" == exchange:
            # _bitmex 避免和 bitmex 模块重名,所以加下划线区分
            _bitmex = ccxt.bitmex(setting)
            # 设置为测试服务器
            _bitmex.urls["api"] = _bitmex.urls["test"]
            _bitmex.urls["www"] = _bitmex.urls["test"]
            # 引入bitmex官方的对象
            _bitmex.client = bitmex.bitmex(test=True, api_key=setting["apiKey"], api_secret=setting["secret"])
            return _bitmex
        elif "BITMEX_REAL" == exchange:
            # bitmex实盘对象
            # _bitmex 避免和 bitmex 模块重名,所以加下划线区分
            _bitmex = ccxt.bitmex(setting)

            # 引入bitmex官方的对象
            _bitmex.client = bitmex.bitmex(test=False, api_key=setting["apiKey"], api_secret=setting["secret"])
            return _bitmex
        elif "OKEX" == exchange:
            obj_okex = ccxt.okex3()
            return obj_okex
        else:
            pass
Ejemplo n.º 2
0
 def start_check_from_ccxt(self):
     binance = ccxt.binance({
         'enableRateLimit': True, })
     self.check_ccxt_exchange(binance, KLINE_TIMEFRAME_12HOUR)
     okex3 = ccxt.okex3({
         'enableRateLimit': True, })
     self.check_ccxt_exchange(okex3, KLINE_TIMEFRAME_12HOUR)
     self.check_ccxt_exchange(okex3, KLINE_TIMEFRAME_1DAY)
     gate = ccxt.gateio({
         'enableRateLimit': True, })
     self.check_ccxt_exchange(gate, KLINE_TIMEFRAME_12HOUR)
     self.check_ccxt_exchange(gate, KLINE_TIMEFRAME_1DAY)
     huobi = ccxt.huobipro({
         'enableRateLimit': True, })
Ejemplo n.º 3
0
    def __init__(self, event_engine: EventEngine):
        """
        
        :param event_engine: 事件引擎
        :param gateway_name: 交易接口名
        """
        super().__init__(event_engine, "OKEX")
        self.gateway = ccxt.okex3()
        # 数据库对象
        self.database_manager = database_manager

        self.leverage = 0

        self.order_count = 10000
        self.order_count_lock = Lock()

        self.connect_time = 0
Ejemplo n.º 4
0
class ArbitrageDate(DataHandler):
    exchangeok = ccxt.okex3()
    '''经过一上午的反思我终于知道这里改如何写了,写一个DATe生成器,同时得到两个交易所,的价格
    然后计算价差,对到队列中去,队列拿到后,根据策略去计算这个价差,整个套利流程就到一块了,获取合约
    的websockt单独弄一个api模块,封到外面去,这样还做到了解耦和复用。
    在这里的实现是用队列,api那面接到数据后处理完成把干净对数据直接对到队列里,这面从队列里拿,拿走算价差,最后推给新的队列
    时间上目前细粒度要求不高,所以1m以上都OK,不用考虑tick的问题,也就是1分钟去交易所拉或者推一次就行,毕竟不是高频套利。
    这里只是把两个合约打个包然后直接给回测,具体的处理由策略来做,在这里不要去求价差,这么做并不合理和连续。
    '''
    def __init__(self, events, symbol_list, exchange=exchangeok):
        self.exchange = exchange
        self.symbol_list = symbol_list
        self.events = events
        self.continue_backtest = True

    def _make_adate(self):
        '''具体的数据解封,交给strgerty,这里就直接打包好数据就行。不要算出价差,不需要这样
        这里只是把两个合约打个包然后直接给回测,具体的处理由策略来做,在这里不要去求价差,这么做并不合理和连续。
        '''
        b = self.exchange.fetch_ohlcv(symbol='BTC-USD-SWAP',
                                      timeframe='1m',
                                      limit=1)
        b = b[0]  #为了和接口对接上,这里考虑是DF? 两个DF相减,理论上也是可以的啊。
        bar = DataHandler.Bar('OKex', datetime.fromtimestamp(b[0] / 1000),
                              b[1], b[2], b[3], b[4], b[5])
        print(bar, '111111111111')
        return bar

    def get_latest_bars(self, symbol, N=1):
        '''从latest_symbol列表中返回最新的N个bar,或者所能返回的最大数量的bar
        这里主要是为了计算指标的,暂时不用实现。套利不需要指标。'''
        pass

    def update_bars(self):
        bar = self._make_adate()
        if bar is not None:
            # self.latest_symbol_data[s].append(bar)

            self.events.put(BarEvent(bar))
Ejemplo n.º 5
0

config = json.load(open('config.json'))
Base = config["Base"]
Quote = config["Quote"]
Contract = config["Contract"]
futurePair = Base + '-' + Quote
stockPair = Base + '/' + 'USDT'
delay = 5
# 10% price change
basis_threshold = 0.20
old_basis = -1
estimatedRate_threshold = 0.20
old_estimatedRate = -1

exchange = ccxt.okex3(config["okex"])
exchange.load_markets()
for symbol in exchange.markets:
    if futurePair in symbol:
        market = exchange.markets[symbol]
        if market['info']['alias'] == 'quarter':
            futurePair = market['symbol']
            break

n = 10

while True:
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    time.sleep(delay)
    try:
        fundingRate = exchange.swapGetInstrumentsInstrumentIdFundingTime(
Ejemplo n.º 6
0
deribit = ccxt.deribit()
deribit_markets = deribit.load_markets()
deribit_sep = deribit_markets['BTC-27SEP19']
deribit_dec = deribit_markets['BTC-27DEC19']
deribit_perp = deribit_markets['BTC-PERPETUAL']

okex = ccxt.okex()
okex_markets = okex.load_markets()
okex_sep = okex_markets['BTC-USD-190927']
#okex_dec = okex_markets['BTC-27DEC19']
#okex_perp = okex_markets['BTC-PERPETUAL']
'''

bitmex = ccxt.bitmex()
deribit = ccxt.deribit()
okex = ccxt.okex3()

deribit_markets = deribit.load_markets()['BTC-27SEP19']
#pprint(deribit_markets)

#pprint(okex.load_markets())
#bitmex.urls['api'] = bitmex.urls['test']
#print(bitmex.load_markets())
bitmex_sep_book = bitmex.fetchOrderBook('XBTU19', limit=10000)
bitmex_dec_book = bitmex.fetchOrderBook('XBTZ19', limit=10000)
bitmex_perp_book = bitmex.fetchOrderBook('BTC/USD', limit=10000)

deribit_sep_book = deribit.fetchOrderBook('BTC-27SEP19', limit=10000)
deribit_dec_book = deribit.fetchOrderBook('BTC-27DEC19', limit=10000)
deribit_perp_book = deribit.fetchOrderBook('BTC-PERPETUAL', limit=10000)
Ejemplo n.º 7
0
# import asyncio
#
# async def main():
#     while True:
#         print('Hello ...')
#         # await asyncio.sleep(1)
#         print('... World!')
#         await asyncio.sleep(1)
#
# # Python 3.7+
# asyncio.run(main())
# from xquant.engine.okex_api import dataqueue
# # from xquant.engine.data import ArbitrageDate
# # ArbitrageDate(dataqueue=dataqueue)._make_adate()
# # print('go')
#
# print(dataqueue.get(timeout=2))
#今天先写到这里,明天继续,目前写到了如何让TEST和api 利用队列通信,能够拿到实时的数据并做各种处理。
# import time
# from xquant.engine.okex_api import dataqueue
# for i in range(3):
#     time.sleep(2)
#     print(dataqueue.get(i))
'''今天先写到这里,目前准备去健身,明天继续写,目前写到数据之间的通信有点问题,就是怎么把API的数据,给到HANDLER,
怎么去通信的问题。,明天上午继续。。'''
from xquant.engine.data import ArbitrageDate, BarEvent
import ccxt

aa = ArbitrageDate(BarEvent, exchange=ccxt.okex3())
aa._make_adate()
'''测试成功,顺利拿到我想要的数据。'''
Ejemplo n.º 8
0
formatter = logging.Formatter('[%(asctime)s] %(message)s')
handler = logging.FileHandler("btc_%s.txt" % time.strftime("%Y-%m-%d %H-%M-%S"))
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
logger.addHandler(console)
logger.addHandler(handler)

f = open('accounts.txt')
lines = f.readlines()
acct_id = int(lines[-1])
api_key = lines[acct_id*2 - 2].strip('\n')
seceret_key = lines[acct_id*2 - 1].strip('\n')
fcoin = Fcoin()
fcoin.auth(api_key, seceret_key)  # fcoin.margin_buy('ethusdt', 0.01, 10)
ex0 = ccxt.fcoin()
ex1 = ccxt.okex3()
ex2 = ccxt.binance()
ex3 = ccxt.huobipro()
type = 'limit'
trend = 0 
trend_0, trend_1, trend_2, trend_3, trend_cmb = [], [], [], [], []
pre_price_0 = 0
pre_price_1, score_1 = 0, 0
pre_price_2, score_2 = 0, 0
pre_price_3, score_3 = 0, 0
pre_price_4, score_4 = 0, 0
pre_price_5, score_5 = 0, 0
pre_price_cmb, score_cmb = 0, 0
buy_id = []
sell_id = []
loop = 0
Ejemplo n.º 9
0
#!/usr/bin/env python3
import json
import time
import ccxt
import smtplib
import os

config = json.load(open('config.json'))

A = ccxt.binance(config["binance"])
A_spot = ccxt.binance(config["binance_spot"])
B = ccxt.okex3(config["okex"])

A.load_markets()
A_spot.load_markets()
B.load_markets()


def get_binance_balance(A, A_spot):
    try:
        balance_A = A.fetchBalance()
        print(balance_A["info"]["totalMarginBalance"])
        balance_spot_A = A_spot.fetchBalance()
        print(balance_spot_A)
    except Exception as err:
        print(err)
        pass


def get_okex_balance(B):
    try:
from trading_utils.trading_executor import *
from trading_utils.send_email import *
from statistics_model.orm_tables import *

with open("../config/config.json", 'r') as config_file:
    config = json.load(config_file)
    apiKey = config["api_config"]["apiKey"]
    secret = config["api_config"]["secret"]
    password = config["api_config"]["password"]
    exchange_name = config["exchange_name"]
    use_database = config["use_database"]
    assets_to_buy = config["assets_to_buy"]
    transaction_fee = float(config["transaction_fee"])

if exchange_name == "okex":
    exchange = ccxt.okex3()
elif exchange_name == "huobi":
    exchange = ccxt.huobipro()
    password = None
else:
    exchange = None
    print("暂时不支持{}交易所".format(exchange_name))
    exit()

trading_executor = TradingExecutor(exchange=exchange,
                                   api_key=apiKey,
                                   secret=secret,
                                   password=password)
if use_database:
    with open("../config/database.json", 'r') as database_file:
        database_config = json.load(database_file)
Ejemplo n.º 11
0
# ===使用私有函数获取合约K线数据
import ccxt

ok = ccxt.okex3()

ok.fetch_markets()

Ejemplo n.º 12
0
import ccxt
from time import sleep
from datetime import datetime
import functions as fs
import message as msg
from setting import Settings

my_settings = Settings()

myOKEX = ccxt.okex3()
myOKEX.apiKey = my_settings.okex_entry['apikey']
myOKEX.secret = my_settings.okex_entry['secret']
myOKEX.password = my_settings.okex_entry['password']
myOKEX.proxies = my_settings.proxies

# 初始化参数
symbol = 'BTC/USDT'     # ccxt采用“/”连接币对,OKEX采用“-”连接
trade_coin = symbol.split('/')[0]
base_coin = symbol.split('/')[-1]
time_interval = '15m'   # 确定获取哪个时间周期的K线

# ----有问题------------------有问题--------------有问题--------------有问题
signal_last = 'closing'  # 上一次交易类型,初始交易状态为平仓
# ----有问题------------------有问题--------------有问题--------------有问题

# 开始主循环
while True:
    # 1、取得并等到获取数据的时间点
    run_time = fs.next_run_time(time_interval)
    sleep(max(0, (run_time - datetime.now()).seconds))
    while True:
Ejemplo n.º 13
0
import pandas as pd
from ccxt import okex3
import time
from multiprocessing.dummy import Pool as ThreadPool
from datetime import datetime, timedelta
from pathlib import Path
from concurrent.futures import ProcessPoolExecutor

pd.set_option('expand_frame_repr', False)

exchange = okex3()
contracts = exchange.futuresGetInstruments()
depth_size = 10
# frequency in seconds
fetch_frequency = 0.2

futures_contracts = []
length = len(contracts)
for index in range(0, length, 3):
    week_contract_id = contracts[index]['instrument_id']
    next_week_contract_id = contracts[index + 1]['instrument_id']
    season_contract_id = contracts[index + 2]['instrument_id']
    if week_contract_id.split('-')[0] in ('BTC', 'ETH', 'EOS', 'BSV', 'BCH') and week_contract_id.split('-')[1] == season_contract_id.split('-')[1] == 'USD':
        futures_contracts.append((week_contract_id, next_week_contract_id, season_contract_id))
futures_contracts.sort(key=lambda tple: tple[0][:3])


def obtain_futures_ticker(instrument_id, size=depth_size):
    while True:
        try:
            ticker = exchange.futuresGetInstrumentsInstrumentIdBook(