STU 04 直播代码 ==> papertrading部分的策略代码
发布于 1 个月前 作者 yutiansut 191 次浏览 来自 代码实现
#
import datetime
import json
import threading
import time
import uuid

import pandas as pd

import QUANTAXIS as QA
from QAPUBSUB.consumer import subscriber
from QUANTAXIS.QAEngine.QAThreadEngine import QA_Thread
from QUANTAXIS.QAIndicator.indicators import QA_indicator_MA


"""
本代码是STU04直播时随手写的, 不超过100行, 完整讲述了如何

1. 基于QIFI流程订阅数据

2. 接受推送的行情并进行处理

3. 维护一个模拟账户/ 把单子发送出去  [订单流]

4. 此代码需要配合直播中讲的  QAREALTIME_COLLECTOR / QARANDOM_PRICE使用

"""


class QASIMStrategy(QA_Thread):
    def __init__(self, code, freq):
        super().__init__()

        self.code = code
        self.freq = freq

        self.sub = subscriber(
            exchange='realtime_{}_{}'.format(self.freq, self.code))

        self.sub.callback = self.receive_bar

        self.market_data = []
        self.dt = None

        threading.Thread(target=self.sub.start).start()

        self.user = QA.QA_User(username='admin', password='admin')
        self.port = self.user.new_portfolio('test', )
        self.account = self.port.new_account(
            str(uuid.uuid4()), init_cash=100000, market_type=QA.MARKET_TYPE.FUTURE_CN)

        self.account.save()

        QA.DATABASE.risk.update({
            'account_cookie': self.account.account_cookie,
            'portfolio_cookie': self.account.portfolio_cookie,
            'user_cookie': self.account.user_cookie
        }, {
            'account_cookie': self.account.account_cookie,
            'portfolio_cookie': self.account.portfolio_cookie,
            'user_cookie': self.account.user_cookie
        }, upsert=True)

    def receive_bar(self, a, b, c, bar):
        lastest_data = json.loads(str(bar, encoding='utf-8'))

        self.datetime = lastest_data['datetime']

        if self.dt != lastest_data['datetime'][0:16] or len(self.market_data) < 1:
            self.dt = lastest_data['datetime'][0:16]
            print('生成新的bar {}'.format(self.datetime))
            self.market_data.append(lastest_data)

        else:
            self.market_data[-1] = lastest_data

        self.on_bar(self.market_data)

    def on_bar(self, bar):
        data = pd.DataFrame(bar).set_index(['datetime', 'code'])

        # print(data)

        ind = QA_indicator_MA(data, 3, 5)

        # print(ind)

        if (ind.MA3-ind.MA5).iloc[-1] > 0:
            # 上穿

            if self.account.hold_available.get(self.code, 0) == 0:
                self.send_order(direction='BUY', offset='OPEN',
                                price=float(bar[-1]['close']), volume=10)

        else:

            if self.account.hold_available.get(self.code, 0) > 0:
                self.send_order(direction='SELL', offset='CLOSE',
                                price=float(bar[-1]['close']), volume=10)
            #self.send_order(self.code, bar[-1].close)

    def send_order(self, direction='BUY', offset='OPEN', price=3925, volume=10, order_id=QA.QA_util_random_with_topic('QASIM')):
        print('下单 {} {} {} {}'.format(direction, offset, price, volume))
        towards = eval('QA.ORDER_DIRECTION.{}_{}'.format(direction, offset))
        self.account.receive_simpledeal(
            code=self.code, trade_price=price,
            trade_amount=volume, trade_towards=towards,
            order_id=order_id, trade_time=self.datetime
        )
        self.account.save()

    def run(self):
        """run

        此处是主线程逻辑/  你可以在此处理风控/ 监听等相关/ 或者是维护一个事件驱动
        """
        while True:
            time.sleep(1)


if __name__ == "__main__":
    QASIMStrategy('RB2001', '1min').start()

2 回复

分别开启三个

QARC_Random  --code  RB2001 --date 20191009 --price 3800  --interval 1
QARC_CTP  --code RB2001
QARC_Resample --code RB2001 --freq 1min

赞~~~~~~~~~~~~~~~~~~~~~~~~

回到顶部