# 📦 BrokerPackage

`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.

---

## 🚀 Features

* 🔐 Login & session handling
* 📊 Fetch market quotes (API + local fallback)
* 📈 View orders, positions, and portfolio
* 💰 Check available cash & margin requirements
* 🛒 Place, modify, and cancel orders
* 🔄 Automatic failover (primary → secondary server)
* 🎯 Token-based instrument identification
* ⚡ Tick-size rounding utility for F&O (.05 precision)

---

This script requires the following libraries:

- openpyxl==3.1.2
- pandas==1.5.3
- numpy==1.23.5

## 📦 Installation

```bash
pip install openpyxl==3.1.2 pandas==1.5.3 numpy==1.23.5 
```

---

## 🧑‍💻 Usage

### 1. Initialize

```python
from BrokerPackage import BrokerPackage

broker = BrokerPackage(username="your_username")
```

---

### 2. Login

```python
broker.login()
```

---

### 3. Get Token

```python
token = broker.get_token(name="RELIANCE")
```

---

### 4. Get Quote

```python
quote_df = broker.get_quote(name="RELIANCE")
print(quote_df)
```

---

### 5. Get LTP (Last Traded Price)

```python
ltp = broker.get_ltp(name="RELIANCE")
print(ltp)
```

---

### 6. Place Order

```python
order_id = broker.place_order(
    transaction_type="BUY",
    price_=2500,
    quantity=10,
    name="RELIANCE"
)
print(order_id)
```

---

### 7. Modify Order

```python
broker.modify_order(order_id="12345", price=2550, quantity=10)
```

---

### 8. Cancel Order

```python
broker.cancel_order(order_id="12345")
```

---

### 9. View Orders / Positions / Portfolio

```python
orders = broker.orders()
positions = broker.positions()
portfolio = broker.portfolio()
```

---

### 10. Account Info

```python
cash = broker.get_available_cash()
margin = broker.get_required_margin(
    transaction_type="BUY",
    token=token,
    price_=2500,
    product="MIS"
)
```

---

## 🔄 Failover Mechanism

All API calls:

* Try **Primary URL**
* On failure → fallback to **Secondary URL**

---

## 🌐 API Endpoints Used

| Endpoint               | Description              |
| ---------------------- | ------------------------ |
| `/get_file`            | Fetch user configuration |
| `/login`               | Login using config       |
| `/get_token`           | Get instrument token     |
| `/get_quote`           | Fetch market data        |
| `/place_order`         | Place trade              |
| `/modify_order`        | Modify trade             |
| `/cancel_order`        | Cancel trade             |
| `/orders`              | Get order book           |
| `/positions`           | Get positions            |
| `/portfolio`           | Get holdings             |
| `/get_available_cash`  | Cash balance             |
| `/get_required_margin` | Margin calculation       |

---

## 📊 Local Quote Fallback

Method: `get_quote_api()`

Flow:

1. Try local service (`quotetickcandle-secvice`)
2. If failed → fallback to broker API

---

## 🎯 Tick Size Rounding

Utility method:

```python
broker.round_to(12569.67)
```

* Default precision: **0.05 (F&O tick size)**
* Supports dynamic precision via column or value

---

## ⚠️ Error Handling

* All API responses checked for `"error"`
* Raises `Exception` if any issue occurs
* Network failures auto-switch to secondary server

---

## 🧩 Dependencies

* `pandas`
* `requests`
* `numpy`
* `typing`

---

## 📝 Notes

* Ensure API services are running:

  * `broker-api-service`
  * `quotetickcandle-secvice`
* URLs can be overridden via config file (`get_file` response)

---

## 📌 Example Workflow

```python
broker = BrokerPackage("user1")
broker.login()

token = broker.get_token("NIFTY")
ltp = broker.get_ltp(name="NIFTY")

order_id = broker.place_order(
    transaction_type="BUY",
    price_=ltp,
    quantity=50,
    name="NIFTY"
)
```

---

## 📄 License

This project is intended for internal/private trading system usage.

---