#coding:gbk import pandas as pd import numpy as np import talib from datetime import datetime,timedelta import requests import json import time class TradeHelper: def __init__(self): self.periods = ['1m','5m','1d'] self.accId = "510800046918" self.fields = ["open","high","low","close","volume","amount"] self.headers = { "Content-Type": "application/json; charset=UTF-8" } self.api = "http://localhost:5000/api/v1" self.state = {} self.stocks ={} def initialize(self,C): print('Start function "TradeHelper.initialize"') url = self.api + "/trade/all_stocks" self.stocks = json.loads(requests.get(url,headers = self.headers).text) C.set_universe(list(self.stocks.keys())) print(f'Done function "initialize". count={len(self.stocks.keys())}') def get_history_data_byperiod(self,C, stock, period,start_time,end_time,count=-1): try: prices = C.get_market_data_ex(helper.fields,[stock], start_time = start_time, end_time = end_time, period = period,count=count,dividend_type='front',fill_data=True,subscribe=True) if stock in prices and len(prices[stock].index)==0: print(f'Download history data. stock={stock}, period={period}, base_eriod={period}') download_history_data(stock, period,start_time,end_time) prices = C.get_market_data_ex(self.fields,[stock], start_time = start_time, end_time = end_time, period = period,count=count,dividend_type='front',fill_data=True,subscribe=True) print(f'Retrieved {len(prices[stock].index)} items after download') return self.convert_to_kdata(stock, period, prices[stock]) except BaseException as error: print(f'Error occured on get history data. stock={stock}, period={period}, Error={error}') return None def convert_to_kdata(self, stock, period, prices): kdata = [] for index,row in prices.iterrows(): kdata.append({ "code": stock, "datetime":index, "period": period, "open":row['open'], "high":row['high'], "low":row['low'], "close":row['close'], "volume":row['volume'], "amount":row['amount'] }) return kdata def detect_bs_signal(self,C): kdata = [] bartime = timetag_to_datetime(C.get_bar_timetag(C.barpos),"%Y%m%d%H%M%S") #period = '1m' #prices = C.get_market_data_ex(helper.fields,list(self.stocks.keys()), \ # start_time = "", end_time = bartime, \ # period = period,count=1,dividend_type='none',fill_data=True,subscribe=True) #for stock in prices.keys(): # for item in self.convert_to_kdata(stock, period, prices[stock]): # kdata.append(item) period = '5m' prices = C.get_market_data_ex(helper.fields,list(self.stocks.keys()),start_time = "", end_time = bartime, period = period,count=1,dividend_type='front',fill_data=True,subscribe=True) for stock in prices.keys(): for item in self.convert_to_kdata(stock, period, prices[stock]): kdata.append(item) period ='1d' prices = C.get_market_data_ex(helper.fields,list(self.stocks.keys()),start_time = "", end_time = bartime, period = period,count=1,dividend_type='front',fill_data=True,subscribe=True) for stock in prices.keys(): for item in self.convert_to_kdata(stock, period, prices[stock]): kdata.append(item) acct_info = get_trade_detail_data(self.accId,'stock', 'account') url = self.api + "/bssignal/detect" data = json.dumps({ 'realTime': bartime, 'kdata':kdata, 'positionInfos': self.get_position_infos(C), 'allowTrade': True, 'account':{ 'Balance': acct_info[0].m_dBalance, 'available': acct_info[0].m_dAvailable, } }) if len(kdata)==0: return None responseBody = requests.post(url,data = data,headers=self.headers).text return json.loads(responseBody) def get_can_use_volume(self,stock, C): for item in get_trade_detail_data(self.accId, 'stock', 'position',"TRADEHELPER"): position_stock = f"{item.m_strInstrumentID}.{item.m_strExchangeID}" if position_stock == stock: return item.m_nCanUseVolume return 0 def get_position_infos(self,C): position_infos = [] for item in get_trade_detail_data(self.accId, 'stock', 'position',"TRADEHELPER"): stock = f"{item.m_strInstrumentID}.{item.m_strExchangeID}" position_infos.append({"code":stock, "canUseVolume":item.m_nCanUseVolume, "volume":item.m_nVolume, "price":item.m_dOpenPrice, "profit":item.m_dPositionProfit, "profitRate":item.m_dProfitRate}) return position_infos def sync_order_details(self,C,dealInfo): print(f'Start function "sync_order_details".') stock = f'{dealInfo.m_strInstrumentID}.{dealInfo.m_strExchangeID}' url = url = self.api + f"/trade/dealsync/{stock}/{dealInfo.m_strOrderSysID}" barRealTime = timetag_to_datetime(C.get_bar_timetag(C.barpos),"%Y%m%d%H%M%S") data = json.dumps({ 'dealPrice': dealInfo.m_dPrice, 'bsDirection': dealInfo.m_nOffsetFlag, 'dealTime':dealInfo.m_strTradeTime, 'dealDate':dealInfo.m_strTradeDate, 'barRealTime': barRealTime, 'volume': dealInfo.m_nVolume }) print(f'requestUrl:{url} requestBody:{data}') responseBody = requests.patch(url,data = data,headers=self.headers).text print(f'Done {responseBody}') helper = TradeHelper() def init(C): print(f'Start function "init".') helper.initialize(C) C.set_account(helper.accId) print(C.get_universe()) print(f'Done function "init".') def handlebar(C): if C.is_last_bar()==False: return else: print(f'Start function "handlebar", Bar:{get_bar_realtime(C,1)}') signals = helper.detect_bs_signal(C) if signals ==None: print('Invalid BSSignal..') return acct_info = get_trade_detail_data(helper.accId,'stock', 'account') print(f"balance {round(acct_info[0].m_dBalance,2)}, m_dAvailable:{round(acct_info[0].m_dAvailable,2)}") for stock in signals: bsas = signals[stock] limit = bsas["limit"] amount =min(acct_info[0].m_dBalance * limit,acct_info[0].m_dAvailable) volume = bsas["volume"] #建仓 if bsas["direction"]==48: if amount>=20000: passorder(23, 1102, helper.accId, stock, 5, 0,amount, 2, C) print(f"买入 {stock}") else: print(f'[买入]可用资金不足. 当前可用资金:{amount}') elif bsas["direction"]==51: #加仓 # 按 {amount} 金额加仓 if amount>=20000: passorder(23, 1102, helper.accId, stock, 5, 0,amount, 2, C) print('append') else: print(f'[加仓]可用资金不足. 当前可用资金:{amount}') elif bsas["direction"]==52: #减仓 # # 按 {volume} 持股数量 减仓 passorder(24, 1101, helper.accId, stock, 14, -1, volume, '减仓模型', 2, '', C) elif bsas["direction"]==49: volume = helper.get_can_use_volume(stock,C) if volume > 0: passorder(24, 1101, helper.accId, stock, 14, -1, volume, '减仓模型', 2, '', C) else: pass def get_bar_realtime(C,mode = 0): if mode == 1: return timetag_to_datetime(C.get_bar_timetag(C.barpos),"%Y-%m-%d %H:%M:%S") else: return timetag_to_datetime(C.get_bar_timetag(C.barpos),"%Y%m%d%H%M%S") def deal_callback(C, dealInfo): helper.sync_order_details(C,dealInfo) print('=========== dealInfo ============================================') print("资金账号" ,dealInfo.m_strAccountID) print("交易所代码" ,dealInfo.m_strExchangeID) print("交易所名称" ,dealInfo.m_strExchangeName) print("品种代码" ,dealInfo.m_strProductID) print("品种名称" ,dealInfo.m_strProductName) print("证券代码" ,dealInfo.m_strInstrumentID) print("证券名称" ,dealInfo.m_strInstrumentName) print("成交编号" ,dealInfo.m_strTradeID) print("任务号" ,dealInfo.m_nTaskId) print("下单引用,等于股票的内部委托号" ,dealInfo.m_strOrderRef) print("合同编号,报单编号,委托号" ,dealInfo.m_strOrderSysID) print("开平,股票的买卖" ,dealInfo.m_nOffsetFlag) print("成交均价" ,dealInfo.m_dPrice) print("成交量" ,dealInfo.m_nVolume) print("成交日期" ,dealInfo.m_strTradeDate) print("成交时间" ,dealInfo.m_strTradeTime) print("手续费" ,dealInfo.m_dComssion) print("成交额" ,dealInfo.m_dTradeAmount) print("合约编号" ,dealInfo.m_strCompactNo)