Almost all code was automatically generated by copilot so use at your own risk. The author is not responsible for any financial losses or issues arising from the use of this library.
Java client for the Polymarket Central Limit Order Book (CLOB).
Migrated from Python: This repository has been migrated from Python to Java, maintaining full API compatibility and functionality.
Full documentation available at Polymarket Docs.
- Java 17+
- Maven 3.6+ (for building)
- Private key that owns funds on Polymarket
- Optional: Store secrets in environment variables (e.g., with
.envfiles)
Add to your pom.xml:
<dependency>
<groupId>com.polymarket</groupId>
<artifactId>java-clob-client</artifactId>
<version>1.0.0</version>
</dependency>git clone https://github.com/javifalces/java-clob-client.git
cd java-clob-client
mvn clean installThe examples below demonstrate the three client modes and common operations.
Level 0 client provides access to public endpoints without authentication:
import com.polymarket.clob.ClobClient;
public class Example {
public static void main(String[] args) {
// Create Level 0 client (no authentication)
ClobClient client = new ClobClient("https://clob.polymarket.com");
// Check server health
Object ok = client.getOk();
System.out.println(ok);
// Get server time
Object time = client.getServerTime();
System.out.println(time);
}
}Level 1 client allows creating API credentials and accessing authenticated endpoints:
import com.polymarket.clob.ClobClient;
import com.polymarket.clob.model.ApiCreds;
public class Example {
public static void main(String[] args) {
String host = "https://clob.polymarket.com";
int chainId = 137; // Polygon mainnet
String privateKey = System.getenv("PRIVATE_KEY");
// Create Level 1 client
ClobClient client = new ClobClient(host, chainId, privateKey);
// Create or derive API credentials
ApiCreds creds = client.createOrDeriveApiCreds();
// Upgrade to Level 2
client.setApiCreds(creds);
System.out.println("Address: " + client.getAddress());
System.out.println("API Key: " + creds.getApiKey());
}
}Level 2 client provides access to all endpoints including trading:
import com.polymarket.clob.ClobClient;
import com.polymarket.clob.model.ApiCreds;
public class Example {
public static void main(String[] args) {
String host = "https://clob.polymarket.com";
int chainId = 137;
String privateKey = System.getenv("PRIVATE_KEY");
// API credentials (store securely!)
ApiCreds creds = new ApiCreds(
System.getenv("API_KEY"),
System.getenv("API_SECRET"),
System.getenv("API_PASSPHRASE")
);
// Create Level 2 client
ClobClient client = new ClobClient(host, chainId, privateKey, creds);
// Now you can access all endpoints
Object orders = client.getOrders(null);
System.out.println(orders);
}
}import com.polymarket.clob.ClobClient;
public class Example {
public static void main(String[] args) {
ClobClient client = new ClobClient("https://clob.polymarket.com");
String tokenId = "your-token-id"; // Get from Polymarket Gamma API
// Get midpoint price
Object midpoint = client.getMidpoint(tokenId);
System.out.println("Midpoint: " + midpoint);
// Get price for buying
Object price = client.getPrice(tokenId, "BUY");
System.out.println("Buy price: " + price);
// Get order book
Object orderBook = client.getOrderBook(tokenId);
System.out.println("Order book: " + orderBook);
// Get spread
Object spread = client.getSpread(tokenId);
System.out.println("Spread: " + spread);
}
}import com.polymarket.clob.ClobClient;
public class Example {
public static void main(String[] args) {
ClobClient client = new ClobClient("https://clob.polymarket.com");
// Get all markets
Object markets = client.getMarkets();
System.out.println(markets);
// Get specific market by condition ID
String conditionId = "your-condition-id";
Object market = client.getMarket(conditionId);
System.out.println(market);
}
}import com.polymarket.clob.ClobClient;
import com.polymarket.clob.model.*;
public class Example {
public static void main(String[] args) {
// Create Level 2 client (with credentials)
String host = "https://clob.polymarket.com";
int chainId = 137;
String privateKey = System.getenv("PRIVATE_KEY");
ApiCreds creds = new ApiCreds(
System.getenv("API_KEY"),
System.getenv("API_SECRET"),
System.getenv("API_PASSPHRASE")
);
ClobClient client = new ClobClient(host, chainId, privateKey, creds);
// Get your open orders
Object orders = client.getOrders(null);
System.out.println("Orders: " + orders);
// Get your trade history
Object trades = client.getTrades(null);
System.out.println("Trades: " + trades);
// Get specific order
String orderId = "your-order-id";
Object order = client.getOrder(orderId);
System.out.println("Order: " + order);
}
}import com.polymarket.clob.ClobClient;
import com.polymarket.clob.model.ApiCreds;
public class Example {
public static void main(String[] args) {
// Create Level 2 client
ClobClient client = new ClobClient(
"https://clob.polymarket.com",
137,
System.getenv("PRIVATE_KEY"),
new ApiCreds(
System.getenv("API_KEY"),
System.getenv("API_SECRET"),
System.getenv("API_PASSPHRASE")
)
);
// Cancel a specific order
String orderId = "your-order-id";
Object result = client.cancel(orderId);
System.out.println(result);
// Cancel all orders
Object cancelAll = client.cancelAll();
System.out.println(cancelAll);
}
}java-clob-client/
├── src/
│ ├── main/
│ │ └── java/
│ │ └── com/polymarket/clob/
│ │ ├── ClobClient.java # Main client class
│ │ ├── Constants.java # Constants and configuration
│ │ ├── Endpoints.java # API endpoints
│ │ ├── config/
│ │ │ └── Config.java # Contract configuration
│ │ ├── exception/
│ │ │ └── PolyException.java # Exception handling
│ │ ├── http/
│ │ │ ├── Headers.java # Header utilities
│ │ │ ├── HttpClient.java # HTTP client
│ │ │ └── QueryBuilder.java # Query parameter builder
│ │ ├── model/
│ │ │ ├── ApiCreds.java # API credentials
│ │ │ ├── OrderArgs.java # Order arguments
│ │ │ ├── OrderType.java # Order types enum
│ │ │ └── ... # Other model classes
│ │ ├── signing/
│ │ │ ├── Signer.java # Ethereum signing
│ │ │ ├── Eip712.java # EIP-712 utilities
│ │ │ ├── HmacSignature.java # HMAC signing
│ │ │ └── ClobAuth.java # Auth model
│ │ └── examples/
│ │ └── ... # Example programs
│ └── test/
│ └── java/
│ └── com/polymarket/clob/
│ └── ... # Unit tests
├── pom.xml # Maven configuration
└── README.md # This file
- ✅ Level 0-2 Authentication: Support for public, L1 (private key), and L2 (full API) authentication modes
- ✅ Complete API Coverage: Access to all CLOB endpoints (market data, trading, orders, etc.)
- ✅ EIP-712 Signing: Proper Ethereum signing with Web3j
- ✅ HMAC Authentication: Secure API credential authentication
- ✅ Type Safety: Strongly-typed models with Lombok annotations
- ✅ HTTP/2 Support: Efficient communication with OkHttp
- ✅ Comprehensive Testing: JUnit 5 tests for all components
- ✅ Examples: Ready-to-use example programs
- Web3j: Ethereum functionality and signing
- OkHttp: HTTP client
- Jackson: JSON processing
- Bouncy Castle: Cryptography
- Lombok: Reduce boilerplate code
- SLF4J: Logging
- JUnit 5: Testing
# Build the project
mvn clean install
# Run tests
mvn test
# Run a specific example
mvn exec:java -Dexec.mainClass="com.polymarket.clob.examples.GetOkExample"
# Package as JAR
mvn packageFor security, store sensitive information in environment variables:
export PRIVATE_KEY="0x..."
export API_KEY="your-api-key"
export API_SECRET="your-api-secret"
export API_PASSPHRASE="your-api-passphrase"Or use a .env file with a library like dotenv-java.
- No authentication required
- Access to public endpoints (markets, prices, order books)
- Create with:
new ClobClient(host)
- Private key authentication
- Can create/derive API credentials
- Create with:
new ClobClient(host, chainId, privateKey)
- Full authentication with API credentials
- Access to all endpoints (trading, orders, balances)
- Create with:
new ClobClient(host, chainId, privateKey, apiCreds)
This repository has been migrated from the original py-clob-client. Key differences:
- Language: Python → Java
- Build System: pip/setup.py → Maven
- Dependencies: Python packages → Java libraries (Web3j, OkHttp, Jackson)
- Type System: Dynamic typing → Static typing with Java generics
- Package Structure: Python modules → Java packages following standard conventions
API compatibility has been maintained where possible, with adjustments for Java idioms and patterns.
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes with tests
- Submit a pull request
MIT License - see LICENSE file for details.
For issues and questions:
- GitHub Issues: https://github.com/javifalces/java-clob-client/issues
- Polymarket Discord: https://discord.gg/polymarket
This is an unofficial Java port. Use at your own risk. Always test with small amounts first.
### Manage orders
**Note**: EOA/MetaMask users must set token allowances before trading. See [Token Allowances section](#important-token-allowances-for-metamaskeoa-users) below.
```python
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import OpenOrderParams
HOST = "https://clob.polymarket.com"
CHAIN_ID = 137
PRIVATE_KEY = "<your-private-key>"
FUNDER = "<your-funder-address>"
client = ClobClient(
HOST, # The CLOB API endpoint
key=PRIVATE_KEY, # Your wallet's private key
chain_id=CHAIN_ID, # Polygon chain ID (137)
signature_type=1, # 1 for email/Magic wallet signatures
funder=FUNDER # Address that holds your funds
)
client.set_api_creds(client.create_or_derive_api_creds())
open_orders = client.get_orders(OpenOrderParams())
order_id = open_orders[0]["id"] if open_orders else None
if order_id:
client.cancel(order_id)
client.cancel_all()
from py_clob_client.client import ClobClient
client = ClobClient("https://clob.polymarket.com")
markets = client.get_simplified_markets()
print(markets["data"][:1])Note: EOA/MetaMask users must set token allowances before trading. See Token Allowances section below.
from py_clob_client.client import ClobClient
HOST = "https://clob.polymarket.com"
CHAIN_ID = 137
PRIVATE_KEY = "<your-private-key>"
FUNDER = "<your-funder-address>"
client = ClobClient(
HOST, # The CLOB API endpoint
key=PRIVATE_KEY, # Your wallet's private key
chain_id=CHAIN_ID, # Polygon chain ID (137)
signature_type=1, # 1 for email/Magic wallet signatures
funder=FUNDER # Address that holds your funds
)
client.set_api_creds(client.create_or_derive_api_creds())
last = client.get_last_trade_price("<token-id>")
trades = client.get_trades()
print(last, len(trades))- Using email/Magic wallet? No action needed - allowances are set automatically.
- Using MetaMask or hardware wallet? You need to set allowances before trading.
Think of allowances as permissions. Before Polymarket can move your funds to execute trades, you need to give the exchange contracts permission to access your USDC and conditional tokens.
You need to approve two types of tokens:
- USDC (for deposits and trading)
- Conditional Tokens (the outcome tokens you trade)
Each needs approval for the exchange contracts to work properly.
Here's a simple breakdown of what needs to be approved:
For USDC (your trading currency):
- Token:
0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174 - Approve for these contracts:
0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E(Main exchange)0xC5d563A36AE78145C45a50134d48A1215220f80a(Neg risk markets)0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296(Neg risk adapter)
For Conditional Tokens (your outcome tokens):
- Token:
0x4D97DCd97eC945f40cF65F87097ACe5EA0476045 - Approve for the same three contracts above
See this Python example for setting allowances programmatically.
Pro tip: You only need to set these once per wallet. After that, you can trade freely.
- To discover token IDs, use the Markets API Explorer: Get Markets.
- Prices are in dollars from 0.00 to 1.00. Shares are whole or fractional units of the outcome token.
See /example for more.