@@ -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