-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrading.js
More file actions
83 lines (70 loc) · 2.55 KB
/
trading.js
File metadata and controls
83 lines (70 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const { ClobClient, OrderType, Side } = require('@polymarket/clob-client');
const { ethers } = require('ethers');
require('dotenv').config();
// Initialize Client
async function initClient() {
const provider = new ethers.JsonRpcProvider('https://polygon-rpc.com');
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
// You might need to change chainId to 137 (Polygon Mainnet) if testing live
const clobClient = new ClobClient(
'https://clob.polymarket.com',
137,
wallet
);
// Perform L2 Auth headers derivation
// In a real script, you might want to cache the creds
const creds = await clobClient.deriveApiKey();
console.log("CLOB Client Initialized for address:", wallet.address);
return clobClient;
}
/**
* Places a limit order to BUY (Long/Short outcome token)
*/
async function enterPosition(client, marketId, side, amount, price) {
// Basic Error Checking
if (!client) throw new Error("Client not initialized");
console.log(`Attempting to ENTER: ${side} ${amount} @ ${price}`);
try {
const order = await client.createOrder({
tokenID: marketId, // Token ID of the outcome (Yes or No token)
price: price, // Limit price
side: side === 'BUY' ? Side.Buy : Side.Sell, // Usually 'BUY' to enter
size: amount, // Amount of shares
feeRateBps: 0, // Maker orders often 0, check docs
nonce: Date.now(), // Unique nonce
});
const resp = await client.postOrder(order);
console.log("Order Placed:", resp);
return resp;
} catch (err) {
console.error("Failed to Enter Position:", err.message);
}
}
/**
* Places a limit order to SELL (closing the position)
*/
async function exitPosition(client, marketId, side, amount, price) {
console.log(`Attempting to EXIT: ${side} ${amount} @ ${price}`);
// To exit a long position, we SELL.
// If we bought 'YES' tokens, we now SELL 'YES' tokens.
try {
const order = await client.createOrder({
tokenID: marketId,
price: price,
side: side === 'BUY' ? Side.Buy : Side.Sell, // 'SELL' to exit usually
size: amount,
feeRateBps: 0,
nonce: Date.now(),
});
const resp = await client.postOrder(order);
console.log("Exit Order Placed:", resp);
return resp;
} catch (err) {
console.error("Failed to Exit Position:", err.message);
}
}
module.exports = {
initClient,
enterPosition,
exitPosition
};