admin

A Python Example to Publish Trading Signal using REST API

How it work


Hi there! If you are managing your own trading system(s) on a local server, and want to list them on Algo Marketplace to attract investors, this article will present you how to publish your trading signals to ALGOGENE server.


Preparation

All you need is to get an API Key which will be your account credential for data exchange with ALGOGENE server. You can generate the API key as follows:

Generate API Key

Example for Random Trading Strategy

For demonstration purpose, we will implement a simple random trade strategy as follows:

  • For every 1 minutes, we generate a random indicator for "BUY", "SELL", and "DO NOTHING"
  • Close all outstanding orders first if any
  • If the indicator
    • value = "BUY", we open 1 lot of BUY position for BTCUSD
    • value = "SELL", we open 1 lot of SELL position for BTCUSD

Python Implementation

We will base on REST API (https://algogene.com/RestDoc) to implement this random trade strategy.

First of all, let's import the necessary python modules, and also define the variables to connect our ALGOGENE account.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import requests, random
from datetime import datetime, timedelta
from time import sleep, time

base_url = "https://algogene.com/rest/v1"

api_key = "YOUR_API_KEY"
user = "YOUR_USER_ID"
runmode = "livetest"
accountid = "YOUR_ACCOUNT_ID"

Then, we will create four python functions for

  1. obtain session token
  2. open order
  3. close order by trade ID
  4. query order by trade ID

1. obtain session token (https://algogene.com/RestDoc#/operations/get-session)

1
2
3
4
5
6
7
8
def get_session_token():
    url = base_url+"/session"
    data = {
        "api_key": api_key,
        "user": user
    }
    r = requests.get(url, params=data)
    return r.json()

2. open order (https://algogene.com/RestDoc#/operations/post-open_order)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def open_order(instrument, buysell, volume, orderRef=""):
    url = base_url+"/open_order"
    data = {
        "api_key": api_key,
        "user": user,
        "runmode": runmode,
        "accountid": accountid,
        "instrument": instrument, 
        "buysell": buysell, 
        "volume": volume,
        "orderRef": orderRef,
        "ordertype": "MKT",
        "token": token
    }
    r = requests.post(url, data=json.dumps(data))
    return r.json()

3. close order by trade ID (https://algogene.com/RestDoc#/operations/post-close_orders)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def close_order(tradeID):
    url = base_url+"/close_orders"
    data = {
        "api_key": api_key,
        "user": user,
        "runmode": runmode,
        "accountid": accountid,
        "tradeIDs": tradeID,
        "token": token
    }
    r = requests.post(url, data=json.dumps(data))
    return r.json()

4. query order by trade ID (https://algogene.com/RestDoc#/operations/get-query_order)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def query_order(tradeID):
    url = base_url+"/opened_trades"
    data = {
        "api_key": api_key,
        "user": user,
        "runmode": runmode,
        "accountid": accountid,
        "tradeID": tradeID,
        "token": token
    }
    r = requests.get(url, params=data)
    return r.json()

Now, we are ready to implement the random trade strategy.

 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
token, token_expiry = "", ""
tradeID = ""
dt = datetime.utcnow()-timedelta(minutes=60)
while True:
    if datetime.utcnow()>=dt+timedelta(seconds=60):
        dt = datetime.utcnow()
        # renew session token
        if str(dt)>token_expiry:
            res = get_session_token()
            token = res['res']['token']
            token_expiry = res['res']['expired_utc']
            
        # close previous orders
        if tradeID!="":
            res = query_order(tradeID)
            print('query_order ... ', res)

            res = close_order(tradeID)
            print('close_order ... ', res)

        # generate indicator and open order
        buysell = random.choice(["BUY","SELL",""])
        if buysell!="":
            res = open_order(instrument="BTCUSD", buysell=buysell, volume=1)
            tradeID = res['tradeID']
            print('open_order ... ', res)

    sleep(1)


Full Python Script

For those who would like to try out, here is the full script for your easier reference.

 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import requests, random
from datetime import datetime, timedelta
from time import sleep, time

base_url = "https://algogene.com/rest/v1"

api_key = "YOUR_API_KEY"
user = "YOUR_USER_ID"
runmode = "livetest"
accountid = "YOUR_ACCOUNT_ID"

def open_order(instrument, buysell, volume, orderRef=""):
    url = base_url+"/open_order"
    data = {
        "api_key": api_key,
        "user": user,
        "runmode": runmode,
        "accountid": accountid,
        "instrument": instrument, 
        "buysell": buysell, 
        "volume": volume,
        "orderRef": orderRef,
        "ordertype": "MKT",
        "token": token
    }
    r = requests.post(url, data=json.dumps(data))
    return r.json()

def close_order(tradeID):
    url = base_url+"/close_orders"
    data = {
        "api_key": api_key,
        "user": user,
        "runmode": runmode,
        "accountid": accountid,
        "tradeIDs": tradeID,
        "token": token
    }
    r = requests.post(url, data=json.dumps(data))
    return r.json()

def query_order(tradeID):
    url = base_url+"/opened_trades"
    data = {
        "api_key": api_key,
        "user": user,
        "runmode": runmode,
        "accountid": accountid,
        "tradeID": tradeID,
        "token": token
    }
    r = requests.get(url, params=data)
    return r.json()

def get_session_token():
    url = base_url+"/session"
    data = {
        "api_key": api_key,
        "user": user
    }
    r = requests.get(url, params=data)
    return r.json()



token, token_expiry = "", ""
tradeID = ""
dt = datetime.utcnow()-timedelta(minutes=60)
while True:
    if datetime.utcnow()>=dt+timedelta(seconds=60):
        dt = datetime.utcnow()
        # renew session token
        if str(dt)>token_expiry:
            res = get_session_token()
            token = res['res']['token']
            token_expiry = res['res']['expired_utc']
            
        # close previous orders
        if tradeID!="":
            res = query_order(tradeID)
            print('query_order ... ', res)

            res = close_order(tradeID)
            print('close_order ... ', res)

        # generate indicator and open order
        buysell = random.choice(["BUY","SELL",""])
        if buysell!="":
            res = open_order(instrument="BTCUSD", buysell=buysell, volume=1)
            tradeID = res['tradeID']
            print('open_order ... ', res)

    sleep(1)

Result

Running the program above, you will see results like this.


open_order ...  {'status': 'PENDING_TO_FILL', 'timestamp_utc': '2023-08-31 14:00:51.330180', 'tradeID': 746805590705}
query_order ...  {'count': 1, 'res': [{'broker': 'ALGOGENE', 'buysell': 1, 'channel': 'api', 'expiry': '', 'holdtime': 0.0, 'instrument': 'BTCUSD', 'market': 'CRYPTO', 'openclose': 'open', 'order_Ref': '', 'price': 30086.67, 'product_type': 'SPOT', 'right': '', 'stopLossLevel': 0.0, 'strike': 0.0, 'symbol': 'BTCUSD', 'takeProfitLevel': 0.0, 'timestamp': '2023-08-31 14:00:53.787035', 'trade_ID': '746805590705', 'unrealizedPL': -36.56, 'volume': 1.0}]}
close_order ...  {'res': "Submitted close order request for '746805590705',", 'status': 'SUCCESS'}
open_order ...  {'status': 'PENDING_TO_FILL', 'timestamp_utc': '2023-08-31 14:01:55.921894', 'tradeID': 746805715738}
query_order ...  {'count': 1, 'res': [{'broker': 'ALGOGENE', 'buysell': 1, 'channel': 'api', 'expiry': '', 'holdtime': 0.0, 'instrument': 'BTCUSD', 'market': 'CRYPTO', 'openclose': 'open', 'order_Ref': '', 'price': 30086.67, 'product_type': 'SPOT', 'right': '', 'stopLossLevel': 0.0, 'strike': 0.0, 'symbol': 'BTCUSD', 'takeProfitLevel': 0.0, 'timestamp': '2023-08-31 14:01:55.947898', 'trade_ID': '746805715738', 'unrealizedPL': -36.56, 'volume': 1.0}]}
close_order ...  {'res': "Submitted close order request for '746805715738',", 'status': 'SUCCESS'}
open_order ...  {'status': 'PENDING_TO_FILL', 'timestamp_utc': '2023-08-31 14:02:56.596691', 'tradeID': 746805776466}
query_order ...  {'count': 1, 'res': [{'broker': 'ALGOGENE', 'buysell': 1, 'channel': 'api', 'expiry': '', 'holdtime': 0.0, 'instrument': 'BTCUSD', 'market': 'CRYPTO', 'openclose': 'open', 'order_Ref': '', 'price': 30086.67, 'product_type': 'SPOT', 'right': '', 'stopLossLevel': 0.0, 'strike': 0.0, 'symbol': 'BTCUSD', 'takeProfitLevel': 0.0, 'timestamp': '2023-08-31 14:02:56.645858', 'trade_ID': '746805776466', 'unrealizedPL': -36.56, 'volume': 1.0}]}
close_order ...  {'res': "Submitted close order request for '746805776466',", 'status': 'SUCCESS'}


Remarks

  • All available trading instruments can be found from here
  • If you want to trade on broker accounts, please firstly configure the broker connection on [Setting] page
  • If you have multiple strategies, you will need to open and run on multiple ALGOGENE accounts. Please head to [Service] page to upgrade your account!

Happy Trading!


 
小霸王
Thanks for providing the source code!