# Miner Setup Guide

This guide walks you step-by-step through everything required to run a Sportstensor miner and connect it to the Almanac dApp for scoring, weighting, and payouts.

Before diving into this guide, we recommend building a strong foundation with the [Bittensor documentation](https://docs.bittensor.com/). A solid foundation on Bittensor will make this guide extremely easy to follow.

### 1. Setting Up Your Bittensor Wallet

To participate in the Bittensor network, you need two types of wallets: **Coldkey** and **Hotkey**.

#### 1.1 Coldkey vs. Hotkey

* **Coldkey**: This is a secure, offline wallet used to hold TAO tokens and make important administrative decisions. Think of it as your "savings account."
* **Hotkey**: A wallet used for day-to-day operations like mining. This is more like your "checking account," used for frequent transactions but not for storing large amounts of TAO.

#### 1.2 Setting Up the Wallets

**Prerequisites**

1. **Install Bittensor SDK and Command Line Interface**: First, you need to install the Bittensor software development kit (SDK). This can be done via Python’s package manager.

   ```bash
   pip install bittensor bittensor-cli
   ```
2. **Open Terminal or Command Line Interface**: All wallet creation commands will be executed here.

**Creating a Coldkey**

During this process you will be prompted to name the coldkey and hotkey. This is important for later on where you will use those same names when registering the keys on the subnet and when you'll be starting your miner.

1. Run the following command in the terminal:

   ```bash
   btcli wallet new-coldkey
   ```
2. This command generates a coldkey wallet and provides you with a recovery phrase or private key. **Store this information securely**, as it cannot be recovered if lost.

**Creating a Hotkey**

1. In the same way, create a hotkey wallet with the following command:

   ```bash
   bbtcli wallet new-hotkey
   ```
2. Your hotkey wallet will be stored on your system and used for mining operations.

***

### 2. Funding Your Wallet

Mining on Bittensor requires you to have a funded wallet. TAO tokens are necessary for paying transaction fees, registering as a miner, and staking within the network.

#### 2.1 How to Acquire TAO Tokens

1. **Exchanges**: TAO tokens can be purchased from exchanges that list them. Check [Coinranking ](https://coinranking.com/coin/pgv7xSFi6+bittensor-tao/exchanges)for a list of supported exchanges.
2. **Transfers**: Another option is transfers. Existing token holders can transfer TAO to your wallet.

#### 2.2 Funding Process

Once you have TAO, transfer it to your **coldkey** wallet. This wallet will be used for administrative transactions and initial registration fees.

To transfer TAO tokens to your coldkey, use the following command and retrieve the destination wallet's address:

```bash
btcli w overview
```

You can now transfer TAO tokens from any wallet to your newly set up coldkey wallet.

***

### 3. Registering as a Miner on Subnet 41 (Sportstensor)

#### 3.1 Prerequisites for Registration

1. **A Funded Coldkey**: Ensure your coldkey wallet has enough TAO to cover registration costs.
2. You can check the Registration Cost here: [SN41 taostats page](https://taostats.io/subnets/41/metagraph).

#### 3.2 Step-by-Step Registration

To start mining on subnet 41, you’ll need to register with the Bittensor network, as follows:

1. **Initiate the Registration Process**: Open your terminal and run:

   ```bash
   btcli s register --netuid 41 --wallet-name coldkey --wallet-hotkey hotkey
   ```
2. **Confirmation**: The network will guide you through the confirmation process, and some TAO will be deducted from your coldkey wallet as a registration fee. Once confirmed, you’re officially a miner on Sportstensor.

{% hint style="warning" %}
The Registration Cost is effectively burnt once you have successfully registered.
{% endhint %}

***

### 4. Link Your Miner to the Almanac dApp

This is **new** and required for:

* identity
* scoring
* reward allocation
* dashboard visibility

***

### 4.1 Go to the dApp

If you've already signed up on Almanac, head to <https://almanac.market> and open the **Profile page**. If you haven't yet, check [how-to-signup-on-almanac](https://docs.sportstensor.com/mining-comprehensive-guide/how-to-signup-on-almanac "mention") first.

***

### 4.2 Connect Your Bittensor Wallet

Once you’ve registered your miner on subnet 41, you need to link that Bittensor identity to your Almanac account.

1. Go to Almanac.
2. Open **Account → Bittensor Integration.**
3. Paste your **Bittensor hotkey address** into the **Bittensor Address** field.
4. Click **Save / Connect.**

The dApp will store this mapping:

> Almanac user ↔ Bittensor hotkey ↔ Miner on subnet 41

The dApp will:

* verify your miner registration
* match your miner to your Polymarket trading profile
* allow the dashboard to display scoring & payouts
* handle your Alpha token rewards

> Miners who do **not** link their Bittensor wallet to the dApp **will not appear in dashboards** and **cannot receive Alpha payouts**.

***

### 5. Setting Up and Running Your Miner

Once registered, it’s time to set up and start mining.

#### 5.1 Configuration

* **Stable Internet Connection**: A reliable internet connection is essential for uninterrupted mining.
* **Network Port Configuration**: Ensure the necessary firewall permissions and open ports to enable the miner to communicate with the network.

1. To start, clone the repository and `cd` to it:

```
git clone https://github.com/sportstensor/sn41/
cd sn41
```

2. Next, install the `Sportstensor` package: `pip install -e .`

#### 5.2 Create `api_trading.env`

In the same folder, create a file called **`api_trading.env`** with your EOA + Polymarket credentials.

Fields:

```env
# Your EOA that trades on Polymarket
EOA_WALLET_ADDRESS=0xYourWallet
EOA_WALLET_PK=your_private_key_without_spaces

# Address of the proxy / funder used by Almanac infra (given by team or in docs)
EOA_PROXY_FUNDER=0xProxyFunderWallet

# Polymarket CLOB API credentials
POLYMARKET_API_KEY=...
POLYMARKET_API_SECRET=...
POLYMARKET_API_PASSPHRASE=...
```

> ⚠️ **Never commit this file to git.**\
> Treat it as a secret — it contains your private key.

***

### 6. How Miners Place Trades Programmatically

Your **strategy / miner** is now  “a brain that calls `place_order` on good opportunities”.

The flow implemented in `api_trading.py` is:

1. **Create an Almanac trading session** (binds your EOA + Polymarket keys to a session ID)
2. **Search markets**, pick one
3. **Place orders** via \~`/v1/trading/orders` with session headers

All of this is already wrapped for you.

#### 6.1 Create a trading session

`initiate_trading_session()` signs a message with your EOA private key and sends it to:

> `POST /v1/trading/sessions` on `https://almanac.market/api`

It returns something like:

```json
{
  "success": true,
  "data": {
    "sessionId": "abcd1234",
    "walletAddress": "0xYourWallet",
    "proxyWallet": "0xProxyFunder",
    "expiresAt": "2025-11-17T15:10:50.983Z"
  },
  "timestamp": "2025-11-16T15:10:50.983Z"
}
```

The script stores this in `CURRENT_SESSION` and automatically sets the required headers:

* `x-session-id`
* `x-wallet-address`

You can either:

* run the interactive flow:

```bash
python api_trading.py
# choose "1) Start Trading" → this will auto-create a session if needed
```

or, from your own Python strategy:

```python
from api_trading import initiate_trading_session, CURRENT_SESSION

session = initiate_trading_session()
print(session)
```

#### 6.2 Placing an order (programmatic)

The low-level function you care about is:

```python
from api_trading import place_order
```

Signature (simplified):

```python
place_order(
    market_id: str,
    side_upper: str,     # "BUY" or "SELL"
    size: float,         # quantity
    price: float,        # 0.01–0.99
    order_type: str = "GTC",
    chosen_outcome_name: str | None = None,
    chosen_token_id: str | None = None,
)
```

Example:

```python
from api_trading import initiate_trading_session, place_order

# 1) Create or refresh trading session
session = initiate_trading_session()
if not session:
    raise RuntimeError("Could not create trading session")

# 2) Use your own model / logic to choose a market + side + size + price
market_id = "bitcoin-up-or-down-november-12-2am-et"
side = "BUY"      # "BUY" or "SELL"
size = 20.0       # number of shares
price = 0.35      # 35 cents = 35% implied prob

# 3) Submit the order
place_order(
    market_id=market_id,
    side_upper=side,
    size=size,
    price=price,
    order_type="GTC",
    chosen_outcome_name="DOWN",   # optional, for logging
    chosen_token_id="41557..."    # Polymarket tokenId, if you have it
)
```

Internally, `place_order` will:

* optionally build an **EIP-712 signed order** for Polymarket’s CTF exchange (using `EIP712_DOMAIN_CONTRACT`)
* enforce a **$5 minimum notional** and a **1% platform fee display** using `VOLUME_FEE` from `constants.py`
* POST the order to the Almanac API, which routes it to Polymarket’s CLOB

#### 6.3 Using the interactive mode (for manual miners / debugging)

If you’re not ready to fully automate:

```bash
python api_trading.py
```

Then:

1. Choose **“1) Start Trading”**
2. The script:
   * creates a trading session if needed
   * lets you **search markets**
   * lets you choose an outcome
   * walks you through side/size/price/order type
   * calls `place_order()` for you and prints a full order summary with fee and total

This is ideal for:

* sanity checking credentials
* understanding how your orders look
* testing connectivity to Almanac + Polymarket

#### 6.4 How this ties back to mining

As a **Sportstensor miner**, your job is now:

1. Run a **strategy process** that:
   * monitors markets (via Polymarket / Almanac APIs)
   * computes edges / probabilities
   * calls `place_order(...)` whenever your model sees value
2. Ensure:
   * your **Bittensor hotkey is linked** in the dApp
   * your **miner is registered** on subnet 41
   * your **EOA + Polymarket API keys** are configured in `api_trading.env`
3. Once trades settle:
   * the Almanac backend logs your **volume, PnL, correctness**
   * the **scoring mechanism** converts this into **qualified volume + ROI**
   * the **incentive mechanism** turns that into **Alpha token emissions** to your miner

***

### **7. GET /api/markets** — Active Markets Endpoint

This endpoint returns **all active, open, unexpired markets** that can be traded right now.

#### Hardcoded filters (already applied server-side)

You **do not** need to add filters manually.\
The service automatically returns only:

* `active: true`
* `closed: false`
* `archived: false`
* `endDateWithinMonths: 3`

Meaning:

* only markets currently trading
* no invalid, resolved, or hidden markets
* nothing expiring >3 months away (keeps list manageable)

***

### Request Parameters

| Query Param | Default | Max | Description                          |
| ----------- | ------- | --- | ------------------------------------ |
| `limit`     | 20      | 100 | Number of markets to return per page |
| `offset`    | 0       | —   | Pagination offset                    |

***

### Response Format

```json
{
  "success": true,
  "data": [...markets...],
  "count": 20,
  "pagination": {
    "limit": 20,
    "offset": 0,
    "total": 20
  },
  "timestamp": "2025-11-18T09:18:43.000Z"
}
```

Each object inside `"data"` is a **market record** containing:

* market metadata
* outcome tokens
* end date
* active flags
* pricing info (comes directly from the Polymarket CLOB)

Miners only need `"marketId"` and `"tokens"` to trade, but full metadata is returned for more advanced strategies.

***

### 8. Monitoring and Adjusting

Once the miner is running, it’s essential to monitor performance and make adjustments as needed:

To assess the effectiveness of your miner, it’s essential to review performance metrics such as the **Incentive Value**. [Taostats](https://taostats.io/) provides a detailed performance overview for each miner, including specific metrics that reflect how well a miner is contributing to the network. For your miner on Sportstensor, you can view subnet 41-specific metrics.

#### 8.1 Using Taostats to Evaluate Performance

1. **Visit the Taostats Website**: Go to [taostats.io](https://taostats.io/subnets/41/metagraph) subnet 41-specific page.
2. **Understanding the Key Metrics**: On the subnet 41 dashboard, you’ll see a list of all miners currently active on Sportstensor, along with performance indicators. The primary metrics you should focus on is:
   * **Incentive Value**: This is a crucial metric for evaluating a miner’s reward potential. The Incentive Value indicates how much TAO the network is currently willing to allocate to a miner based on the miner’s contributions.
3. **Locate Your Miner**: Use your hotkey address (the address you used for mining) to locate your specific miner on the subnet 41 performance page. You can search by wallet or scroll through the list to find your miner.
4. **Analyzing the Incentive Value**:
   * **High Incentive Value**: A high Incentive Value suggests that your miner is performing well, producing quality outputs, and earning substantial rewards.
   * **Low Incentive Value**: If the Incentive Value is low, it may indicate that your miner’s outputs are not as valued by the network and you'll be at risk of de-registration and forced to go through the registration phase to participate again. In this case, consider improving your model, adjusting configurations, or reviewing the quality of your predictions.
5. **Monitor Trends Over Time**: Taostats allows you to track these metrics over time. By observing changes in your miner’s Incentive Value, you can gauge the impact of any adjustments you make to improve performance.
6. **Adjustments Based on Performance**: If your miner’s Incentive Value remains low, consider optimizing your model: Experiment with different machine learning models to improve the quality of outputs.
