Skip to main content
Anatomy of a CODY strategy

How to write and troubleshoot python trading strategies

Updated over a week ago

CODY is a powerful trading bot that enables developers to create, test, and execute trading algorithms for cryptocurrencies. It supports backtesting, and live trading, allowing developers to test and optimize their trading strategies before deploying them in the real world.

When you write an algorithm to work with CODY, there are two main functions that need to be implemented: initialize() and run_iteration():

initialize()

The initialize function is called once at the beginning of the algorithm and is used to set up any initial state or configuration for the algorithm. Here's an example of an initialize function:

def initialize(self, state, context, args):
state['position'] = None
state['entry_price'] = None
state['target_price'] = None
state['stop_price'] = None

Note: Configuration parameters that only need to be set once upon start of the algorithm can be defined here. Here we are initializing position, entry_price, target_price and stop_price as None in the state dict, which is then available in the run_iteration function and can be used or updated at every execution interval.

run_iteration()

The run_iteration function is called once for each execution interval defined in the settings UI. This function is used to implement the trading logic of the algorithm. Here's an example of a run_iteration function:

def run_iteration(self, state, context, args):
try:
symbol = args.params['pair']
capital_base = float(args.params['capitalBase'])
base_currency = symbol.split('/')[0]
quote_currency = symbol.split('/')[1]
amount_to_trade = 100 # Fixed amount of DOGE to trade

# Fetch the latest price
ticker = self.exchange.fetch_ticker(symbol)
current_price = ticker['last']

# Check if we have an open position
if state['position'] is None:
# No open position, place a buy order
order = self.exchange.create_order(type='market', side='buy', symbol=symbol, amount=amount_to_trade)
state['position'] = 'long'
state['entry_price'] = current_price
state['target_price'] = state['entry_price'] * 1.01 # 1% profit target
state['stop_price'] = state['entry_price'] * 0.98 # 2% stop loss
log.info(f"Bought {amount_to_trade} {base_currency} at {state['entry_price']} {quote_currency}")
else:
# We have an open position, check for target or stop loss
if current_price >= state['target_price']:
# Target reached, sell the position
order = self.exchange.create_order(type='market', side='sell', symbol=symbol, amount=amount_to_trade)
log.info(f"Sold {amount_to_trade} {base_currency} at {current_price} {quote_currency} for profit")
state['position'] = None
state['entry_price'] = None
state['target_price'] = None
state['stop_price'] = None
elif current_price <= state['stop_price']:
# Stop loss reached, sell the position
order = self.exchange.create_order(type='market', side='sell', symbol=symbol, amount=amount_to_trade)
log.info(f"Sold {amount_to_trade} {base_currency} at {current_price} {quote_currency} for loss")
state['position'] = None
state['entry_price'] = None
state['target_price'] = None
state['stop_price'] = None

except Exception as e:
log.error(f"Error in run_iteration: {str(e)}")

The above example was generated using the following prompt:
​
​Trade 100 DOGE/USDT using a scalping strategy on the 5 minute timeframe with 1% profit target and 2% stop loss.
​

The python code generated is generally very readable and has sufficient comments to explain the logic being implemented. If you have questions about a certain feature of the framework, the best place to get assistance is by chatting with Cody on ChatGPT Plus.

Did this answer your question?