1
lhr
2024-07-12 9ea34726d18efeab27a94abdcd7d3685ea51b3bd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import time
import datetime
import decimal
import logging
# import threading
from gm.api import *
# 引入基础方法模块
import basic_methods
# 引入全局变量模块
import data_cache
 
 
 
# 第一步:初始化context函数,数据订阅
def init(context):
    # init_data()
 
    # 初始化get_subscribe_data方法函数,下单买逻辑才会运行中。。。【核心主线程,随时考虑其启动顺序】>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # threading.Thread(target=lambda: get_subscribe_data(), daemon=True).start()
 
    # subscribe(symbols='SZSE.000333', frequency='tick', count=5, unsubscribe_previous=True)
    # time.sleep(5)
    # print(f"test===={test}")
 
    # account_finance = context.account(account_id = 'aaee2221-839c-11ee-a7cd-00163e022aa6').cash
    # print(f"账户对象列表==={account_finance}")
    # print(f"资金初始时间==={account_finance.created_at}")
    # print(f"资金变更时间==={account_finance.updated_at}")
 
    # print(f"总资金==={account_finance.nav}")
    # print(f"可用资金==={account_finance.available}")
    # print(f"持仓占用资金==={account_finance.frozen}")
    # print(f"冻结资金==={account_finance.order_frozen}")
    # print(f"盈亏===={account_finance.pnl}")
    # print(f"持仓浮动盈亏==={account_finance.fpnl}")
    # print(f"持仓市值==={account_finance.market_value}")
    # print(f"资金余额==={account_finance.balance}")
    # print(f"累计出入金额==={account_finance.cum_inout}")
    # print(f"累计交易金额==={account_finance.cum_trade}")
    # print(f"累计盈亏==={account_finance.cum_pnl}")
    # print(f"累计委托==={account_finance.cum_commission}")
    # print(f"最后一笔交易==={account_finance.last_trade}")
    # print(f"最后一笔委托==={account_finance.last_commission}")
    # print(f"最后一笔出入金额==={account_finance.last_inout}")
    # print(f"允许保释??==={account_finance.enable_bail}")
    # print(f"纯浮动盈亏??==={account_finance.fpnl_diluted}")
    # 保持开启 , 为了实现永不完成这堆初始化线程 ,因为一旦完成,整体获取current数据变慢为15S+
    while True:  # 不得擅动!!!
        time.sleep(10)
 
 
# 仓位管理策略(核心逻辑流程:先卖后买,止盈止损)
# 如果有持仓,那么就看开盘价是否为涨停价(是则不卖,炸板则卖),开盘价是否为当日涨幅>5%(是则不卖,走跌则卖),否则开盘走跌振幅大于1.5%则卖。
def position_management(context):
    # 仓位管理及查询函数
    def position_query():
        Account_positions = context.account(account_id = data_cache.account_id).positions()  # 查询当前账户全部持仓
        # print(f"Account_positions==={Account_positions}")
        for d in Account_positions:
            data_cache.position_symbols_set.add(d['symbol'])
        print(
            f"仓位管理启动时持仓===============================================================【{data_cache.position_symbols_set}】")
        print(
            f"仓位管理前持仓数量===============================================================【{len(data_cache.position_symbols_set)}】")
        for d in Account_positions:
            symbol = d['symbol']
            symbol_code = symbol.split('.')[1]  # 将symbol转为纯数字编号
            available_now = d['available_now']
            # price = d['price']   #当前行情价,,,非最新价,没有实际意义不要用!!!
            vwap = d['vwap']
            volume = d['volume']
            volume_today = d['volume_today']
            volume_yesterday = volume - volume_today
            new_price = current(symbol, fields='price')[0]['price']
            # print(symbol,available_now, price, vwap)
            instruments = get_instruments(symbols=symbol, exchanges=None, sec_types=None, names=None,
                                          fields="symbol,sec_name,pre_close,upper_limit",
                                          df=False)
            if available_now != 0:  # 如果可用资金不等于0  昨日收盘价获取到非0值时(不知名原因导致有些票会获取到0值导致后续公式报错,阻止intraday_growth函数正常运行)
                print(f"持仓可用股{symbol}")
                data_cache.available_symbols_set.add(symbol)
                print(f"今日可用持仓数量=================================================================【{len(data_cache.available_symbols_set)}】")
                history_data = history(symbol=symbol, frequency='1d', start_time=data_cache.double_pre_trading_day,
                                       end_time=data_cache.pre_trading_day, fields='open, close, low, high, eob',
                                       adjust=ADJUST_PREV, df=False)
                # print(f"len(history_data)==={len(history_data)}history_data========={history_data} ")
                print(
                    f"【{instruments[0]['sec_name']}】上个交易日 最高{history_data[1]['high']},收盘{history_data[1]['close']}")
                # 获取昨日涨停价 目前函数中的pre_close应该传入前天的收盘价,而非昨天的
                yesterday_limit_up_price = basic_methods.limit_up_price(history_data[0]['close'])
                today_limit_up_price = basic_methods.limit_up_price(history_data[1]['close'])
                # print(f'涨停价算对了吗?{yesterday_top_price}')
                if history_data[0]['close'] == 0:
                    print(f"{symbol}的修改后的history_data的昨日收盘价也为000000000000000000")
                today_growth = basic_methods.intraday_growth(new_price, history_data[1]['close'])
                # 如果持仓股 昨日未涨停 并且 今日最新价不等于今日涨停价 并且 今日涨幅小于3%
                if abs(yesterday_limit_up_price - float(decimal.Decimal(history_data[1]['close']))) < 0.001:
                    print(
                        f"昨日涨停  不卖!【{instruments[0]['sec_name']}】它的今日涨幅为{today_growth}。它的最新价:{new_price},它的昨日收盘价:{history_data[1]['close']},它的昨日涨停价{yesterday_limit_up_price}")
                elif today_limit_up_price == new_price:
                    print(
                        f"今日涨停  不卖!【{instruments[0]['sec_name']}】它的今日涨幅为{today_growth}。它的最新价:{new_price},它的昨日收盘价:{history_data[1]['close']},它的昨日涨停价{yesterday_limit_up_price}")
                elif today_growth > 2:
                    print(
                        f"开盘涨幅大于2%  不卖!【{instruments[0]['sec_name']}】它的今日涨幅为{today_growth}。它的最新价:{new_price},它的昨日收盘价:{history_data[1]['close']},它的昨日涨停价{yesterday_limit_up_price}")
                else:
                    print(f"卖前持仓数量{len(data_cache.position_symbols_set)}")
                    # sell_order(symbol, volume_yesterday, instruments[0]['sec_name'])
 
                    if history_data[1]['close'] == history_data[1]['high']:
                        print(f"昨日涨停可能判断出错!!!{instruments[0]['sec_name']}")
                    print(
                        f"持仓可用今日开盘涨幅【{instruments[0]['sec_name']}】,它的今日涨幅为{today_growth}。它的最新价:{new_price},它的昨日收盘价:{history_data[1]['close']},它的昨日涨停价{yesterday_limit_up_price},它的前日收盘价:{history_data[0]['close']}")
                # print(f"持仓股 历史数据{history_data}")
                print(f"--------------------------------------------------------------------------------------[分割线]")
 
            if available_now == 0:  # 如果可用资金等于0,又在持仓中,就是今天新增持仓
                data_cache.addition_position_symbols_set.add(symbol)
        print(f"今日新增持仓数量=================================================================【{len(data_cache.addition_position_symbols_set)}】")
 
    # 仓位管理时间定时执行函数  (默认设定为9:31)
    def check_time():
        # now = global_context.now  # 获取当前时间
        now = datetime.datetime.now()
        hour = now.hour
        minute = now.minute
        if hour > 9 or (hour == 9 and minute >= 40):
            print(f"开盘时间到了:{now}")
            position_query()
            return False  # 返回False,表示结束循环
        else:
            return True  # 返回True,表示继续循环
 
    # 使用while循环和check_time函数检查时间,并设置固定的时间间隔
    while check_time():
        time.sleep(1)
 
def maximum_buying_ratio():
    # 可用余额比例分配方法函数
    if len(data_cache.addition_position_symbols_set) < 1:
        ratio = 0.25
    elif len(data_cache.addition_position_symbols_set) < 2:
        ratio = 0.33
    elif len(data_cache.addition_position_symbols_set) < 3:
        ratio = 0.5
    elif len(data_cache.addition_position_symbols_set) < 4:
        ratio = 0.75
    else:
        ratio = 0.01
 
    # account_finance = data_cache.account(account_id='aaee2221-839c-11ee-a7cd-00163e022aa6').cash
    # ratio_value = int(account_finance.available * ratio)
    # print(f"可用金额=={account_finance.available}")
    # print(f"计划下单金额==={ratio_value}")        data_cache.context,, ratio_value