Skip to content

Commit 81d564a

Browse files
committed
feat: Update main script for WebSocket support
- Add asyncio event loop handling - Add proper WebSocket initialization - Add graceful shutdown handling - Update configuration for real-time data - Remove polling interval
1 parent cc63584 commit 81d564a

2 files changed

Lines changed: 46 additions & 23 deletions

File tree

traid/main.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Main entry point for trading bot."""
22
from decimal import Decimal
3+
import asyncio
34
from traid.runner import TradingBotRunner
45

56
def get_user_config():
@@ -15,15 +16,14 @@ def get_user_config():
1516
except:
1617
print("Invalid input! Please enter a valid number.")
1718

18-
def main():
19-
"""Run trading bot."""
19+
async def run_bot():
20+
"""Run trading bot with WebSocket connection."""
2021
# Get user configuration
2122
INITIAL_BALANCE = get_user_config()
2223

2324
# Fixed configuration
2425
SYMBOL = "BTC/USDT"
25-
TIMEFRAME = "1h"
26-
UPDATE_INTERVAL = 3600 # 1 hour in seconds
26+
TIMEFRAME = "1m" # 1 minute for more frequent updates
2727

2828
print(f"\nStarting bot with:")
2929
print(f"Initial Portfolio: {INITIAL_BALANCE} USDT")
@@ -34,17 +34,25 @@ def main():
3434
bot = TradingBotRunner(
3535
symbol=SYMBOL,
3636
timeframe=TIMEFRAME,
37-
initial_balance=INITIAL_BALANCE,
38-
update_interval=UPDATE_INTERVAL
37+
initial_balance=INITIAL_BALANCE
3938
)
4039

4140
try:
42-
bot.start()
43-
input("\nPress Enter to stop the bot...\n")
41+
await bot.start()
42+
print("\nBot is running with real-time data. Press Ctrl+C to stop.")
43+
while True:
44+
await asyncio.sleep(1)
4445
except KeyboardInterrupt:
4546
print("\nStopping bot...")
4647
finally:
47-
bot.stop()
48+
await bot.stop()
49+
50+
def main():
51+
"""Entry point."""
52+
try:
53+
asyncio.run(run_bot())
54+
except KeyboardInterrupt:
55+
print("\nBot stopped by user.")
4856

4957
if __name__ == "__main__":
5058
main()

traid/trading/execution.py

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -116,17 +116,21 @@ def _can_buy(self, timestamp: int) -> bool:
116116
Returns:
117117
bool: True if buy conditions are met
118118
"""
119-
# Check trade interval
120-
if timestamp - self._last_trade_time < self._min_trade_interval:
121-
return False
119+
# Calculate total portfolio value currently in positions
120+
total_position_value = Decimal("0")
121+
for symbol, volume in self.simulator.positions.items():
122+
if symbol in self.simulator.current_prices:
123+
total_position_value += volume * self.simulator.current_prices[symbol]
122124

123-
# Check consecutive trades
124-
if self._consecutive_trades >= 3: # Maximum 3 consecutive trades
125+
# Don't use more than 80% of total available balance
126+
available_portfolio = self.simulator.balance.available * Decimal("0.8")
127+
if total_position_value >= available_portfolio:
125128
return False
126129

127-
# Check if we already have a position
128-
current_position = self.simulator.positions.get(self.symbol, Decimal("0"))
129-
if current_position > 0:
130+
# Maximum 20% of portfolio per position
131+
position_size = self._calculate_position_size(self.simulator.current_prices[self.symbol])
132+
max_position_value = self.simulator.balance.available * Decimal("0.2")
133+
if position_size * self.simulator.current_prices[self.symbol] > max_position_value:
130134
return False
131135

132136
return True
@@ -140,15 +144,26 @@ def _can_sell(self, timestamp: int) -> bool:
140144
Returns:
141145
bool: True if sell conditions are met
142146
"""
143-
# Check trade interval
144-
if timestamp - self._last_trade_time < self._min_trade_interval:
147+
# Can sell if we have a position
148+
current_position = self.simulator.positions.get(self.symbol, Decimal("0"))
149+
if current_position <= 0:
145150
return False
146151

147-
# Check consecutive trades
148-
if self._consecutive_trades >= 3:
149-
return False
152+
# Calculate current position value
153+
position_value = current_position * self.simulator.current_prices[self.symbol]
150154

151-
return True
155+
# Calculate profit/loss percentage
156+
buy_trades = [t for t in self.trades if t['type'] == 'buy' and t['symbol'] == self.symbol]
157+
if not buy_trades:
158+
return True
159+
160+
avg_buy_price = sum(Decimal(str(t['price'])) * Decimal(str(t['volume'])) for t in buy_trades) / \
161+
sum(Decimal(str(t['volume'])) for t in buy_trades)
162+
163+
profit_percentage = (self.simulator.current_prices[self.symbol] - avg_buy_price) / avg_buy_price * 100
164+
165+
# Sell if profit is above 5% or loss is more than 2%
166+
return profit_percentage >= 5 or profit_percentage <= -2
152167

153168
def _calculate_position_size(self, price: Decimal) -> Decimal:
154169
"""Calculate appropriate position size based on current balance.

0 commit comments

Comments
 (0)