def init(ContextInfo):
#输入券商名称
ContextInfo.set_broker("broker")
#输入账号
ContextInfo.set_account("account")
#输入登录密码
ContextInfo.set_password("pw")
#输入通讯密码;如无通讯密码,无需输入
ContextInfo.set_passwordCommu("pwCom")
#输入投顾老师对应投顾服务名称
#若留空,则自动选择近期最优投顾老师的产品
ContextInfo.service = ""
#以下是条件单系统代码,请勿随意修改
def handlebar(ContextInfo):
account = ContextInfo.get_account()
current_date = datetime.strftime(ContextInfo.get_bar_timetag(ContextInfo.barpos), '%Y-%m-%d')
# 获取持仓和现金
holdings = {p.m_strInstrumentID: p.m_nVolume
for p in get_trade_detail_data(account, 'STOCK', 'POSITION')}
available_cash = get_trade_detail_data(account, "STOCK", "ACCOUNT")[0].m_dAvailable
# 处理止盈止损
for stock in list(holdings):
current_price = ContextInfo.get_last_price(stock)
buy_price = ContextInfo.buy_prices.get(stock)
if current_price and buy_price:
profit_ratio = (current_price - buy_price) / buy_price
if profit_ratio >= ContextInfo.stop_profit or profit_ratio <= -ContextInfo.stop_loss:
# 卖出操作
passorder(24, 1101, account, stock, 5, -1, holdings[stock], ContextInfo)
del ContextInfo.buy_prices[stock], holdings[stock]
print(f'{"止盈" if profit_ratio > 0 else "止损"} | {stock} | 收益率: {profit_ratio:.1%}')
# 交易参数
ContextInfo.stop_profit = profitTarget # 止盈比例
ContextInfo.stop_loss = lossTarget # 止损比例
ContextInfo.buy_prices = {} # 买入价格记录
# 执行买入逻辑
target_stock_count = max(1, int(available_cash // 10000))
stock_pool = TradeTools().get_securities(ContextInfo.service)
for stock in (s for s in stock_pool if s not in holdings):
if target_stock_count <= 0: break
current_price = ContextInfo.get_last_price(stock)
min_lot = 200 if stock.startswith('688') else 100 # 科创板200股/手
if current_price and (shares := (min(10000, available_cash) // current_price // min_lot * min_lot) >= min_lot:
passorder(23, 1101, account, stock, 5, -1, shares, ContextInfo)
ContextInfo.buy_prices[stock] = current_price
available_cash -= shares * current_price
target_stock_count -= 1
# 回调函数组
def account_callback(_, acc): print(f'[账户] 可用:{acc.m_dAvailable:.1f} 总资产:{acc.m_dBalance:.1f}')
def order_callback(_, ord): print(f'[委托] {ord.m_strInstrumentID} {ord.m_strStatus} {ord.m_nVolume}手')
def deal_callback(_, deal): print(f'[成交] {deal.m_strInstrumentID} {deal.m_nVolume}@{deal.m_dPrice:.2f}')
class TradeTools:
"""股票池获取工具"""
def get_securities(self, service):
try:
response = requests.post("https://www.shgsec.com/api/investment/strategy/securities/list",
json={"strategy": service}, timeout=5).json()
return [s for s in response.get('stocks', [])
if re.match(r'^(60\d{4}|00\d{4}|688\d{3})\.(SH|SZ)$', s)]
except Exception as e:
return self._load_local_cache(service)
def _load_local_cache(self, service):
cache_file = f"stock_cache_{service}.json"
return json.load(open(cache_file)) if os.path.exists(cache_file) else []