Example #1
0
def test_close_position():
    """
    测试关闭头寸
    """
    flag = []

    def onPositionClosed(order, position):
        flag.append([order, position])

    trader = Trader()
    trader.bind('onPositionClosed', onPositionClosed)
    # 创建一个头寸供关闭使用
    openOrder = trader.openPosition(getDefaultInstrumentId(), 'buy', 1)
    position = openOrder.position
    trader.onPositionOpened(openOrder, position)
    assert position.state == 'open'

    # 测试头寸关闭操作
    closeOrder = trader.closePosition(position.id)
    assert isinstance(closeOrder, ModelOrder)
    assert closeOrder.id is not None
    assert closeOrder.position == position
    assert closeOrder.action == 'close'
    assert closeOrder.state == 'insert'
    assert closeOrder.finishTime is None
    assert closeOrder.closeLimitPrice == 0
    position = ModelPosition.objects.get(id=position.id)
    assert closeOrder.position == position
    assert position.state == 'preclose'
    assert position.closeTime is None
    assert position.closeLimitPrice == 0

    # 模拟头寸正常关闭事件
    trader.onPositionClosed(closeOrder, position)
    assert closeOrder.state == 'finish'
    assert closeOrder.finishTime is not None
    assert position.state == 'close'
    assert position.closeTime is not None

    # NOTE: 因为trader还为实现议价机制,所以此时价格仍为空
    assert position.closePrice is None
    assert closeOrder.closePrice is None

    # 检查事件正常传递
    assert len(flag) == 1
    assert flag[0][0] == closeOrder
    assert flag[0][1] == position
Example #2
0
def test_open_and_close_position_with_limit_price():
    """
    测试使用限价打开和关闭头寸
    """
    openLimitPrice = 1000
    closeLimitPrice = 2000
    trader = Trader()

    # 打开头寸
    order = trader.openPosition(
        instrumentId=getDefaultInstrumentId(),
        direction='buy',
        volume=1,
        openLimitPrice=openLimitPrice
    )
    position = order.position
    assert order.openLimitPrice == openLimitPrice
    assert position.openLimitPrice == openLimitPrice

    # 打开头寸成功
    trader.onPositionOpened(order, position)
    order = ModelOrder.objects.get(id=order.id)
    position = ModelPosition.objects.get(id=position.id)
    assert order.openLimitPrice == openLimitPrice
    assert position.openLimitPrice == openLimitPrice

    # 关闭头寸
    order = trader.closePosition(position.id, closeLimitPrice=closeLimitPrice)
    position = ModelPosition.objects.get(id=position.id)
    assert order.closeLimitPrice == closeLimitPrice
    assert position.closeLimitPrice == closeLimitPrice

    # 关闭头寸成功
    trader.onPositionClosed(order, position)
    order = ModelOrder.objects.get(id=order.id)
    position = ModelPosition.objects.get(id=position.id)
    assert order.closeLimitPrice == closeLimitPrice
    assert position.closeLimitPrice == closeLimitPrice