{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6ba03e09",
   "metadata": {},
   "source": [
    "# Monitorare"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f135ac6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import time\n",
    "from datetime import datetime, timedelta\n",
    "import tpqoa"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0f41f63",
   "metadata": {},
   "source": [
    "Il codice fino ad ora"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f83f4f05",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Trader(tpqoa.tpqoa):\n",
    "    \n",
    "    def __init__(self,config_file, instrument, period, window, units):\n",
    "        super().__init__(config_file)\n",
    "        self.instrument = instrument\n",
    "        self.period=period\n",
    "        self.tickData = pd.DataFrame()\n",
    "        self.rawData = None \n",
    "        self.ultimoPeriodo = None \n",
    "        self.data = None\n",
    "        self.units = units\n",
    "        self.posizione = 0\n",
    "        \n",
    "        ########################## STRATEGY SPECIFIC ATTRIBUTES ##############################\n",
    "        self.window = window\n",
    "        \n",
    "    def getMostRecent(self, days=5): \n",
    "        '''questo metodo scarica i dati FINO ad adesso'''\n",
    "        while True:\n",
    "            now = datetime.now(timezone.utc)\n",
    "            now = now - timedelta(microseconds = now.microsecond) # pay attention, microseconds and then microsecond (singular!!!)\n",
    "            yesterday = now - timedelta(days= days) # lo chiamo YESTERDAY, ma è l'inizio del periodo da scaricare\n",
    "            df = self.get_history(instrument = self.instrument, start = str(yesterday)[:-6], end = str(now)[:-6],\n",
    "                        granularity= \"S5\", price=\"M\", localize=False)[\"c\"].to_frame() \n",
    "                        # scarico a 5secondi, il che vuol dire che period non può essere più corto!\n",
    "            df.rename(columns={\"c\":self.instrument},inplace=True)\n",
    "            self.rawData = df.resample(self.period, label=\"right\").last().dropna().iloc[:-1]\n",
    "            self.ultimoPeriodo = self.rawData.index[-1]\n",
    "            if pd.to_datetime(datetime.now(timezone.utc)) - self.ultimoPeriodo < pd.to_timedelta(self.period):\n",
    "                break\n",
    "            else:\n",
    "                time.sleep(2)\n",
    "    \n",
    "    def on_success(self, time, bid, ask):\n",
    "        print(self.ticks, end=\" \")\n",
    "        tickCorrente = pd.to_datetime(time)\n",
    "        df = pd.DataFrame({self.instrument:(ask+bid)/2}, index=[tickCorrente])\n",
    "        self.tickData=pd.concat((self.tickData,df),axis=0)\n",
    "        if tickCorrente - self.ultimoPeriodo > pd.to_timedelta(self.period):\n",
    "            self.resampleJoin()\n",
    "            self.defineStrategy()\n",
    "            self.executeTrade()\n",
    "    \n",
    "    def resampleJoin(self):\n",
    "        self.rawData=pd.concat((self.rawData,self.tickData.resample(self.period,label=\"right\").last().ffill().iloc[:-1] ),axis=0)\n",
    "        self.tickData = self.tickData.iloc[-1:] \n",
    "        self.ultimoPeriodo = self.rawData.index[-1] \n",
    "        \n",
    "    def defineStrategy(self):\n",
    "        df = self.rawData.copy()\n",
    "        df[\"logRet\"]=np.log(df[self.instrument] / df[self.instrument].shift(1))\n",
    "        df[\"posizione\"]= - np.sign(df.logRet.rolling(self.window).mean())\n",
    "        self.data = df.copy()\n",
    "        \n",
    "    def executeTrade(self):\n",
    "        if self.data.posizione.iloc[-1] == 1: # andiamo lunghi\n",
    "            if self.posizione == 0:\n",
    "                order = self.create_order(instrument = self.instrument, units = self.units, suppress=True, ret = True)\n",
    "                print(\"VADO LUNGO\",self.units,order[\"price\"])\n",
    "            elif self.posizione == -1:\n",
    "                order = self.create_order(instrument = self.instrument, units = 2*self.units, suppress=True, ret = True)\n",
    "                print(\"CHIUDO POSIZIONE CORTA E VADO LUNGO\",2*self.units,order[\"price\"])\n",
    "            self.posizione=1\n",
    "        elif self.data.posizione.iloc[-1] == -1: # andiamo corti\n",
    "            if self.posizione == 0:\n",
    "                order = self.create_order(instrument = self.instrument, units = -self.units, suppress=True, ret = True)\n",
    "                print(\"VADO CORTO\",-self.units,order[\"price\"])\n",
    "            elif self.posizione == 1:\n",
    "                order = self.create_order(instrument = self.instrument, units = -2*self.units, suppress=True, ret = True)\n",
    "                print(\"CHIUDO POSIZIONE LUNGA E VADO CORTO\",-2*self.units,order[\"price\"])\n",
    "            self.posizione=-1\n",
    "        elif self.data.posizione.iloc[-1] == 0: # andiamo neutri\n",
    "            if self.posizione == 1:\n",
    "                order = self.create_order(instrument = self.instrument, units = -self.units, suppress=True, ret = True)\n",
    "                print(\"CHIUDO POSIZIONE LUNGA\",-self.units,order[\"price\"])\n",
    "            elif self.posizione == -1:\n",
    "                order = self.create_order(instrument = self.instrument, units = self.units, suppress=True, ret = True)\n",
    "                print(\"CHIUDO POSIZIONE CORTA\",self.units,order[\"price\"])\n",
    "            self.posizione=0\n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4de5836",
   "metadata": {},
   "source": [
    "Aggiungiamo un metodo report_trade e modifichiamo i print in execute_trade"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c92f3919",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "efe1f5cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "trader = Trader(\"oandaMY.cfg\",\"EUR_USD\",\"1min\", window=1, units=100000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c038e645",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(datetime.now(timezone.utc))\n",
    "trader.getMostRecent()\n",
    "trader.stream_data(trader.instrument,stop=150)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6e4767ba",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "47f04aa1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7fa0db48",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "a87c40e0",
   "metadata": {},
   "source": [
    "Inseriamo la chiusura finale in stream_data direttamente"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7e2276e",
   "metadata": {},
   "outputs": [],
   "source": [
    "trader.stream_data??"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6b4a7b8d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c5bc25b",
   "metadata": {},
   "outputs": [],
   "source": [
    "trader = Trader(\"oandaMY.cfg\",\"EUR_USD\",\"1min\", window=1, units=100000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a7c8db0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(datetime.now(timezone.utc))\n",
    "trader.getMostRecent()\n",
    "trader.stream_data(trader.instrument,stop=150)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d998e508",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
