brokerpackage 0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,257 @@
1
+
2
+ import pandas as pd
3
+ import requests
4
+ from typing import Tuple, Union
5
+ import numpy as np
6
+
7
+ class BrokerPackage:
8
+ def __init__(self, username:str) -> None:
9
+ self.default_url = 'http://broker-api-service:7777/'
10
+ self.file = {}
11
+ self.get_file()
12
+
13
+ if 'primary_url' in self.file.keys():
14
+ self.primary_url = self.file['primary_url']
15
+ else: self.primary_url = self.default_url
16
+
17
+ if 'secondary_url' in self.file.keys():
18
+ self.secondary_url = self.file['secondary_url']
19
+ else: self.secondary_url = self.default_url
20
+
21
+ self.quotetickcandle_url = 'http://quotetickcandle-secvice:7777/quotedata'
22
+ self.username = username
23
+
24
+ def get_file(self) -> None:
25
+ data_inp = {'username': self.username}
26
+ res = requests.post(self.default_url + 'get_file', json = data_inp)
27
+ res_json = res.json()
28
+ if res_json['error'] != '': raise Exception(res_json['error'])
29
+ self.file = res_json['file']
30
+
31
+ def login(self) -> None:
32
+ data_inp = {'file': self.file}
33
+ res = requests.post(self.primary_url + 'login', json = data_inp)
34
+ res_json = res.json()
35
+ if res_json['error'] != '': raise Exception(res_json['error'])
36
+
37
+ def get_token(self, name:str, exchange:str = 'NSE', expiry:str = '', strike:str = '', optionType:str = '') -> str:
38
+ data_inp = {'username': self.username,
39
+ 'name': name,
40
+ 'exchange': exchange,
41
+ 'expiry': expiry,
42
+ 'strike': strike,
43
+ 'optionType': optionType
44
+ }
45
+ try:
46
+ res = requests.post(self.primary_url + 'get_token', json = data_inp)
47
+ except:
48
+ res = requests.post(self.secondary_url + 'get_token', json = data_inp)
49
+ res_json = res.json()
50
+ if res_json['error'] != '': raise Exception(res_json['error'])
51
+ return res_json['token']
52
+
53
+ def get_name(self, token:str) -> Tuple[str, str, str, str, str]:
54
+ data_inp = {'username': self.username,
55
+ 'token': token
56
+ }
57
+ try:
58
+ res = requests.post(self.primary_url + 'get_name', json = data_inp)
59
+ except:
60
+ res = requests.post(self.secondary_url + 'get_name', json = data_inp)
61
+ res_json = res.json()
62
+ if res_json['error'] != '': raise Exception(res_json['error'])
63
+ return res_json['data']['name'], res_json['data']['expiry'], res_json['data']['strike'], res_json['data']['optionType'], res_json['data']['lots']
64
+
65
+ def orders(self) -> pd.DataFrame:
66
+ data_inp = {'username': self.username}
67
+ try:
68
+ res = requests.post(self.primary_url + 'orders', json = data_inp)
69
+ except:
70
+ res = requests.post(self.secondary_url + 'orders', json = data_inp)
71
+ res_json = res.json()
72
+ if res_json['error'] != '': raise Exception(res_json['error'])
73
+ return pd.DataFrame.from_dict(res_json['data'])
74
+
75
+ def order_update_time(self) -> Union[int, str]:
76
+ data_inp = {'username': self.username}
77
+ try:
78
+ res = requests.post(self.primary_url + 'order_update_time', json = data_inp)
79
+ except:
80
+ res = requests.post(self.secondary_url + 'order_update_time', json = data_inp)
81
+ res_json = res.json()
82
+ if res_json['error'] != '': raise Exception(res_json['error'])
83
+ return res_json['order_update_time']
84
+
85
+ def positions(self) -> pd.DataFrame:
86
+ data_inp = {'username': self.username}
87
+ try:
88
+ res = requests.post(self.primary_url + 'positions', json = data_inp)
89
+ except:
90
+ res = requests.post(self.secondary_url + 'positions', json = data_inp)
91
+ res_json = res.json()
92
+ if res_json['error'] != '': raise Exception(res_json['error'])
93
+ return pd.DataFrame.from_dict(res_json['data'])
94
+
95
+ def position_update_time(self) -> Union[int, str]:
96
+ data_inp = {'username': self.username}
97
+ try:
98
+ res = requests.post(self.primary_url + 'position_update_time', json = data_inp)
99
+ except:
100
+ res = requests.post(self.secondary_url + 'position_update_time', json = data_inp)
101
+ res_json = res.json()
102
+ if res_json['error'] != '': raise Exception(res_json['error'])
103
+ return res_json['position_update_time']
104
+
105
+ def portfolio(self) -> pd.DataFrame:
106
+ data_inp = {'username': self.username}
107
+ try:
108
+ res = requests.post(self.primary_url + 'portfolio', json = data_inp)
109
+ except:
110
+ res = requests.post(self.secondary_url + 'portfolio', json = data_inp)
111
+ res_json = res.json()
112
+ if res_json['error'] != '': raise Exception(res_json['error'])
113
+ return pd.DataFrame.from_dict(res_json['data'])
114
+
115
+ def get_available_cash(self) -> float:
116
+ data_inp = {'username': self.username}
117
+ try:
118
+ res = requests.post(self.primary_url + 'get_available_cash', json = data_inp)
119
+ except:
120
+ res = requests.post(self.secondary_url + 'get_available_cash', json = data_inp)
121
+ res_json = res.json()
122
+ if res_json['error'] != '': raise Exception(res_json['error'])
123
+ return res_json['available_cash']
124
+
125
+ def get_required_margin(self, transaction_type:str = '', token:str = '', price_:float = 0, product:str = '') -> float:
126
+ data_inp = {'username': self.username,
127
+ 'transaction_type': transaction_type,
128
+ 'token': token,
129
+ 'price_': price_,
130
+ 'product': product
131
+ }
132
+ try:
133
+ res = requests.post(self.primary_url + 'get_required_margin', json = data_inp)
134
+ except:
135
+ res = requests.post(self.secondary_url + 'get_required_margin', json = data_inp)
136
+ res_json = res.json()
137
+ if res_json['error'] != '': raise Exception(res_json['error'])
138
+ return res_json['required_margin']
139
+
140
+ def get_quote(self, token:str = '', name:str = '', exchange:str = 'NSE', expiry:str = '', strike:str = '', optionType:str = '') -> pd.DataFrame:
141
+ data_inp = {'username': self.username,
142
+ 'token': token,
143
+ 'name': name,
144
+ 'exchange': exchange,
145
+ 'expiry': expiry,
146
+ 'strike': strike,
147
+ 'optionType': optionType
148
+ }
149
+ try:
150
+ res = requests.post(self.primary_url + 'get_quote', json = data_inp)
151
+ except:
152
+ res = requests.post(self.secondary_url + 'get_quote', json = data_inp)
153
+ res_json = res.json()
154
+ if res_json['error'] != '': raise Exception(res_json['error'])
155
+ return pd.DataFrame.from_dict(res_json['data'])
156
+
157
+ def place_order(self, transaction_type:str, price_:float, quantity:int, token:str = '', name:str = '', exchange:str = 'NSE', expiry:str = '', strike:str = '', optionType:str = '', trigger:float = 0, product:str = '') -> str:
158
+ data_inp = {'username': self.username,
159
+ 'transaction_type': transaction_type,
160
+ 'price_': price_,
161
+ 'quantity': quantity,
162
+ 'token': token,
163
+ 'name': name,
164
+ 'exchange': exchange,
165
+ 'expiry': expiry,
166
+ 'strike': strike,
167
+ 'optionType': optionType,
168
+ 'trigger': trigger,
169
+ 'product': product
170
+ }
171
+ try:
172
+ res = requests.post(self.primary_url + 'place_order', json = data_inp)
173
+ except:
174
+ res = requests.post(self.secondary_url + 'place_order', json = data_inp)
175
+ res_json = res.json()
176
+ if res_json['error'] != '': raise Exception(res_json['error'])
177
+ return res_json['orderid']
178
+
179
+ def modify_order(self, order_id:str, price:float, quantity:Union[int, str] = '', trigger:float = 0) -> str:
180
+ data_inp = {'username': self.username,
181
+ 'order_id': order_id,
182
+ 'price': price,
183
+ 'quantity': quantity,
184
+ 'trigger': trigger
185
+ }
186
+ try:
187
+ res = requests.post(self.primary_url + 'modify_order', json = data_inp)
188
+ except:
189
+ res = requests.post(self.secondary_url + 'modify_order', json = data_inp)
190
+ res_json = res.json()
191
+ if res_json['error'] != '': raise Exception(res_json['error'])
192
+ return res_json['orderid']
193
+
194
+ def cancel_order(self, order_id:str) -> str:
195
+ data_inp = {'username': self.username,
196
+ 'order_id': order_id
197
+ }
198
+ try:
199
+ res = requests.post(self.primary_url + 'cancel_order', json = data_inp)
200
+ except:
201
+ res = requests.post(self.secondary_url + 'cancel_order', json = data_inp)
202
+ res_json = res.json()
203
+ if res_json['error'] != '': raise Exception(res_json['error'])
204
+ return res_json['orderid']
205
+
206
+ def get_quote_local(self, name = '', exchange = 'NSE', expiry = '', strike = '', optionType = ''):
207
+ data_inp = {'name': name,
208
+ 'exchange': exchange,
209
+ 'expiry': expiry,
210
+ 'strike': str(strike),
211
+ 'optionType': optionType,
212
+ }
213
+ try:
214
+ res = requests.post(self.quotetickcandle_url, json = data_inp)
215
+ df = pd.json_normalize(res.json())
216
+ if df.ltp.iloc[0] == '': raise Exception("Unable to get quote from quotes api")
217
+ else: return df
218
+ except Exception as e:
219
+ raise Exception("Unable to get quote from quotes api")
220
+
221
+ def get_quote_api(self, name = '', exchange = 'NSE', expiry = '', strike = '', optionType = ''):
222
+ try:
223
+ df = self.get_quote_local(name, exchange, expiry, strike, optionType)
224
+ return df
225
+ except Exception as e:
226
+ return self.get_quote(name=name, exchange=exchange, expiry=expiry, strike=strike, optionType=optionType)
227
+
228
+ def get_ltp(self, name='', exchange='NSE', expiry='', strike='', optionType=''):
229
+ return self.round_to(self.get_quote_api(name=name, exchange=exchange, expiry=expiry, strike=strike, optionType=optionType).iloc[0]['ltp'])
230
+
231
+ def round_to(self, row, num_column = 'open', precision_column_val=.05):
232
+ ''' Round given number to nearsest tick size which is .05 in FNO
233
+ Source: https://stackoverflow.com/questions/4265546/python-round-to-nearest-05
234
+
235
+ Parameters
236
+ ----------
237
+ row: int/float/Series - 12569.67 or Series with columns __ num_column, optional __ precision_column_val
238
+ num_column: str - 'date' Column name to round
239
+ precision_column_val: float, int, str 100, 2.5 or 'roundvalue' tick_size of the item or Column name contaning tick_size
240
+
241
+ '''
242
+ if type(row) in [int, float, np.float64, np.float32, np.float16, np.int8, np.int16, np.int32, np.int64, str]:
243
+ n = row
244
+ else:
245
+ n = row[num_column]
246
+
247
+ if type(precision_column_val)==str:
248
+ if type(row) == int or type(row) == float:
249
+ precision = .05
250
+ else:
251
+ precision = row[precision_column_val]
252
+ else:
253
+ precision = precision_column_val
254
+
255
+ n = float(n)
256
+ correction = 0.5 if n >= 0 else -0.5
257
+ return round(int( n/precision+correction ) * precision, 2)
@@ -0,0 +1,2 @@
1
+ from .BrokerPackage import BrokerPackage
2
+ from .version import __version__
@@ -0,0 +1 @@
1
+ __version__ = '0.1'
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2018 The Python Packaging Authority
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1,253 @@
1
+ Metadata-Version: 2.1
2
+ Name: brokerpackage
3
+ Version: 0.1
4
+ Summary: Package is a Python client library designed to interact with a broker API service. It provides functionalities to manage and execute trading strategies, handle orders, and retrieve market data.
5
+ Home-page: UNKNOWN
6
+ Author: Vadlamani Rampratap Sharma
7
+ Author-email: rampratap.optalpha@gmail.com
8
+ License: MIT
9
+ Platform: UNKNOWN
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.9.7
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+
17
+ # 📦 BrokerPackage
18
+
19
+ `BrokerPackage` is a Python client library designed to interact with a broker API service. It provides a structured interface to perform trading operations such as login, fetching quotes, placing orders, managing positions, and more.
20
+
21
+ ---
22
+
23
+ ## 🚀 Features
24
+
25
+ * 🔐 Login & session handling
26
+ * 📊 Fetch market quotes (API + local fallback)
27
+ * 📈 View orders, positions, and portfolio
28
+ * 💰 Check available cash & margin requirements
29
+ * 🛒 Place, modify, and cancel orders
30
+ * 🔄 Automatic failover (primary → secondary server)
31
+ * 🎯 Token-based instrument identification
32
+ * ⚡ Tick-size rounding utility for F&O (.05 precision)
33
+
34
+ ---
35
+
36
+ This script requires the following libraries:
37
+
38
+ - openpyxl==3.1.2
39
+ - pandas==1.5.3
40
+ - numpy==1.23.5
41
+
42
+ ## 📦 Installation
43
+
44
+ ```bash
45
+ pip install openpyxl==3.1.2 pandas==1.5.3 numpy==1.23.5
46
+ ```
47
+
48
+ ---
49
+
50
+ ## 🧑‍💻 Usage
51
+
52
+ ### 1. Initialize
53
+
54
+ ```python
55
+ from BrokerPackage import BrokerPackage
56
+
57
+ broker = BrokerPackage(username="your_username")
58
+ ```
59
+
60
+ ---
61
+
62
+ ### 2. Login
63
+
64
+ ```python
65
+ broker.login()
66
+ ```
67
+
68
+ ---
69
+
70
+ ### 3. Get Token
71
+
72
+ ```python
73
+ token = broker.get_token(name="RELIANCE")
74
+ ```
75
+
76
+ ---
77
+
78
+ ### 4. Get Quote
79
+
80
+ ```python
81
+ quote_df = broker.get_quote(name="RELIANCE")
82
+ print(quote_df)
83
+ ```
84
+
85
+ ---
86
+
87
+ ### 5. Get LTP (Last Traded Price)
88
+
89
+ ```python
90
+ ltp = broker.get_ltp(name="RELIANCE")
91
+ print(ltp)
92
+ ```
93
+
94
+ ---
95
+
96
+ ### 6. Place Order
97
+
98
+ ```python
99
+ order_id = broker.place_order(
100
+ transaction_type="BUY",
101
+ price_=2500,
102
+ quantity=10,
103
+ name="RELIANCE"
104
+ )
105
+ print(order_id)
106
+ ```
107
+
108
+ ---
109
+
110
+ ### 7. Modify Order
111
+
112
+ ```python
113
+ broker.modify_order(order_id="12345", price=2550, quantity=10)
114
+ ```
115
+
116
+ ---
117
+
118
+ ### 8. Cancel Order
119
+
120
+ ```python
121
+ broker.cancel_order(order_id="12345")
122
+ ```
123
+
124
+ ---
125
+
126
+ ### 9. View Orders / Positions / Portfolio
127
+
128
+ ```python
129
+ orders = broker.orders()
130
+ positions = broker.positions()
131
+ portfolio = broker.portfolio()
132
+ ```
133
+
134
+ ---
135
+
136
+ ### 10. Account Info
137
+
138
+ ```python
139
+ cash = broker.get_available_cash()
140
+ margin = broker.get_required_margin(
141
+ transaction_type="BUY",
142
+ token=token,
143
+ price_=2500,
144
+ product="MIS"
145
+ )
146
+ ```
147
+
148
+ ---
149
+
150
+ ## 🔄 Failover Mechanism
151
+
152
+ All API calls:
153
+
154
+ * Try **Primary URL**
155
+ * On failure → fallback to **Secondary URL**
156
+
157
+ ---
158
+
159
+ ## 🌐 API Endpoints Used
160
+
161
+ | Endpoint | Description |
162
+ | ---------------------- | ------------------------ |
163
+ | `/get_file` | Fetch user configuration |
164
+ | `/login` | Login using config |
165
+ | `/get_token` | Get instrument token |
166
+ | `/get_quote` | Fetch market data |
167
+ | `/place_order` | Place trade |
168
+ | `/modify_order` | Modify trade |
169
+ | `/cancel_order` | Cancel trade |
170
+ | `/orders` | Get order book |
171
+ | `/positions` | Get positions |
172
+ | `/portfolio` | Get holdings |
173
+ | `/get_available_cash` | Cash balance |
174
+ | `/get_required_margin` | Margin calculation |
175
+
176
+ ---
177
+
178
+ ## 📊 Local Quote Fallback
179
+
180
+ Method: `get_quote_api()`
181
+
182
+ Flow:
183
+
184
+ 1. Try local service (`quotetickcandle-secvice`)
185
+ 2. If failed → fallback to broker API
186
+
187
+ ---
188
+
189
+ ## 🎯 Tick Size Rounding
190
+
191
+ Utility method:
192
+
193
+ ```python
194
+ broker.round_to(12569.67)
195
+ ```
196
+
197
+ * Default precision: **0.05 (F&O tick size)**
198
+ * Supports dynamic precision via column or value
199
+
200
+ ---
201
+
202
+ ## ⚠️ Error Handling
203
+
204
+ * All API responses checked for `"error"`
205
+ * Raises `Exception` if any issue occurs
206
+ * Network failures auto-switch to secondary server
207
+
208
+ ---
209
+
210
+ ## 🧩 Dependencies
211
+
212
+ * `pandas`
213
+ * `requests`
214
+ * `numpy`
215
+ * `typing`
216
+
217
+ ---
218
+
219
+ ## 📝 Notes
220
+
221
+ * Ensure API services are running:
222
+
223
+ * `broker-api-service`
224
+ * `quotetickcandle-secvice`
225
+ * URLs can be overridden via config file (`get_file` response)
226
+
227
+ ---
228
+
229
+ ## 📌 Example Workflow
230
+
231
+ ```python
232
+ broker = BrokerPackage("user1")
233
+ broker.login()
234
+
235
+ token = broker.get_token("NIFTY")
236
+ ltp = broker.get_ltp(name="NIFTY")
237
+
238
+ order_id = broker.place_order(
239
+ transaction_type="BUY",
240
+ price_=ltp,
241
+ quantity=50,
242
+ name="NIFTY"
243
+ )
244
+ ```
245
+
246
+ ---
247
+
248
+ ## 📄 License
249
+
250
+ This project is intended for internal/private trading system usage.
251
+
252
+ ---
253
+
@@ -0,0 +1,236 @@
1
+ # 📦 BrokerPackage
2
+
3
+ `BrokerPackage` is a Python client library designed to interact with a broker API service. It provides a structured interface to perform trading operations such as login, fetching quotes, placing orders, managing positions, and more.
4
+
5
+ ---
6
+
7
+ ## 🚀 Features
8
+
9
+ * 🔐 Login & session handling
10
+ * 📊 Fetch market quotes (API + local fallback)
11
+ * 📈 View orders, positions, and portfolio
12
+ * 💰 Check available cash & margin requirements
13
+ * 🛒 Place, modify, and cancel orders
14
+ * 🔄 Automatic failover (primary → secondary server)
15
+ * 🎯 Token-based instrument identification
16
+ * ⚡ Tick-size rounding utility for F&O (.05 precision)
17
+
18
+ ---
19
+
20
+ This script requires the following libraries:
21
+
22
+ - openpyxl==3.1.2
23
+ - pandas==1.5.3
24
+ - numpy==1.23.5
25
+
26
+ ## 📦 Installation
27
+
28
+ ```bash
29
+ pip install openpyxl==3.1.2 pandas==1.5.3 numpy==1.23.5
30
+ ```
31
+
32
+ ---
33
+
34
+ ## 🧑‍💻 Usage
35
+
36
+ ### 1. Initialize
37
+
38
+ ```python
39
+ from BrokerPackage import BrokerPackage
40
+
41
+ broker = BrokerPackage(username="your_username")
42
+ ```
43
+
44
+ ---
45
+
46
+ ### 2. Login
47
+
48
+ ```python
49
+ broker.login()
50
+ ```
51
+
52
+ ---
53
+
54
+ ### 3. Get Token
55
+
56
+ ```python
57
+ token = broker.get_token(name="RELIANCE")
58
+ ```
59
+
60
+ ---
61
+
62
+ ### 4. Get Quote
63
+
64
+ ```python
65
+ quote_df = broker.get_quote(name="RELIANCE")
66
+ print(quote_df)
67
+ ```
68
+
69
+ ---
70
+
71
+ ### 5. Get LTP (Last Traded Price)
72
+
73
+ ```python
74
+ ltp = broker.get_ltp(name="RELIANCE")
75
+ print(ltp)
76
+ ```
77
+
78
+ ---
79
+
80
+ ### 6. Place Order
81
+
82
+ ```python
83
+ order_id = broker.place_order(
84
+ transaction_type="BUY",
85
+ price_=2500,
86
+ quantity=10,
87
+ name="RELIANCE"
88
+ )
89
+ print(order_id)
90
+ ```
91
+
92
+ ---
93
+
94
+ ### 7. Modify Order
95
+
96
+ ```python
97
+ broker.modify_order(order_id="12345", price=2550, quantity=10)
98
+ ```
99
+
100
+ ---
101
+
102
+ ### 8. Cancel Order
103
+
104
+ ```python
105
+ broker.cancel_order(order_id="12345")
106
+ ```
107
+
108
+ ---
109
+
110
+ ### 9. View Orders / Positions / Portfolio
111
+
112
+ ```python
113
+ orders = broker.orders()
114
+ positions = broker.positions()
115
+ portfolio = broker.portfolio()
116
+ ```
117
+
118
+ ---
119
+
120
+ ### 10. Account Info
121
+
122
+ ```python
123
+ cash = broker.get_available_cash()
124
+ margin = broker.get_required_margin(
125
+ transaction_type="BUY",
126
+ token=token,
127
+ price_=2500,
128
+ product="MIS"
129
+ )
130
+ ```
131
+
132
+ ---
133
+
134
+ ## 🔄 Failover Mechanism
135
+
136
+ All API calls:
137
+
138
+ * Try **Primary URL**
139
+ * On failure → fallback to **Secondary URL**
140
+
141
+ ---
142
+
143
+ ## 🌐 API Endpoints Used
144
+
145
+ | Endpoint | Description |
146
+ | ---------------------- | ------------------------ |
147
+ | `/get_file` | Fetch user configuration |
148
+ | `/login` | Login using config |
149
+ | `/get_token` | Get instrument token |
150
+ | `/get_quote` | Fetch market data |
151
+ | `/place_order` | Place trade |
152
+ | `/modify_order` | Modify trade |
153
+ | `/cancel_order` | Cancel trade |
154
+ | `/orders` | Get order book |
155
+ | `/positions` | Get positions |
156
+ | `/portfolio` | Get holdings |
157
+ | `/get_available_cash` | Cash balance |
158
+ | `/get_required_margin` | Margin calculation |
159
+
160
+ ---
161
+
162
+ ## 📊 Local Quote Fallback
163
+
164
+ Method: `get_quote_api()`
165
+
166
+ Flow:
167
+
168
+ 1. Try local service (`quotetickcandle-secvice`)
169
+ 2. If failed → fallback to broker API
170
+
171
+ ---
172
+
173
+ ## 🎯 Tick Size Rounding
174
+
175
+ Utility method:
176
+
177
+ ```python
178
+ broker.round_to(12569.67)
179
+ ```
180
+
181
+ * Default precision: **0.05 (F&O tick size)**
182
+ * Supports dynamic precision via column or value
183
+
184
+ ---
185
+
186
+ ## ⚠️ Error Handling
187
+
188
+ * All API responses checked for `"error"`
189
+ * Raises `Exception` if any issue occurs
190
+ * Network failures auto-switch to secondary server
191
+
192
+ ---
193
+
194
+ ## 🧩 Dependencies
195
+
196
+ * `pandas`
197
+ * `requests`
198
+ * `numpy`
199
+ * `typing`
200
+
201
+ ---
202
+
203
+ ## 📝 Notes
204
+
205
+ * Ensure API services are running:
206
+
207
+ * `broker-api-service`
208
+ * `quotetickcandle-secvice`
209
+ * URLs can be overridden via config file (`get_file` response)
210
+
211
+ ---
212
+
213
+ ## 📌 Example Workflow
214
+
215
+ ```python
216
+ broker = BrokerPackage("user1")
217
+ broker.login()
218
+
219
+ token = broker.get_token("NIFTY")
220
+ ltp = broker.get_ltp(name="NIFTY")
221
+
222
+ order_id = broker.place_order(
223
+ transaction_type="BUY",
224
+ price_=ltp,
225
+ quantity=50,
226
+ name="NIFTY"
227
+ )
228
+ ```
229
+
230
+ ---
231
+
232
+ ## 📄 License
233
+
234
+ This project is intended for internal/private trading system usage.
235
+
236
+ ---
@@ -0,0 +1,253 @@
1
+ Metadata-Version: 2.1
2
+ Name: brokerpackage
3
+ Version: 0.1
4
+ Summary: Package is a Python client library designed to interact with a broker API service. It provides functionalities to manage and execute trading strategies, handle orders, and retrieve market data.
5
+ Home-page: UNKNOWN
6
+ Author: Vadlamani Rampratap Sharma
7
+ Author-email: rampratap.optalpha@gmail.com
8
+ License: MIT
9
+ Platform: UNKNOWN
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.9.7
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+
17
+ # 📦 BrokerPackage
18
+
19
+ `BrokerPackage` is a Python client library designed to interact with a broker API service. It provides a structured interface to perform trading operations such as login, fetching quotes, placing orders, managing positions, and more.
20
+
21
+ ---
22
+
23
+ ## 🚀 Features
24
+
25
+ * 🔐 Login & session handling
26
+ * 📊 Fetch market quotes (API + local fallback)
27
+ * 📈 View orders, positions, and portfolio
28
+ * 💰 Check available cash & margin requirements
29
+ * 🛒 Place, modify, and cancel orders
30
+ * 🔄 Automatic failover (primary → secondary server)
31
+ * 🎯 Token-based instrument identification
32
+ * ⚡ Tick-size rounding utility for F&O (.05 precision)
33
+
34
+ ---
35
+
36
+ This script requires the following libraries:
37
+
38
+ - openpyxl==3.1.2
39
+ - pandas==1.5.3
40
+ - numpy==1.23.5
41
+
42
+ ## 📦 Installation
43
+
44
+ ```bash
45
+ pip install openpyxl==3.1.2 pandas==1.5.3 numpy==1.23.5
46
+ ```
47
+
48
+ ---
49
+
50
+ ## 🧑‍💻 Usage
51
+
52
+ ### 1. Initialize
53
+
54
+ ```python
55
+ from BrokerPackage import BrokerPackage
56
+
57
+ broker = BrokerPackage(username="your_username")
58
+ ```
59
+
60
+ ---
61
+
62
+ ### 2. Login
63
+
64
+ ```python
65
+ broker.login()
66
+ ```
67
+
68
+ ---
69
+
70
+ ### 3. Get Token
71
+
72
+ ```python
73
+ token = broker.get_token(name="RELIANCE")
74
+ ```
75
+
76
+ ---
77
+
78
+ ### 4. Get Quote
79
+
80
+ ```python
81
+ quote_df = broker.get_quote(name="RELIANCE")
82
+ print(quote_df)
83
+ ```
84
+
85
+ ---
86
+
87
+ ### 5. Get LTP (Last Traded Price)
88
+
89
+ ```python
90
+ ltp = broker.get_ltp(name="RELIANCE")
91
+ print(ltp)
92
+ ```
93
+
94
+ ---
95
+
96
+ ### 6. Place Order
97
+
98
+ ```python
99
+ order_id = broker.place_order(
100
+ transaction_type="BUY",
101
+ price_=2500,
102
+ quantity=10,
103
+ name="RELIANCE"
104
+ )
105
+ print(order_id)
106
+ ```
107
+
108
+ ---
109
+
110
+ ### 7. Modify Order
111
+
112
+ ```python
113
+ broker.modify_order(order_id="12345", price=2550, quantity=10)
114
+ ```
115
+
116
+ ---
117
+
118
+ ### 8. Cancel Order
119
+
120
+ ```python
121
+ broker.cancel_order(order_id="12345")
122
+ ```
123
+
124
+ ---
125
+
126
+ ### 9. View Orders / Positions / Portfolio
127
+
128
+ ```python
129
+ orders = broker.orders()
130
+ positions = broker.positions()
131
+ portfolio = broker.portfolio()
132
+ ```
133
+
134
+ ---
135
+
136
+ ### 10. Account Info
137
+
138
+ ```python
139
+ cash = broker.get_available_cash()
140
+ margin = broker.get_required_margin(
141
+ transaction_type="BUY",
142
+ token=token,
143
+ price_=2500,
144
+ product="MIS"
145
+ )
146
+ ```
147
+
148
+ ---
149
+
150
+ ## 🔄 Failover Mechanism
151
+
152
+ All API calls:
153
+
154
+ * Try **Primary URL**
155
+ * On failure → fallback to **Secondary URL**
156
+
157
+ ---
158
+
159
+ ## 🌐 API Endpoints Used
160
+
161
+ | Endpoint | Description |
162
+ | ---------------------- | ------------------------ |
163
+ | `/get_file` | Fetch user configuration |
164
+ | `/login` | Login using config |
165
+ | `/get_token` | Get instrument token |
166
+ | `/get_quote` | Fetch market data |
167
+ | `/place_order` | Place trade |
168
+ | `/modify_order` | Modify trade |
169
+ | `/cancel_order` | Cancel trade |
170
+ | `/orders` | Get order book |
171
+ | `/positions` | Get positions |
172
+ | `/portfolio` | Get holdings |
173
+ | `/get_available_cash` | Cash balance |
174
+ | `/get_required_margin` | Margin calculation |
175
+
176
+ ---
177
+
178
+ ## 📊 Local Quote Fallback
179
+
180
+ Method: `get_quote_api()`
181
+
182
+ Flow:
183
+
184
+ 1. Try local service (`quotetickcandle-secvice`)
185
+ 2. If failed → fallback to broker API
186
+
187
+ ---
188
+
189
+ ## 🎯 Tick Size Rounding
190
+
191
+ Utility method:
192
+
193
+ ```python
194
+ broker.round_to(12569.67)
195
+ ```
196
+
197
+ * Default precision: **0.05 (F&O tick size)**
198
+ * Supports dynamic precision via column or value
199
+
200
+ ---
201
+
202
+ ## ⚠️ Error Handling
203
+
204
+ * All API responses checked for `"error"`
205
+ * Raises `Exception` if any issue occurs
206
+ * Network failures auto-switch to secondary server
207
+
208
+ ---
209
+
210
+ ## 🧩 Dependencies
211
+
212
+ * `pandas`
213
+ * `requests`
214
+ * `numpy`
215
+ * `typing`
216
+
217
+ ---
218
+
219
+ ## 📝 Notes
220
+
221
+ * Ensure API services are running:
222
+
223
+ * `broker-api-service`
224
+ * `quotetickcandle-secvice`
225
+ * URLs can be overridden via config file (`get_file` response)
226
+
227
+ ---
228
+
229
+ ## 📌 Example Workflow
230
+
231
+ ```python
232
+ broker = BrokerPackage("user1")
233
+ broker.login()
234
+
235
+ token = broker.get_token("NIFTY")
236
+ ltp = broker.get_ltp(name="NIFTY")
237
+
238
+ order_id = broker.place_order(
239
+ transaction_type="BUY",
240
+ price_=ltp,
241
+ quantity=50,
242
+ name="NIFTY"
243
+ )
244
+ ```
245
+
246
+ ---
247
+
248
+ ## 📄 License
249
+
250
+ This project is intended for internal/private trading system usage.
251
+
252
+ ---
253
+
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ BrokerPackage/BrokerPackage.py
5
+ BrokerPackage/__init__.py
6
+ BrokerPackage/version.py
7
+ brokerpackage.egg-info/PKG-INFO
8
+ brokerpackage.egg-info/SOURCES.txt
9
+ brokerpackage.egg-info/dependency_links.txt
10
+ brokerpackage.egg-info/requires.txt
11
+ brokerpackage.egg-info/top_level.txt
@@ -0,0 +1,3 @@
1
+ openpyxl==3.1.2
2
+ pandas==1.5.3
3
+ numpy==1.23.5
@@ -0,0 +1 @@
1
+ BrokerPackage
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,28 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ with open("README.md", "r", encoding="utf-8") as fh:
4
+ long_description = fh.read()
5
+
6
+ setup(
7
+ name='brokerpackage',
8
+ version='0.1',
9
+ description='Package is a Python client library designed to interact with a broker API service. It provides functionalities to manage and execute trading strategies, handle orders, and retrieve market data.',
10
+ author='Vadlamani Rampratap Sharma',
11
+ author_email='rampratap.optalpha@gmail.com',
12
+ packages=find_packages(),
13
+ install_requires=[
14
+ 'openpyxl==3.1.2',
15
+ 'pandas==1.5.3',
16
+ 'numpy==1.23.5'
17
+ ],
18
+ long_description=long_description,
19
+ long_description_content_type='text/markdown',
20
+ license="MIT",
21
+ classifiers=[
22
+ 'Programming Language :: Python :: 3',
23
+ 'License :: OSI Approved :: MIT License',
24
+ 'Operating System :: OS Independent',
25
+ ],
26
+ python_requires='>=3.9.7',
27
+ include_package_data=True
28
+ )