Skip to content

Commit

Permalink
add real time trading and intraday examples
Browse files Browse the repository at this point in the history
  • Loading branch information
brillliantz committed Nov 15, 2017
1 parent 9c32db4 commit 6a4ff4c
Show file tree
Hide file tree
Showing 3 changed files with 288 additions and 64 deletions.
165 changes: 165 additions & 0 deletions jaqs/example/eventdriven/DoubleMA.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
# encoding: utf-8

import time

import numpy as np

from jaqs.trade import common
from jaqs.trade.strategy import EventDrivenStrategy
from jaqs.data.dataservice import RemoteDataService
from jaqs.trade import model
from jaqs.trade.realtime import EventRealTimeInstance
from jaqs.trade.backtest import EventBacktestInstance
from jaqs.trade.tradegateway import RealTimeTradeApi, BacktestTradeApi
from jaqs.trade.portfoliomanager import PortfolioManager
import jaqs.util as jutil
import jaqs.trade.analyze.analyze as ana

result_dir_path = jutil.join_relative_path('../output/double_ma')
is_backtest = True


class DoubleMaStrategy(EventDrivenStrategy):
""""""
def __init__(self):
super(DoubleMaStrategy, self).__init__()
self.symbol = ''

self.fast_ma_len = 13
self.slow_ma_len = 23

self.window_count = 0
self.window = self.slow_ma_len + 1

self.price_arr = np.zeros(self.window)
self.fast_ma = 0
self.slow_ma = 0
self.pos = 0

self.buy_size_unit = 1
self.output = True

def init_from_config(self, props):
super(DoubleMaStrategy, self).init_from_config(props)
self.symbol = props.get('symbol')
self.init_balance = props.get('init_balance')

def buy(self, quote, size=1):
if hasattr(quote, 'bidprice1'):
ref_price = (quote.bidprice1 + quote.askprice1) / 2.0
else:
ref_price = quote.close

task_id, msg = self.ctx.trade_api.place_order(quote.symbol, common.ORDER_ACTION.BUY, ref_price + 3, self.buy_size_unit * size)
if (task_id is None) or (task_id == 0):
print("place_order FAILED! msg = {}".format(msg))

def sell(self, quote, size=1):
if hasattr(quote, 'bidprice1'):
ref_price = (quote.bidprice1 + quote.askprice1) / 2.0
else:
ref_price = quote.close

task_id, msg = self.ctx.trade_api.place_order(quote.symbol, common.ORDER_ACTION.SHORT, ref_price - 3, self.buy_size_unit * size)
if (task_id is None) or (task_id == 0):
print("place_order FAILED! msg = {}".format(msg))

def on_tick(self, quote):
if hasattr(quote, 'bidprice1'):
mid = (quote.bidprice1 + quote.askprice1) / 2.0
else:
mid = quote.close
self.price_arr[0: self.window - 1] = self.price_arr[1: self.window]
self.price_arr[-1] = mid
self.window_count += 1

if self.window_count <= self.window:
return

self.fast_ma = np.mean(self.price_arr[-self.fast_ma_len - 1:])
self.slow_ma = np.mean(self.price_arr[-self.slow_ma_len - 1:])

print(quote)
print("Fast MA = {:.2f} Slow MA = {:.2f}".format(self.fast_ma, self.slow_ma))
if self.fast_ma > self.slow_ma:
if self.pos == 0:
self.buy(quote, 1)

elif self.pos < 0:
self.buy(quote, 2)

elif self.fast_ma < self.slow_ma:
if self.pos == 0:
self.sell(quote, 1)
elif self.pos > 0:
self.sell(quote, 2)

def on_quote(self, quote_dic):
quote = quote_dic.get(self.symbol)
self.on_tick(quote)

def on_trade(self, ind):
print "\nStrategy on trade: "
print(ind)
self.pos = self.ctx.pm.get_pos(self.symbol)

def on_order_status(self, ind):
if self.output:
print "\nStrategy on order status: "
print(ind)

def on_task_status(self, ind):
if self.output:
print "\nStrategy on task ind: "
print(ind)


def run_strategy():
if is_backtest:
props = {"symbol": "rb1710.SHF",
"start_date": 20170510,
"end_date": 20170930,
"bar_type": "1M", # '1d'
"init_balance": 2e4}

tapi = BacktestTradeApi()
ins = EventBacktestInstance()

else:
props = {'symbol': 'rb1801.SHF'}
tapi = RealTimeTradeApi()
ins = EventRealTimeInstance()

tapi.use_strategy(8)

ds = RemoteDataService()
strat = DoubleMaStrategy()
pm = PortfolioManager()

context = model.Context(data_api=ds, trade_api=tapi, instance=ins,
strategy=strat, pm=pm)

ins.init_from_config(props)
if not is_backtest:
ds.subscribe(props['symbol'])

ins.run()
if not is_backtest:
time.sleep(9999)
ins.save_results(folder_path=result_dir_path)


def analyze():
ta = ana.EventAnalyzer()

ds = RemoteDataService()
ds.init_from_config()

ta.initialize(data_server_=ds, file_folder=result_dir_path)

ta.do_analyze(result_dir=result_dir_path, selected_sec=[])


if __name__ == "__main__":
run_strategy()
analyze()
123 changes: 123 additions & 0 deletions jaqs/example/eventdriven/IntradaySpread.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# encoding: utf-8

import numpy as np

from jaqs.trade.strategy import EventDrivenStrategy
from jaqs.trade import common, model

from jaqs.data.dataservice import RemoteDataService
from jaqs.trade.backtest import EventBacktestInstance
from jaqs.trade.tradegateway import BacktestTradeApi
from jaqs.trade.portfoliomanager import PortfolioManager
import jaqs.util as jutil
import jaqs.trade.analyze.analyze as ana

result_dir_path = jutil.join_relative_path('../output/calendar_spread')


class SpreadStrategy(EventDrivenStrategy):
""""""
def __init__(self):
super(SpreadStrategy, self).__init__()
self.symbol = ''

self.s1 = ''
self.s2 = ''
self.quote1 = None
self.quote2 = None

self.window = 8
self.idx = -1
self.spread_arr = np.empty(self.window, dtype=float)

self.threshold = 6.5

def init_from_config(self, props):
super(SpreadStrategy, self).init_from_config(props)
self.symbol = props.get('symbol')
self.init_balance = props.get('init_balance')

self.s1, self.s2 = self.symbol.split(',')

def on_cycle(self):
pass

def long_spread(self, quote1, quote2):
self.ctx.trade_api.place_order(quote1.symbol, common.ORDER_ACTION.BUY, quote1.close + 1, 1)
self.ctx.trade_api.place_order(quote2.symbol, common.ORDER_ACTION.SELL, quote2.close - 1, 1)

def short_spread(self, quote1, quote2):
self.ctx.trade_api.place_order(quote2.symbol, common.ORDER_ACTION.BUY, quote2.close + 1, 1)
self.ctx.trade_api.place_order(quote1.symbol, common.ORDER_ACTION.SELL, quote1.close - 1, 1)

def on_quote(self, quote_dic):
q1 = quote_dic.get(self.s1)
q2 = quote_dic.get(self.s2)
self.quote1 = q1
self.quote2 = q2

if self.quote1.time > 142800 and self.quote1.time < 200000:
# self.cancel_all_orders()
# self.liquidate(self.quote1, 3, tick_size=1.0, pos=self.ctx.pm.get_pos(self.quote1.symbol))
# self.liquidate(self.quote2, 3, tick_size=1.0, pos=self.ctx.pm.get_pos(self.quote2.symbol))
# return
pass

spread = q1.close - q2.close
self.idx += 1
self.spread_arr[self.idx % self.window] = spread

if self.idx <= self.window:
return

mean = self.spread_arr.mean()
if (spread - mean) > self.threshold:
self.short_spread(q1, q2)
elif (spread - mean) < -self.threshold:
self.long_spread(q1, q2)

def on_trade(self, ind):
print(ind)
print(self.ctx.pm.get_position(ind.symbol))


props = {
"symbol" : "rb1801.SHF,hc1801.SHF",
"start_date" : 20170801,
"end_date" : 20170910,
"bar_type" : "1M",
"init_balance" : 3e4,
"commission_rate": 2E-4
}


def run_strategy():
tapi = BacktestTradeApi()
ins = EventBacktestInstance()

ds = RemoteDataService()
strat = SpreadStrategy()
pm = PortfolioManager()

context = model.Context(data_api=ds, trade_api=tapi, instance=ins,
strategy=strat, pm=pm)

ins.init_from_config(props)
ins.run()
ins.save_results(folder_path=result_dir_path)


def analyze():
ta = ana.EventAnalyzer()

ds = RemoteDataService()
ds.init_from_config()

ta.initialize(data_server_=ds, file_folder=result_dir_path)

ta.do_analyze(result_dir=result_dir_path, selected_sec=props['symbol'].split(','))


if __name__ == "__main__":
run_strategy()
analyze()
64 changes: 0 additions & 64 deletions jaqs/example/eventdriven/spread.py

This file was deleted.

0 comments on commit 6a4ff4c

Please sign in to comment.