Skip to content

broker

broker_connection_base

Base class for Broker Connection

BrokerConnectionBase

Base class for Broker Connection

get_all_instruments(self)

All instruments enlisted by the broker

Returns:

Type Description

list of all instruments

Source code in pyalgotrading/broker/broker_connection_base.py
20
21
22
23
24
25
26
27
@abstractmethod
def get_all_instruments(self):
    """
    All instruments enlisted by the broker
    Returns:
        list of all instruments
    """
    raise NotImplementedError

get_circuit_limits(self, *args, **kwargs)

Fetch the circuit limits

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

circuit limit value

Source code in pyalgotrading/broker/broker_connection_base.py
55
56
57
58
59
60
61
62
63
64
65
66
@abstractmethod
def get_circuit_limits(self, *args, **kwargs):
    """
    Fetch the circuit limits
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        circuit limit value
    """
    raise NotImplementedError

get_close_price_last_day(self, *args, **kwargs)

Fetch the closed price of the day

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

closed price value

Source code in pyalgotrading/broker/broker_connection_base.py
185
186
187
188
189
190
191
192
193
194
195
196
@abstractmethod
def get_close_price_last_day(self, *args, **kwargs):
    """
    Fetch the closed price of the day
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        closed price value
    """
    raise NotImplementedError

get_funds(self, *args, **kwargs)

Fetch the available funds

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

available funds value

Source code in pyalgotrading/broker/broker_connection_base.py
226
227
228
229
230
231
232
233
234
235
236
237
@abstractmethod
def get_funds(self, *args, **kwargs):
    """
    Fetch the available funds
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        available funds value
    """
    raise NotImplementedError

get_high_price_day(self, *args, **kwargs)

Fetch the high price of the day

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

high price value

Source code in pyalgotrading/broker/broker_connection_base.py
159
160
161
162
163
164
165
166
167
168
169
170
@abstractmethod
def get_high_price_day(self, *args, **kwargs):
    """
    Fetch the high price of the day
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        high price value
    """
    raise NotImplementedError

get_historical_data(self, instrument, candle_interval, start_date, end_date)

Fetch the historical data

Parameters:

Name Type Description Default
instrument

instrument key

required
candle_interval

candle interval

required
start_date

date from which to fetch the historical data

required
end_date

date till which to fetch the historical data

required

Returns:

Type Description

historical data

Source code in pyalgotrading/broker/broker_connection_base.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
@abstractmethod
def get_historical_data(self, instrument, candle_interval, start_date, end_date):
    """
    Fetch the historical data
    Args:
        instrument: instrument key
        candle_interval: candle interval
        start_date: date from which to fetch the historical data
        end_date: date till which to fetch the historical data

    Returns:
        historical data
    """
    raise NotImplementedError

get_instrument(self, *args, **kwargs)

Fetch a single instrument

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

a single instrument

Source code in pyalgotrading/broker/broker_connection_base.py
29
30
31
32
33
34
35
36
37
38
39
40
@abstractmethod
def get_instrument(self, *args, **kwargs):
    """
    Fetch a single instrument
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        a single instrument
    """
    raise NotImplementedError

get_low_price_day(self, *args, **kwargs)

Fetch the low price of the day

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

low price value

Source code in pyalgotrading/broker/broker_connection_base.py
172
173
174
175
176
177
178
179
180
181
182
183
@abstractmethod
def get_low_price_day(self, *args, **kwargs):
    """
    Fetch the low price of the day
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        low price value
    """
    raise NotImplementedError

get_ltp(self, *args, **kwargs)

Fetch the Last Trading Price (LTP)

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

ltp value

Source code in pyalgotrading/broker/broker_connection_base.py
68
69
70
71
72
73
74
75
76
77
78
79
@abstractmethod
def get_ltp(self, *args, **kwargs):
    """
    Fetch the Last Trading Price (LTP)
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        ltp value
    """
    raise NotImplementedError

get_ltq(self, *args, **kwargs)

Fetch the Last Trading Quantity (LTQ)

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

ltq value

Source code in pyalgotrading/broker/broker_connection_base.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@abstractmethod
def get_ltq(self, *args, **kwargs):
    """
    Fetch the Last Trading Quantity (LTQ)
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        ltq value
    """
    raise NotImplementedError

get_ltt(self, *args, **kwargs)

Fetch the Last Trading Time (LTT)

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

ltt value

Source code in pyalgotrading/broker/broker_connection_base.py
81
82
83
84
85
86
87
88
89
90
91
92
@abstractmethod
def get_ltt(self, *args, **kwargs):
    """
    Fetch the Last Trading Time (LTT)
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        ltt value
    """
    raise NotImplementedError

get_margins(self, *args, **kwargs)

Fetch the margins

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

margin value

Source code in pyalgotrading/broker/broker_connection_base.py
213
214
215
216
217
218
219
220
221
222
223
224
@abstractmethod
def get_margins(self, *args, **kwargs):
    """
    Fetch the margins
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        margin value
    """
    raise NotImplementedError

get_market_depth(self, *args, **kwargs)

Fetch the market depth

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

market depth value

Source code in pyalgotrading/broker/broker_connection_base.py
42
43
44
45
46
47
48
49
50
51
52
53
@abstractmethod
def get_market_depth(self, *args, **kwargs):
    """
    Fetch the market depth
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        market depth value
    """
    raise NotImplementedError

get_name(self)

Name of the broker

Returns:

Type Description

broker name

Source code in pyalgotrading/broker/broker_connection_base.py
11
12
13
14
15
16
17
18
@abstractmethod
def get_name(self):
    """
    Name of the broker
    Returns:
        broker name
    """
    raise NotImplementedError

get_open_price_day(self, *args, **kwargs)

Fetch the open price of the day

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

open price value

Source code in pyalgotrading/broker/broker_connection_base.py
146
147
148
149
150
151
152
153
154
155
156
157
@abstractmethod
def get_open_price_day(self, *args, **kwargs):
    """
    Fetch the open price of the day
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        open price value
    """
    raise NotImplementedError

get_order_status(self, order_id)

Fetch the status of the order

Parameters:

Name Type Description Default
order_id

order id

required

Returns:

Type Description

the status of the order

Source code in pyalgotrading/broker/broker_connection_base.py
270
271
272
273
274
275
276
277
278
279
280
@abstractmethod
def get_order_status(self, order_id):
    """
    Fetch the status of the order
    Args:
        order_id: order id

    Returns:
        the status of the order
    """
    raise NotImplementedError

get_profile(self)

Fetch the profile

Returns:

Type Description

profile information

Source code in pyalgotrading/broker/broker_connection_base.py
239
240
241
242
243
244
245
246
@abstractmethod
def get_profile(self):
    """
    Fetch the profile
    Returns:
        profile information
    """
    raise NotImplementedError

get_total_pending_buy_quantity(self, *args, **kwargs)

Fetch the total pending buy quantity for instrument

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

total quantity value

Source code in pyalgotrading/broker/broker_connection_base.py
107
108
109
110
111
112
113
114
115
116
117
118
@abstractmethod
def get_total_pending_buy_quantity(self, *args, **kwargs):
    """
    Fetch the total pending buy quantity for instrument
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        total quantity value
    """
    raise NotImplementedError

get_total_pending_sell_quantity(self, *args, **kwargs)

Fetch the total pending sell quantity for the instrument

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

total quantity value

Source code in pyalgotrading/broker/broker_connection_base.py
120
121
122
123
124
125
126
127
128
129
130
131
@abstractmethod
def get_total_pending_sell_quantity(self, *args, **kwargs):
    """
    Fetch the total pending sell quantity for the instrument
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        total quantity value
    """
    raise NotImplementedError

get_total_volume_day(self, *args, **kwargs)

Fetch the total volume for the day

Parameters:

Name Type Description Default
*args

a variable-length argument list

()
**kwargs

a keyworded, variable-length argument list

{}

Returns:

Type Description

total volume value

Source code in pyalgotrading/broker/broker_connection_base.py
133
134
135
136
137
138
139
140
141
142
143
144
@abstractmethod
def get_total_volume_day(self, *args, **kwargs):
    """
    Fetch the total volume for the day
    Args:
        *args: a variable-length argument list
        **kwargs: a keyworded, variable-length argument list

    Returns:
        total volume value
    """
    raise NotImplementedError

place_order(self, instrument, order_transaction_type, order_type, order_code, order_variety, quantity, price=None, trigger_price=None, stoploss_trigger=None, target_trigger=None, trailing_stoploss_trigger=None)

Place an order

Parameters:

Name Type Description Default
instrument

instrument key

required
order_transaction_type

buy or sell

required
order_type

regular or bracket

required
order_code

orde code

required
order_variety

market / limit / stoploss market / stoploss limit

required
quantity

quantity

required
price

amount / value

None
trigger_price

trigger price amount / value

None
stoploss_trigger

stoploss trigger amount / value

None
target_trigger

target trigger amount / value

None
trailing_stoploss_trigger

trailing stoploss trigger amount / value

None

Returns:

Type Description

order id

Source code in pyalgotrading/broker/broker_connection_base.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
@abstractmethod
def place_order(self, instrument, order_transaction_type, order_type, order_code, order_variety, quantity, price=None, trigger_price=None, stoploss_trigger=None, target_trigger=None, trailing_stoploss_trigger=None):
    """
    Place an order
    Args:
        instrument: instrument key
        order_transaction_type: buy or sell
        order_type: regular or bracket
        order_code: orde code
        order_variety: market / limit / stoploss market / stoploss limit
        quantity: quantity
        price: amount / value
        trigger_price: trigger price amount / value
        stoploss_trigger: stoploss trigger amount / value
        target_trigger: target trigger amount / value
        trailing_stoploss_trigger: trailing stoploss trigger amount / value

    Returns:
        order id
    """
    raise NotImplementedError

broker_connection_zerodha

Module for class BrokerConnectionZerodha

BrokerConnectionZerodha

class for Broker Connection Zerodha

__init__(self, api_key, api_secret) special

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

Parameters:

Name Type Description Default
api_key

api key given by the broker

required
api_secret

api secret to be used for making an authenticated connection with the broker

required
Source code in pyalgotrading/broker/broker_connection_zerodha.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def __init__(self, api_key, api_secret):
    """
    Init method that is used while creating an object of this class
    Args:
        api_key: api key given by the broker
        api_secret: api secret to be used for making an authenticated connection with the broker
    """
    self.api_key = api_key
    self.api_secret = api_secret

    # Create kiteconnect instance
    kiteconnect = import_with_install(package_import_name='kiteconnect', package_install_name='kiteconnect==3.8.2')
    self.api = kiteconnect.KiteConnect(api_key=self.api_key)

    # Print the login url. User will use this to login to broker site and get access token
    print(f'Please login to this link to generate your request token: {self.api.login_url()}')

    # Create other attributes
    self.all_instruments = None
    self.populate_constants()

cancel_order(self, order_id, order_type)

Cancel an order

Parameters:

Name Type Description Default
order_id

order id

required
order_type

order type

required

Returns:

Type Description

Order Status

Source code in pyalgotrading/broker/broker_connection_zerodha.py
373
374
375
376
377
378
379
380
381
382
383
384
def cancel_order(self, order_id, order_type):
    """
    Cancel an order
    Args:
        order_id: order id
        order_type: order type

    Returns:
        Order Status
    """
    _variety = BrokerConnectionZerodha.ORDER_TYPE_MAP[order_type]  # What we call as 'Order Type', Zerodha calls it as 'variety'
    return self.api.cancel_order(variety=_variety, order_id=order_id)

get_all_instruments(self)

Fetches all instruments

Returns:

Type Description

list of all instruments

Source code in pyalgotrading/broker/broker_connection_zerodha.py
87
88
89
90
91
92
93
94
def get_all_instruments(self):
    """
    Fetches all instruments
    Returns:
        list of all instruments
    """
    self.all_instruments = pd.DataFrame(self.api.instruments())
    return self.all_instruments

get_circuit_limits(self, instrument)

Fetch the circuit limits

Parameters:

Name Type Description Default
instrument Instrument

Financial Instrument

required

Returns:

Type Description

circuit limit value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
143
144
145
146
147
148
149
150
151
152
153
154
155
def get_circuit_limits(self, instrument: Instrument):
    """
    Fetch the circuit limits
    Args:
        instrument: Financial Instrument

    Returns:
        circuit limit value
    """
    quote = self.get_quote(instrument)
    lower_circuit_limit = quote['lower_circuit_limit']
    upper_circuit_limit = quote['upper_circuit_limit']
    return lower_circuit_limit, upper_circuit_limit

get_close_price_last_day(self, instrument)

Fetch the closed price of the day

Parameters:

Name Type Description Default
instrument Instrument

Financial Instrument

required

Returns:

Type Description

closed price value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
274
275
276
277
278
279
280
281
282
283
284
285
def get_close_price_last_day(self, instrument: Instrument):
    """
    Fetch the closed price of the day
    Args:
        instrument: Financial Instrument

    Returns:
        closed price value
    """
    quote = self.get_quote(instrument)
    close_price_day = quote['ohlc']['close']
    return close_price_day

get_funds(self, segment)

Fetch the available funds

Parameters:

Name Type Description Default
segment

segment

required

Returns:

Type Description

available funds value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
315
316
317
318
319
320
321
322
323
324
325
326
def get_funds(self, segment):
    """
    Fetch the available funds
    Args:
        segment: segment

    Returns:
        available funds value
    """
    list_permissible_segments = ['equity', 'commodity']
    assert (segment in list_permissible_segments), f'segment should be one of {list_permissible_segments}'
    return self.api.margins(segment=segment)['net']

get_high_price_day(self, instrument)

Fetch the high price of the day

Parameters:

Name Type Description Default
instrument Instrument

Financial Instrument

required

Returns:

Type Description

high price value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
248
249
250
251
252
253
254
255
256
257
258
259
def get_high_price_day(self, instrument: Instrument):
    """
    Fetch the high price of the day
    Args:
        instrument: Financial Instrument

    Returns:
        high price value
    """
    quote = self.get_quote(instrument)
    high_price_day = quote['ohlc']['high']
    return high_price_day

get_historical_data(self, instrument, candle_interval, start_date, end_date)

Fetch the historical data

Parameters:

Name Type Description Default
instrument

Financial Instrument

required
candle_interval

candle interval

required
start_date

date from which to fetch the historical data

required
end_date

date till which to fetch the historical data

required

Returns:

Type Description

historical data

Source code in pyalgotrading/broker/broker_connection_zerodha.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
def get_historical_data(self, instrument, candle_interval, start_date, end_date):
    """
    Fetch the historical data
    Args:
        instrument: Financial Instrument
        candle_interval: candle interval
        start_date: date from which to fetch the historical data
        end_date: date till which to fetch the historical data

    Returns:
        historical data
    """
    return pd.DataFrame(self.api.historical_data(instrument.broker_token, from_date=start_date, to_date=end_date, interval=candle_interval)) \
        .reindex(['date', 'open', 'high', 'low', 'close', 'volume'], axis="columns").rename(columns={'date': 'timestamp'})

get_instrument(self, segment, tradingsymbol)

Fetch an instrument

Parameters:

Name Type Description Default
segment str

Segment to which instrument belongs to

required
tradingsymbol str

Trading symbol of the instrument

required

Returns:

Type Description
Instrument

Instrument object

Source code in pyalgotrading/broker/broker_connection_zerodha.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def get_instrument(self, segment: str, tradingsymbol: str) -> Instrument:
    """
    Fetch an instrument
    Args:
        segment: Segment to which instrument belongs to
        tradingsymbol: Trading symbol of the instrument

    Returns:
       Instrument object
    """
    if self.all_instruments is None:
        self.all_instruments = self.get_all_instruments()
    try:
        _inst = self.all_instruments[(self.all_instruments.segment == segment) & (self.all_instruments.tradingsymbol == tradingsymbol)].iloc[0]
        instrument = Instrument(segment=_inst['segment'], exchange=_inst['exchange'], tradingsymbol=_inst['tradingsymbol'], broker_token=_inst['instrument_token'], tick_size=_inst['tick_size'], lot_size=_inst['lot_size'], expiry=_inst['expiry'],
                                strike_price=_inst['strike'])
        return instrument
    except IndexError:
        print('ERROR: Instrument not found. Either it is expired and hence not available, or you have misspelled the "segment" and "tradingsymbol" parameters.')

get_low_price_day(self, instrument)

Fetch the low price of the day

Parameters:

Name Type Description Default
instrument Instrument

Financial Instrument

required

Returns:

Type Description

low price value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
261
262
263
264
265
266
267
268
269
270
271
272
def get_low_price_day(self, instrument: Instrument):
    """
    Fetch the low price of the day
    Args:
        instrument: Financial Instrument

    Returns:
        low price value
    """
    quote = self.get_quote(instrument)
    low_price_day = quote['ohlc']['low']
    return low_price_day

get_ltp(self, instrument)

Fetch the Last Trading Price (LTP)

Parameters:

Name Type Description Default
instrument Instrument

Financial Instrument

required

Returns:

Type Description

ltp value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
157
158
159
160
161
162
163
164
165
166
167
168
def get_ltp(self, instrument: Instrument):
    """
    Fetch the Last Trading Price (LTP)
    Args:
        instrument: Financial Instrument

    Returns:
        ltp value
    """
    quote = self.get_quote(instrument)
    ltp = quote['last_price']
    return ltp

get_ltq(self, instrument)

Fetch the Last Trading Quantity (LTQ)

Parameters:

Name Type Description Default
instrument

Financial Instrument

required

Returns:

Type Description

ltq value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
183
184
185
186
187
188
189
190
191
192
193
194
def get_ltq(self, instrument):
    """
    Fetch the Last Trading Quantity (LTQ)
    Args:
        instrument: Financial Instrument

    Returns:
        ltq value
    """
    quote = self.get_quote(instrument)
    ltq = quote['last_quantity']
    return ltq

get_ltt(self, instrument)

Fetch the Last Trading Time (LTT)

Parameters:

Name Type Description Default
instrument

Financial Instrument

required

Returns:

Type Description

ltt value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
170
171
172
173
174
175
176
177
178
179
180
181
def get_ltt(self, instrument):
    """
    Fetch the Last Trading Time (LTT)
    Args:
        instrument: Financial Instrument

    Returns:
        ltt value
    """
    quote = self.get_quote(instrument)
    ltt = quote['last_trade_time']
    return ltt

get_margins(self, segment)

Fetch the margins

Parameters:

Name Type Description Default
segment

segment

required

Returns:

Type Description

margin value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
302
303
304
305
306
307
308
309
310
311
312
313
def get_margins(self, segment):
    """
    Fetch the margins
    Args:
        segment: segment

    Returns:
        margin value
    """
    list_permissible_segments = ['equity', 'commodity']
    assert (segment in list_permissible_segments), f'segment should be one of {list_permissible_segments}'
    return self.api.margins(segment=segment)

get_market_depth(self, instrument)

Fetch the market depth

Parameters:

Name Type Description Default
instrument Instrument

Financial Instrument

required

Returns:

Type Description

market depth value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
129
130
131
132
133
134
135
136
137
138
139
140
141
def get_market_depth(self, instrument: Instrument):
    """
    Fetch the market depth
    Args:
        instrument: Financial Instrument

    Returns:
        market depth value
    """
    quote = self.get_quote(instrument)
    buy_market_depth = pd.DataFrame(quote['depth']['buy'])
    sell_market_depth = pd.DataFrame(quote['depth']['sell'])
    return buy_market_depth, sell_market_depth

get_name(self)

Fetch the name of the broker

Returns:

Type Description

name of the broker

Source code in pyalgotrading/broker/broker_connection_zerodha.py
44
45
46
47
48
49
50
def get_name(self):
    """
    Fetch the name of the broker
    Returns:
        name of the broker
    """
    return 'ZERODHA'

get_open_price_day(self, instrument)

Fetch the open price of the day

Parameters:

Name Type Description Default
instrument Instrument

Financial Instrument

required

Returns:

Type Description

open price value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
235
236
237
238
239
240
241
242
243
244
245
246
def get_open_price_day(self, instrument: Instrument):
    """
    Fetch the open price of the day
    Args:
        instrument: Financial Instrument

    Returns:
        open price value
    """
    quote = self.get_quote(instrument)
    open_price_day = quote['ohlc']['open']
    return open_price_day

get_order_status(self, order_id)

Fetch the status of the order

Parameters:

Name Type Description Default
order_id

order id

required

Returns:

Type Description

the status of the order

Source code in pyalgotrading/broker/broker_connection_zerodha.py
362
363
364
365
366
367
368
369
370
371
def get_order_status(self, order_id):
    """
    Fetch the status of the order
    Args:
        order_id: order id

    Returns:
        the status of the order
    """
    return self.api.order_history(order_id)[-1]['status']

get_profile(self)

Fetch the profile

Returns:

Type Description

profile information

Source code in pyalgotrading/broker/broker_connection_zerodha.py
328
329
330
331
332
333
334
def get_profile(self):
    """
    Fetch the profile
    Returns:
        profile information
    """
    return self.api.profile()

get_quote(self, instrument)

Fetch the quote

Parameters:

Name Type Description Default
instrument Instrument

Financial Instrument

required

Returns:

Type Description

quote value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
116
117
118
119
120
121
122
123
124
125
126
127
def get_quote(self, instrument: Instrument):
    """
    Fetch the quote
    Args:
        instrument: Financial Instrument

    Returns:
        quote value
    """
    _inst = f'{instrument.segment}:{instrument.tradingsymbol}'
    quote = self.api.quote([_inst])[_inst]
    return quote

get_total_pending_buy_quantity(self, instrument)

Fetch the total pending buy quantity for instrument

Parameters:

Name Type Description Default
instrument

Financial Instrument

required

Returns:

Type Description

total quantity value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
196
197
198
199
200
201
202
203
204
205
206
207
def get_total_pending_buy_quantity(self, instrument):
    """
    Fetch the total pending buy quantity for instrument
    Args:
        instrument: Financial Instrument

    Returns:
        total quantity value
    """
    quote = self.get_quote(instrument)
    total_buy_quantity_day = quote['buy_quantity']
    return total_buy_quantity_day

get_total_pending_sell_quantity(self, instrument)

Fetch the total pending sell quantity for instrument

Parameters:

Name Type Description Default
instrument Instrument

Financial Instrument

required

Returns:

Type Description

total quantity value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
209
210
211
212
213
214
215
216
217
218
219
220
def get_total_pending_sell_quantity(self, instrument: Instrument):
    """
    Fetch the total pending sell quantity for instrument
    Args:
        instrument: Financial Instrument

    Returns:
        total quantity value
    """
    quote = self.get_quote(instrument)
    total_sell_quantity_day = quote['sell_quantity']
    return total_sell_quantity_day

get_total_volume_day(self, instrument)

Fetch the total volume for the day

Parameters:

Name Type Description Default
instrument Instrument

Financial Instrument

required

Returns:

Type Description

total volume value

Source code in pyalgotrading/broker/broker_connection_zerodha.py
222
223
224
225
226
227
228
229
230
231
232
233
def get_total_volume_day(self, instrument: Instrument):
    """
    Fetch the total volume for the day
    Args:
        instrument: Financial Instrument

    Returns:
        total volume value
    """
    quote = self.get_quote(instrument)
    total_volume_day = quote['volume']
    return total_volume_day

place_order(self, instrument, order_transaction_type, order_type, order_code, order_variety, quantity, price=None, trigger_price=None, stoploss=None, target=None, trailing_stoploss=None)

Place an order

Parameters:

Name Type Description Default
instrument

Financial Instrument

required
order_transaction_type

buy or sell

required
order_type

regular or bracket

required
order_code

orde code

required
order_variety

market / limit / stoploss market / stoploss limit

required
quantity

quantity

required
price

amount / value

None
trigger_price

trigger price amount / value

None
stoploss

stoploss amount / value

None
target

target amount / value

None
trailing_stoploss

trailing stoploss amount / value

None

Returns:

Type Description

Order status

Source code in pyalgotrading/broker/broker_connection_zerodha.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def place_order(self, instrument, order_transaction_type, order_type, order_code, order_variety, quantity, price=None, trigger_price=None, stoploss=None, target=None, trailing_stoploss=None):
    """
    Place an order
    Args:
        instrument: Financial Instrument
        order_transaction_type: buy or sell
        order_type: regular or bracket
        order_code: orde code
        order_variety: market / limit / stoploss market / stoploss limit
        quantity: quantity
        price: amount / value
        trigger_price: trigger price amount / value
        stoploss: stoploss amount / value
        target: target amount / value
        trailing_stoploss: trailing stoploss amount / value

    Returns:
        Order status
    """
    _variety = BrokerConnectionZerodha.ORDER_TYPE_MAP[order_type]  # what we call as 'Order Type', Zerodha calls it as 'variety'
    _transaction_type = BrokerConnectionZerodha.ORDER_TRANSACTION_TYPE_MAP[order_transaction_type]
    _product = BrokerConnectionZerodha.ORDER_CODE_MAP[order_code]  # what we call as 'Order Code', Zerodha calls it as 'product'
    _order_type = BrokerConnectionZerodha.ORDER_VARIETY_MAP[order_variety]  # What we call as 'Order Variety', Zerodha calls it as 'order_type'
    return self.api.place_order(variety=_variety, exchange=instrument.exchange, tradingsymbol=instrument.tradingsymbol, transaction_type=_transaction_type, quantity=quantity, product=_product, order_type=_order_type, price=price,
                                trigger_price=trigger_price, squareoff=target, stoploss=stoploss, trailing_stoploss=trailing_stoploss)

populate_constants(self)

Map pyalgotrading constants to broker constants :return: None

Source code in pyalgotrading/broker/broker_connection_zerodha.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def populate_constants(self):
    """
    Map pyalgotrading constants to broker constants
    :return: None
    """
    _ = import_with_install(package_import_name='kiteconnect', package_install_name='kiteconnect==3.8.2').KiteConnect

    BrokerConnectionZerodha.ORDER_TRANSACTION_TYPE_MAP = {BrokerOrderTransactionTypeConstants.BUY: _.TRANSACTION_TYPE_BUY,
                                                          BrokerOrderTransactionTypeConstants.SELL: _.TRANSACTION_TYPE_SELL}

    BrokerConnectionZerodha.ORDER_TYPE_MAP = {BrokerOrderTypeConstants.REGULAR: _.VARIETY_REGULAR,
                                              BrokerOrderTypeConstants.BRACKET: _.VARIETY_BO,
                                              BrokerOrderTypeConstants.COVER: _.VARIETY_CO,
                                              BrokerOrderTypeConstants.AMO: _.VARIETY_AMO}

    BrokerConnectionZerodha.ORDER_CODE_MAP = {BrokerOrderCodeConstants.INTRADAY: _.PRODUCT_MIS,
                                              BrokerOrderCodeConstants.DELIVERY: _.PRODUCT_CNC}

    BrokerConnectionZerodha.ORDER_VARIETY_MAP = {BrokerOrderVarietyConstants.MARKET: _.ORDER_TYPE_MARKET,
                                                 BrokerOrderVarietyConstants.LIMIT: _.ORDER_TYPE_LIMIT,
                                                 BrokerOrderVarietyConstants.STOPLOSS_LIMIT: _.ORDER_TYPE_SL,
                                                 BrokerOrderVarietyConstants.STOPLOSS_MARKET: _.ORDER_TYPE_SLM}

set_access_token(self, request_token)

Sets the access token

Parameters:

Name Type Description Default
request_token

the request token

required

Returns:

Type Description

None

Source code in pyalgotrading/broker/broker_connection_zerodha.py
75
76
77
78
79
80
81
82
83
84
85
def set_access_token(self, request_token):
    """
    Sets the access token
    Args:
        request_token: the request token

    Returns:
        None
    """
    data = self.api.generate_session(request_token, api_secret=self.api_secret)
    self.api.set_access_token(data["access_token"])

utils

Module for calculating crossover

crossover(val1_hist, val2_hist, accuracy_decimals=2)

Computes crossover of 2 data series - val1_hist and val2_hist.

Parameters:

Name Type Description Default
val1_hist Union[Tuple, List, pandas.core.series.Series]

Any object which can be converted to a list of data points. (Ex: pandas.Series, tuple, list)

required
val2_hist Union[Tuple, List, pandas.core.series.Series]

Any object which can be converted to a list of data points. (Ex: pandas.Series, tuple, list)

required
accuracy_decimals int

Positive integer, specifying number of decimal places to be looked into until we consider two numbers as equal. Ex: with accuracy_decimals=2, 3.456 and 3.457 are considered equal, but 3.456 and 3.466 are considered unequal.

2

Returns:

Type Description
int
  • 1 if val1_hist(OHLC) cuts val2_hist upwards
  • -1 if val1_hist cuts val2_hist downwards
  • 0 if there is no cut between val1_hist and val2_hist
Source code in pyalgotrading/broker/utils.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def crossover(val1_hist: Union[Tuple, List, pd.Series], val2_hist: Union[Tuple, List, pd.Series], accuracy_decimals: int = 2) -> int:
    """
    Computes crossover of 2 data series - val1_hist and val2_hist.

    Args:
        val1_hist: Any object which can be converted to a list of data points. (Ex: pandas.Series, tuple, list)
        val2_hist: Any object which can be converted to a list of data points. (Ex: pandas.Series, tuple, list)
        accuracy_decimals: Positive integer, specifying number of decimal places to be looked into until we consider two numbers as equal.
                           Ex: with accuracy_decimals=2, 3.456 and 3.457 are considered equal, but 3.456 and 3.466 are considered unequal.

    Returns:
        - `1` if `val1_hist(OHLC)` cuts `val2_hist` upwards
        - `-1` if `val1_hist` cuts `val2_hist` downwards
        - `0` if there is no cut between `val1_hist` and `val2_hist`

    """
    # This is a dummy function with a sole purpose of mimicing the signature of the actual function on the AlgoBulls platform, as described in the documentation.
    pass

Last update:

Comments