def context_setting(self): """ API trading and quote context setting :returns: trade context, quote context """ if self.unlock_password == "": raise Exception("请先配置交易解锁密码! password: {}".format( self.unlock_password)) quote_ctx = ft.OpenQuoteContext(host=self.api_svr_ip, port=self.api_svr_port) if 'HK.' in self.stock: trade_ctx = ft.OpenHKTradeContext(host=self.api_svr_ip, port=self.api_svr_port) if self.trade_env == ft.TrdEnv.REAL: ret_code, ret_data = trade_ctx.unlock_trade( self.unlock_password) if ret_code == ft.RET_OK: print('解锁交易成功!') else: raise Exception("请求交易解锁失败: {}".format(ret_data)) else: print('解锁交易成功!') elif 'US.' in self.stock: if self.trade_env != 0: raise Exception("美股交易接口不支持仿真环境 trade_env: {}".format( self.trade_env)) trade_ctx = ft.OpenUSTradeContext(host=self.api_svr_ip, port=self.api_svr_port) else: raise Exception("stock输入错误 stock: {}".format(self.stock)) return quote_ctx, trade_ctx
def open_api(self): SQLog.info("open_api,quote already open=", self.is_open()) if self._quote_ctx is None: self._quote_ctx = futu.OpenQuoteContext(self.ApiIP, self.ApiPort) if self._trade_ctx is None: if self.Market == futu.Market.HK: self._trade_ctx = futu.OpenHKTradeContext( self.ApiIP, self.ApiPort) elif self.Market == futu.Market.US: self._trade_ctx = futu.OpenUSTradeContext( self.ApiIP, self.ApiPort) else: raise Exception("open_api failed,Market parameter wrong.") if self.EnvType == futu.TrdEnv.REAL: ret, data = self._trade_ctx.unlock_trade( self.TradePassword, self.TradePasswordMd5) if futu.RET_OK != ret: raise Exception( "open_api failed,unlock_trade failed,data=" + str(data)) ret, data = self._trade_ctx.get_acc_list() SQLog.debug("open_api,get_acc_list,ret=", ret, "data=\n", data) self._trade_ctx.set_handler(TradeOrderHanbler(self)) self._trade_ctx.set_handler(TradeDealHandler()) self._trade_ctx.start() super().open_api() if self.AveVolaStockCodes and self._frame: self._frame.load_savequote_data( self.AveVolaStockCodes.split(',')) return True
def context_setting(api_svr_ip, api_svr_port, unlock_password): quote_ctx = ft.OpenQuoteContext(host=api_svr_ip, port=api_svr_port) hk_trade_ctx = ft.OpenHKTradeContext(host=api_svr_ip, port=api_svr_port) ret_code, ret_data = hk_trade_ctx.unlock_trade(unlock_password) if ret_code != ft.RET_OK: hk_trade_ctx = None hkcc_trade_ctx = ft.OpenHKCCTradeContext(host=api_svr_ip, port=api_svr_port) ret_code, ret_data = hkcc_trade_ctx.unlock_trade(unlock_password) if ret_code != ft.RET_OK: hkcc_trade_ctx = None us_trade_ctx = ft.OpenUSTradeContext(host=api_svr_ip, port=api_svr_port) ret_code, ret_data = us_trade_ctx.unlock_trade(unlock_password) if ret_code != ft.RET_OK: us_trade_ctx = None return quote_ctx, hk_trade_ctx, hkcc_trade_ctx, us_trade_ctx
def __init__(self, password): """ https://futunnopen.github.io/futuquant/api/Market_API_Python_Doc.html """ self.quote_ctx = ft.OpenQuoteContext(host="127.0.0.1", port=11111) self.USTrade_ctx = ft.OpenUSTradeContext(host='127.0.0.1', port=11111) self.HKTrade_ctx = ft.OpenHKTradeContext(host='127.0.0.1', port=11111) self.quote_ctx.start() self.USTrade_ctx.start() self.HKTrade_ctx.start() self.password = password
def establish_connections(user_connection_type, unlock_trade=True, user_host='127.0.0.1', user_port=11111, user_is_encrypt=None, user_security_firm=SecurityFirm.FUTUINC): ''' Ingest: Pass in connection criterias Output: Initialized instance/object of either trade/quote ''' #Validate connection type connection_type_choices = ['trade', 'quote'] assert user_connection_type in connection_type_choices, \ f'connection type must be in {[choice for choice in connection_type_choices]}' try: #Intialized trading API if user_connection_type == 'trade': trader = ft.OpenUSTradeContext(host=user_host, port=user_port, is_encrypt=user_is_encrypt, security_firm=user_security_firm) #If user wants to unlock account, ask for password to unlock if unlock_trade == True: user_pass = getpass.getpass() #Log in first in order to pull account info trader.unlock_trade(password=user_pass, is_unlock=True) return trader #Initialize quote API elif user_connection_type == 'quote': quoter = ft.OpenQuoteContext(host=user_host, port=user_port, is_encrypt=user_is_encrypt) return quoter except Exception as e: raise e
def _process_init_api(self): if type(self._quote_ctx) != int or type(self._trade_ctx) != int: return # 创建futu api对象 if self._quote_ctx == 0: self._quote_ctx = ft.OpenQuoteContext(self._api_ip, self._api_port) if self._trade_ctx == 0: if self._market == MARKET_HK: self._trade_ctx = ft.OpenHKTradeContext( self._api_ip, self._api_port) elif self._market == MARKET_US: self._trade_ctx = ft.OpenUSTradeContext( self._api_ip, self._api_port) else: raise Exception("error param!") if self._env_type == ft.TrdEnv.REAL: ret, _ = self._trade_ctx.unlock_trade(self._trade_password) if 0 != ret: raise Exception("error param!") # 开始futu api异步数据推送 self._quote_ctx.start() self._trade_ctx.start() # 市场状态检查 self._check_market_event = FutuMarketEvent(self._market, self._quote_ctx, self._event_engine) #定阅行情数据 self._futu_data_event = FutuDataEvent(self, self._quote_ctx, self._event_engine, self._tiny_strate.symbol_pools) # 启动事件 self._tiny_strate.on_start()
# 一个简单的追涨杀跌策略 import time import futu as ft list = [] quote_ctx = ft.OpenQuoteContext(host="10.0.30.140", port=11111) code = 'US.AAPL' # 选择标的 LENGTH = 12 # 样本容量 quote_ctx.subscribe(code, [ ft.SubType.QUOTE, ft.SubType.TICKER, ft.SubType.K_DAY, ft.SubType.ORDER_BOOK, ft.SubType.RT_DATA, ft.SubType.BROKER ]) # 实例化美股交易上下文对象 trade_us_ctx = ft.OpenUSTradeContext(host="10.0.30.140", port=11111) trade_us_ctx.unlock_trade(password='******') def doTicker(): print("开始执行追涨杀跌策略购买AAPL") last = quote_ctx.get_stock_quote(code) #获取最新报价 last_price = last[1].last_price if len(list) < LENGTH: list.append(last_price) #累加最近(=逐笔) else: pMax = max(list) # 取出最高价 pMin = min(list) # 取出最低价 if last_price > pMax: # 最新价是周期内的新高(追涨) account = trade_us_ctx.accinfo_query(trd_env=ft.TrdEnv.SIMULATE) print("buy " + str(account)) if account[1].power > last_price: # 资产足够(买1股) trade_us_ctx.place_order(price=last_price,
import futu as ft import pandas as pd import numpy as np import configparser config = configparser.ConfigParser() config.read('futu.config') pwd_unlock = config['DEFAULT']['Password'] trd_ctx = ft.OpenUSTradeContext(host='127.0.0.1', port=11111) trd_ctx.unlock_trade(pwd_unlock) deal_list = trd_ctx.history_deal_list_query(start=config['US']['StartDate'], end=config['US']['EndDate']) print(pd.DataFrame.to_csv(deal_list[1])) trd_ctx.close()