{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6ba03e09",
   "metadata": {},
   "source": [
    "# Strategia in tempo reale SU IBKR: SMA su 50 e 200 minuti"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2f135ac6",
   "metadata": {},
   "outputs": [],
   "source": [
    "from ib_insync import * \n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import datetime as dt\n",
    "from IPython.display import display, clear_output\n",
    "util.startLoop()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4c53c7fa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<IB connected to 127.0.0.1:7497 clientId=1>"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ib = IB()\n",
    "ib.connect()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "72e72d19",
   "metadata": {},
   "source": [
    "<font color=RED><b><font size=+2>Il mercato deve essere aperto!!!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a974637f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# parameteri\n",
    "sma_s = 50\n",
    "sma_l = 200\n",
    "freq = \"1 min\"\n",
    "units = 10000\n",
    "contract = Forex('EURUSD') # usiamo questo per ottenere i dati\n",
    "ib.qualifyContracts(contract)\n",
    "cfd = CFD(\"EUR\", currency = \"USD\") # usiamo questo per fare trading\n",
    "ib.qualifyContracts(cfd)\n",
    "conID = cfd.conId"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7ba8f945",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Esiste?\n",
    "conID"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a7bd1930",
   "metadata": {},
   "outputs": [],
   "source": [
    "def onBarUpdate(bars, hasNewBar):  \n",
    "    global df, last_bar\n",
    "    \n",
    "    if bars[-1].date > last_bar: \n",
    "        last_bar = bars[-1].date\n",
    "    \n",
    "        df = pd.DataFrame(bars)[[\"date\", \"open\", \"high\", \"low\", \"close\"]].iloc[:-1] \n",
    "        df.set_index(\"date\", inplace = True)\n",
    "        \n",
    "        ######\n",
    "        df = df[[\"close\"]].copy() # per togliere le altre info\n",
    "        df[\"sma_s\"] = df.close.rolling(sma_s).mean()\n",
    "        df[\"sma_l\"] = df.close.rolling(sma_l).mean()\n",
    "        df.dropna(inplace = True)\n",
    "        df[\"position\"] = np.where(df[\"sma_s\"] > df[\"sma_l\"], 1, -1 )\n",
    "        ######\n",
    "        \n",
    "        # Facciamo qui il trading\n",
    "        target = df[\"position\"][-1] * units\n",
    "        execute_trade(target = target)\n",
    "        \n",
    "        # qui mostriamo il df\n",
    "        clear_output(wait=True)\n",
    "        display(df)\n",
    "\n",
    "def execute_trade(target):\n",
    "    global current_pos\n",
    "    try:\n",
    "        current_pos = [pos.position for pos in ib.positions() if pos.contract.conId == conID][0]\n",
    "    except:\n",
    "        current_pos = 0 # nel caso non ci sia perché abbiamo appena iniziato\n",
    "         \n",
    "    trades = target - current_pos # quale trade dobbiamo fare\n",
    "    if trades > 0:\n",
    "        order = MarketOrder(\"BUY\", abs(trades))\n",
    "        trade = ib.placeOrder(cfd, order)  \n",
    "    elif trades < 0:\n",
    "        order = MarketOrder(\"SELL\", abs(trades))\n",
    "        trade = ib.placeOrder(cfd, order)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a07b1d7d",
   "metadata": {},
   "outputs": [],
   "source": [
    "bars = ib.reqHistoricalData(contract,endDateTime=\"\",durationStr='1 D', # lungo a sufficienza per farci stare la media lunga\n",
    "        barSizeSetting=freq, whatToShow='MIDPOINT', useRTH=True, formatDate=2, keepUpToDate=True)\n",
    "last_bar = bars[-1].date\n",
    "bars.updateEvent += onBarUpdate\n",
    "# aspettare la prossima fine di minuto"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39bd1906",
   "metadata": {},
   "outputs": [],
   "source": [
    "ib.cancelHistoricalData(bars)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59d77df6",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "3dc2c766",
   "metadata": {},
   "source": [
    "## Monitorare i trade"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "296f7aad",
   "metadata": {},
   "outputs": [],
   "source": [
    "ib.fills()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93f3ac5a",
   "metadata": {},
   "outputs": [],
   "source": [
    "pd.DataFrame([fs.execution for fs in ib.fills()])[[\"execId\", \"time\", \"side\", \"cumQty\", \"avgPrice\"]].set_index(\"execId\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95d59fa5",
   "metadata": {},
   "outputs": [],
   "source": [
    "pd.DataFrame([fs.commissionReport for fs in ib.fills()])[[\"execId\", \"realizedPNL\"]].set_index(\"execId\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "82e33b94",
   "metadata": {},
   "outputs": [],
   "source": [
    "# parameteri\n",
    "sma_s = 2\n",
    "sma_l = 5 # più corti perché voglio vedere tanti trade per testing\n",
    "freq = \"1 min\"\n",
    "units = 1000\n",
    "contract = Forex('EURUSD') # usiamo questo per ottenere i dati\n",
    "ib.qualifyContracts(contract)\n",
    "cfd = CFD(\"EUR\", currency = \"USD\") # usiamo questo per fare trading\n",
    "ib.qualifyContracts(cfd)\n",
    "conID = cfd.conId"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "11a87dff",
   "metadata": {},
   "outputs": [],
   "source": [
    "def onBarUpdate(bars, hasNewBar):  \n",
    "    global df, last_bar\n",
    "    \n",
    "    if bars[-1].date > last_bar: \n",
    "        last_bar = bars[-1].date\n",
    "    \n",
    "        df = pd.DataFrame(bars)[[\"date\", \"open\", \"high\", \"low\", \"close\"]].iloc[:-1] \n",
    "        df.set_index(\"date\", inplace = True)\n",
    "        \n",
    "        ######\n",
    "        df = df[[\"close\"]].copy() # per togliere le altre info\n",
    "        df[\"sma_s\"] = df.close.rolling(sma_s).mean()\n",
    "        df[\"sma_l\"] = df.close.rolling(sma_l).mean()\n",
    "        df.dropna(inplace = True)\n",
    "        df[\"position\"] = np.where(df[\"sma_s\"] > df[\"sma_l\"], 1, -1 )\n",
    "        ######\n",
    "        \n",
    "        # Facciamo qui il trading\n",
    "        target = df[\"position\"][-1] * units\n",
    "        execute_trade(target = target)\n",
    "        \n",
    "        # qui mostriamo il df\n",
    "        clear_output(wait=True)\n",
    "        display(df)\n",
    "    # NUOVO\n",
    "    else:\n",
    "        try:\n",
    "            trade_reporting() # la eseguiamo ogni tanto, quando non c'è una barra completa, per non disturbare il sistema\n",
    "        except:\n",
    "            pass\n",
    "\n",
    "def execute_trade(target):\n",
    "    global current_pos\n",
    "    try:\n",
    "        current_pos = [pos.position for pos in ib.positions() if pos.contract.conId == conID][0]\n",
    "    except:\n",
    "        current_pos = 0 # nel caso non ci sia perché abbiamo appena iniziato\n",
    "         \n",
    "    trades = target - current_pos # quale trade dobbiamo fare\n",
    "    if trades > 0:\n",
    "        order = MarketOrder(\"BUY\", abs(trades))\n",
    "        trade = ib.placeOrder(cfd, order)  \n",
    "    elif trades < 0:\n",
    "        order = MarketOrder(\"SELL\", abs(trades))\n",
    "        trade = ib.placeOrder(cfd, order)\n",
    "        \n",
    "# NUOVO\n",
    "def trade_reporting():\n",
    "    global report\n",
    "    \n",
    "    fill_df = pd.DataFrame([fs.execution for fs in ib.fills()])[[\"execId\", \"time\", \"side\", \"cumQty\", \"avgPrice\"]].set_index(\"execId\")\n",
    "    profit_df = pd.DataFrame([fs.commissionReport for fs in ib.fills()])[[\"execId\", \"realizedPNL\"]].set_index(\"execId\")\n",
    "    report = pd.concat([fill_df, profit_df], axis = 1).set_index(\"time\").loc[session_start:] # session_start:  per evitare di prendere dati di sessioni precedenti\n",
    "    report = report.groupby(\"time\").agg({\"side\":\"first\", \"cumQty\":\"max\", \"avgPrice\":\"mean\", \"realizedPNL\":\"sum\"}) #  aggreghiamo lo stesso trade che potrebbe venire spezzato\n",
    "    report[\"cumPNL\"] = report.realizedPNL.cumsum()\n",
    "        \n",
    "    clear_output(wait=True)\n",
    "    display(df, report)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "5d3715f3",
   "metadata": {},
   "outputs": [],
   "source": [
    "session_start = pd.to_datetime(dt.datetime.utcnow()).tz_localize(\"utc\") # session_start:  per evitare di prendere dati di sessioni precedenti\n",
    "bars = ib.reqHistoricalData(contract, endDateTime='', durationStr='1 D',\n",
    "        barSizeSetting=freq, whatToShow='MIDPOINT', useRTH=True, formatDate=2, keepUpToDate=True)\n",
    "last_bar = bars[-1].date\n",
    "bars.updateEvent += onBarUpdate\n",
    "# ATTENZIONE che nel report c'è il tempo effettivo del trade e nel df sopra la chiusura delle barre invece"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d43b6fdd",
   "metadata": {},
   "outputs": [],
   "source": [
    "ib.cancelHistoricalData(bars) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ddbe2ec9",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6d0e03f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Per fermare la sessione di trading:\n",
    "# - a un tempo preciso\n",
    "# - a un limite di guadagno o perdita"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "3f8cd849",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>close</th>\n",
       "      <th>sma_s</th>\n",
       "      <th>sma_l</th>\n",
       "      <th>position</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>date</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2024-09-29 21:19:00+00:00</th>\n",
       "      <td>1.116085</td>\n",
       "      <td>1.116060</td>\n",
       "      <td>1.116069</td>\n",
       "      <td>-1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-09-29 21:20:00+00:00</th>\n",
       "      <td>1.116145</td>\n",
       "      <td>1.116115</td>\n",
       "      <td>1.116097</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-09-29 21:21:00+00:00</th>\n",
       "      <td>1.116030</td>\n",
       "      <td>1.116087</td>\n",
       "      <td>1.116073</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-09-29 21:22:00+00:00</th>\n",
       "      <td>1.116095</td>\n",
       "      <td>1.116062</td>\n",
       "      <td>1.116078</td>\n",
       "      <td>-1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-09-29 21:23:00+00:00</th>\n",
       "      <td>1.116130</td>\n",
       "      <td>1.116113</td>\n",
       "      <td>1.116097</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-09-30 14:16:00+00:00</th>\n",
       "      <td>1.116425</td>\n",
       "      <td>1.116400</td>\n",
       "      <td>1.116266</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-09-30 14:17:00+00:00</th>\n",
       "      <td>1.116415</td>\n",
       "      <td>1.116420</td>\n",
       "      <td>1.116340</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-09-30 14:18:00+00:00</th>\n",
       "      <td>1.116265</td>\n",
       "      <td>1.116340</td>\n",
       "      <td>1.116378</td>\n",
       "      <td>-1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-09-30 14:19:00+00:00</th>\n",
       "      <td>1.116175</td>\n",
       "      <td>1.116220</td>\n",
       "      <td>1.116331</td>\n",
       "      <td>-1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-09-30 14:20:00+00:00</th>\n",
       "      <td>1.116045</td>\n",
       "      <td>1.116110</td>\n",
       "      <td>1.116265</td>\n",
       "      <td>-1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>1022 rows × 4 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                              close     sma_s     sma_l  position\n",
       "date                                                             \n",
       "2024-09-29 21:19:00+00:00  1.116085  1.116060  1.116069        -1\n",
       "2024-09-29 21:20:00+00:00  1.116145  1.116115  1.116097         1\n",
       "2024-09-29 21:21:00+00:00  1.116030  1.116087  1.116073         1\n",
       "2024-09-29 21:22:00+00:00  1.116095  1.116062  1.116078        -1\n",
       "2024-09-29 21:23:00+00:00  1.116130  1.116113  1.116097         1\n",
       "...                             ...       ...       ...       ...\n",
       "2024-09-30 14:16:00+00:00  1.116425  1.116400  1.116266         1\n",
       "2024-09-30 14:17:00+00:00  1.116415  1.116420  1.116340         1\n",
       "2024-09-30 14:18:00+00:00  1.116265  1.116340  1.116378        -1\n",
       "2024-09-30 14:19:00+00:00  1.116175  1.116220  1.116331        -1\n",
       "2024-09-30 14:20:00+00:00  1.116045  1.116110  1.116265        -1\n",
       "\n",
       "[1022 rows x 4 columns]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>side</th>\n",
       "      <th>cumQty</th>\n",
       "      <th>avgPrice</th>\n",
       "      <th>realizedPNL</th>\n",
       "      <th>cumPNL</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>time</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2024-09-30 14:12:06+00:00</th>\n",
       "      <td>SLD</td>\n",
       "      <td>1000.0</td>\n",
       "      <td>1.11610</td>\n",
       "      <td>0.00000</td>\n",
       "      <td>0.00000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-09-30 14:15:05+00:00</th>\n",
       "      <td>BOT</td>\n",
       "      <td>2000.0</td>\n",
       "      <td>1.11645</td>\n",
       "      <td>-4.35002</td>\n",
       "      <td>-4.35002</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-09-30 14:19:05+00:00</th>\n",
       "      <td>SLD</td>\n",
       "      <td>2000.0</td>\n",
       "      <td>1.11610</td>\n",
       "      <td>-2.35000</td>\n",
       "      <td>-6.70002</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2024-09-30 14:21:12+00:00</th>\n",
       "      <td>BOT</td>\n",
       "      <td>1000.0</td>\n",
       "      <td>1.11605</td>\n",
       "      <td>-1.95000</td>\n",
       "      <td>-8.65002</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                          side  cumQty  avgPrice  realizedPNL   cumPNL\n",
       "time                                                                  \n",
       "2024-09-30 14:12:06+00:00  SLD  1000.0   1.11610      0.00000  0.00000\n",
       "2024-09-30 14:15:05+00:00  BOT  2000.0   1.11645     -4.35002 -4.35002\n",
       "2024-09-30 14:19:05+00:00  SLD  2000.0   1.11610     -2.35000 -6.70002\n",
       "2024-09-30 14:21:12+00:00  BOT  1000.0   1.11605     -1.95000 -8.65002"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Finito!\n"
     ]
    }
   ],
   "source": [
    "from datetime import timedelta\n",
    "end_time = dt.datetime.utcnow() + timedelta(minutes=10)  \n",
    "while True:\n",
    "    ib.sleep(5) \n",
    "    if dt.datetime.utcnow() >= end_time: \n",
    "        execute_trade(target = 0) # chiudo tutto\n",
    "        ib.cancelHistoricalData(bars) \n",
    "        ib.sleep(10)\n",
    "        try:\n",
    "            trade_reporting() \n",
    "        except:\n",
    "            pass\n",
    "        print(\"Finito!\")\n",
    "        ib.disconnect()\n",
    "        break\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d80e4709",
   "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.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
