added live trade actions (wip) and candle chart

This commit is contained in:
Dobromir Popov 2025-03-17 02:35:15 +02:00
parent 991cf57274
commit d9d0ba9da8

View File

@ -327,6 +327,12 @@ class TradingEnvironment:
self.optimal_tops = []
self.optimal_signals = np.array([])
# Add these new attributes
self.leverage = MAX_LEVERAGE
self.futures_symbol = "ETH_USDT" # Example futures symbol
self.position_mode = "hedge" # For simultaneous long/short positions
self.margin_mode = "cross" # Cross margin mode
def reset(self):
"""Reset the environment to initial state"""
self.balance = self.initial_balance
@ -1482,6 +1488,60 @@ class TradingEnvironment:
return potential_profit
async def initialize_futures(self, exchange):
"""Initialize futures trading parameters"""
if not self.demo:
try:
# Set up futures trading parameters
await exchange.set_position_mode(True) # Hedge mode
await exchange.set_margin_mode("cross", symbol=self.futures_symbol)
await exchange.set_leverage(self.leverage, symbol=self.futures_symbol)
logger.info(f"Futures initialized with {self.leverage}x leverage")
except Exception as e:
logger.error(f"Failed to initialize futures: {e}")
raise
async def execute_real_trade(self, exchange, action, current_price):
"""Execute real futures trade on MEXC"""
try:
position_size = self.calculate_position_size()
if action == 1: # Open long
order = await exchange.create_order(
symbol=self.futures_symbol,
type='market',
side='buy',
amount=position_size,
params={'positionSide': 'LONG'}
)
logger.info(f"Opened LONG position: {order}")
elif action == 2: # Open short
order = await exchange.create_order(
symbol=self.futures_symbol,
type='market',
side='sell',
amount=position_size,
params={'positionSide': 'SHORT'}
)
logger.info(f"Opened SHORT position: {order}")
elif action == 3: # Close position
position_side = 'LONG' if self.position == 'long' else 'SHORT'
order = await exchange.create_order(
symbol=self.futures_symbol,
type='market',
side='sell' if position_side == 'LONG' else 'buy',
amount=self.position_size,
params={'positionSide': position_side}
)
logger.info(f"Closed {position_side} position: {order}")
return order
except Exception as e:
logger.error(f"Trade execution failed: {e}")
return None
# Ensure GPU usage if available
def get_device():
"""Get the best available device (CUDA GPU or CPU)"""
@ -1722,21 +1782,35 @@ class Agent:
return False
def add_chart_to_tensorboard(self, env, global_step):
"""Add candlestick chart with signals to TensorBoard"""
if len(env.data) < 30: # Need enough data to create a meaningful chart
"""Add enhanced trading chart to TensorBoard"""
if len(env.data) < 10: # Minimum data to show
return
# Create candlestick chart
chart_img = create_candlestick_figure(
env.data[-100:], # Last 100 candles
env.trade_signals,
window_size=100,
title=f"Trading Chart (Step {global_step})"
)
# Add to TensorBoard
self.writer.add_image('Trading Chart', np.array(chart_img).transpose(2, 0, 1), global_step)
self.chart_step = global_step
try:
# Create chart with annotations
chart_img = create_candlestick_figure(
env.data,
env.trade_signals,
window_size=100,
title=f"Trading Chart (Step {global_step})"
)
# Add to TensorBoard
self.writer.add_image('Trading Chart', np.array(chart_img).transpose(2, 0, 1), global_step)
self.chart_step = global_step
# Also log position information
if env.position != 'flat':
position_info = {
'position_type': env.position,
'entry_price': env.entry_price,
'position_size': env.position_size,
'unrealized_pnl': env.total_pnl
}
self.writer.add_text('Position', str(position_info), global_step)
except Exception as e:
logger.error(f"Error creating chart: {e}")
async def get_live_prices(symbol="ETH/USDT", timeframe="1m"):
"""Get live price data using websockets"""