Skip to content

algobulls

Package for interacting with the AlgoBulls backend

api

Module for handling API calls to the AlgoBulls backend.

AlgoBullsAPI

AlgoBulls API

__init__(self) special

Init method that is used while creating an object of this class

Source code in pyalgotrading/algobulls/api.py
20
21
22
23
24
25
26
27
def __init__(self):
    """
    Init method that is used while creating an object of this class
    """
    self.headers = None
    self.__key_backtesting = None  # cstc id
    self.__key_papertrading = None  # cstc id
    self.__key_realtrading = None  # cstc id

create_strategy(self, strategy_name, strategy_details, abc_version)

Create a new strategy for the user on the AlgoBulls platform.

Parameters:

Name Type Description Default
strategy_name str

name of the strategy

required
strategy_details str

Python code of the strategy

required
abc_version str

value of one of the enums available under AlgoBullsEngineVersion

required

Returns:

Type Description
dict

JSON Response received from AlgoBulls platform after (attempt to) creating a new strategy.

Warning

For every user, the strategy_name should be unique. You cannot create multiple strategies with the same name.

ENDPOINT

POST v2/user/strategy/build/python

Source code in pyalgotrading/algobulls/api.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def create_strategy(self, strategy_name: str, strategy_details: str, abc_version: str) -> dict:
    """
    Create a new strategy for the user on the AlgoBulls platform.

    Args:
        strategy_name: name of the strategy
        strategy_details: Python code of the strategy
        abc_version: value of one of the enums available under [AlgoBullsEngineVersion]()

    Returns:
        JSON Response received from AlgoBulls platform after (attempt to) creating a new strategy.

    Warning:
        For every user, the `strategy_name` should be unique. You cannot create multiple strategies with the same name.

    Info: ENDPOINT
        `POST` v2/user/strategy/build/python
    """
    try:
        json_data = {'strategyName': strategy_name, 'strategyDetails': strategy_details, 'abcVersion': abc_version}
        endpoint = f'v2/user/strategy/build/python'
        print(f"Uploading strategy '{strategy_name}' ...", end=' ')
        response = self._send_request(endpoint=endpoint, method='post', json_data=json_data)
        print('Success.')
        return response
    except (AlgoBullsAPIForbiddenError, AlgoBullsAPIInsufficientBalanceError) as ex:
        print('Fail.')
        print(f'{ex.get_error_type()}: {ex.response}')

get_all_strategies(self)

Get all the Python strategies created by the user on the AlgoBulls platform

Returns:

Type Description
dict

JSON Response received from AlgoBulls platform with list of all the created strategies.

ENDPOINT

OPTIONS v2/user/strategy/build/python

Source code in pyalgotrading/algobulls/api.py
172
173
174
175
176
177
178
179
180
181
182
183
184
def get_all_strategies(self) -> dict:
    """
    Get all the Python strategies created by the user on the AlgoBulls platform

    Returns:
        JSON Response received from AlgoBulls platform with list of all the created strategies.

    Info: ENDPOINT
        `OPTIONS` v2/user/strategy/build/python
    """
    endpoint = f'v2/user/strategy/build/python'
    response = self._send_request(endpoint=endpoint, method='options')
    return response

get_job_status(self, strategy_code, trading_type)

Get status for a BACKTESTING/PAPERTRADING/REALTRADING Job

Parameters:

Name Type Description Default
strategy_code str

Strategy code

required
trading_type TradingType

Trading type

required

Returns:

Type Description
dict

Job status

ENDPOINT

GET v2/user/strategy/status

Source code in pyalgotrading/algobulls/api.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
def get_job_status(self, strategy_code: str, trading_type: TradingType) -> dict:
    """


    Get status for a BACKTESTING/PAPERTRADING/REALTRADING Job

    Args:
        strategy_code: Strategy code
        trading_type: Trading type

    Returns:
        Job status

    Info: ENDPOINT
        `GET` v2/user/strategy/status
    """
    key = self.__get_key(strategy_code=strategy_code, trading_type=trading_type)
    params = {'key': key}
    endpoint = f'v2/user/strategy/status'
    response = self._send_request(endpoint=endpoint, params=params)
    return response

get_reports(self, strategy_code, trading_type, report_type)

Get reports for a BACKTESTING/PAPERTRADING/REALTRADING Job

Parameters:

Name Type Description Default
strategy_code str

Strategy code

required
trading_type TradingType

Value of TradingType Enum

required
report_type TradingReportType

Value of TradingReportType Enum

required

Returns:

Type Description
dict

Report data

ENDPOINT

GET v1/customer_strategy_algotrading_reports

Source code in pyalgotrading/algobulls/api.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def get_reports(self, strategy_code: str, trading_type: TradingType, report_type: TradingReportType) -> dict:
    """
    Get reports for a BACKTESTING/PAPERTRADING/REALTRADING Job

    Args:
        strategy_code: Strategy code
        trading_type: Value of TradingType Enum
        report_type: Value of TradingReportType Enum

    Returns:
        Report data

    Info: ENDPOINT
        `GET` v1/customer_strategy_algotrading_reports
    """
    if report_type is TradingReportType.PNL_TABLE:
        endpoint = 'v2/user/strategy/pltable'
    elif report_type is TradingReportType.STATS_TABLE:
        endpoint = 'v2/user/strategy/statstable'
    elif report_type is TradingReportType.ORDER_HISTORY:
        endpoint = 'v2/user/strategy/orderhistory'
    else:
        raise NotImplementedError

    key = self.__get_key(strategy_code=strategy_code, trading_type=trading_type)
    params = {'key': key}
    response = self._send_request(endpoint=endpoint, params=params)
    return response

get_strategy_details(self, strategy_code)

Get strategy details for

Parameters:

Name Type Description Default
strategy_code str

unique code of strategy, which is received while creating the strategy or

required

Returns:

Type Description
dict

JSON

ENDPOINT

GET v2/user/strategy/build/python

Source code in pyalgotrading/algobulls/api.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def get_strategy_details(self, strategy_code: str) -> dict:
    """
    Get strategy details for

    Arguments:
        strategy_code: unique code of strategy, which is received while creating the strategy or

    Return:
        JSON

    Info: ENDPOINT
        `GET` v2/user/strategy/build/python
    """
    params = {'strategyCode': strategy_code}
    endpoint = f'v2/user/strategy/build/python'
    response = self._send_request(endpoint=endpoint, params=params)
    return response

search_instrument(self, instrument)

Parameters:

Name Type Description Default
instrument str

instrument key

required

Returns:

Type Description
dict

JSON Response

ENDPOINT

GET v2/instrument/search

Source code in pyalgotrading/algobulls/api.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def search_instrument(self, instrument: str) -> dict:
    """

    Args:
        instrument: instrument key

    Returns:
        JSON Response


    Info: ENDPOINT
        `GET` v2/instrument/search
    """
    params = {'instrument': instrument}
    endpoint = f'v2/instrument/search'
    response = self._send_request(endpoint=endpoint, params=params, requires_authorization=False)
    return response

set_access_token(self, access_token)

Sets access token to the header attribute, which is needed for APIs requiring authorization Package for interacting with AlgoBulls Algorithmic Trading Platform (https://www.algobulls.com)

Parameters:

Name Type Description Default
access_token str

Access token generated by logging to the URL given by the get_authorization_url() method

required
Source code in pyalgotrading/algobulls/api.py
29
30
31
32
33
34
35
36
37
38
39
def set_access_token(self, access_token: str):
    """
    Sets access token to the header attribute, which is needed for APIs requiring authorization
    Package for interacting with AlgoBulls Algorithmic Trading Platform (https://www.algobulls.com)

    Args:
        access_token: Access token generated by logging to the URL given by the `get_authorization_url()` method
    """
    self.headers = {
        'Authorization': f'{access_token}'
    }

set_strategy_config(self, strategy_code, strategy_config, trading_type)

Parameters:

Name Type Description Default
strategy_code str

strategy code

required
strategy_config dict

strategy configuration

required
trading_type TradingType

BACKTESTING, PAPER TRADING or REAL TRADING

required

Returns:

Type Description
(<class 'str'>, <class 'dict'>)

Info: ENDPOINT PATCH v2/portfolio/strategy

Source code in pyalgotrading/algobulls/api.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def set_strategy_config(self, strategy_code: str, strategy_config: dict, trading_type: TradingType) -> (str, dict):
    """

    Args:
        strategy_code: strategy code
        strategy_config: strategy configuration
        trading_type: BACKTESTING, PAPER TRADING or REAL TRADING

    Returns:

    Info: ENDPOINT
       PATCH v2/portfolio/strategy
    """

    # Configure the params
    json_data = {**strategy_config, 'overwrite': True}
    key = self.__get_key(strategy_code=strategy_code, trading_type=trading_type)
    endpoint = f'v2/user/strategy/{key}/tweak'
    print('Setting Strategy Config...', end=' ')
    response = self._send_request(method='patch', endpoint=endpoint, json_data=json_data)
    print('Success.')
    return key, response

start_strategy_algotrading(self, strategy_code, trading_type)

Submit Backtesting / Paper Trading / Real Trading job for strategy with code strategy_code & return the job ID.

ENDPOINT

POST v2/customer_strategy_algotrading

Source code in pyalgotrading/algobulls/api.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def start_strategy_algotrading(self, strategy_code: str, trading_type: TradingType) -> dict:
    """
    Submit Backtesting / Paper Trading / Real Trading job for strategy with code strategy_code & return the job ID.

    Info: ENDPOINT
        `POST` v2/customer_strategy_algotrading
    """
    if trading_type == TradingType.REALTRADING:
        endpoint = 'v2/portfolio/strategies'
    elif trading_type == TradingType.PAPERTRADING:
        endpoint = 'v2/papertrading/strategies'
    elif trading_type == TradingType.BACKTESTING:
        endpoint = 'v2/backtesting/strategies'
    else:
        raise NotImplementedError

    try:
        key = self.__get_key(strategy_code=strategy_code, trading_type=trading_type)
        json_data = {'method': 'update', 'newVal': 1, 'key': key, 'record': {'status': 0}}
        print(f'Submitting {trading_type.name} job...', end=' ')
        response = self._send_request(method='post', endpoint=endpoint, json_data=json_data)
        print('Success.')
        return response
    except (AlgoBullsAPIForbiddenError, AlgoBullsAPIInsufficientBalanceError) as ex:
        print('Fail.')
        print(f'{ex.get_error_type()}: {ex.response}')

stop_strategy_algotrading(self, strategy_code, trading_type)

Stop Backtesting / Paper Trading / Real Trading job for strategy with code strategy_code & return the job ID.

ENDPOINT

POST v1/customer_strategy_algotrading

Source code in pyalgotrading/algobulls/api.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def stop_strategy_algotrading(self, strategy_code: str, trading_type: TradingType) -> dict:
    """
    Stop Backtesting / Paper Trading / Real Trading job for strategy with code strategy_code & return the job ID.

    Info: ENDPOINT
        `POST` v1/customer_strategy_algotrading
    """
    if trading_type == TradingType.REALTRADING:
        endpoint = 'v2/portfolio/strategies'
    elif trading_type == TradingType.PAPERTRADING:
        endpoint = 'v2/papertrading/strategies'
    elif trading_type == TradingType.BACKTESTING:
        endpoint = 'v2/backtesting/strategies'
    else:
        raise NotImplementedError

    try:
        key = self.__get_key(strategy_code=strategy_code, trading_type=trading_type)
        json_data = {'method': 'update', 'newVal': 0, 'key': key, 'record': {'status': 2}}
        print(f'Stopping {trading_type.name} job...', end=' ')
        response = self._send_request(method='post', endpoint=endpoint, json_data=json_data)
        print('Success.')
        return response
    except (AlgoBullsAPIForbiddenError, AlgoBullsAPIInsufficientBalanceError) as ex:
        print('Fail.')
        print(f'{ex.get_error_type()}: {ex.response}')

update_strategy(self, strategy_name, strategy_details, abc_version)

Update an already existing strategy on the AlgoBulls platform

Parameters:

Name Type Description Default
strategy_name str

name of the strategy

required
strategy_details str

Python code of the strategy

required
abc_version str

value of one of the enums available under AlgoBullsEngineVersion

required

Returns:

Type Description
dict

JSON Response received from AlgoBulls platform after (attempt to) updating an existing strategy.

ENDPOINT

PUT v2/user/strategy/build/python

Source code in pyalgotrading/algobulls/api.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def update_strategy(self, strategy_name: str, strategy_details: str, abc_version: str) -> dict:
    """
    Update an already existing strategy on the AlgoBulls platform

    Args:
        strategy_name: name of the strategy
        strategy_details: Python code of the strategy
        abc_version: value of one of the enums available under `AlgoBullsEngineVersion`

    Returns:
        JSON Response received from AlgoBulls platform after (attempt to) updating an existing strategy.

    Info: ENDPOINT
        PUT v2/user/strategy/build/python
    """
    json_data = {'strategyName': strategy_name, 'strategyDetails': strategy_details, 'abcVersion': abc_version}
    endpoint = f'v2/user/strategy/build/python'
    response = self._send_request(endpoint=endpoint, method='put', json_data=json_data)
    return response

connection

Module for AlgoBulls connection

AlgoBullsConnection

Class for AlgoBulls connection

__init__(self) special

Init method that is used while creating an object of this class

Source code in pyalgotrading/algobulls/connection.py
21
22
23
24
25
def __init__(self):
    """
    Init method that is used while creating an object of this class
    """
    self.api = AlgoBullsAPI()

backtest(self, strategy_code, start_timestamp, end_timestamp, instrument, lots, strategy_parameters, candle_interval, strategy_mode=<StrategyMode.INTRADAY: 0>)

Submit a backtesting job for a strategy on the AlgoBulls Platform

Parameters:

Name Type Description Default
strategy_code

strategy code

required
start_timestamp

start date/time

required
end_timestamp

end date/time

required
instrument

instrument key

required
lots

Number of lots of the passed instrument to trade on

required
strategy_parameters

parameters

required
candle_interval

candle interval

required
strategy_mode

intraday or delivery

<StrategyMode.INTRADAY: 0>

Returns:

Type Description

backtest job submission status

Source code in pyalgotrading/algobulls/connection.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def backtest(self, strategy_code, start_timestamp, end_timestamp, instrument, lots, strategy_parameters, candle_interval, strategy_mode=StrategyMode.INTRADAY):
    """
    Submit a backtesting job for a strategy on the AlgoBulls Platform

    Args:
        strategy_code: strategy code
        start_timestamp: start date/time
        end_timestamp: end date/time
        instrument: instrument key
        lots: Number of lots of the passed instrument to trade on
        strategy_parameters: parameters
        candle_interval: candle interval
        strategy_mode: intraday or delivery

    Returns:
        backtest job submission status
    """
    # Sanity checks - Validate config parameters
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    assert (isinstance(start_timestamp, dt) is True), f'Argument "start_timestamp" should be an instance of type datetime.datetime'
    assert (isinstance(end_timestamp, dt) is True), f'Argument "start_timestamp" should be an instance of type datetime.datetime'
    assert (isinstance(instrument, str) is True), f'Argument "instrument" should be a string. You can find the right id using the \'get_instrument()\' method of AlgoBullsConnection class'
    assert (isinstance(lots, int) is True and lots > 0), f'Argument "lots" should be a positive integer.'
    assert (isinstance(strategy_parameters, dict) is True), f'Argument "strategy_parameters" should be a dict'
    assert (isinstance(strategy_mode, StrategyMode) is True), f'Argument "strategy_mode" should be enum of type StrategyMode'
    assert (isinstance(candle_interval, CandleInterval)), f'Argument "candle_interval" should be an enum of type CandleInterval'

    # Setup config for Backtesting
    strategy_config = {'tradingTime': [start_timestamp.strftime('%d-%m-%Y %H:%M'), end_timestamp.strftime('%d-%m-%Y %H:%M')],
                       'instruments': [instrument],
                       'lots': lots,
                       'parameters': strategy_parameters,
                       'candle': candle_interval.value,
                       'strategyMode': strategy_mode.value}
    self.api.set_strategy_config(strategy_code=strategy_code, strategy_config=strategy_config, trading_type=TradingType.BACKTESTING)

    # Submit Backtesting job
    response = self.api.start_strategy_algotrading(strategy_code=strategy_code, trading_type=TradingType.BACKTESTING)

create_strategy(self, strategy, overwrite=False, abc_version=None)

Method to upload new strategy.

Else

  • Create strategy for latest version
Source code in pyalgotrading/algobulls/connection.py
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
94
def create_strategy(self, strategy, overwrite=False, abc_version=None):
    """
    Method to upload new strategy.

    All strategies are unique by name, per customer.
    If customer tries to upload strategy with the same name as an already existing strategy -
    if overwrite is False:
        - AlgoBullsAPIBadRequest Exception will be thrown. No change would be done in the backend database.
    If overwrite is True,
        - Existing strategy with strategy_name would be overwritten. No exception will be thrown.
    If abc_version is not None,
        - Create strategy for specific version
    else:
        - Create strategy for latest version
    """

    # Sanity checks
    assert issubclass(strategy, StrategyBase), f'strategy should be a subclass of class StrategyBase. Got class of type: type{strategy}'

    # Validate class by creating an instance
    # Todo: Temporarily disabling strategy validation for this bug fix: Validating strategy which has assert checks for strategy parameters to be of specific type (say 'int') fails with TypeError.
    #       In future, if assert checks can be taken care of dynamically, turn this validation ON.
    # print('Validating Strategy...')
    # strategy()

    # Get source code, and upload as new strategy (if strategy_code is None) else edit same strategy
    strategy_name = strategy.name()
    strategy_details = inspect.getsource(strategy)
    versions_supported = strategy.versions_supported()

    if abc_version is None:
        if isinstance(versions_supported, list):
            _abc_version = strategy.versions_supported()[0].value       # Take the first version
            # TODO: Once 3.3.0 is available for pyalgotrading, change index from '0' to '-1' to take the latest version
        else:
            _abc_version = strategy.versions_supported().value
    else:
        _abc_version = abc_version.value

    if overwrite is False:
        response = self.api.create_strategy(strategy_name=strategy_name, strategy_details=strategy_details, abc_version=_abc_version)
    else:
        response = self.api.update_strategy(strategy_name=strategy_name, strategy_details=strategy_details, abc_version=_abc_version)

    return response

get_all_strategies(self)

Fetch all available strategies

Returns:

Type Description

list of available strategies

Source code in pyalgotrading/algobulls/connection.py
 96
 97
 98
 99
100
101
102
103
104
105
106
def get_all_strategies(self):
    """
    Fetch all available strategies
    Returns:
        list of available strategies
    """
    response = self.api.get_all_strategies()
    if isinstance(response['data'], list):
        return pd.DataFrame(response['data'])
    else:
        return response

get_authorization_url() staticmethod

Fetches the authorization URL

Returns:

Type Description

authorization URL

Source code in pyalgotrading/algobulls/connection.py
27
28
29
30
31
32
33
34
35
36
@staticmethod
def get_authorization_url():
    """
    Fetches the authorization URL
    Returns:
        authorization URL
    """
    url = 'https://app.algobulls.com/user/login'
    print(f'Please login to this URL with your AlgoBulls credentials and get your developer access token: {url}')
    return url

get_backtesting_job_status(self, strategy_code)

Gets BACKTESTING job status for given strategy_code

Source code in pyalgotrading/algobulls/connection.py
253
254
255
256
257
258
def get_backtesting_job_status(self, strategy_code):
    """
    Gets BACKTESTING job status for given strategy_code
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.get_job_status(strategy_code, TradingType.BACKTESTING)

get_backtesting_logs(self, strategy_code)

Fetch backtesting logs

Parameters:

Name Type Description Default
strategy_code required

Returns:

Type Description

report details

Source code in pyalgotrading/algobulls/connection.py
272
273
274
275
276
277
278
279
280
281
282
def get_backtesting_logs(self, strategy_code):
    """
    Fetch backtesting logs
    Args:
        strategy_code:

    Returns:
        report details
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.get_logs(strategy_code, trading_type=TradingType.BACKTESTING)

get_backtesting_report_order_history(self, strategy_code)

Fetch backtesting order history

Parameters:

Name Type Description Default
strategy_code

strategy code

required

Returns:

Type Description

report details

Source code in pyalgotrading/algobulls/connection.py
309
310
311
312
313
314
315
316
317
318
319
def get_backtesting_report_order_history(self, strategy_code):
    """
    Fetch backtesting order history
    Args:
        strategy_code: strategy code

    Returns:
        report details
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.get_report(strategy_code=strategy_code, trading_type=TradingType.BACKTESTING, report_type=TradingReportType.ORDER_HISTORY)

get_backtesting_report_pnl_table(self, strategy_code, show_all_rows=False)

Fetch backtesting Profit / Loss details

Parameters:

Name Type Description Default
strategy_code

strategy code

required
show_all_rows

True or False

False

Returns:

Type Description

report details

Source code in pyalgotrading/algobulls/connection.py
284
285
286
287
288
289
290
291
292
293
294
295
def get_backtesting_report_pnl_table(self, strategy_code, show_all_rows=False):
    """
    Fetch backtesting Profit / Loss details
    Args:
        strategy_code: strategy code
        show_all_rows: True or False

    Returns:
        report details
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.get_report(strategy_code=strategy_code, trading_type=TradingType.BACKTESTING, report_type=TradingReportType.PNL_TABLE, render_as_dataframe=True, show_all_rows=show_all_rows)

get_backtesting_report_statistics(self, strategy_code)

Fetch backtesting report statistics

Parameters:

Name Type Description Default
strategy_code

strategy code

required

Returns:

Type Description

report details

Source code in pyalgotrading/algobulls/connection.py
297
298
299
300
301
302
303
304
305
306
307
def get_backtesting_report_statistics(self, strategy_code):
    """
    Fetch backtesting report statistics
    Args:
        strategy_code: strategy code

    Returns:
        report details
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.get_report(strategy_code=strategy_code, trading_type=TradingType.BACKTESTING, report_type=TradingReportType.STATS_TABLE, render_as_dataframe=True)

get_job_status(self, strategy_code, trading_type)

Gets job status for given strategy_code and trading_type

Source code in pyalgotrading/algobulls/connection.py
139
140
141
142
143
144
145
146
147
def get_job_status(self, strategy_code, trading_type):
    """
    Gets job status for given strategy_code and trading_type
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    assert (isinstance(trading_type, TradingType) is True), f'Argument "trading_type" should be an enum of type {TradingType.__name__}'

    response = self.api.get_job_status(strategy_code=strategy_code, trading_type=trading_type)
    return response

get_logs(self, strategy_code, trading_type)

Fetch logs for a strategy

Parameters:

Name Type Description Default
strategy_code

strategy code

required
trading_type

trading type

required

Returns:

Type Description

Execution logs

Source code in pyalgotrading/algobulls/connection.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def get_logs(self, strategy_code, trading_type):
    """
    Fetch logs for a strategy

    Args:
        strategy_code: strategy code
        trading_type: trading type

    Returns:
        Execution logs
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    assert (isinstance(trading_type, TradingType) is True), f'Argument "trading_type" should be an enum of type {TradingType.__name__}'

    return self.api.get_logs(strategy_code=strategy_code, trading_type=trading_type).get('data')

get_papertrading_job_status(self, strategy_code)

Get papertrading job status

Parameters:

Name Type Description Default
strategy_code required

Returns:

Type Description

job status

Source code in pyalgotrading/algobulls/connection.py
359
360
361
362
363
364
365
366
367
368
369
def get_papertrading_job_status(self, strategy_code):
    """
    Get papertrading job status
    Args:
        strategy_code:

    Returns:
        job status
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.get_job_status(strategy_code, TradingType.PAPERTRADING)

get_papertrading_logs(self, strategy_code)

Fetch papertrading logs

Parameters:

Name Type Description Default
strategy_code

strategy code

required

Returns:

Type Description

report details

Source code in pyalgotrading/algobulls/connection.py
383
384
385
386
387
388
389
390
391
392
393
def get_papertrading_logs(self, strategy_code):
    """
    Fetch papertrading logs
    Args:
        strategy_code: strategy code

    Returns:
        report details
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.get_logs(strategy_code=strategy_code, trading_type=TradingType.PAPERTRADING)

get_papertrading_report_order_history(self, strategy_code)

Fetch papertrading order history

Parameters:

Name Type Description Default
strategy_code

strategy code

required

Returns:

Type Description

report details

Source code in pyalgotrading/algobulls/connection.py
420
421
422
423
424
425
426
427
428
429
430
def get_papertrading_report_order_history(self, strategy_code):
    """
    Fetch papertrading order history
    Args:
        strategy_code: strategy code

    Returns:
        report details
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.get_report(strategy_code=strategy_code, trading_type=TradingType.PAPERTRADING, report_type=TradingReportType.ORDER_HISTORY)

get_papertrading_report_pnl_table(self, strategy_code, show_all_rows=False)

Fetch papertrading Profit / Loss details

Parameters:

Name Type Description Default
strategy_code

strategy code

required
show_all_rows

True or False

False

Returns:

Type Description

report details

Source code in pyalgotrading/algobulls/connection.py
395
396
397
398
399
400
401
402
403
404
405
406
def get_papertrading_report_pnl_table(self, strategy_code, show_all_rows=False):
    """
    Fetch papertrading Profit / Loss details
    Args:
        strategy_code: strategy code
        show_all_rows: True or False

    Returns:
        report details
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.get_report(strategy_code=strategy_code, trading_type=TradingType.PAPERTRADING, report_type=TradingReportType.PNL_TABLE, render_as_dataframe=True, show_all_rows=show_all_rows)

get_papertrading_report_statistics(self, strategy_code)

Fetch papertrading report statistics

Parameters:

Name Type Description Default
strategy_code

strategy code

required

Returns:

Type Description

report details

Source code in pyalgotrading/algobulls/connection.py
408
409
410
411
412
413
414
415
416
417
418
def get_papertrading_report_statistics(self, strategy_code):
    """
    Fetch papertrading report statistics
    Args:
        strategy_code: strategy code

    Returns:
        report details
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.get_report(strategy_code=strategy_code, trading_type=TradingType.PAPERTRADING, report_type=TradingReportType.STATS_TABLE, render_as_dataframe=True)

get_realtrading_job_status(self, strategy_code)

Fetch realtrading job status

Parameters:

Name Type Description Default
strategy_code

strategy code

required

Returns:

Type Description

job status

Source code in pyalgotrading/algobulls/connection.py
471
472
473
474
475
476
477
478
479
480
481
482
483
def get_realtrading_job_status(self, strategy_code):
    """
    Fetch realtrading job status
    Args:
        strategy_code: strategy code

    Returns:
        job status
    """
    # assert (isinstance(broker, AlgoBullsSupportedBrokers) is True), f'Argument broker should be an enum of type {AlgoBullsSupportedBrokers.__name__}'
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'

    return self.get_job_status(strategy_code, TradingType.REALTRADING)

get_realtrading_logs(self, strategy_code)

Fetch realtrading logs

Parameters:

Name Type Description Default
strategy_code

strategy code

required

Returns:

Type Description

report details

Source code in pyalgotrading/algobulls/connection.py
498
499
500
501
502
503
504
505
506
507
508
509
510
def get_realtrading_logs(self, strategy_code):
    """
    Fetch realtrading logs
    Args:
        strategy_code: strategy code

    Returns:
        report details
    """
    # assert (isinstance(broker, AlgoBullsSupportedBrokers) is True), f'Argument broker should be an enum of type {AlgoBullsSupportedBrokers.__name__}'
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'

    return self.get_logs(strategy_code=strategy_code, trading_type=TradingType.REALTRADING)

get_realtrading_report_order_history(self, strategy_code)

Fetch realtrading order history

Parameters:

Name Type Description Default
# broker

broker name

required
strategy_code

strategy code

required

Returns:

Type Description

report details

Source code in pyalgotrading/algobulls/connection.py
542
543
544
545
546
547
548
549
550
551
552
553
554
555
def get_realtrading_report_order_history(self, strategy_code):
    """
    Fetch realtrading order history
    Args:
        # broker: broker name
        strategy_code: strategy code

    Returns:
        report details
    """
    # assert (isinstance(broker, AlgoBullsSupportedBrokers) is True), f'Argument broker should be an enum of type {AlgoBullsSupportedBrokers.__name__}'
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'

    return self.get_report(strategy_code=strategy_code, trading_type=TradingType.REALTRADING, report_type=TradingReportType.ORDER_HISTORY)

get_realtrading_report_pnl_table(self, strategy_code, show_all_rows=False)

Fetch realtrading Profit / Loss table

Parameters:

Name Type Description Default
# broker

broker name

required
strategy_code

strategy code

required
show_all_rows

True or False

False

Returns:

Type Description

report details

Source code in pyalgotrading/algobulls/connection.py
512
513
514
515
516
517
518
519
520
521
522
523
524
525
def get_realtrading_report_pnl_table(self, strategy_code, show_all_rows=False):
    """
    Fetch realtrading Profit / Loss table
    Args:
        # broker: broker name
        strategy_code: strategy code
        show_all_rows: True or False

    Returns:
        report details
    """
    # assert (isinstance(broker, AlgoBullsSupportedBrokers) is True), f'Argument broker should be an enum of type {AlgoBullsSupportedBrokers.__name__}'
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.get_report(strategy_code=strategy_code, trading_type=TradingType.REALTRADING, report_type=TradingReportType.PNL_TABLE, render_as_dataframe=True, show_all_rows=show_all_rows)

get_realtrading_report_statistics(self, strategy_code)

Fetch realtrading report statistics

Parameters:

Name Type Description Default
# broker

broker name

required
strategy_code

strategy code

required

Returns:

Type Description

report details

Source code in pyalgotrading/algobulls/connection.py
527
528
529
530
531
532
533
534
535
536
537
538
539
540
def get_realtrading_report_statistics(self, strategy_code):
    """
    Fetch realtrading report statistics
    Args:
        # broker: broker name
        strategy_code: strategy code

    Returns:
        report details
    """
    # assert (isinstance(broker, AlgoBullsSupportedBrokers) is True), f'Argument broker should be an enum of type {AlgoBullsSupportedBrokers.__name__}'
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'

    return self.get_report(strategy_code=strategy_code, trading_type=TradingType.REALTRADING, report_type=TradingReportType.STATS_TABLE, render_as_dataframe=True)

get_report(self, strategy_code, trading_type, report_type, render_as_dataframe=False, show_all_rows=False)

Fetch report for a strategy

Parameters:

Name Type Description Default
strategy_code

strategy code

required
trading_type

trading type

required
report_type

report type

required
render_as_dataframe

True or False

False
show_all_rows

True or False

False

Returns:

Type Description

report details

Source code in pyalgotrading/algobulls/connection.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def get_report(self, strategy_code, trading_type, report_type, render_as_dataframe=False, show_all_rows=False):
    """
    Fetch report for a strategy

    Args:
        strategy_code: strategy code
        trading_type: trading type
        report_type: report type
        render_as_dataframe: True or False
        show_all_rows: True or False

    Returns:
        report details
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    assert (isinstance(trading_type, TradingType) is True), f'Argument "trading_type" should be an enum of type {TradingType.__name__}'
    assert (isinstance(report_type, TradingReportType) is True), f'Argument "report_type" should be an enum of type {TradingReportType.__name__}'
    assert (isinstance(render_as_dataframe, bool) is True), f'Argument "render_as_dataframe" should be a bool'
    assert (isinstance(show_all_rows, bool) is True), f'Argument "show_all_rows" should be a bool'
    # assert (broker is None or isinstance(broker, AlgoBullsSupportedBrokers) is True), f'Argument broker should be None or an enum of type {AlgoBullsSupportedBrokers.__name__}'

    response = self.api.get_reports(strategy_code=strategy_code, trading_type=trading_type, report_type=report_type)
    if response.get('data'):
        if render_as_dataframe:
            if show_all_rows:
                pandas_dataframe_all_rows()
            _response = pd.DataFrame(response['data'])
        else:
            _response = response['data']
        return _response
    else:
        print('Report not available yet. Please retry in sometime')

get_strategy_details(self, strategy_code)

Fetch the strategy details of a particular strategy

Parameters:

Name Type Description Default
strategy_code

strategy code

required

Returns:

Type Description

strategy program / code

Source code in pyalgotrading/algobulls/connection.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def get_strategy_details(self, strategy_code):
    """
    Fetch the strategy details of a particular strategy
    Args:
        strategy_code: strategy code

    Returns:
        strategy program / code
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'

    try:
        response = self.api.get_strategy_details(strategy_code)
        strategy_code = response['data']
        return strategy_code
    except AlgoBullsAPIBadRequest:
        print(f'ERROR: No strategy found with ID: {strategy_code}')

papertrade(self, strategy_code, start_time, end_time, instrument, lots, strategy_parameters, candle_interval, strategy_mode=<StrategyMode.INTRADAY: 0>)

Start a paper trading session

Parameters:

Name Type Description Default
strategy_code

strategy code

required
start_time

start time

required
end_time

end time

required
instrument

instrument key

required
lots

Number of lots of the passed instrument to trade on

required
strategy_parameters

parameters

required
candle_interval

candle interval

required
strategy_mode

intraday or delivery

<StrategyMode.INTRADAY: 0>

Returns:

Type Description

job status

Source code in pyalgotrading/algobulls/connection.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
def papertrade(self, strategy_code, start_time, end_time, instrument, lots, strategy_parameters, candle_interval, strategy_mode=StrategyMode.INTRADAY):
    """
    Start a paper trading session
    Args:
        strategy_code: strategy code
        start_time: start time
        end_time: end time
        instrument: instrument key
        lots: Number of lots of the passed instrument to trade on
        strategy_parameters: parameters
        candle_interval: candle interval
        strategy_mode: intraday or delivery

    Returns:
        job status
    """
    # Sanity checks - Validate config parameters
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    assert (isinstance(start_time, time) is True), f'Argument "start_timestamp" should be an instance of type datetime.datetime'
    assert (isinstance(end_time, time) is True), f'Argument "start_timestamp" should be an instance of type datetime.datetime'
    assert (isinstance(instrument, str) is True), f'Argument "instrument" should be a string. You can find the right id using the \'get_instrument()\' method of AlgoBullsConnection class'
    assert (isinstance(lots, int) is True and lots > 0), f'Argument "lots" should be a positive integer.'
    assert (isinstance(strategy_parameters, dict) is True), f'Argument "strategy_parameters" should be a dict'
    assert (isinstance(strategy_mode, StrategyMode) is True), f'Argument "strategy_mode" should be enum of type StrategyMode'
    assert (isinstance(candle_interval, CandleInterval)), f'Argument "candle_interval" should be an enum of type CandleInterval'

    # Setup config for Paper Trading
    strategy_config = {'tradingTime': [start_time.strftime('%H:%M'), end_time.strftime('%H:%M')],
                       'instruments': [instrument],
                       'lots': lots,
                       'parameters': strategy_parameters,
                       'candle': candle_interval.value,
                       'strategyMode': strategy_mode.value}
    self.api.set_strategy_config(strategy_code=strategy_code, strategy_config=strategy_config, trading_type=TradingType.PAPERTRADING)

    # Submit Paper Trading job
    response = self.api.start_strategy_algotrading(strategy_code=strategy_code, trading_type=TradingType.PAPERTRADING)

realtrade(self, strategy_code, start_time, end_time, instrument, lots, strategy_parameters, candle_interval, strategy_mode=<StrategyMode.INTRADAY: 0>)

Start a realtrading session

Parameters:

Name Type Description Default
strategy_code

strategy code

required
start_time

start time

required
end_time

end time

required
instrument

instrument key

required
lots

Number of lots of the passed instrument to trade on

required
strategy_parameters

parameters

required
candle_interval

candle interval

required
strategy_mode

intraday or delivery

<StrategyMode.INTRADAY: 0>

Returns:

Type Description

job status

Source code in pyalgotrading/algobulls/connection.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
def realtrade(self, strategy_code, start_time, end_time, instrument, lots, strategy_parameters, candle_interval, strategy_mode=StrategyMode.INTRADAY):
    """
    Start a realtrading session
    Args:
        strategy_code: strategy code
        start_time: start time
        end_time: end time
        instrument: instrument key
        lots: Number of lots of the passed instrument to trade on
        strategy_parameters: parameters
        candle_interval: candle interval
        strategy_mode: intraday or delivery

    Returns:
        job status
    """
    # Sanity checks - Validate config parameters
    # assert (isinstance(broker, AlgoBullsSupportedBrokers) is True), f'Argument broker should be an enum of type {AlgoBullsSupportedBrokers.__name__}'
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    assert (isinstance(start_time, time) is True), f'Argument "start_time" should be an instance of type datetime.time'
    assert (isinstance(end_time, time) is True), f'Argument "end_time" should be an instance of type datetime.time'
    assert (isinstance(instrument, str) is True), f'Argument "instrument" should be a string. You can find the right id using the \'get_instrument()\' method of AlgoBullsConnection class'
    assert (isinstance(lots, int) is True and lots > 0), f'Argument "lots" should be a positive integer.'
    assert (isinstance(strategy_parameters, dict) is True), f'Argument "strategy_parameters" should be a dict'
    assert (isinstance(strategy_mode, StrategyMode) is True), f'Argument "strategy_mode" should be enum of type StrategyMode'
    assert (isinstance(candle_interval, CandleInterval)), f'Argument "candle_interval" should be an enum of type CandleInterval'

    # Setup config for backtesting
    strategy_config = {'tradingTime': [start_time.strftime('%H:%M'), end_time.strftime('%H:%M')],
                       'instruments': [instrument],
                       'lots': lots,
                       'parameters': strategy_parameters,
                       'candle': candle_interval.value,
                       'strategyMode': strategy_mode.value}
    self.api.set_strategy_config(strategy_code=strategy_code, strategy_config=strategy_config, trading_type=TradingType.REALTRADING)

    # Submit Real Trading job
    response = self.api.start_strategy_algotrading(strategy_code=strategy_code, trading_type=TradingType.REALTRADING)

search_instrument(self, instrument)

Search for an instrument

Parameters:

Name Type Description Default
instrument

instrument key

required

Returns:

Type Description

True or False

Source code in pyalgotrading/algobulls/connection.py
126
127
128
129
130
131
132
133
134
135
136
137
def search_instrument(self, instrument):
    """
    Search for an instrument
    Args:
        instrument: instrument key

    Returns:
        True or False
    """
    assert (isinstance(instrument, str) is True), f'Argument "instrument" should be a string'
    response = self.api.search_instrument(instrument).get('data')
    return response

set_access_token(self, access_token)

Set the access token

Parameters:

Name Type Description Default
access_token

access token

required

Returns:

Type Description

None

Source code in pyalgotrading/algobulls/connection.py
38
39
40
41
42
43
44
45
46
47
48
def set_access_token(self, access_token):
    """
    Set the access token
    Args:
        access_token: access token

    Returns:
        None
    """
    assert (isinstance(access_token, str) is True), f'Argument "access_token" should be a string'
    self.api.set_access_token(access_token)

stop_backtesting_job(self, strategy_code)

Stops the BACKTESTING job

Parameters:

Name Type Description Default
strategy_code

Strategy Code / ID

required

Returns:

Type Description

None

Source code in pyalgotrading/algobulls/connection.py
260
261
262
263
264
265
266
267
268
269
270
def stop_backtesting_job(self, strategy_code):
    """
    Stops the BACKTESTING job
    Args:
        strategy_code: Strategy Code / ID

    Returns:
        None
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.stop_job(strategy_code=strategy_code, trading_type=TradingType.BACKTESTING)

stop_job(self, strategy_code, trading_type)

Stops a job

Parameters:

Name Type Description Default
strategy_code

strategy code

required
trading_type

trading type

required

Returns:

Type Description

job status

Source code in pyalgotrading/algobulls/connection.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def stop_job(self, strategy_code, trading_type):
    """
    Stops a job
    Args:
        strategy_code: strategy code
        trading_type: trading type

    Returns:
        job status
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    assert (isinstance(trading_type, TradingType) is True), f'Argument "trading_type" should be an enum of type {TradingType.__name__}'

    response = self.api.stop_strategy_algotrading(strategy_code=strategy_code, trading_type=trading_type)

stop_papertrading_job(self, strategy_code)

Stop the papertrading session

Parameters:

Name Type Description Default
strategy_code

strategy code

required

Returns:

Type Description

None

Source code in pyalgotrading/algobulls/connection.py
371
372
373
374
375
376
377
378
379
380
381
def stop_papertrading_job(self, strategy_code):
    """
    Stop the papertrading session
    Args:
        strategy_code: strategy code

    Returns:
        None
    """
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.stop_job(strategy_code=strategy_code, trading_type=TradingType.PAPERTRADING)

stop_realtrading_job(self, strategy_code)

Stop the realtrading session

Parameters:

Name Type Description Default
strategy_code

strategy code

required

Returns:

Type Description

None

Source code in pyalgotrading/algobulls/connection.py
485
486
487
488
489
490
491
492
493
494
495
496
def stop_realtrading_job(self, strategy_code):
    """
    Stop the realtrading session
    Args:
        strategy_code: strategy code

    Returns:
        None
    """
    # assert (isinstance(broker, AlgoBullsSupportedBrokers) is True), f'Argument broker should be an enum of type {AlgoBullsSupportedBrokers.__name__}'
    assert (isinstance(strategy_code, str) is True), f'Argument "strategy_code" should be a string'
    return self.stop_job(strategy_code=strategy_code, trading_type=TradingType.REALTRADING)

pandas_dataframe_all_rows()

Returns: None

Source code in pyalgotrading/algobulls/connection.py
558
559
560
561
562
563
564
565
566
567
def pandas_dataframe_all_rows():
    """

    Returns: None

    """
    pd.set_option('display.max_rows', None)
    pd.set_option('display.max_columns', None)
    pd.set_option('display.width', None)
    pd.set_option('display.max_colwidth', None)

exceptions

AlgoBullsAPIBadRequest

Exception class for HTTP status code of 400 (Bad Request)

AlgoBullsAPIBaseException

Base exception class for all API related exceptions

AlgoBullsAPIForbiddenError

Exception class for HTTP status code of 403 (Operation not permitted) Use case: Trying to START or STOP a strategy when it is in intermediate state.

AlgoBullsAPIInsufficientBalanceError

Exception class for HTTP status code of 402 (Insufficient Balance)

AlgoBullsAPIInternalServerErrorException

Exception class for HTTP status code of 500 (Internal Server Error)

AlgoBullsAPIResourceNotFoundError

Exception class for HTTP status code of 404 (Resource Not Found)

AlgoBullsAPIUnauthorizedError

Exception class for HTTP status code of 401 (Unauthorized)


Last update:

Comments