Implement trend signals

This commit is contained in:
2022-12-06 19:46:06 +00:00
parent 242c9fbaed
commit 3b3faecdf1
5 changed files with 87 additions and 3 deletions

View File

@@ -296,7 +296,7 @@ def execute_strategy(callback, strategy, func):
:param strategy: Strategy object
"""
# Only check times for entries. We can always exit trades.
# Only check times for entries. We can always exit trades and set trends.
if func == "entry":
# Check if we can trade now!
now_utc = datetime.utcnow()
@@ -380,6 +380,31 @@ def execute_strategy(callback, strategy, func):
response = account.client.close_position(side, symbol)
log.debug(f"Close position response: {response}")
return
# Set the trend
elif func == "trend":
if strategy.trends is None:
strategy.trends = {}
strategy.trends[symbol] = direction
strategy.save()
log.debug(f"Set trend for {symbol}: {direction}")
return
# Check if we are trading against the trend
if strategy.trend_signals is not None:
if strategy.trends is None:
log.debug("Refusing to trade with no trend signals received")
return
if symbol not in strategy.trends:
log.debug("Refusing to trade asset without established trend")
return
else:
if strategy.trends[symbol] != direction:
log.debug("Refusing to trade against the trend")
return
else:
log.debug(f"Trend check passed for {symbol} - {direction}")
type = strategy.order_type
# Get the account's balance in the native account currency
@@ -443,6 +468,17 @@ def execute_strategy(callback, strategy, func):
def process_callback(callback):
log.info(f"Received callback for {callback.hook} - {callback.signal}")
# Scan for trend
log.debug("Scanning for trend strategies...")
strategies = Strategy.objects.filter(trend_signals=callback.signal, enabled=True)
log.debug(f"Matched strategies: {strategies}")
for strategy in strategies:
log.debug(f"Executing strategy {strategy}")
if callback.hook.user != strategy.user:
log.error("Ownership differs between callback and strategy.")
continue
execute_strategy(callback, strategy, func="trend")
# Scan for entry
log.debug("Scanning for entry strategies...")
strategies = Strategy.objects.filter(entry_signals=callback.signal, enabled=True)