Exemplo n.º 1
0
    def __init__(self, event_engine: EventEngine = None):
        """"""
        if event_engine:
            self.event_engine = event_engine
        else:
            self.event_engine = EventEngine()
        self.event_engine.start()

        self.engines = {'Event':self.event_engine}
        self.exchanges = []
Exemplo n.º 2
0
    def __init__(self, event_engine: EventEngine = None):
        """"""
        if event_engine:
            self.event_engine = event_engine
        else:
            self.event_engine = EventEngine()
        self.event_engine.start()

        self.gateways = {}
        self.engines = {}
        self.apps = {}

        self.init_engines()
Exemplo n.º 3
0
    def __init__(self, event_engine: EventEngine = None):
        """"""
        if event_engine:
            self.event_engine: EventEngine = event_engine
        else:
            self.event_engine = EventEngine()
        self.event_engine.start()

        self.gateways: Dict[str, BaseGateway] = {}
        self.engines: Dict[str, BaseEngine] = {}
        self.apps: Dict[str, BaseApp] = {}
        self.exchanges: List[Exchange] = []

        os.chdir(TRADER_DIR)  # Change working directory
        self.init_engines()  # Initialize function engines
Exemplo n.º 4
0
    def __init__(self):

        Strategy.__init__(self)

        self.pm = PortfolioManager()
        self.pm.strategy = self

        # TODO remove
        self.eventEngine = EventEngine()
        self.eventEngine.register(eventType.EVENT_TIMER, self.on_cycle)
        self.eventEngine.register(eventType.EVENT_MD_QUOTE, self.on_quote)
        self.eventEngine.register(eventType.EVENT_TRADE_IND,
                                  self.pm.on_trade_ind)
        self.eventEngine.register(eventType.EVENT_ORDERSTATUS_IND,
                                  self.pm.on_order_status)
def main():
    """主程序入口"""
    # 创建Qt应用对象
    qApp = createQApp()

    # 创建事件引擎
    ee = EventEngine()

    # 创建主引擎
    me = MainEngine(ee)

    # 添加交易接口
    me.addGateway(secGateway)
    me.addGateway(ctpGateway)
    me.addGateway(ctpsecGateway)

    # 添加上层应用
    me.addApp(riskManager)
    me.addApp(optionMaster)

    # 创建主窗口
    mw = MainWindow(me, ee)
    mw.showMaximized()

    # 在主线程中启动Qt事件循环
    sys.exit(qApp.exec_())
Exemplo n.º 6
0
def main():
    """主程序入口"""
    # 创建Qt应用对象
    qApp = createQApp()

    # 创建事件引擎
    ee = EventEngine()

    # 创建主引擎
    me = MainEngine(ee)

    # 添加交易接口
    me.addGateway(ctpGateway)
    #  me.addGateway(oandaGateway)
    #  me.addGateway(ibGateway)

    # 添加上层应用
    me.addApp(ctaStrategy)
    me.addApp(riskManager)
    me.addApp(spreadTrading)
    me.addApp(dataRecorder)

    # 创建主窗口
    mw = MainWindow(me, ee)
    mw.showMaximized()

    # 在主线程中启动Qt事件循环
    sys.exit(qApp.exec_())
Exemplo n.º 7
0
def main():
    qapp = create_qapp('My Trading System')

    event_engine = EventEngine()
    # event_engine.start()
    main_engine = MainEngine(event_engine)
    main_window = MainWindow(main_engine, event_engine)
    main_window.showMaximized()

    qapp.exec()
Exemplo n.º 8
0
def main():
    """主程序入口"""
    le = LogEngine()
    le.setLogLevel(le.LEVEL_INFO)
    le.addConsoleHandler()
    le.addFileHandler()

    le.info(u'启动JAQS服务进程')

    ee = EventEngine()
    le.info(u'事件引擎创建成功')

    me = MainEngine(ee)
    me.addGateway(ctpGateway)
    me.addApp(jaqsService)
    le.info(u'主引擎创建成功')

    ee.register(EVENT_LOG, le.processLogEvent)
    ee.register(EVENT_JS_LOG, le.processLogEvent)
    le.info(u'注册日志事件监听')

    me.connect('CTP')
    le.info(u'连接CTP接口')

    while True:
        sleep(1)
Exemplo n.º 9
0
def main():
    """"""
    qapp = create_qapp()

    event_engine = EventEngine()

    main_engine = MainEngine(event_engine)

    main_engine.add_gateway(CtpGateway)

    main_window = MainWindow(main_engine, event_engine)
    main_window.showMaximized()

    qapp.exec()
Exemplo n.º 10
0
class MainEngine:

    def __init__(self, event_engine: EventEngine = None):
        """"""
        if event_engine:
            self.event_engine = event_engine
        else:
            self.event_engine = EventEngine()
        self.event_engine.start()

        self.engines = {'Event':self.event_engine}
        self.exchanges = []


    def add_engine(self, engine_class: Any):
        """
        Add function engine.
        """
        engine = engine_class(self, self.event_engine)
        # print(engine.engine_name)
        self.engines[engine.engine_name] = engine
        return engine


    def subscribe(self, req:OrderRequest ):
        """
        Subscribe tick data update of a specific gateway.
        """


        gateway = Gateway(self.event_engine,req.symbol, req.exchange)
        gateway.generate_Tick()


    def send_order(self, req: OrderRequest, ):
        """
        Send new order request
        """
        self.subscribe(req)


        self.event_engine.put(req)


    def close(self):
        """
        Make sure every gateway and app is closed properly before
        programme exit.
        """
        # Stop event engine first to prevent new timer event.
        self.event_engine.stop()
Exemplo n.º 11
0
def main():
    """主程序入口"""
    # 创建Qt应用对象
    qApp = createQApp()
    
    # 创建事件引擎
    ee = EventEngine()
    
    # 创建主引擎
    reqAddress = 'tcp://localhost:2014'
    subAddress = 'tcp://localhost:0602'    
    me = MainEngineProxy(ee)
    me.init(reqAddress, subAddress)
    
    # 创建主窗口
    mw = MainWindow(me, ee)
    mw.showMaximized()
    
    # 在主线程中启动Qt事件循环
    sys.exit(qApp.exec_())
Exemplo n.º 12
0
def main():
    """主程序入口"""
    # 创建Qt应用对象
    qApp = createQApp()

    # 创建事件引擎
    ee = EventEngine()

    # 创建主引擎
    me = MainEngine(ee)

    # 添加交易接口
    me.addGateway(ctpGateway)

    # 添加上层应用
    me.addApp(jaqsService)

    # 创建主窗口
    mw = MainWindow(me, ee)
    mw.showMaximized()

    # 在主线程中启动Qt事件循环
    sys.exit(qApp.exec_())
Exemplo n.º 13
0
class MainEngine:
    """
    Acts as the core of VN Trader.
    """
    def __init__(self, event_engine: EventEngine = None):
        """"""
        if event_engine:
            self.event_engine: EventEngine = event_engine
        else:
            self.event_engine = EventEngine()
        self.event_engine.start()

        self.gateways: Dict[str, BaseGateway] = {}
        self.engines: Dict[str, BaseEngine] = {}
        self.apps: Dict[str, BaseApp] = {}
        self.exchanges: List[Exchange] = []

        os.chdir(TRADER_DIR)  # Change working directory
        self.init_engines()  # Initialize function engines

    def add_engine(self, engine_class: Any) -> "BaseEngine":
        """
        Add function engine.
        """
        engine = engine_class(self, self.event_engine)
        self.engines[engine.engine_name] = engine
        return engine

    def add_gateway(self, gateway_class: Type[BaseGateway]) -> BaseGateway:
        """
        Add gateway.
        """
        gateway = gateway_class(self.event_engine)
        self.gateways[gateway.gateway_name] = gateway

        # Add gateway supported exchanges into engine
        for exchange in gateway.exchanges:
            if exchange not in self.exchanges:
                self.exchanges.append(exchange)

        return gateway

    def add_app(self, app_class: Type[BaseApp]) -> "BaseEngine":
        """
        Add app.
        """
        app = app_class()
        self.apps[app.app_name] = app

        engine = self.add_engine(app.engine_class)
        return engine

    def init_engines(self) -> None:
        """
        Init all engines.
        """
        self.add_engine(LogEngine)
        self.add_engine(OmsEngine)
        self.add_engine(EmailEngine)

    def write_log(self, msg: str, source: str = "") -> None:
        """
        Put log event with specific message.
        """
        log = LogData(msg=msg, gateway_name=source)
        event = Event(EVENT_LOG, log)
        self.event_engine.put(event)

    def get_gateway(self, gateway_name: str) -> BaseGateway:
        """
        Return gateway object by name.
        """
        gateway = self.gateways.get(gateway_name, None)
        if not gateway:
            self.write_log(f"找不到底层接口:{gateway_name}")
        return gateway

    def get_engine(self, engine_name: str) -> "BaseEngine":
        """
        Return engine object by name.
        """
        engine = self.engines.get(engine_name, None)
        if not engine:
            self.write_log(f"找不到引擎:{engine_name}")
        return engine

    def get_default_setting(self,
                            gateway_name: str) -> Optional[Dict[str, Any]]:
        """
        Get default setting dict of a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            return gateway.get_default_setting()
        return None

    def get_all_gateway_names(self) -> List[str]:
        """
        Get all names of gatewasy added in main engine.
        """
        return list(self.gateways.keys())

    def get_all_apps(self) -> List[BaseApp]:
        """
        Get all app objects.
        """
        return list(self.apps.values())

    def get_all_exchanges(self) -> List[Exchange]:
        """
        Get all exchanges.
        """
        return self.exchanges

    def connect(self, setting: dict, gateway_name: str) -> None:
        """
        Start connection of a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            gateway.connect(setting)

    def subscribe(self, req: SubscribeRequest, gateway_name: str) -> None:
        """
        Subscribe tick data update of a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            gateway.subscribe(req)

    def send_order(self, req: OrderRequest, gateway_name: str) -> str:
        """
        Send new order request to a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            return gateway.send_order(req)
        else:
            return ""

    def cancel_order(self, req: CancelRequest, gateway_name: str) -> None:
        """
        Send cancel order request to a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            gateway.cancel_order(req)

    def send_orders(self, reqs: Sequence[OrderRequest],
                    gateway_name: str) -> List[str]:
        """
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            return gateway.send_orders(reqs)
        else:
            return ["" for req in reqs]

    def cancel_orders(self, reqs: Sequence[CancelRequest],
                      gateway_name: str) -> None:
        """
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            gateway.cancel_orders(reqs)

    def query_history(self, req: HistoryRequest,
                      gateway_name: str) -> Optional[List[BarData]]:
        """
        Send cancel order request to a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            return gateway.query_history(req)
        else:
            return None

    def close(self) -> None:
        """
        Make sure every gateway and app is closed properly before
        programme exit.
        """
        # Stop event engine first to prevent new timer event.
        self.event_engine.stop()

        for engine in self.engines.values():
            engine.close()

        for gateway in self.gateways.values():
            gateway.close()
Exemplo n.º 14
0
class EventDrivenStrategy(Strategy, Subscriber):
    def __init__(self):

        Strategy.__init__(self)

        self.pm = PortfolioManager()
        self.pm.strategy = self

        # TODO remove
        self.eventEngine = EventEngine()
        self.eventEngine.register(eventType.EVENT_TIMER, self.on_cycle)
        self.eventEngine.register(eventType.EVENT_MD_QUOTE, self.on_quote)
        self.eventEngine.register(eventType.EVENT_TRADE_IND,
                                  self.pm.on_trade_ind)
        self.eventEngine.register(eventType.EVENT_ORDERSTATUS_IND,
                                  self.pm.on_order_status)

    @abstractmethod
    def on_new_day(self, trade_date):
        pass

    @abstractmethod
    def on_quote(self, quote):
        pass

    @abstractmethod
    def on_cycle(self):
        pass

    def initialize(self, runmode):
        if runmode == common.RUN_MODE.REALTIME:
            self.subscribe_events()

    def subscribe_events(self):
        universe = self.context.universe
        data_server = self.context.dataserver
        for i in xrange(len(universe)):
            self.subscribe(data_server, universe[i])

    def subscribe(self, publisher, topic):
        publisher.add_subscriber(self, topic)

    def start(self):
        self.eventEngine.start(False)

    def stop(self):
        self.eventEngine.stop()

    def register_event(self, event):
        self.eventEngine.put(event)
Exemplo n.º 15
0
from trader.engine import MainEngine
from trader.setting import get_settings

if __name__ == '__main__':
    from vnpy.app.cta_strategy.backtesting import BacktestingEngine, OptimizationSetting
    from celue.fx.EMA_fx_mz_strategy import (
        EmaFxMzStrategy,
    )
    from datetime import datetime

    # engine = BacktestingEngine()
    # engine.set_parameters(
    #     vt_symbol="BTCUSDT.BINANCE",
    #     interval="1h",
    #     start=datetime(2020, 1, 25),
    #     end=datetime(2020, 11, 5),
    #     rate=0.25 / 10000,
    #     slippage=0.2,
    #     size=100,
    #     pricetick=0.2,
    #     capital=1_000_000,
    # )
    # engine.add_strategy(EmaFxMzStrategy, {})
    # engine.load_data()
    # engine.run_backtesting()
    # df = engine.calculate_result()
    # engine.calculate_statistics()

    event_engine = EventEngine()
    main_engine = MainEngine(event_engine)
    main_engine.get_account('a')
Exemplo n.º 16
0
class MainEngine:
    """
    Acts as the core of VN Trader.
    """
    def __init__(self, event_engine: EventEngine = None):
        """"""
        if event_engine:
            self.event_engine = event_engine
        else:
            self.event_engine = EventEngine()
        self.event_engine.start()

        self.gateways = {}
        self.engines = {}
        self.apps = {}

        self.init_engines()

    def add_engine(self, engine_class: Any):
        """
        Add function engine.
        """
        engine = engine_class(self, self.event_engine)
        self.engines[engine.engine_name] = engine

    def add_gateway(self, gateway_class: BaseGateway):
        """
        Add gateway.
        """
        gateway = gateway_class(self.event_engine)
        self.gateways[gateway.gateway_name] = gateway

    def add_app(self, app_class: BaseApp):
        """
        Add app.
        """
        app = app_class()
        self.apps[app.app_name] = app

        self.add_engine(app.engine_class)

    def init_engines(self):
        """
        Init all engines.
        """
        self.add_engine(LogEngine)
        # self.add_engine(OmsEngine)
        # self.add_engine(EmailEngine)
        self.add_engine(StEngine)

    def write_log(self, msg: str):
        """
        Put log event with specific message.
        """
        log = StLogData(msg=msg)
        event = Event(EVENT_LOG, log)
        self.event_engine.put(event)

    def get_gateway(self, gateway_name: str):
        """
        Return gateway object by name.
        """
        gateway = self.gateways.get(gateway_name, None)
        if not gateway:
            self.write_log(f"找不到底层接口:{gateway_name}")
        return gateway

    def get_engine(self, engine_name: str):
        """
        Return engine object by name.
        """
        engine = self.engines.get(engine_name, None)
        if not engine:
            self.write_log(f"找不到引擎:{engine_name}")
        return engine

    def get_default_setting(self, gateway_name: str):
        """
        Get default setting dict of a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            return gateway.get_default_setting()
        return None

    def get_all_gateway_names(self):
        """
        Get all names of gatewasy added in main engine.
        """
        return list(self.gateways.keys())

    def get_all_apps(self):
        """
        Get all app objects.
        """
        return list(self.apps.values())

    def query_contract(self, gateway_name: str):
        """
        Get contract of a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            gateway.query_contract()

    def query_position(self, strategy_name: str, symbol: str,
                       gateway_name: str):
        """
        Get position of a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            gateway.query_position(strategy_name, symbol)

    def connect(self, setting: dict, gateway_name: str):
        """
        Start connection of a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            gateway.connect(gateway.default_setting)

    def subscribe(self, req: SubscribeRequest, gateway_name: str):
        """
        Subscribe tick data update of a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            gateway.subscribe(req)

    def un_subscribe(self, req: SubscribeRequest, gateway_name: str):
        """
        unSubscribe tick data update of a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            gateway.un_subscribe(req)

    def send_order(self, req: OrderRequest, gateway_name: str):
        """
        Send new order request to a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            return gateway.send_order(req)
        else:
            return ""

    def cancel_order(self, req: CancelRequest, gateway_name: str):
        """
        Send cancel order request to a specific gateway.
        """
        gateway = self.get_gateway(gateway_name)
        if gateway:
            gateway.cancel_order(req)

    def close(self):
        """
        Make sure every gateway and app is closed properly before
        programme exit.
        """
        # Stop event engine first to prevent new timer event.
        self.event_engine.stop()

        for engine in self.engines.values():
            engine.close()

        for gateway in self.gateways.values():
            gateway.close()