Trend Follower
An example of how to implement a trend following rule on exchanges supported on the gateway;
import os
import pytz
import asyncio
from decimal import Decimal
from dotenv import load_dotenv
load_dotenv()
from datetime import datetime
import quantpylib.standards.markets as markets
from quantpylib.standards import Period
from quantpylib.gateway.master import Gateway
from quantpylib.datapoller.master import DataPoller
from quantpylib.simulator.gene import GeneticAlpha
exc = "hyperliquid"
config_keys = {
exc: {
"key" : os.getenv("HPL_DEMO_KEY"),
"secret" : os.getenv("HPL_DEMO_SECRET"),
}
}
datapoller = DataPoller(config_keys=config_keys)
gateway = Gateway(config_keys=config_keys)
interval = Period.DAILY
async def main():
await gateway.init_clients()
capital = (await gateway.account.account_balance(exc=exc))[markets.ACCOUNT_EQUITY]
contracts = await gateway.exchange.contract_specifications(exc=exc)
tickers = list(contracts.keys())[:20]
period_start = datetime(2016,1,1, tzinfo=pytz.utc)
period_end = datetime.now(pytz.utc)
ticker_dfs = await asyncio.gather(*[
datapoller.crypto.get_trade_bars(
ticker=ticker,
start=period_start,
end=period_end,
granularity=interval,
kline_close=True,
src=exc
) for ticker in tickers
])
dfs = {ticker:df for ticker,df in zip(tickers,ticker_dfs)}
strat_configs = {
"dfs":dfs,
"granularity":interval,
"instruments":tickers,
"execrates": [0.0005] * len(tickers),
"longswps": [0.1] * len(tickers),
"shortswps": [-0.1] * len(tickers),
"weekend_trading":True,
"positional_inertia": 0.1
}
alpha = GeneticAlpha(genome="tszscre_12(close)",portfolio_vol=0.25,**strat_configs)
df = await alpha.run_simulation()
held = await gateway.positions.positions_get(exc=exc)
take = alpha.get_positions_for_capital(capital=capital,held={k:v[markets.AMOUNT] for k,v in held.items()})
trade = {inst : Decimal(str(take[inst])) - (Decimal('0') if inst not in held else held[inst][markets.AMOUNT]) for inst in tickers}
trade = {inst : round(amount,int(contracts[inst][markets.SYMBOL_QUANTITY_PRECISION])) for inst,amount in trade.items()}
print(trade)
for inst,amount in trade.items():
res = await gateway.executor.market_order(exc=exc,ticker=inst,amount=amount)
if __name__ == "__main__":
asyncio.run(main())
Say you want to run this every day, on a new candle, we can schedule it on cron: