-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathbasic_usage.py
More file actions
203 lines (169 loc) · 6.64 KB
/
basic_usage.py
File metadata and controls
203 lines (169 loc) · 6.64 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
"""
Basic usage example for the EdgeX Python SDK.
This example demonstrates the basic functionality of the SDK:
- Creating a client
- Getting server time and metadata
- Getting account assets and positions
- Getting market data (K-lines, order book depth)
- Creating orders (commented out to avoid actual order creation)
- Using WebSockets for real-time data
"""
import asyncio
import os
from datetime import datetime, timedelta
from edgex_sdk import (
Client,
OrderSide,
GetKLineParams,
GetOrderBookDepthParams,
KlineType,
WebSocketManager,
GetWithdrawalRecordsParams,
CreateTransferOutParams,
TransferReason
)
from edgex_sdk.account.client import RegisterAccountParams
from edgex_sdk.asset.client import CreateWithdrawalParams, GetAssetOrdersParams
from edgex_sdk.order.types import CancelOrderParams, CreateOrderParams, OrderType
from edgex_sdk.transfer.client import GetWithdrawAvailableAmountParams
async def main():
# Load configuration from environment variables
base_url = os.getenv("EDGEX_BASE_URL", "https://testnet.edgex.exchange")
account_id = int(os.getenv("EDGEX_ACCOUNT_ID", "your_account_id"))
stark_private_key = os.getenv("EDGEX_STARK_PRIVATE_KEY", "your_private_key")
# Create a new client
client = Client(
base_url=base_url,
account_id=account_id,
stark_private_key=stark_private_key
)
# Get server time
server_time = await client.get_server_time()
print(f"Server Time: {server_time}")
# Get exchange metadata first (required for transfer operations)
metadata = await client.get_metadata()
print(f"Available contracts: {len(metadata.get('data', {}).get('contractList', []))}")
# Get account assets
assets = await client.get_account_asset()
print(f"Account Assets: {assets}")
# Get K-line data for BTCUSDT (contract ID: 10000001)
kline_params = GetKLineParams(
contract_id="10000001", # BTCUSDT
kline_type=KlineType.MINUTE_1,
size=10
)
klines = await client.quote.get_k_line(kline_params)
print(f"K-lines: {klines}")
# Get account positions
positions = await client.get_account_positions()
print(f"Account Positions: {positions}")
# Get 24-hour market data for BNBUSDT (contract ID: 10000004)
quote = await client.get_24_hour_quote("10000004")
print(f"BNBUSDT Price: {quote}")
# Get K-line data for BTCUSDT (contract ID: 10000001)
kline_params = GetKLineParams(
contract_id="10000001", # BTCUSDT
kline_type=KlineType.MINUTE_1,
size=10
)
klines = await client.quote.get_k_line(kline_params)
print(f"K-lines: {klines}")
# Get order book depth for ETHUSDT (contract ID: 10000002)
depth_params = GetOrderBookDepthParams(
contract_id="10000002", # ETHUSDT
limit=15 # Valid values are 15 or 200
)
depth = await client.quote.get_order_book_depth(depth_params)
print(f"Order Book Depth: {depth}")
maxOrderSize = await client.get_max_order_size("10000001", 100000.0)
print(f"Max Order size: {maxOrderSize}")
# Create a limit order (commented out to avoid actual order creation)
order = await client.create_order(CreateOrderParams(
contract_id="10000004", # BNBUSDT
size="0.01",
price="600.00",
type=OrderType.LIMIT,
side=OrderSide.BUY,
))
print(f"Order created: {order}")
# Create a market order
order = await client.create_order(CreateOrderParams(
contract_id="10000004", # BNBUSDT
size="0.01",
price="0",
type=OrderType.MARKET,
side=OrderSide.BUY
))
print(f"Order created: {order}")
param = CancelOrderParams(
client_order_id ="676249092405330305"
)
cancelRes = await client.cancel_order(param)
print(f"Cancel Order: {cancelRes}")
# Create a transfer out order with new optional parameters
try:
transferMaxAmount = await client.transfer.get_transferout_available_amount("1000")
print(transferMaxAmount)
# Set expiration time to 24 hours from now
expire_time = datetime.now() + timedelta(hours=24)
transfer_result = await client.create_transfer_out(
CreateTransferOutParams(
coin_id="1000",
amount="10",
receiver_account_id="your-receiver-account-id",
receiver_l2_key="your-receiver-l2-key", # "0x111111"
transfer_reason=TransferReason.USER_TRANSFER,
expire_time=expire_time,
extra_type="CUSTOM_TYPE",
extra_data_json='{"custom_field": "custom_value"}'
))
print(f"Transfer out result: {transfer_result}")
transferOrders = await client.asset.get_asset_orders(
GetAssetOrdersParams(
size=10,
filter_start_created_time_inclusive=1761408000,
filter_end_created_time_exclusive=1762099199
)
)
print(f"Tranfer orders: {transferOrders}")
except ValueError as e:
print(f"Failed to create transfer out: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
# Create a withdrawal order
withdrawResult = await client.create_normal_withdrawal(CreateWithdrawalParams(
coin_id="1000",
amount="10",
eth_address="your-eth-address", # "0x111111"
tag=""
))
print(f"WithdrawResult: {withdrawResult}")
maxWithdrawalAmount = await client.asset.get_withdrawable_amount(address="your_eth_address")
print(f"Max withdrawal amount: {maxWithdrawalAmount}")
# Get withdrawal records with default parameters
withdrawal_params = GetWithdrawalRecordsParams(size="10")
withdrawResult = await client.asset.get_withdrawal_records(withdrawal_params)
print(f"withdrawResult: {withdrawResult}")
# WebSocket example
ws_url = os.getenv("EDGEX_WS_URL", "wss://quote-testnet.edgex.exchange")
ws_manager = WebSocketManager(
base_url=ws_url,
account_id=account_id,
stark_pri_key=stark_private_key
)
# Define message handlers
def ticker_handler(message):
print(f"Ticker Update: {message}")
def kline_handler(message):
print(f"K-line Update: {message}")
# Connect to public WebSocket for market data
ws_manager.connect_public()
# Subscribe to real-time updates for BNBUSDT (contract ID: 10000004)
ws_manager.subscribe_ticker("10000004", ticker_handler)
ws_manager.subscribe_kline("10000004", "1m", kline_handler)
# Wait for updates
await asyncio.sleep(30)
# Disconnect all connections
ws_manager.disconnect_all()
if __name__ == "__main__":
asyncio.run(main())