Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow limiting to one strategy #67

Merged
merged 3 commits into from
Aug 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,18 @@ def initialize_database(engine):
logger.error('Failed to initialize database', extra={'error': str(e)})
raise

async def initialize_system_components(config):
async def initialize_system_components(config, strategy_name=None):
try:
brokers = initialize_brokers(config)
logger.info('Brokers initialized successfully')
strategies = await initialize_strategies(brokers, config)
strategies = await initialize_strategies(brokers, config, strategy_name)
logger.info('Strategies initialized successfully')
return brokers, strategies
except Exception as e:
logger.error('Failed to initialize system components', extra={'error': str(e)})
raise

async def initialize_brokers_and_strategies(config):
async def initialize_brokers_and_strategies(config, strategy_name=None):
engine = create_database_engine(config)
if config.get('rename_strategies'):
for strategy in config['rename_strategies']:
Expand All @@ -51,22 +51,22 @@ async def initialize_brokers_and_strategies(config):
raise
# Initialize the brokers and strategies
try:
brokers, strategies = await initialize_system_components(config)
brokers, strategies = await initialize_system_components(config, strategy_name)
except Exception as e:
logger.error('Failed to initialize brokers', extra={'error': str(e)})
return

# Initialize the strategies
try:
strategies = await initialize_strategies(brokers, config)
strategies = await initialize_strategies(brokers, config, strategy_name)
logger.info('Strategies initialized successfully')
except Exception as e:
logger.error('Failed to initialize strategies', extra={'error': str(e)})
return
return brokers, strategies

# TODO: fix the need to restart to refresh the tastytrade token
async def start_trading_system(config_path):
async def start_trading_system(config_path, strategy_name=None):
logger.info('Starting the trading system', extra={'config_path': config_path})

# Parse the configuration file
Expand All @@ -85,7 +85,7 @@ async def start_trading_system(config_path):
initialize_database(engine)

# Initialize the brokers and strategies
brokers, strategies = await initialize_brokers_and_strategies(config)
brokers, strategies = await initialize_brokers_and_strategies(config, strategy_name)

# Execute the strategies loop
rebalance_intervals = { s: timedelta(minutes=strategies[s].rebalance_interval_minutes) for s in strategies }
Expand All @@ -108,7 +108,7 @@ async def start_trading_system(config_path):
except Exception as e:
# Try to reinitalize the brokers and strategies
logger.error(f'Error during rebalancing strategy {strategy_name}', extra={'error': str(e)})
brokers, strategies = await initialize_brokers_and_strategies(config)
brokers, strategies = await initialize_brokers_and_strategies(config, strategy_name)
await asyncio.sleep(60) # Check every minute
logger.info('Trading system finished 24 hours of trading')

Expand Down Expand Up @@ -187,14 +187,15 @@ async def main():
parser.add_argument('--mode', choices=['trade', 'api', 'sync'], required=True, help='Mode to run the system in: "trade", "api", or "sync"')
parser.add_argument('--config', type=str, help='Path to the YAML configuration file.')
parser.add_argument('--local_testing', action='store_true', help='Run API server with local testing configuration.')
parser.add_argument('--strategy', type=str, help='Run a single strategy.')
args = parser.parse_args()

if args.mode == 'trade':
if not args.config:
parser.error('--config is required when mode is "trade"')
while True:
try:
await start_trading_system(args.config)
await start_trading_system(args.config, args.strategy)
except Exception as e:
logger.error('Error in trading system', extra={'error': str(e)})
logger.info('Restarting the trading system')
Expand Down
5 changes: 4 additions & 1 deletion utils/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,13 @@ async def initialize_strategy(strategy_name, strategy_type, broker, config):
else:
return strategy

async def initialize_strategies(brokers, config):
async def initialize_strategies(brokers, config, name=None):
strategies_config = config['strategies']
strategies = {}
for strategy_name in strategies_config:
if name and strategy_name != name:
logger.info(f"Skipping strategy '{strategy_name}'")
continue
try:
strategy_config = strategies_config[strategy_name]
strategy_type = strategy_config['type']
Expand Down
4 changes: 0 additions & 4 deletions utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,6 @@ def black_scholes_delta_theta(position):
d1 = (math.log(S / float(K)) + (r + 0.5 * sigma ** 2) * T) / (sigma * math.sqrt(T))
d2 = d1 - sigma * math.sqrt(T)

print(f"S: {S}, K: {float(K)}, T: {T}, r: {r}, sigma: {sigma}, d1: {d1}, d2: {d2}")

delta = 0.0
theta = 0.0
if option_type == 'C':
Expand All @@ -195,8 +193,6 @@ def black_scholes_delta_theta(position):
delta = -norm.cdf(-d1)
theta = (-S * norm.pdf(d1) * sigma / (2 * math.sqrt(T)) + r * float(K) * math.exp(-r * T) * norm.cdf(-d2)) / 365.0

print(f"delta: {delta}, theta: {theta}")

return delta, theta
except Exception as e:
logger.error(f"Error calculating Black-Scholes delta and theta: {e}")
Expand Down
Loading