Skip to content

Instantly share code, notes, and snippets.

@tistaharahap
Created March 25, 2024 04:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tistaharahap/14e632c64e79ae05bd5fa4b056109324 to your computer and use it in GitHub Desktop.
Save tistaharahap/14e632c64e79ae05bd5fa4b056109324 to your computer and use it in GitHub Desktop.
Modeling example
class Candle(BaseCutsModel):
open_time: int
open: Decimal
high: Decimal
low: Decimal
close: Decimal
volume: Decimal
close_time: int
quote_asset_volume: Decimal
number_of_trades: int
taker_buy_base_asset_volume: Decimal
taker_buy_quote_asset_volume: Decimal
volume_ma: Decimal | None = None
taker_buy_volume_ma: Decimal | None = None
async def get_candles(symbol: str, timeframe: Timeframes, limit: int = 529) -> List[Candle]:
url = f"{BINANCE_BASE_URL}/fapi/v1/klines"
params = {"symbol": symbol, "interval": timeframe.value, "limit": limit + 4}
def _map_candle(x: list) -> Candle:
return Candle(
open_time=x[0],
open=Decimal(x[1]),
high=Decimal(x[2]),
low=Decimal(x[3]),
close=Decimal(x[4]),
volume=Decimal(x[5]),
close_time=x[6],
quote_asset_volume=Decimal(x[7]),
number_of_trades=x[8],
taker_buy_base_asset_volume=Decimal(x[9]),
taker_buy_quote_asset_volume=Decimal(x[10]),
)
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params) as response:
data = await response.json()
results = [_map_candle(x) for x in data]
if len(results) == 0:
return []
# MA
try:
vol_ma = talib.SMA(np.array([float(x.quote_asset_volume) for x in results]), timeperiod=limit)
taker_buy_vol_ma = talib.SMA(
np.array([float(x.taker_buy_quote_asset_volume) for x in results]), timeperiod=limit
)
except Exception:
return []
results[-1].volume_ma = Decimal(vol_ma[-1])
results[-2].volume_ma = Decimal(vol_ma[-2])
results[-1].taker_buy_volume_ma = Decimal(taker_buy_vol_ma[-1])
results[-2].taker_buy_volume_ma = Decimal(taker_buy_vol_ma[-2])
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment