Gary Fung

How to close orders by orderRef?

Programming


Hey there! I have a backtest script containing multiple strategies. 
I managed the orders in a way that orders opened from the same strategy will have the same order reference. 
Sometime when a strategy doesn't performance well. I would like to close all outstanding orders created by that strategy. 

Instead of keep track of all trade ID and close 1 by 1, is there a way that I can close all orders with the same order reference?
 
admin

We support close orders by 'orderRef'. You can refer to sample12 under the "Place Order" section in tech doc. (i.e. https://algogene.com/TechDoc#PlaceOrder)

However, this feature is only supported when position netting is set to false.

Here is a quick example for your reference. Let's say we keep opening new orders every day. Also, we assign orderRef=1 for the first 10 orders. Then we want to close the first ten orders on day 20.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from AlgoAPI import AlgoAPIUtil, AlgoAPI_Backtest, PATH_CO_CLIENT
from datetime import datetime, timedelta

class AlgoEvent:
    def __init__(self): 
        self.timer = datetime(1970,1,1)
        self.cnt = 0
    
    def start(self, mEvt): 
        self.evt = AlgoAPI_Backtest.AlgoEvtHandler(self, mEvt)
        self.evt.start()
    
    def on_marketdatafeed(self, md, ab):
        if md.timestamp>=self.timer+timedelta(hours=24):
            self.timer = md.timestamp
            self.cnt+=1

            # assign order reference
            if self.cnt<=10:
                orderRef = 1
            else:
                orderRef = 2

            # open order
            order = AlgoAPIUtil.OrderObject(
                orderRef = orderRef,
                instrument = md.instrument,
                buysell = 1,
                volume = 0.01,
                ordertype = 0,
                openclose = 'open'
            )
            self.evt.sendOrder(order)

            # close all orders with the same order reference
            if self.cnt==20:
                order = AlgoAPIUtil.OrderObject(
                    openclose='close',
                    orderRef=1
                )
                self.evt.sendOrder(order)