-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhedge_mode.py
More file actions
137 lines (113 loc) · 4.48 KB
/
hedge_mode.py
File metadata and controls
137 lines (113 loc) · 4.48 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
#!/usr/bin/env python3
"""
Hedge Mode Entry Point
This script serves as the main entry point for hedge mode trading.
It imports and runs the appropriate hedge mode implementation based on the exchange parameter.
Usage:
python hedge_mode.py --exchange <exchange> [other arguments]
Supported exchanges:
- backpack: Uses HedgeBot from hedge_mode_bp.py (Backpack + Lighter)
- extended: Uses HedgeBot from hedge_mode_ext.py (Extended + Lighter)
Cross-platform compatibility:
- Works on Linux, macOS, and Windows
- Direct imports instead of subprocess calls for better performance
"""
import asyncio
import sys
import argparse
from decimal import Decimal
from pathlib import Path
import dotenv
def parse_arguments():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description='Hedge Mode Trading Bot Entry Point',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python hedge_mode.py --exchange backpack --ticker BTC --size 0.01 --iter 10
python hedge_mode.py --exchange extended --ticker ETH --size 0.1 --iter 5
"""
)
parser.add_argument('--exchange', type=str, required=True,
help='Exchange to use (backpack or extended)')
parser.add_argument('--ticker', type=str, default='BTC',
help='Ticker symbol (default: BTC)')
parser.add_argument('--size', type=str, required=True,
help='Number of tokens to buy/sell per order')
parser.add_argument('--iter', type=int, required=True,
help='Number of iterations to run')
parser.add_argument('--fill-timeout', type=int, default=5,
help='Timeout in seconds for maker order fills (default: 5)')
parser.add_argument('--env-file', type=str, default=".env",
help=".env file path (default: .env)")
return parser.parse_args()
def validate_exchange(exchange):
"""Validate that the exchange is supported."""
supported_exchanges = ['backpack', 'extended']
if exchange.lower() not in supported_exchanges:
print(f"Error: Unsupported exchange '{exchange}'")
print(f"Supported exchanges: {', '.join(supported_exchanges)}")
sys.exit(1)
def get_hedge_bot_class(exchange):
"""Import and return the appropriate HedgeBot class."""
try:
if exchange.lower() == 'backpack':
from hedge.hedge_mode_bp import HedgeBot
return HedgeBot
elif exchange.lower() == 'extended':
from hedge.hedge_mode_ext import HedgeBot
return HedgeBot
else:
raise ValueError(f"Unsupported exchange: {exchange}")
except ImportError as e:
print(f"Error importing hedge mode implementation: {e}")
sys.exit(1)
async def main():
"""Main entry point that creates and runs the appropriate hedge bot."""
args = parse_arguments()
env_path = Path(args.env_file)
if not env_path.exists():
print(f"Env file not find: {env_path.resolve()}")
sys.exit(1)
dotenv.load_dotenv(args.env_file)
# Validate exchange
validate_exchange(args.exchange)
# Get the appropriate HedgeBot class
try:
HedgeBotClass = get_hedge_bot_class(args.exchange)
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
print(f"Starting hedge mode for {args.exchange} exchange...")
print(f"Ticker: {args.ticker}, Size: {args.size}, Iterations: {args.iter}")
print("-" * 50)
try:
# Create the hedge bot instance
if args.exchange.lower() == 'backpack':
bot = HedgeBotClass(
ticker=args.ticker.upper(),
order_quantity=Decimal(args.size),
fill_timeout=args.fill_timeout,
iterations=args.iter
)
else: # extended
bot = HedgeBotClass(
ticker=args.ticker.upper(),
order_quantity=Decimal(args.size),
fill_timeout=args.fill_timeout,
iterations=args.iter
)
# Run the bot
await bot.run()
except KeyboardInterrupt:
print("\nHedge mode interrupted by user")
return 1
except Exception as e:
print(f"Error running hedge mode: {e}")
import traceback
print(f"Full traceback: {traceback.format_exc()}")
return 1
return 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))