久久国产成人av_抖音国产毛片_a片网站免费观看_A片无码播放手机在线观看,色五月在线观看,亚洲精品m在线观看,女人自慰的免费网址,悠悠在线观看精品视频,一级日本片免费的,亚洲精品久,国产精品成人久久久久久久

分享

迅投QMT量化平臺交易接口封裝

 taozl2022 2022-12-10 發(fā)布于安徽

迅投QMT量化平臺提供了極簡客戶端,,可直接使用Python調(diào)用其提供的交易功能,。本文使用Python中的Sanic異步框架將交易接口進一步封裝成HTTP訪問接口,,方便從遠程Linux主機調(diào)用,。

定義全局環(huán)境

導入xtquant庫,、aiohttp庫,、sanic庫,設(shè)置訪問路由為/xtquant/trade,,運行的http端口為7800:

from xtquant import xtdata, xttrader, xtconstantfrom xtquant.xttrader import XtQuantTrader, XtQuantTraderCallbackfrom xtquant.xttype import StockAccountimport aiohttp, randomfrom sanic import Sanic, Blueprint, response api = Blueprint('xtquant', url_prefix='/xtquant/trade') @api.listener('before_server_start')async def before_server_start(app, loop): '''全局共享session''' global session, trader jar = aiohttp.CookieJar(unsafe=True) session = aiohttp.ClientSession(cookie_jar=jar, connector=aiohttp.TCPConnector(ssl=False)) trader = Trader() @api.listener('after_server_stop')async def after_server_stop(app, loop): '''關(guān)閉session''' await session.close() order_status = { xtconstant.ORDER_UNREPORTED: '未報', xtconstant.ORDER_WAIT_REPORTING: '待報', xtconstant.ORDER_REPORTED: '已報', xtconstant.ORDER_REPORTED_CANCEL: '已報待撤', xtconstant.ORDER_PARTSUCC_CANCEL: '部成待撤', xtconstant.ORDER_PART_CANCEL: '部撤', xtconstant.ORDER_CANCELED: '已撤', xtconstant.ORDER_PART_SUCC: '部成', xtconstant.ORDER_SUCCEEDED: '已成', xtconstant.ORDER_JUNK: '廢單', xtconstant.ORDER_UNKNOWN: '未知'} if __name__ == '__main__': app = Sanic(name='xtquant') app.config.RESPONSE_TIMEOUT = 600000 app.config.REQUEST_TIMEOUT = 600000 app.config.KEEP_ALIVE_TIMEOUT = 600 app.blueprint(api) app.run(host='0.0.0.0', port=7800, workers=1, auto_reload=True, debug=False)

定義交易賬戶全局信息類

這里使用單例模式,,確保Trader中的RPC實例和賬戶信息唯一:

class Singleton(object):    _instance = None     def __new__(class_, *args, **kwargs):        if not isinstance(class_._instance, class_):            class_._instance = object.__new__(class_, *args, **kwargs)        return class_._instance class Trader(Singleton):    xt_trader = None    account = None     def set_trader(self, qmt_dir, session_id):        self.xt_trader = XtQuantTrader(qmt_dir, session_id)        # 啟動交易線程        self.xt_trader.start()        # 建立交易連接,返回0表示連接成功        connect_result = self.xt_trader.connect()        return connect_result        def set_account(self, account_id, account_type):        self.account = StockAccount(account_id, account_type=account_type)        return self.account     @property    def get_account(self):        return self.account        @property    def get_trader(self):        return self.xt_trader

賬號登錄

隨機設(shè)置一個session_id值,,并傳入極簡客戶端用戶目錄和賬號ID,、類型,連接客戶端:

@api.route('/login', methods=['GET'])async def login(request): ''' 賬號登錄 ''' session_id = int(request.args.get('session_id', random.randint(20000, 60000))) qmt_dir = request.args.get('qmt_dir', 'C:\\gszq\\qmt\\userdata_mini') account_id = request.args.get('account_id', '') account_type = request.args.get('account_type', 'STOCK') # 賬號類型,,可選STOCK,、CREDIT connect_result = trader.set_trader(qmt_dir, session_id) trader.set_account(account_id, account_type=account_type) print('交易連接成功!') if connect_result == 0 else print('交易連接失??!') return response.json({'status': connect_result})

查詢功能封裝

查詢資產(chǎn)、當前持倉,、當日成交,、當日委托等:

@api.route('/query/assets', methods=['GET'])async def query_assets(request):    '''    查詢總資產(chǎn)    '''    asset = trader.xt_trader.query_stock_asset(trader.account)    return response.json({'總資產(chǎn)': asset.total_asset, '現(xiàn)金': asset.cash, '持倉市值': asset.market_value, '凍結(jié)金額': asset.frozen_cash}) @api.route('/query/holding', methods=['GET'])async def query_holding(request):    '''    查詢當前持倉    '''    holding = []    for p in trader.xt_trader.query_stock_positions(trader.account):        holding.append([{'股票代碼': p.stock_code, '持倉': p.volume, '可用持倉': p.can_use_volume, '成本': p.open_price, '持倉市值': p.market_value}])    return response.json(holding, ensure_ascii=False) @api.route('/query/trade', methods=['GET'])async def query_trade(request):    '''    查詢當日成交    '''    trades = trader.xt_trader.query_stock_trades(trader.account)     result = []    for trade in trades:        result.append({'股票代碼': trade.stock_code, '委托類型': trade.order_type, '成交數(shù)量': trade.traded_volume, '成交均價': trade.traded_price, '成交金額': trade.traded_amount, '成交時間': trade.traded_time, '成交編號': trade.traded_id, '柜臺合同編號': trade.order_sysid})    return response.json(result, ensure_ascii=False) @api.route('/query/order', methods=['GET'])async def query_order(request):    '''    查詢當日委托    '''    order_id = request.args.get('order_id', '')    if order_id == '':        orders = trader.xt_trader.query_stock_orders(trader.account)    else:        orders = trader.xt_trader.query_stock_order(trader.account, int(order_id))        # 訂單不存在,下單失敗        if orders is None:            return response.json([], ensure_ascii=False)        orders = [orders]    result = []    for order in orders:        result.append({'股票代碼': order.stock_code, '委托數(shù)量': order.order_volume, '成交數(shù)量': order.traded_volume, '委托價格': order.price, '委托類型': order.order_type, '委托狀態(tài)': order_status.get(order.order_status), '訂單編號': order.order_id, '柜臺合同編號': order.order_sysid, '報單時間': order.order_time})    return response.json(result, ensure_ascii=False)

交易功能封裝

包含下單和撤單兩類,,下單成功會返回一個大于0的訂單號,,撤單只需傳入這個訂單號即可,,撤單成功返回0。

注意:有時會存在下單失敗的情況,,因此最好下單后使用查詢當日委托接口查詢訂單是否真的傳送到客戶端,,如果不存在則重新下單

@api.route('/place_order', methods=['GET'])async def trade_place_order(request): ''' 下單 ''' stock_code = request.args.get('stock_code', '510300.SH') direction = xtconstant.STOCK_BUY if request.args.get('direction', 'buy') == 'buy' else xtconstant.STOCK_SELL volumn = int(request.args.get('volumn', '100')) price = float(request.args.get('price', '4.4')) order_id = trader.xt_trader.order_stock(trader.account, stock_code, direction, volumn, xtconstant.FIX_PRICE, price, 'strategy_name', 'remark') return response.json({'order_id': order_id}, ensure_ascii=False) @api.route('/cancel_order', methods=['GET'])async def trade_cancel_order(request): ''' 撤單 ''' order_id = int(request.args.get('order_id', '0')) cancel_order_result = trader.xt_trader.cancel_order_stock(trader.account, order_id) return response.json({'cancel_order_result': cancel_order_result}, ensure_ascii=False)

功能測試

0x00 啟動服務器端

python trade_service.py

0x01 登錄

import requestsprint(requests.get('http://127.0.0.1:7800/xtquant/trade/login?account_id=******').json()) {'status': 0}

0x02 下單

print(requests.get('http://127.0.0.1:7800/xtquant/trade/place_order?stock_code=113025.SH&price=300&volumn=10').json()) {'order_id': 403701775}

0x03 撤單

print(requests.get('http://127.0.0.1:7800/xtquant/trade/cancel_order?order_id=403701775').json()) {'cancel_order_result': 0}

0x04 查詢訂單

print(requests.get('http://127.0.0.1:7800/xtquant/trade/query/order?order_id=403701775').json()) [{'股票代碼': '113025.SH', '委托數(shù)量': 10, '成交數(shù)量': 0, '委托價格': 300.0, '委托類型': 23, '委托狀態(tài)': '已撤', '訂單編號': 403701775, '柜臺合同編號': '131', '報單時間': 165721*****}]

注意:僅供參考,使用后果自負,,由此造成的損失概不負責,。為保證安全請設(shè)置訪問防火墻,禁止用于非法用途,!

    本站是提供個人知識管理的網(wǎng)絡存儲空間,,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點,。請注意甄別內(nèi)容中的聯(lián)系方式,、誘導購買等信息,謹防詐騙,。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多