Toxi
  • Welcome to Toxi
    • 👋 Welcome to Toxi!
    • Fast Links
  • Toxi Integration (API)
    • Trading API
      • TypeScript Example
      • Python Example
    • Data API
  • What is Toxi
    • What is Toxi and how it works
    • Core Features of Toxi
  • Getting Started with Toxi
    • Depositing $SOL into your Wallet
    • Funding Your Toxi Wallet
    • Make your first trade
    • Set up first copytrading wallet
  • Trading on Toxi
    • Basic Trading
    • Portfolio Management
    • Managing Positions
  • Copytrading
    • Understanding Copy Trading
    • Setting Up Copy Trading
    • Managing and Adjusting Copy Trades
  • Settings
    • Settings
  • Security & Self-Custody
    • Security & Self-Custody
    • Self-Custodial Wallets
    • Private Key Encryption
    • Security Tips for Using Toxi
  • Referral Program
    • Referral Program
    • How to Earn with Toxi Referrals
    • Tracking Referral Earnings
    • Referral Rewards and Fees
  • FAQ
    • FAQ
Powered by GitBook
On this page
  1. Toxi Integration (API)
  2. Trading API

Python Example

This page contains a Toxi Bot integration example in Python

PreviousTypeScript ExampleNextData API

Last updated 2 months ago

The code below is simply an interpretation of a TypeScript code from the previous page. We strongly recommend you reading the previous page even if you're not familiar with TypeScript because it contains some useful language-agnostic explanations.

The following code presents a ToxiBotClient class that acts as an abstraction for communicating with Toxi Bot via npm package.

# pip install telethon
from telethon import TelegramClient
from telethon.sessions import StringSession
from typing import Optional, Any
import asyncio


class ToxiBotClient:
    bot_username = "@toxi_solana_bot"
    _bot_chat_id: Optional[int] = None

    def __init__(self, api_id: int, api_hash: str, session_id: str):
        self._client = TelegramClient(
            StringSession(session_id), api_id, api_hash, connection_retries=5
        )

    async def connect(self) -> None:
        if not await self._client.is_connected():
            await self._client.connect()

    async def send_message_to_bot(self, message: str) -> Any:
        chat_id = self._bot_chat_id or self.bot_username
        msg = await self._client.send_message(chat_id, message)
        if not self._bot_chat_id and msg.chat_id:
            self._bot_chat_id = msg.chat_id
        return msg

    async def send_buy_command(self, token_mint: str, buy_amount: float) -> Any:
        return await self.send_message_to_bot(f"/buy {token_mint} {buy_amount}")

    async def send_sell_command(self, token_mint: str, sell_percentage: int) -> Any:
        return await self.send_message_to_bot(f"/sell {token_mint} {sell_percentage}%")

    @classmethod
    async def create_new_session(
        cls,
        api_id: int,
        api_hash: str,
        phone_number: str,
        password: Optional[str] = None,
    ) -> str:
        client = TelegramClient(StringSession(), api_id, api_hash, connection_retries=5)
        await client.start(
            phone=phone_number,
            password=password,
            code_callback=lambda: input(f"Enter Telegram code for {phone_number}: "),
        )
        return client.session.save()

Usage Example

async def main():
    # Create new session
    session_str = await ToxiBotClient.create_new_session(
        api_id=YOUR_API_ID,
        api_hash="YOUR_API_HASH",
        phone_number="+1234567890",
        password="2FA_PASSWORD_IF_ANY",
    )
    print("Session string:", session_str)

    # Initialize client with existing session
    client = ToxiBotClient(
        api_id=YOUR_API_ID, api_hash="YOUR_API_HASH", session_id=session_str
    )

    await client.connect()

    # Send commands
    await client.send_buy_command("TOKEN_MINT_ADDRESS", 0.5)
    await client.send_sell_command("TOKEN_MINT_ADDRESS", 50)
telethon