QAStrategySyncOrders 一个随意的示例跟单代码
发布于 3 个月前 作者 yutiansut 305 次浏览 来自 文档
from QAPUBSUB.consumer import subscriber_routing, subscriber_topic
from QAPUBSUB.producer import publisher_routing
from qaenv import eventmq_ip, mongo_ip
import json
import pymongo
import requests
import datetime
import uuid
import QUANTAXIS as QA
import sys

import pyttsx3

now = str(datetime.datetime.now)

weights ={'Kx21x_5min': 0.2,}
# 下面的参数自行填写
# user, strategy_id, account, code, direction, offset, price, volume,


class QAStrategySyncOrders():
    """

    订单同步器

    如何挂实盘账户请看 QATrader

    http://www.yutiansut.com:3000/topic/5dc865e8c466af76e9e3bdd1

    你可以理解成这是一个流处理的过程

    simid  被跟单的策略的id
    realid 实盘账户id
    realamount  实盘账户的订单数量
    """

    def __init__(self, realid, realamount=1):
        self.m = QA.QAARP.MARKET_PRESET()
        self.sub = subscriber_topic(
            exchange='QASTRATEGY', host='127.0.0.1', routing_key='*')
        self.pub = publisher_routing(user='admin', password='admin',
                                     exchange='QAORDER_ROUTER', host=eventmq_ip, routing_key=realid)
        self.realamount = realamount
        self.realid = realid

        self.db = pymongo.MongoClient('127.0.0.1').QAREALTIME.account
#     def add_subscriber(self, simid):
#         self.sub.add_sub('QAORDER_ROUTER', simid)

    def callback(self, a, b, c, data):
        order = json.loads(data, encoding='utf-8')['trade']
        #print(order)
        # if 'limit_price' not in order:
        #     order['limit_price'] =  order['price']
        p = order['limit_price']
        order['instrument_id'] = order['instrument_id'].replace('_', '.')
        pricetick = self.m.get_price_tick(order['instrument_id'])

        #sig = 1 if order['direction'] == 'BUY' else -1
        sig =0
        
        order['limit_price'] = (int(p/pricetick) + sig)*pricetick
        if order['aid'] == 'insert_order':
            self.on_order(order)

    def on_order(self, order):
        """在此处理你的订单逻辑

        如果你订阅了多个策略账户 则order['account_cookie']不相同

        Arguments:
            order {[type]} -- [description]
            {'aid': 'insert_order', 'user_id': 'Kx21x_5min', 
            'order_id': 'f3b4958c-52a1-11e7-8002-010203040506', 'exchange_id': '', 
            'instrument_id': 'cs2009', 'direction': 'BUY', 'offset': 'CLOSE', 'volume': 1, 
            'price_type': 'LIMIT', 'limit_price': 2485.0, 'volume_condition': 'GFD', 'time_condition': 'AND'}
        """
        # self.send_order(order)

        now = str(datetime.datetime.now())

        order['exchange_id'] = self.m.get_exchange(order['instrument_id'])

        # self.send_axxorder(order)
        mp = QA.QAARP.MARKET_PRESET()
        name = mp.get_name(order['instrument_id'])


        try:

            if order['user_id'] in list(weights.keys()):

                print(order)
                order['order_id'] = 'QAORDER'+str(uuid.uuid4())

                self.send_order(order)

        except Exception as e:
            print('error', e)
        # engine = pyttsx3.init()
        # engine.say(f"{name}{'平仓啦!' if order['offset'] == 'CLOSE' else '开仓啦! '}, 策略{order['user_id'].split('_')[1]},\
        #     {order['user_id'].split('_')[3][:-3]}分钟的{order['instrument_id']}, 方向{'多' if order['direction'] == 'BUY' else '空'} ,\
        #         价格{order['limit_price']} ,{order['volume']}手")
        # engine.runAndWait()
        # 朗读一次  
    def send_order(self, order):

        try:
            order['order_offset'] = order['offset']
            hold = self.db.find_one({'account_cookie': self.realid})['positions']
            pos = hold.get('{}.{}'.format(order['exchange_id'], order['instrument_id']), {})
            order['order_direction'] = order['direction']
            order['price'] = order['limit_price']
            if order['offset'] == 'CLOSE':
                if order['direction'] == 'BUY':
                    if pos['volume_short_his'] >= self.realamount:
                        order['order_offset'] = 'CLOSE'
                    if pos['volume_short_today'] >= self.realamount:
                        order['order_offset'] = 'CLOSETODAY'
                elif order['direction'] == 'SELL':
                    if pos['volume_long_his'] >= self.realamount:
                        order['order_offset'] = 'CLOSE'
                    if pos['volume_long_today'] >= self.realamount:
                        order['order_offset'] = 'CLOSETODAY'

            order['topic'] = 'sendorder'
            order['code'] = order['instrument_id']
            order['account_cookie'] = self.realid
            order['user_id'] = self.realid
            order['volume'] = self.realamount
            order['order_direction'] = order['direction']
            print('order to send', order)
            self.pub.pub(json.dumps(order), routing_key=self.realid)
        except Exception as e:
            print("--------------ERROR-------------", type(e), e)

    def lang(self):
        engine = pyttsx3.init()
        engine.say('QUANTAXIS 系统正在启动')
        print('say')
        engine.runAndWait()

    def start(self):
        self.sub.callback = self.callback
        self.sub.start()


if __name__ == "__main__":
    b = QAStrategySyncOrders('自行填写跟单')
    b.lang()
    b.start()
回到顶部