Example #1
0
class DemoTask:
    def __init__(self):
        self.api = TqApi()
        self.tm = TaskManager(self.api)

    def task_main(self):
        print("start")
        quote = self.api.get_quote("SHFE.cu1805")
        while True:
            wait_result = yield {
                "QUOTE_CHANGED": lambda: self.api.is_changing(quote),
                "TIMEOUT": 0.2,
            }
            if wait_result["QUOTE_CHANGED"]:
                print("Quote", quote)
            if wait_result["TIMEOUT"]:
                print("Timeout")

    def run(self):
        self.tm.start_task(self.task_main())
        self.api.run()
Example #2
0
class DemoMa:
    def __init__(self):
        self.api = TqApi()
        self.tm = TaskManager(self.api)

    def task_main(self):
        print("start")
        symbol = "SHFE.cu1805"
        kline_serial_5s = self.api.get_kline_serial(symbol, 5)
        kline_serial_1m = self.api.get_kline_serial(symbol, 60)
        while True:
            yield {
                "KLINE_DATA_UPDATED":
                lambda: self.api.is_changing(kline_serial_1m) or self.api.
                is_changing(kline_serial_5s),
            }
            # 计算最近3根5秒线均价
            average_price_15s = (kline_serial_5s[-1]["close"] +
                                 kline_serial_5s[-2]["close"] +
                                 kline_serial_5s[-3]["close"]) / 3
            # 计算最近30根1分钟线均价
            average_price_30m = sum(kline_serial_1m.close[-30:]) / 30
            # 如果条件符合
            print("average_price_15s", average_price_15s, "average_price_30m",
                  average_price_30m)
            if average_price_15s > average_price_30m:
                self.api.insert_order(symbol=symbol,
                                      direction="BUY",
                                      offset="OPEN",
                                      volume=1,
                                      limit_price=5000)
        print("finish")

    def run(self):
        self.tm.start_task(self.task_main())
        self.api.run()
Example #3
0
'''
连续3根阴线就做空,连续3根阳线就做多,否则空仓
'''

api = TqApi("SIM")
# 设定连续多少根阳线/阴线
length = 3
# 获得 rb1901 10秒K线的引用, 长度为 length+1
klines = api.get_kline_serial("SHFE.rb1901", 10, data_length = length + 1)
# 创建 rb1901 的目标持仓 task,该 task 负责调整 rb1901 的仓位到指定的目标仓位, offset_priority的用法详见文档
target_pos = TargetPosTask(api, "SHFE.rb1901", offset_priority="今昨开")

while True:
    api.wait_update()
    # 只有在新创建出K线时才判断开平仓条件
    if api.is_changing(klines[-1], "datetime"):
        # 将K线转为pandas.DataFrame, 跳过最后一根刚生成的K线
        df = klines.to_dataframe()[:-1]
        # 比较收盘价和开盘价,判断是阳线还是阴线
        # df["close"] 为收盘价序列, df["open"] 为开盘价序列, ">"(pandas.Series.gt) 返回收盘价是否大于开盘价的一个新序列
        up = df["close"] > df["open"]
        down = df["close"] < df["open"]
        if all(up):
            print("连续阳线: 目标持仓 多头1手")
            # 设置目标持仓为正数表示多头,负数表示空头,0表示空仓
            target_pos.set_target_volume(1)
        elif all(down):
            print("连续阴线: 目标持仓 空头1手")
            target_pos.set_target_volume(-1)
        else:
            print("目标持仓: 空仓")
Example #4
0
__author__ = 'chengzhi'

from tqsdk.api import TqApi

'''
如果当前价格大于10秒K线的MA15则开多仓
如果小于则平仓
'''
api = TqApi("SIM")
# 获得 m1901 10秒K线的引用
klines = api.get_kline_serial("DCE.m1901", 10)

# 判断开仓条件
while True:
    api.wait_update()
    if api.is_changing(klines):
        ma = sum(klines.close[-15:])/15
        print("最新价", klines.close[-1], "MA", ma)
        if klines.close[-1] > ma:
            print("最新价大于MA: 市价开仓")
            api.insert_order(symbol="DCE.m1901", direction="BUY", offset="OPEN", volume=5)
            break
# 判断平仓条件
while True:
    api.wait_update()
    if api.is_changing(klines):
        ma = sum(klines.close[-15:])/15
        print("最新价", klines.close[-1], "MA", ma)
        if klines.close[-1] < ma:
            print("最新价小于MA: 市价平仓")
            api.insert_order(symbol="DCE.m1901", direction="SELL", offset="CLOSE", volume=5)
Example #5
0
from tqsdk.api import TqApi
from tqsdk.lib import TargetPosTask
'''
价差回归
当近月-远月的价差大于200时做空近月,做多远月
当价差小于150时平仓
'''
api = TqApi("SIM")
quote_near = api.get_quote("SHFE.rb1810")
quote_deferred = api.get_quote("SHFE.rb1901")
# 创建 rb1810 的目标持仓 task,该 task 负责调整 rb1810 的仓位到指定的目标仓位
target_pos_near = TargetPosTask(api, "SHFE.rb1810")
# 创建 rb1901 的目标持仓 task,该 task 负责调整 rb1901 的仓位到指定的目标仓位
target_pos_deferred = TargetPosTask(api, "SHFE.rb1901")

while True:
    api.wait_update()
    if api.is_changing(quote_near) or api.is_changing(quote_deferred):
        spread = quote_near["last_price"] - quote_deferred["last_price"]
        print("当前价差:", spread)
        if spread > 200:
            print("目标持仓: 空近月,多远月")
            # 设置目标持仓为正数表示多头,负数表示空头,0表示空仓
            target_pos_near.set_target_volume(-1)
            target_pos_deferred.set_target_volume(1)
        elif spread < 150:
            print("目标持仓: 空仓")
            target_pos_near.set_target_volume(0)
            target_pos_deferred.set_target_volume(0)
Example #6
0
#!/usr/bin/env python
#  -*- coding: utf-8 -*-
__author__ = 'chengzhi'

from tqsdk.api import TqApi

api = TqApi("SIM")
quote = api.get_quote("SHFE.cu1812")

while True:
    api.wait_update()
    # 如果 cu1812 的任何字段有变化,is_changing就会返回 True
    if api.is_changing(quote):
        print(quote)
    # 只有当 cu1812 的最新价有变化,is_changing才会返回 True
    if api.is_changing(quote, "last_price"):
        print("最新价变化", quote["last_price"])
    # 当 cu1812 的买1价/买1量/卖1价/卖1量中任何一个有变化,is_changing都会返回 True
    if api.is_changing(
            quote, ["ask_price1", "ask_volume1", "bid_price1", "bid_volume1"]):
        print("盘口变化", quote["ask_price1"], quote["ask_volume1"],
              quote["bid_price1"], quote["bid_volume1"])
Example #7
0
#!/usr/bin/env python
#  -*- coding: utf-8 -*-
__author__ = 'chengzhi'

from tqsdk.api import TqApi
import datetime

api = TqApi("SIM")
# 获得cu1812 tick序列的引用
ticks = api.get_tick_serial("SHFE.cu1812")
# 获得cu1812 10秒K线的引用
klines = api.get_kline_serial("SHFE.cu1812", 10)

while True:
    api.wait_update()
    # 判断整个tick序列是否有变化
    if api.is_changing(ticks):
        # ticks[-1]返回序列中最后一个tick
        print("tick变化", ticks[-1])
    # 判断最后一根K线的时间是否有变化,如果发生变化则表示新产生了一根K线
    if api.is_changing(klines[-1], "datetime"):
        # datetime: 自unix epoch(1970-01-01 00:00:00 GMT)以来的纳秒数
        print("新K线",
              datetime.datetime.fromtimestamp(klines[-1]["datetime"] / 1e9))
    # 判断最后一根K线的收盘价是否有变化
    if api.is_changing(klines[-1], "close"):
        # klines.close返回收盘价序列
        print("K线变化",
              datetime.datetime.fromtimestamp(klines[-1]["datetime"] / 1e9),
              klines.close[-1])
Example #8
0
#!/usr/bin/env python
#  -*- coding: utf-8 -*-
__author__ = 'chengzhi'

from tqsdk.api import TqApi

api = TqApi("SIM")
# 获得 cu1812 的持仓引用,当持仓有变化时 position 中的字段会对应更新
position = api.get_position("SHFE.cu1812")
# 获得资金账户引用,当账户有变化时 account 中的字段会对应更新
account = api.get_account()
# 下单并返回委托单的引用,当该委托单有变化时 order 中的字段会对应更新
order = api.insert_order(symbol="SHFE.cu1812",
                         direction="BUY",
                         offset="OPEN",
                         volume=5)

while True:
    api.wait_update()
    if api.is_changing(order, ["status", "volume_orign", "volume_left"]):
        print("单状态: %s, 已成交: %d 手" %
              (order["status"], order["volume_orign"] - order["volume_left"]))
    if api.is_changing(position, "volume_long_today"):
        print("今多头: %d 手" % (position["volume_long_today"]))
    if api.is_changing(account, "available"):
        print("可用资金: %.2f" % (account["available"]))
Example #9
0
    range = max(HH - LC, HC - LL)
    buy_line = current_open + range * K1  # 上轨
    sell_line = current_open - range * K2  # 下轨

    print("当前开盘价:", current_open, "\n上轨:", buy_line, "\n下轨:", sell_line)
    return buy_line, sell_line


api = TqApi("SIM")
quote = api.get_quote(symbol)
klines = api.get_kline_serial(symbol, 24 * 60 * 60)  # 86400使用日线
target_pos = TargetPosTask(api, symbol)
buy_line, sell_line = dual_thrust(quote, klines)  # 获取上下轨

while True:
    api.wait_update()
    if api.is_changing(klines[-1], "datetime") or api.is_changing(
            quote, "open"):  # 新产生一根日线或开盘价发生变化: 重新计算上下轨
        buy_line, sell_line = dual_thrust(quote, klines)

    if api.is_changing(quote, "last_price"):
        print("最新价变化", quote["last_price"], end=':')
        if quote["last_price"] > buy_line:  # 高于上轨
            print("高于上轨,目标持仓 多头3手")
            target_pos.set_target_volume(3)  # 交易
        elif quote["last_price"] < sell_line:  # 低于下轨
            print("低于下轨,目标持仓 空头3手")
            target_pos.set_target_volume(-3)  # 交易
        else:
            print('未穿越上下轨,不调整持仓')
Example #10
0
                    if len(newSar) > self.n:
                        newSar.pop(0)
                    self.sar["value"][-1] = min(newSar)
                    self.sar["trends"][-1] = 1
                    self.sar["step"][-1] = self.step
                return self.sar


sarLittleValue = [0]
sarBigValue = [0]
sarLittle = SAR(sarLittleValue, K_Line_three, 4, 0.02, 0.2)
sarBig = SAR(sarBigValue, K_Line_two, 4, 0.02, 0.2)

while True:
    api.wait_update()
    if api.is_changing(ticks):
        tickPrice = ticks[-1]["last_price"]
    if api.is_changing(K_Line_three[-1], "datetime"):  #计算止损SAR,到时更新
        sarLittleValue[-1] = sarLittle.getSAR()
        if sarLittleValue[-1]["trends"][-1] == 1:
            sarLittleUp.append(sarLittleValue[-1])
        else:
            sarLittleDown.append(sarLittleValue[-1])
        if len(sarLittleUp) > 10:
            sarLittleUp.pop(0)
        if len(sarLittleDown) > 10:
            sarLittleDown.pop(0)
    if api.is_changing(K_Line_two[-1], "datetime"):  #计算止盈SAR,到时更新
        sarBigValue[-1] = sarBig.getSAR()
        if sarBigValue[-1]["trends"][-1] == 1:
            sarBigUp.append(sarBigValue[-1])