def __init__(self, dbconfig, credential): self.__my_future_client = OKCoinFuture(credential['okcoinRESTURL'], credential['apikey'], credential['secretkey']) self.__my_spot_client = OKCoinSpot(credential['okcoinRESTURL'], credential['apikey'], credential['secretkey']) self.__mydb = MySQL(dbconfig['host'], dbconfig['user'], dbconfig['passwd'], dbconfig['db'])
def api_get(self, method, params={}): # 现货API if self.account: apikey, secretkey = get_account_key("okex", self.account) okcoinSpot = OKCoinFuture(okcoinRESTURL, apikey, secretkey) if method == "future_userinfo_4fix": api_do = "okcoinSpot.%s()" % (method) return eval(api_do) elif method == "future_position_4fix": return okcoinSpot.future_position_4fix(params["symbol"], params["contractType"], params["type"]) elif method == "trade": return okcoinSpot.future_trade(params["symbol"], params["contractType"], params["price"], params["amount"], params["type"], params["match_price"], params["lever_rate"]) elif method == "ticker": return okcoinSpot.future_ticker(params["symbol"], params["contractType"]) elif method == "order_info": return okcoinSpot.future_orderinfo(params["symbol"], params["contractType"], params["id"]) elif method == "cancelOrder": return okcoinSpot.future_cancel(params["symbol"], params["contractType"], params["id"])
class Trades(object): __my_future_client = None __my_spot_client = None __mydb = None def __init__(self,dbconfig,credential): self.__my_future_client = OKCoinFuture(credential['okcoinRESTURL'],credential['apikey'],credential['secretkey']) self.__my_spot_client = OKCoinSpot(credential['okcoinRESTURL'],credential['apikey'],credential['secretkey']) self.__mydb = MySQL(dbconfig['host'],dbconfig['user'],dbconfig['passwd'],dbconfig['db']) def collect_future_trades(self,symbol,contract_type): hjson = self.__my_future_client.future_trades(symbol,contract_type) collected = 0 for i in range(0,len(hjson)): amount = float(hjson[i]['amount']) date = hjson[i]['date'] date = datetime.datetime.fromtimestamp(date) date = date.strftime("%Y-%m-%d %H:%M:%S") date_ms = hjson[i]['date_ms'] / 1000 date_ms = datetime.datetime.fromtimestamp(date_ms) date_ms = date_ms.strftime("%Y-%m-%d %H:%M:%S") price = float(hjson[i]['price']) tid = hjson[i]['tid'] trade_type = hjson[i]['type'] if self.__mydb.future_trade_exist(symbol, date_ms, tid, contract_type) == 0: self.__mydb.insert_trades(amount,date,date_ms,price,tid,trade_type,symbol,0,contract_type) collected = collected+1 print (symbol +' ' + contract_type +' future trade history' + ' is done! collected ' + str(collected) + ' records!') ##end of def collect_future_trades def collect_spot_trades(self,symbol): max_trade_id = self.__mydb.get_max_trade_id(symbol,1) hjson = self.__my_spot_client.trades(symbol,max_trade_id) collected = 0 for i in range(0,len(hjson)): amount = float(hjson[i]['amount']) date = hjson[i]['date'] date = datetime.datetime.fromtimestamp(date) date = date.strftime("%Y-%m-%d %H:%M:%S") date_ms = hjson[i]['date_ms'] / 1000 date_ms = datetime.datetime.fromtimestamp(date_ms) date_ms = date_ms.strftime("%Y-%m-%d %H:%M:%S") price = float(hjson[i]['price']) tid = hjson[i]['tid'] trade_type = hjson[i]['type'] if tid > max_trade_id: self.__mydb.insert_trades(amount,date,date_ms,price,tid,trade_type,symbol,1) collected = collected+1 print (symbol +' spot trade history' + ' is done! collected ' + str(collected) + ' records!') ##end of def collect_spot_trades
def read_key(): okcoinRESTURL = 'www.okcoin.com' #请求注意:国内账号需要 修改为 www.okcoin.cn with open('lijianhui', 'r') as apis: keys = json.loads(apis.read()) #现货API okcoinSpot = OKCoinSpot(okcoinRESTURL, keys["api"], keys["secret"]) #期货API okcoinFuture = OKCoinFuture(okcoinRESTURL, keys["api"], keys["secret"]) return okcoinSpot, okcoinFuture
def __init__(self): ##初始化apikey,secretkey,url apikey = config.apikey secretkey = config.secretkey okcoinRESTURL = 'www.okex.com' #请求注意:国内账号需要 修改为 www.okcoin.cn #现货API self.okcoinSpot = OKCoinSpot(okcoinRESTURL,apikey,secretkey) # 期货API self.okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) self.depth = {}
def __init__(self): with open("key","r",encoding="utf-8") as csvfile: key = [ item for item in csv.reader(csvfile) ][0] apikey = key[0] secretkey = key[1] # 请求注意:国内账号需要 修改为 www.okcoin.cn api = 'www.okcoin.com' okcoin = self.okcoin = OKCoinFuture(api, apikey, secretkey) logging.info.basicConfig(level=logging.info.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%b %d %H:%M:%S', filename='turtle.out', filemode='a') self.step = 0.01 # 0.01 即 1% logging.info('设置初始步进: %.1f%%' % (self.step*100)) self.record_info()
class TradeTool(object): """docstring for ClassName""" def __init__(self): self.okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) self.depthSells = [] self.depthBuys = [] def getDepth(self): turl = 'https://www.okex.com/api/v1/future_depth.do?symbol=ltc_usd&contract_type=quarter&size=20' data = urltool.getUrl(turl) ddic = json.loads(data) buys = ddic['bids'] sells = ddic['asks'] return buys, sells #1:开多 2:开空 3:平多 4:平空 def openShort(self, pprice, pamount): print('期货开空') print time.ctime() print self.okcoinFuture.future_trade('ltc_usd', 'quarter', str(pprice), str(pamount), '2', '0', '10') def closeShort(self, pprice, pamount): print('期货平空') print time.ctime() print self.okcoinFuture.future_trade('ltc_usd', 'quarter', str(pprice), str(pamount), '4', '0', '10') def openLong(self, pprice, pamount): print('期货开多') print time.ctime() print self.okcoinFuture.future_trade('ltc_usd', 'quarter', str(pprice), str(pamount), '1', '0', '10') def closeLong(self, pprice, pamount): print('期货平多') print self.okcoinFuture.future_trade('ltc_usd', 'quarter', str(pprice), str(pamount), '3', '0', '10')
def collect_okcoin(): # ------------------------------ # collect data from Okcoin API # ------------------------------ # API_KEY_OKCOIN='b4dd3278-df06-48af-8925-40120f46563b' # API_SECRET_OKCOIN='1F8A97B89F03A095238823CB1FAA3827' import sys sys.path.insert(0, '/Users/G_bgyl/si507/final_project/okcoin_lib') from OkcoinSpotAPI import OKCoinSpot from OkcoinFutureAPI import OKCoinFuture #初始化apikey,secretkey,url okcoinRESTURL = 'www.okcoin.com' #请求注意:国内账号需要 修改为 www.okcoin.cn #现货API okcoinSpot = OKCoinSpot(okcoinRESTURL, API_KEY_OKCOIN, API_SECRET_OKCOIN) #期货API okcoinFuture = OKCoinFuture(okcoinRESTURL, API_KEY_OKCOIN, API_SECRET_OKCOIN) # pprint.pprint (okcoinSpot.depth('btc_usd')) okcoin_depth = okcoinSpot.depth('btc_usd') # pprint.pprint(okcoin_depth) bids = [] for each_b in okcoin_depth['bids']: bids.append(['bids'] + each_b) asks = [] for each_a in okcoin_depth['bids']: asks.append(['asks'] + each_a) okcoin_data = bids + asks # print(len(okcoin_depth['bids']),len(okcoin_depth['asks']),len(okcoin_data)) return okcoin_data
class Kline(object): __my_future_client = None __my_spot_client = None __mydb = None def __init__(self, dbconfig, credential): self.__my_future_client = OKCoinFuture(credential['okcoinRESTURL'], credential['apikey'], credential['secretkey']) self.__my_spot_client = OKCoinSpot(credential['okcoinRESTURL'], credential['apikey'], credential['secretkey']) self.__mydb = MySQL(dbconfig['host'], dbconfig['user'], dbconfig['passwd'], dbconfig['db']) def collect_future_kline(self, symbol, type, contract_type): max_timestamp = self.__mydb.get_max_timestamp(symbol, type, 0, contract_type) hjson = self.__my_future_client.future_kline(symbol, type, contract_type, 0, max_timestamp) collected = 0 for i in range(0, len(hjson)): timestamp = hjson[i][0] open = hjson[i][1] high = hjson[i][2] low = hjson[i][3] close = hjson[i][4] amount = hjson[i][5] amount_in_coin = hjson[i][6] dateArray = datetime.datetime.fromtimestamp(timestamp / 1000) otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S") if timestamp > max_timestamp: self.__mydb.insert_kline(otherStyleTime, type, open, high, low, close, amount, symbol, 0, amount_in_coin, contract_type) collected = collected + 1 print(symbol + ' ' + type + ' ' + contract_type + ' future kline history' + ' is done! collected ' + str(collected) + ' records!') ##end of def def collect_spot_kline(self, symbol, type): spot = 1 since = 0 max_timestamp = self.__mydb.get_max_timestamp(symbol, type, spot) hjson = self.__my_spot_client.kline(symbol, type, since, max_timestamp) collected = 0 for i in range(0, len(hjson)): timestamp = hjson[i][0] open = hjson[i][1] high = hjson[i][2] low = hjson[i][3] close = hjson[i][4] amount = hjson[i][5] dateArray = datetime.datetime.fromtimestamp(timestamp / 1000) otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S") if timestamp > max_timestamp: self.__mydb.insert_kline(otherStyleTime, type, open, high, low, close, amount, symbol, spot) collected = collected + 1 print(symbol + ' ' + type + ' spot kline history' + ' is done! collected ' + str(collected) + ' records!')
# from TradeAccountAPI import TradeAccount # 初始化apikey,secretkey,url fileName = 'key.json' # path = os.path.abspath(os.path.dirname(__file__)) # print(file) # fileName = os.path.join(path, fileName) # 解析json文件 with open(fileName) as data_file: setting = json.load(data_file) data_file.close() apikey = str(setting['apiKey']) secretkey = str(setting['secretKey']) okcoinRESTURL = 'www.okex.com' # 期货API okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) def price_to_df(symbol, period, frequency, count): price = okcoinFuture.future_kline(symbol, period, frequency, count) df = pd.DataFrame(columns=[ 'timestamp', 'open', 'high', 'low', 'close', 'volume', 'coin_amount' ]) i = 0 for k in price: df.loc[i, :] = k i = i + 1 return df #print(u'获取虚拟合约的K线信息')
# encoding: utf-8 #客户端调用,用于查看API返回结果 from OkcoinSpotAPI import OKCoinSpot from OkcoinFutureAPI import OKCoinFuture #初始化apikey,secretkey,url apikey = 'XXXX' secretkey = 'XXXXX' okcoinRESTURL = 'www.okcoin.com' #请求注意:国内账号需要 修改为 www.okcoin.cn #现货API okcoinSpot = OKCoinSpot(okcoinRESTURL, apikey, secretkey) #期货API okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) print(u' 现货行情 btc_usd') print(okcoinSpot.ticker('btc_usd')) print(u' 美元汇率 ') print(okcoinFuture.exchange_rate()) print(u' 现货深度 ') print(okcoinSpot.depth('btc_usd')) #print (u' 现货历史交易信息 ') #print (okcoinSpot.trades()) #print (u' 用户现货账户信息 ') #print (okcoinSpot.userinfo())
#客户端调用,用于查看API返回结果 from OkcoinSpotAPI import OKCoinSpot from OkcoinFutureAPI import OKCoinFuture import ssl #初始化apikey,secretkey,url apikey = 'XXXX' secretkey = 'XXXXX' okcoinRESTURL = 'www.okex.com' #请求注意:国内账号需要 修改为 www.okcoin.cn #现货API okcoinSpot = OKCoinSpot(okcoinRESTURL, apikey, secretkey) #期货API okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) #set ssl config 总是报SSL错误,没办法只能加上下面这句,不验证SSL了。 ssl._create_default_https_context = ssl._create_unverified_context #print (u' 现货行情 ') #print (okcoinSpot.ticker('btc_usd')) #print (u' 现货深度 ') #print (okcoinSpot.depth('btc_usd')) #print (u' 现货历史交易信息 ') #print (okcoinSpot.trades()) #print (u' 用户现货账户信息 ') #print (okcoinSpot.userinfo()) #print (u' 现货下单 ')
#from TradeAccountAPI import TradeAccount # 初始化apikey,secretkey,url fileName = 'key.json' #path = os.path.abspath(os.path.dirname(__file__)) #print(file) #fileName = os.path.join(path, fileName) # 解析json文件 with open(fileName) as data_file: setting = json.load(data_file) data_file.close() apikey = str(setting['apiKey']) secretkey = str(setting['secretKey']) okcoinRESTURL = 'www.okex.com' # 期货API context = OKCoinFuture(okcoinRESTURL, apikey, secretkey) okcoinSpot = OKCoinSpot(okcoinRESTURL, apikey, secretkey) # 网格交易法则 security = ['eth_usd', 'btc_usd'] #period = ['this_week','next_week','quarter'] symbol = 'eth_usd' contractType = 'this_week' unit_volume = 10 timeframe = '1hour' #三天 limit = '72' context.last_price = 1100 def price_to_df(symbol, contractType, frequency, count):
from OkcoinFutureAPI import OKCoinFuture import ssl, json, time import sys import os # 初始化apikey,secretkey,url apikey = 'fdcc0738-1090-4ac6-ae7a-0eb6c6a7d5ef' secretkey = 'B7D1515088B94513FAF2C7B033F83893' okcoinRESTURL = 'www.okex.com' # 请求注意:国内账号需要 修改为 www.okcoin.cn ssl._create_default_https_context = ssl._create_unverified_context # 全局禁用ssl验证 # 现货API okcoinSpot = OKCoinSpot(okcoinRESTURL, apikey, secretkey) # 期货API okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) # 计算是否止损退出 def isLossStop(direction, earnRate, priceNow): global stopPrice, operatePrice, stateLossStop, priceState, forbidPrice if earnRate <= stateLossStop: if direction == 'rise': priceState = 'bullForbid' elif direction == 'fall': priceState = 'bearForbid' forbidPrice = operatePrice print('lossStop 1') return True elif direction == 'rise' and priceNow <= stopPrice: priceState = 'bullForbid'
# from TradeAccountAPI import TradeAccount # 初始化apikey,secretkey,url fileName = 'key.json' # path = os.path.abspath(os.path.dirname(__file__)) # print(file) # fileName = os.path.join(path, fileName) # 解析json文件 with open(fileName) as data_file: setting = json.load(data_file) data_file.close() apikey = str(setting['apiKey']) secretkey = str(setting['secretKey']) okcoinRESTURL = 'www.okex.com' # 期货API okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) def price_to_df(symbol, period, frequency, count): price = okcoinFuture.future_kline(symbol, period, frequency, count) df = pd.DataFrame(columns=[ 'timestamp', 'open', 'high', 'low', 'close', 'volume', 'coin_amount' ]) i = 0 for k in price: df.loc[i, :] = k i = i + 1 return df # print(u'获取虚拟合约的K线信息')
atom_trades = [buy_this_week, sell_this_week, buy_next_week, sell_next_week] hedge_1 = {'buy': buy_this_week, 'sell': sell_next_week} hedge_2 = {'buy': buy_next_week, 'sell': sell_this_week} my_outlier = Outlier(dbconfig) ##slope, intercept, r_value, p_value, std_err = my_outlier.generate_linear('btc_usd', '1min', 'this_week') hedge_1_position = 0 hedge_2_position = 0 while True: time.sleep(0.2) sample_mean = my_outlier.generate_anchor('btc_usd', '1min', 'this_week') print(sample_mean) okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) this_week_depth = okcoinFuture.future_depth('btc_usd', 'this_week', '5') this_week_depth_asks = this_week_depth['asks'] this_week_depth_bids = this_week_depth['bids'] ''' print('this_week_depth_asks') print(this_week_depth_asks) print('this_week_depth_bids') print(this_week_depth_bids) ''' next_week_depth = okcoinFuture.future_depth('btc_usd', 'next_week', '5') next_week_depth_asks = next_week_depth['asks'] next_week_depth_bids = next_week_depth['bids']
def __init__(self): self.okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) self.depthSells = [] self.depthBuys = []
# encoding: utf-8 #客户端调用,用于查看API返回结果 from OkcoinSpotAPI import OKCoinSpot from OkcoinFutureAPI import OKCoinFuture from lamda import * #初始化apikey,secretkey,url apikey = AK secretkey = AS okcoinRESTURL = 'www.okcoin.com' #请求注意:国内账号需要 修改为 www.okcoin.cn #现货API okcoinSpot = OKCoinSpot(okcoinRESTURL,apikey,secretkey) #期货API okcoinFuture = OKCoinFuture(okcoinRESTURL,apikey,secretkey) print (u' 现货行情 ') print (okcoinSpot.ticker('btc_usd')) print (u' 现货深度 ') print (okcoinSpot.depth('btc_usd')) #print (u' 现货历史交易信息 ') #print (okcoinSpot.trades()) #print (u' 用户现货账户信息 ') #print (okcoinSpot.userinfo()) #print (u' 现货下单 ') #print (okcoinSpot.trade('ltc_usd','buy','0.1','0.2'))
# encoding: utf-8 #客户端调用,用于查看API返回结果 from OkcoinSpotAPI import OKCoinSpot from OkcoinFutureAPI import OKCoinFuture #初始化apikey,secretkey,url apikey = 'fdcaed15-7d45-4de2-8ddf-9111c77375e6' secretkey = 'ECEE466D8AF35C5F812CB9F4EA3023A0' okcoinRESTURL = 'www.okcoin.com' #请求注意:国内账号需要 修改为 www.okcoin.cn #现货API okcoinSpot = OKCoinSpot(okcoinRESTURL, apikey, secretkey) #期货API okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) ''' print (u' 现货行情 ') print (okcoinSpot.ticker('btc_usd')) print (u' 现货深度 ') print (okcoinSpot.depth('btc_usd')) print (u' 现货历史交易信息 ') print (okcoinSpot.trades('btc_usd',0)) print (u'期货交易记录信息') print (okcoinFuture.future_trades('ltc_usd','this_week',0)) ''' print(u'期货分钟日线数据') print(okcoinFuture.future_kline('btc_usd', '1min', 'this_week', 0, 0))
#初始化apikey,secretkey,url config = open('.config', 'r') lines = config.readlines() apikey = lines[0].strip() secretkey = lines[1].strip() config.close() #请求注意:国内账号需要 修改为 www.okcoin.cn okcoinRESTURL = 'www.bitz.com' # okexRESTURL = 'www.okex.com' #现货API okcoinSpot = OKCoinSpot(okcoinRESTURL, apikey, secretkey) #期货API okcoinFuture = OKCoinFuture(okexRESTURL, apikey, secretkey) #海龟参数 total_usd = 4000 lever = 20 #头寸 position = 10 #季度 contract_type = 'quarter' kline_type = '1min' N1 = 350 nbdev = 2.5 # N1=55 # nbdev=2 stop_N = 2 entry_price = 0
import datetime import json #Historical Data Initialization #wb = xlwings.Book('Historical Data.xlsx') #DataSheet = wb.sheets['Monitor'] #RowNum = 1 #ColNum = 1 #初始化apikey,secretkey,url apikey = '' secretkey = '' okcoinRESTURL = 'www.okex.com' #请求注意:国内账号需要 修改为 www.okcoin.cn #期货API okcoinFuture = OKCoinFuture(okcoinRESTURL,apikey,secretkey) okcoinSpot = OKCoinSpot(okcoinRESTURL,apikey,secretkey) #Load Spot last/bid/ask #print (u' 期货市场深度信息') #Fut_Data =okcoinFuture.future_depth('btc_usd','this_week','6') #Fut_Ask=Fut_Data.get("asks") #print (Fut_Ask) #Load next week fut spot/bid/last print (u' 期货行情信息') while True: try: Fut_Data_Next_Quarter_BTC = okcoinFuture.future_ticker('btc_usd','quarter') Fut_Data_Next_Quarter_LTC = okcoinFuture.future_ticker('ltc_usd','quarter') LTC_Index = okcoinFuture.future_index('ltc_usd') BTC_Index = okcoinFuture.future_index('btc_usd')
def __init__(self, isTest=True): self.okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) self.depthSells = [] self.depthBuys = [] self.isOpne = False self.isTest = isTest
# encoding: utf-8 #客户端调用,用于查看API返回结果 from OkcoinSpotAPI import OKCoinSpot from OkcoinFutureAPI import OKCoinFuture #初始化apikey,secretkey,url apikey = 'X' secretkey = 'X' okcoinRESTURL = 'www.okex.com' #请求注意:国内账号需要 修改为 www.okex.cn #现货API okcoinSpot = OKCoinSpot(okcoinRESTURL, apikey, secretkey) #期货API okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) #print (u' 现货行情 ') #print (okcoinSpot.ticker('ltc_btc')) #print (u' 现货深度 ') #print (okcoinSpot.depth('btc_usd')) #print (u' 现货历史交易信息 ') #print (okcoinSpot.trades()) #print (u' 用户现货账户信息 ') #print (okcoinSpot.userinfo()) #print (u' 现货下单 ') #print (okcoinSpot.trade('ltc_usd','buy','0.1','0.2'))
fileName = 'key.json' path = os.path.abspath(os.path.dirname(__file__)) fileName = os.path.join(path, fileName) # 解析json文件 with open(fileName) as data_file: setting = json.load(data_file) data_file.close() apikey = str(setting['apiKey']) secretkey = str(setting['secretKey']) okcoinRESTURL = 'www.okex.com' # 现货API okcoinSpot = OKCoinSpot(okcoinRESTURL, apikey, secretkey) # 期货API okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) spotinfo = okcoinSpot.userinfo() spotinfo = json.loads(spotinfo) freeamount = 0 freezedamount = 0 if spotinfo['result']: freeinfo = spotinfo['info']['funds']['free'] freezedinfo = spotinfo['info']['funds']['freezed'] for symbol in freeinfo: if float(freeinfo[symbol]) != 0: if symbol == 'btc': quote = 1.0 elif symbol == 'usdt': quote = 1.0 / float(okcoinSpot.ticker('btc_usdt')['ticker']['last']) else:
import sys import json import time import logging from OkcoinFutureAPI import OKCoinFuture from plan_pingcang import plan from helpers import get_btc_price from conf import okcoin apikey = okcoin.apikey secretkey = okcoin.secretkey okcoinRESTURL = okcoin.okcoinRESTURL okcoinFuture = OKCoinFuture(okcoinRESTURL,apikey,secretkey) category = '' price = 0 trend = '' is_continue = True input_trend = sys.argv[1] input_price = sys.argv[2] input_category = sys.argv[3] if 'duo' in input_category: category = 'duo' elif 'kong' in input_category: category = 'kong' else:
# encoding: utf-8 #客户端调用,用于查看API返回结果 from OkcoinSpotAPI import OKCoinSpot from OkcoinFutureAPI import OKCoinFuture #初始化apikey,secretkey,url apikey = 'XXXXX' secretkey = 'XXXXXXXXXXXXXXXXXXXXXXX' okcoinRESTURL = 'www.okcoin.com' #请求注意:国际账号需要 修改为 www.okcoin.com 国内站账号需要修改为www.okcoin.cn #现货API okcoinSpot = OKCoinSpot(okcoinRESTURL,apikey,secretkey) #期货API okcoinFuture = OKCoinFuture(okcoinRESTURL,apikey,secretkey) print u' 现货行情 ' print okcoinSpot.ticker('btc_usd') print u' 现货深度 ' print okcoinSpot.depth('btc_usd') print u' 现货历史交易信息 ' print okcoinSpot.trades() print u' 用户现货账户信息 ' print okcoinSpot.userinfo() print u' 现货下单 ' print okcoinSpot.trade('ltc_usd','buy','0.1','0.2')
def future_postion(self, symbol): # symbol 样例 btc_usd okcoinFuture = OKCoinFuture(okcoinRESTURL, self.apiKey, self.secretKey) return okcoinFuture.future_position(symbol, 'quarter')
from OkcoinSpotAPI import OKCoinSpot from OkcoinFutureAPI import OKCoinFuture from HttpMD5Util import * #初始化apikey,secretkey,url apikey = '4b36c965-a577-497a-a216-665cedd68655' secretkey = 'D0AB97E9CFE3F57131162952CE368191' okcoinRESTURL = 'www.okex.com' #请求注意:国内账号需要 修改为 www.okcoin.cn #现货API okcoinSpot = OKCoinSpot(okcoinRESTURL,apikey,secretkey) #期货API okcoinFuture = OKCoinFuture(okcoinRESTURL,apikey,secretkey) okcoinFuture.future_trade(symbol='eos_usd',contractType='next_week',price=str(json_eos_next_week['asks'][0][0]), amount='1',tradeType='1',matchPrice='0',leverRate='') params = {'api_key': '4b36c965-a577-497a-a216-665cedd68655', 'amount': '1', 'symbol': 'btc_usd'} params['sign'] = buildMySign(params,secretkey) okcoinFuture.futureFundTransfer('btc_usd','1', '1') okcoinFuture.futureFundTransfer('eos_usd','1', '4.98997989') param = 'symbol=eos_usdt&contract_type=quarter' httpGet("www.okex.com", "/api/v1/future_hold_amount.do", param) okcoinFuture.future_position_4fix('eos_usd','next_week','1') def getAmount(amountJson): if amountJson['holding'] == []: return 0. else: return amountJson['holding']['buy_amount']
def future_orders(self, symbol, status): # print("future_orders:" + symbol) # symbol 样例 btc_usd okcoinFuture = OKCoinFuture(okcoinRESTURL, self.apiKey, self.secretKey) #status = None (0等待成交 1部分成交 2全部成交 -1撤单 4撤单处理中) return okcoinFuture.future_orderinfo(symbol, 'quarter', -1, status=status, currentPage=1)
# create tempdata # tempdata = pd.DataFrame(columns=column) conn = mysql.connector.connect(user='******', password='******', database='btc', use_unicode=True) yconnect = create_engine( 'mysql://*****:*****@localhost:3306/btc?charset=utf8') print('database has connected') #set ssl config 总是报SSL错误,没办法只能加上下面这句,不验证SSL了。 ssl._create_default_https_context = ssl._create_unverified_context #现货API okcoinSpot = OKCoinSpot(okcoinRESTURL, apikey, secretkey) #期货API okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) print('start to request') def job(): zr_mk_qian = okcoinFuture.future_ticker('btc_usd', 'this_week') # print(zr_mk_qian) tempdata = pd.DataFrame( [[zr_mk_qian['date']] + list(zr_mk_qian['ticker'].values())], columns=column) cursor = conn.cursor() # tempdata = [zr_mk_qian['date']] + list(zr_mk_qian['ticker'].values()) # print(len(tempdata)) # cursor.execute("insert into btc_future_thisweek VALUES ([zr_mk_qian['date']] + list(zr_mk_qian['ticker'].values()))") pd.io.sql.to_sql(tempdata, 'btc_future_thisweek',
# -*- coding: utf-8 -*- # encoding: utf-8 import sys import json import time from OkcoinFutureAPI import OKCoinFuture from plan_pingcang import plan from conf import okcoin apikey = okcoin.apikey secretkey = okcoin.secretkey okcoinRESTURL = okcoin.okcoinRESTURL okcoinFuture = OKCoinFuture(okcoinRESTURL, apikey, secretkey) category = '' price = 0 trend = '' is_continue = True input_trend = sys.argv[1] input_price = sys.argv[2] input_category = sys.argv[3] if 'duo' in input_category: category = 'duo' elif 'kong' in input_category: category = 'kong' else: