├── snipe-list.txt ├── storage ├── whitelist.txt └── blacklist.txt ├── listeners ├── index.ts └── listeners.ts ├── readme ├── wsol.png └── output.png ├── .prettierrc ├── helpers ├── promises.ts ├── index.ts ├── wallet.ts ├── token.ts ├── logger.ts ├── market.ts ├── liquidity.ts └── constants.ts ├── transactions ├── index.ts ├── transaction-executor.interface.ts ├── default-transaction-executor.ts ├── warp-transaction-executor.ts └── jito-rpc-transaction-executor.ts ├── cache ├── index.ts ├── snipe-list.cache.ts ├── blacklist.cache.ts ├── pool.cache.ts ├── market.cache.ts ├── whitelist.cache.ts └── technical-analysis.cache.ts ├── filters ├── index.ts ├── burn.filter.ts ├── pool-size.filter.ts ├── blacklist.filter.ts ├── renounced.filter.ts ├── mutable.filter.ts ├── pool-filters.ts └── holders.ts ├── package.json ├── .env.copy ├── .gitignore ├── messaging.ts ├── technicalAnalysis.ts ├── README.md ├── tradeSignals.ts ├── index.ts ├── tsconfig.json ├── bot.ts └── LICENSE.md /snipe-list.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /storage/whitelist.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /listeners/index.ts: -------------------------------------------------------------------------------- 1 | export * from './listeners'; 2 | -------------------------------------------------------------------------------- /readme/wsol.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kapocius/warp-trading-bot/HEAD/readme/wsol.png -------------------------------------------------------------------------------- /readme/output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kapocius/warp-trading-bot/HEAD/readme/output.png -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all", 4 | "printWidth": 120 5 | } -------------------------------------------------------------------------------- /helpers/promises.ts: -------------------------------------------------------------------------------- 1 | export const sleep = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms)); 2 | -------------------------------------------------------------------------------- /transactions/index.ts: -------------------------------------------------------------------------------- 1 | export * from './default-transaction-executor'; 2 | export * from './transaction-executor.interface'; 3 | -------------------------------------------------------------------------------- /cache/index.ts: -------------------------------------------------------------------------------- 1 | export * from './market.cache'; 2 | export * from './pool.cache'; 3 | export * from './snipe-list.cache'; 4 | export * from './blacklist.cache'; 5 | -------------------------------------------------------------------------------- /storage/blacklist.txt: -------------------------------------------------------------------------------- 1 | 8N57pYk1SoHkBZcPMhyJMJCLLfEyHMq3SqYn63W9RoVG 2 | GH8GPjSX9XNvxsVaJHg9KfEXVovqtiY5pyhu8vYrwjTb 3 | BpHihYFRjTywHg6J2KmL8yWGsAQB9Ab2W3bGQyLBzbek 4 | TSLvdd1pWpHVjahSpsvCXUbgwsL3JAcvokwaKt1eokM -------------------------------------------------------------------------------- /helpers/index.ts: -------------------------------------------------------------------------------- 1 | export * from './market'; 2 | export * from './liquidity'; 3 | export * from './logger'; 4 | export * from './constants'; 5 | export * from './token'; 6 | export * from './wallet'; 7 | export * from './promises' 8 | -------------------------------------------------------------------------------- /filters/index.ts: -------------------------------------------------------------------------------- 1 | export * from './burn.filter'; 2 | export * from './mutable.filter'; 3 | export * from './pool-filters'; 4 | export * from './pool-size.filter'; 5 | export * from './renounced.filter'; 6 | export * from './blacklist.filter'; 7 | -------------------------------------------------------------------------------- /transactions/transaction-executor.interface.ts: -------------------------------------------------------------------------------- 1 | import { BlockhashWithExpiryBlockHeight, Keypair, VersionedTransaction } from '@solana/web3.js'; 2 | 3 | export interface TransactionExecutor { 4 | executeAndConfirm( 5 | transaction: VersionedTransaction, 6 | payer: Keypair, 7 | latestBlockHash: BlockhashWithExpiryBlockHeight, 8 | ): Promise<{ confirmed: boolean; signature?: string, error?: string }>; 9 | } 10 | -------------------------------------------------------------------------------- /helpers/wallet.ts: -------------------------------------------------------------------------------- 1 | import { Keypair } from '@solana/web3.js'; 2 | import bs58 from 'bs58'; 3 | 4 | export function getWallet(wallet: string): Keypair { 5 | // most likely someone pasted the private key in binary format 6 | if (wallet.startsWith('[')) { 7 | return Keypair.fromSecretKey(JSON.parse(wallet)); 8 | } 9 | 10 | // most likely someone pasted base58 encoded private key 11 | return Keypair.fromSecretKey(bs58.decode(wallet)); 12 | } 13 | -------------------------------------------------------------------------------- /helpers/token.ts: -------------------------------------------------------------------------------- 1 | import { Token } from '@raydium-io/raydium-sdk'; 2 | import { TOKEN_PROGRAM_ID } from '@solana/spl-token'; 3 | import { PublicKey } from '@solana/web3.js'; 4 | 5 | export function getToken(token: string) { 6 | switch (token) { 7 | case 'WSOL': { 8 | return Token.WSOL; 9 | } 10 | case 'USDC': { 11 | return new Token( 12 | TOKEN_PROGRAM_ID, 13 | new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), 14 | 6, 15 | 'USDC', 16 | 'USDC', 17 | ); 18 | } 19 | default: { 20 | throw new Error(`Unsupported quote mint "${token}". Supported values are USDC and WSOL`); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /helpers/logger.ts: -------------------------------------------------------------------------------- 1 | import pino from 'pino'; 2 | 3 | const transport = pino.transport({ 4 | targets: [ 5 | { 6 | level: 'trace', 7 | target: 'pino-pretty', 8 | options: { 9 | destination: "./logs/activity.log", 10 | colorize: false, 11 | colorizeObjects: false, 12 | translateTime: "SYS:yyyy-mm-dd HH:MM:ss" 13 | }, 14 | }, 15 | { 16 | level: 'trace', 17 | target: 'pino-pretty', 18 | options: {}, 19 | }, 20 | ] 21 | }); 22 | 23 | export const logger = pino( 24 | { 25 | level: 'info', 26 | redact: ['poolKeys'], 27 | serializers: { 28 | error: pino.stdSerializers.err, 29 | }, 30 | base: undefined, 31 | }, 32 | transport, 33 | ); 34 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "warp-solana-bot", 3 | "author": "Filip Dundjer", 4 | "homepage": "https://warp.id", 5 | "version": "2.0.2", 6 | "scripts": { 7 | "start": "ts-node index.ts", 8 | "tsc": "tsc --noEmit" 9 | }, 10 | "dependencies": { 11 | "@metaplex-foundation/mpl-token-metadata": "^3.2.1", 12 | "@raydium-io/raydium-sdk": "^1.3.1-beta.47", 13 | "@solana/spl-token": "^0.4.0", 14 | "@solana/web3.js": "^1.89.1", 15 | "async-mutex": "^0.5.0", 16 | "bigint-buffer": "^1.1.5", 17 | "bn.js": "^5.2.1", 18 | "bs58": "^5.0.0", 19 | "dotenv": "^16.4.1", 20 | "npm": "^10.5.2", 21 | "pino": "^8.18.0", 22 | "pino-pretty": "^10.3.1", 23 | "pino-std-serializers": "^6.2.2", 24 | "telegraf": "^4.16.3" 25 | }, 26 | "devDependencies": { 27 | "@types/bn.js": "^5.1.5", 28 | "prettier": "^3.2.4", 29 | "ts-node": "^10.9.2", 30 | "typescript": "^5.3.3" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /helpers/market.ts: -------------------------------------------------------------------------------- 1 | import { Commitment, Connection, PublicKey } from '@solana/web3.js'; 2 | import { GetStructureSchema, MARKET_STATE_LAYOUT_V3, publicKey, struct } from '@raydium-io/raydium-sdk'; 3 | 4 | export const MINIMAL_MARKET_STATE_LAYOUT_V3 = struct([publicKey('eventQueue'), publicKey('bids'), publicKey('asks')]); 5 | export type MinimalMarketStateLayoutV3 = typeof MINIMAL_MARKET_STATE_LAYOUT_V3; 6 | export type MinimalMarketLayoutV3 = GetStructureSchema; 7 | 8 | export async function getMinimalMarketV3( 9 | connection: Connection, 10 | marketId: PublicKey, 11 | commitment?: Commitment, 12 | ): Promise { 13 | const marketInfo = await connection.getAccountInfo(marketId, { 14 | commitment, 15 | dataSlice: { 16 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('eventQueue'), 17 | length: 32 * 3, 18 | }, 19 | }); 20 | 21 | return MINIMAL_MARKET_STATE_LAYOUT_V3.decode(marketInfo!.data); 22 | } 23 | -------------------------------------------------------------------------------- /cache/snipe-list.cache.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | import { logger, SNIPE_LIST_REFRESH_INTERVAL } from '../helpers'; 4 | 5 | export class SnipeListCache { 6 | private snipeList: string[] = []; 7 | private fileLocation = path.join(__dirname, '../snipe-list.txt'); 8 | 9 | constructor() { 10 | setInterval(() => this.loadSnipeList(), SNIPE_LIST_REFRESH_INTERVAL); 11 | } 12 | 13 | public init() { 14 | this.loadSnipeList(); 15 | } 16 | 17 | public isInList(mint: string) { 18 | return this.snipeList.includes(mint); 19 | } 20 | 21 | private loadSnipeList() { 22 | logger.trace(`Refreshing snipe list...`); 23 | 24 | const count = this.snipeList.length; 25 | const data = fs.readFileSync(this.fileLocation, 'utf-8'); 26 | this.snipeList = data 27 | .split('\n') 28 | .map((a) => a.trim()) 29 | .filter((a) => a); 30 | 31 | if (this.snipeList.length != count) { 32 | logger.info(`Loaded snipe list: ${this.snipeList.length}`); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /cache/blacklist.cache.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | import { logger, BLACKLIST_REFRESH_INTERVAL } from '../helpers'; 4 | 5 | export class BlacklistCache { 6 | private blacklist: string[] = []; 7 | private fileLocation = path.join(__dirname, '../storage/blacklist.txt'); 8 | 9 | constructor() { 10 | setInterval(() => this.loadBlacklist(), BLACKLIST_REFRESH_INTERVAL); 11 | } 12 | 13 | public init() { 14 | this.loadBlacklist(); 15 | } 16 | 17 | public isInList(mint: string) { 18 | return this.blacklist.includes(mint); 19 | } 20 | 21 | private loadBlacklist() { 22 | logger.trace(`Refreshing blacklist...`); 23 | 24 | const count = this.blacklist.length; 25 | const data = fs.readFileSync(this.fileLocation, 'utf-8'); 26 | this.blacklist = data 27 | .split('\n') 28 | .map((a) => a.trim()) 29 | .filter((a) => a); 30 | 31 | if (this.blacklist.length != count) { 32 | logger.info(`Loaded blacklist list: ${this.blacklist.length}`); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /cache/pool.cache.ts: -------------------------------------------------------------------------------- 1 | import { LiquidityStateV4 } from '@raydium-io/raydium-sdk'; 2 | import { logger } from '../helpers'; 3 | 4 | export class PoolCache { 5 | private readonly keys: Map = new Map< 6 | string, 7 | { id: string; state: LiquidityStateV4, sold: boolean } 8 | >(); 9 | 10 | public save(id: string, state: LiquidityStateV4) { 11 | if (!this.keys.has(state.baseMint.toString())) { 12 | logger.trace(`Caching new pool for mint: ${state.baseMint.toString()}`); 13 | this.keys.set(state.baseMint.toString(), { id, state, sold: false }); 14 | } 15 | } 16 | 17 | public async get(mint: string): Promise<{ id: string; state: LiquidityStateV4, sold: boolean }> { 18 | return this.keys.get(mint)!; 19 | } 20 | 21 | public async markAsSold(mint: string) { 22 | //important, so we don't try to sell the same pool twice 23 | const pool = this.keys.get(mint); 24 | if (pool) { 25 | pool.sold = true; 26 | this.keys.set(mint, pool); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /filters/burn.filter.ts: -------------------------------------------------------------------------------- 1 | import { Filter, FilterResult } from './pool-filters'; 2 | import { Connection } from '@solana/web3.js'; 3 | import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; 4 | import { logger } from '../helpers'; 5 | 6 | export class BurnFilter implements Filter { 7 | private cachedResult: FilterResult | undefined = undefined; 8 | 9 | constructor(private readonly connection: Connection) {} 10 | 11 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 12 | if (this.cachedResult) { 13 | return this.cachedResult; 14 | } 15 | 16 | try { 17 | const amount = await this.connection.getTokenSupply(poolKeys.lpMint, this.connection.commitment); 18 | const burned = amount.value.uiAmount === 0; 19 | const result = { ok: burned, message: burned ? undefined : "Burned -> Creator didn't burn LP" }; 20 | 21 | if (result.ok) { 22 | this.cachedResult = result; 23 | } 24 | 25 | return result; 26 | } catch (e: any) { 27 | if (e.code == -32602) { 28 | return { ok: true }; 29 | } 30 | 31 | logger.error({ mint: poolKeys.baseMint }, `Failed to check if LP is burned`); 32 | } 33 | 34 | return { ok: false, message: 'Failed to check if LP is burned' }; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /transactions/default-transaction-executor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BlockhashWithExpiryBlockHeight, 3 | Connection, 4 | Keypair, 5 | Transaction, 6 | VersionedTransaction, 7 | } from '@solana/web3.js'; 8 | import { TransactionExecutor } from './transaction-executor.interface'; 9 | import { logger } from '../helpers'; 10 | 11 | export class DefaultTransactionExecutor implements TransactionExecutor { 12 | constructor(private readonly connection: Connection) { } 13 | 14 | public async executeAndConfirm( 15 | transaction: VersionedTransaction, 16 | payer: Keypair, 17 | latestBlockhash: BlockhashWithExpiryBlockHeight, 18 | ): Promise<{ confirmed: boolean; signature?: string, error?: string }> { 19 | logger.debug('Executing transaction...'); 20 | const signature = await this.execute(transaction); 21 | 22 | logger.debug({ signature }, 'Confirming transaction...'); 23 | return this.confirm(signature, latestBlockhash); 24 | } 25 | 26 | private async execute(transaction: Transaction | VersionedTransaction) { 27 | return this.connection.sendRawTransaction(transaction.serialize(), { 28 | preflightCommitment: this.connection.commitment, 29 | }); 30 | } 31 | 32 | private async confirm(signature: string, latestBlockhash: BlockhashWithExpiryBlockHeight) { 33 | const confirmation = await this.connection.confirmTransaction( 34 | { 35 | signature, 36 | lastValidBlockHeight: latestBlockhash.lastValidBlockHeight, 37 | blockhash: latestBlockhash.blockhash, 38 | }, 39 | this.connection.commitment, 40 | ); 41 | 42 | return { confirmed: !confirmation.value.err, signature }; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /filters/pool-size.filter.ts: -------------------------------------------------------------------------------- 1 | import { Filter, FilterResult } from './pool-filters'; 2 | import { LiquidityPoolKeysV4, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 3 | import { Connection } from '@solana/web3.js'; 4 | import { logger } from '../helpers'; 5 | 6 | export class PoolSizeFilter implements Filter { 7 | constructor( 8 | private readonly connection: Connection, 9 | private readonly quoteToken: Token, 10 | private readonly minPoolSize: TokenAmount, 11 | private readonly maxPoolSize: TokenAmount, 12 | ) {} 13 | 14 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 15 | try { 16 | const response = await this.connection.getTokenAccountBalance(poolKeys.quoteVault, this.connection.commitment); 17 | const poolSize = new TokenAmount(this.quoteToken, response.value.amount, true); 18 | let inRange = true; 19 | 20 | if (!this.maxPoolSize?.isZero()) { 21 | inRange = poolSize.raw.lte(this.maxPoolSize.raw); 22 | 23 | if (!inRange) { 24 | return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} > ${this.maxPoolSize.toFixed()}` }; 25 | } 26 | } 27 | 28 | if (!this.minPoolSize?.isZero()) { 29 | inRange = poolSize.raw.gte(this.minPoolSize.raw); 30 | 31 | if (!inRange) { 32 | return { ok: false, message: `PoolSize -> Pool size ${poolSize.toFixed()} < ${this.minPoolSize.toFixed()}` }; 33 | } 34 | } 35 | 36 | return { ok: inRange }; 37 | } catch (error) { 38 | logger.error({ mint: poolKeys.baseMint }, `Failed to check pool size`); 39 | } 40 | 41 | return { ok: false, message: 'PoolSize -> Failed to check pool size' }; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /helpers/liquidity.ts: -------------------------------------------------------------------------------- 1 | import { PublicKey } from '@solana/web3.js'; 2 | import { Liquidity, LiquidityPoolKeys, LiquidityStateV4, MAINNET_PROGRAM_ID, Market } from '@raydium-io/raydium-sdk'; 3 | import { MinimalMarketLayoutV3 } from './market'; 4 | 5 | export function createPoolKeys( 6 | id: PublicKey, 7 | accountData: LiquidityStateV4, 8 | minimalMarketLayoutV3: MinimalMarketLayoutV3, 9 | ): LiquidityPoolKeys { 10 | return { 11 | id, 12 | baseMint: accountData.baseMint, 13 | quoteMint: accountData.quoteMint, 14 | lpMint: accountData.lpMint, 15 | baseDecimals: accountData.baseDecimal.toNumber(), 16 | quoteDecimals: accountData.quoteDecimal.toNumber(), 17 | lpDecimals: 5, 18 | version: 4, 19 | programId: MAINNET_PROGRAM_ID.AmmV4, 20 | authority: Liquidity.getAssociatedAuthority({ 21 | programId: MAINNET_PROGRAM_ID.AmmV4, 22 | }).publicKey, 23 | openOrders: accountData.openOrders, 24 | targetOrders: accountData.targetOrders, 25 | baseVault: accountData.baseVault, 26 | quoteVault: accountData.quoteVault, 27 | marketVersion: 3, 28 | marketProgramId: accountData.marketProgramId, 29 | marketId: accountData.marketId, 30 | marketAuthority: Market.getAssociatedAuthority({ 31 | programId: accountData.marketProgramId, 32 | marketId: accountData.marketId, 33 | }).publicKey, 34 | marketBaseVault: accountData.baseVault, 35 | marketQuoteVault: accountData.quoteVault, 36 | marketBids: minimalMarketLayoutV3.bids, 37 | marketAsks: minimalMarketLayoutV3.asks, 38 | marketEventQueue: minimalMarketLayoutV3.eventQueue, 39 | withdrawQueue: accountData.withdrawQueue, 40 | lpVault: accountData.lpVault, 41 | lookupTableAccount: PublicKey.default, 42 | }; 43 | } 44 | -------------------------------------------------------------------------------- /filters/blacklist.filter.ts: -------------------------------------------------------------------------------- 1 | import { Filter, FilterResult } from './pool-filters'; 2 | import { Connection } from '@solana/web3.js'; 3 | import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; 4 | import { getPdaMetadataKey } from '@raydium-io/raydium-sdk'; 5 | import { MetadataAccountData, MetadataAccountDataArgs, getMetadataAccountDataSerializer } from '@metaplex-foundation/mpl-token-metadata'; 6 | import { Serializer } from '@metaplex-foundation/umi/serializers'; 7 | import { logger } from '../helpers'; 8 | import { BlacklistCache } from '../cache/blacklist.cache'; 9 | 10 | export class BlacklistFilter implements Filter { 11 | 12 | constructor( 13 | private readonly connection: Connection, 14 | private readonly blacklistCache: BlacklistCache 15 | ) { } 16 | 17 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 18 | try { 19 | 20 | let metadataSerializer: Serializer = getMetadataAccountDataSerializer(); 21 | 22 | const metadataPDA = getPdaMetadataKey(poolKeys.baseMint); 23 | const metadataAccount = await this.connection.getAccountInfo(metadataPDA.publicKey, this.connection.commitment); 24 | 25 | if (!metadataAccount?.data) { 26 | return { ok: false, message: 'Blacklist -> Failed to fetch account data' }; 27 | } 28 | 29 | const deserialize = metadataSerializer.deserialize(metadataAccount.data); 30 | 31 | if (this.blacklistCache.isInList(deserialize[0].updateAuthority.toString())) { 32 | return { ok: false, message: `Blacklist -> ${deserialize[0].updateAuthority.toString()} fuck this guy!` }; 33 | } 34 | 35 | return { ok: true, message: undefined }; 36 | 37 | } catch (e) { 38 | logger.error({ mint: poolKeys.baseMint }, `Blacklist -> Failed to check blacklist`); 39 | } 40 | 41 | return { 42 | ok: false, 43 | message: `Blacklist -> Failed to check for cringe`, 44 | }; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /.env.copy: -------------------------------------------------------------------------------- 1 | # Wallet 2 | PRIVATE_KEY= 3 | 4 | # Connection 5 | RPC_ENDPOINT=https://api.mainnet-beta.solana.com 6 | RPC_WEBSOCKET_ENDPOINT=wss://api.mainnet-beta.solana.com 7 | COMMITMENT_LEVEL=confirmed 8 | 9 | # Bot 10 | LOG_LEVEL=trace 11 | MAX_TOKENS_AT_THE_TIME=1 12 | PRE_LOAD_EXISTING_MARKETS=false 13 | CACHE_NEW_MARKETS=false 14 | # default or warp or jito 15 | TRANSACTION_EXECUTOR=default 16 | # if using default executor, fee below will be applied 17 | COMPUTE_UNIT_LIMIT=101337 18 | COMPUTE_UNIT_PRICE=421197 19 | # if using warp or jito executor, fee below will be applied 20 | CUSTOM_FEE=0.006 21 | MAX_LAG=0 22 | USE_TA=false 23 | USE_TELEGRAM=true 24 | 25 | # Buy 26 | QUOTE_MINT=WSOL 27 | QUOTE_AMOUNT=0.001 28 | AUTO_BUY_DELAY=0 29 | MAX_BUY_RETRIES=10 30 | BUY_SLIPPAGE=20 31 | BUY_SIGNAL_TIME_TO_WAIT=1200000 32 | BUY_SIGNAL_PRICE_INTERVAL=500 33 | BUY_SIGNAL_FRACTION_TIME_TO_WAIT=50 34 | BUY_SIGNAL_LOW_VOLUME_THRESHOLD=100 35 | 36 | # Sell 37 | AUTO_SELL=true 38 | MAX_SELL_RETRIES=10 39 | AUTO_SELL_DELAY=0 40 | PRICE_CHECK_INTERVAL=2000 41 | PRICE_CHECK_DURATION=600000 42 | TAKE_PROFIT=40 43 | STOP_LOSS=20 44 | TRAILING_STOP_LOSS=true 45 | SKIP_SELLING_IF_LOST_MORE_THAN=90 46 | SELL_SLIPPAGE=20 47 | AUTO_SELL_WITHOUT_SELL_SIGNAL=true 48 | KEEP_5_PERCENT_FOR_MOONSHOTS=false 49 | 50 | # Filters 51 | USE_SNIPE_LIST=false 52 | SNIPE_LIST_REFRESH_INTERVAL=30000 53 | FILTER_CHECK_DURATION=60000 54 | FILTER_CHECK_INTERVAL=2000 55 | CONSECUTIVE_FILTER_MATCHES=3 56 | CHECK_IF_MUTABLE=false 57 | CHECK_IF_SOCIALS=true 58 | CHECK_IF_MINT_IS_RENOUNCED=true 59 | CHECK_IF_FREEZABLE=false 60 | CHECK_IF_BURNED=true 61 | MIN_POOL_SIZE=5 62 | MAX_POOL_SIZE=50 63 | BLACKLIST_REFRESH_INTERVAL=600000 64 | WHITELIST_REFRESH_INTERVAL=600000 65 | 66 | # Holders 67 | CHECK_HOLDERS=true 68 | HOLDER_MIN_AMOUNT=10 69 | CHECK_TOKEN_DISTRIBUTION=true 70 | TOP_HOLDER_MAX_PERCENTAGE=35 71 | TOP_10_PERCENTAGE_CHECK=true 72 | TOP_10_MAX_PERCENTAGE=55 73 | CHECK_ABNORMAL_DISTRIBUTION=true 74 | ABNORMAL_HOLDER_NR=3 75 | 76 | # Technical analysis 77 | MACD_SHORT_PERIOD=12 78 | MACD_LONG_PERIOD=26 79 | MACD_SIGNAL_PERIOD=9 80 | 81 | RSI_PERIOD=14 82 | 83 | #Telegram 84 | TELEGRAM_BOT_TOKEN= 85 | TELEGRAM_CHAT_ID= 86 | -------------------------------------------------------------------------------- /cache/market.cache.ts: -------------------------------------------------------------------------------- 1 | import { Connection, PublicKey } from '@solana/web3.js'; 2 | import { getMinimalMarketV3, logger, MINIMAL_MARKET_STATE_LAYOUT_V3, MinimalMarketLayoutV3 } from '../helpers'; 3 | import { MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from '@raydium-io/raydium-sdk'; 4 | 5 | export class MarketCache { 6 | private readonly keys: Map = new Map(); 7 | constructor(private readonly connection: Connection) {} 8 | 9 | async init(config: { quoteToken: Token }) { 10 | logger.debug({}, `Fetching all existing ${config.quoteToken.symbol} markets...`); 11 | 12 | const accounts = await this.connection.getProgramAccounts(MAINNET_PROGRAM_ID.OPENBOOK_MARKET, { 13 | commitment: this.connection.commitment, 14 | dataSlice: { 15 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('eventQueue'), 16 | length: MINIMAL_MARKET_STATE_LAYOUT_V3.span, 17 | }, 18 | filters: [ 19 | { dataSize: MARKET_STATE_LAYOUT_V3.span }, 20 | { 21 | memcmp: { 22 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'), 23 | bytes: config.quoteToken.mint.toBase58(), 24 | }, 25 | }, 26 | ], 27 | }); 28 | 29 | for (const account of accounts) { 30 | const market = MINIMAL_MARKET_STATE_LAYOUT_V3.decode(account.account.data); 31 | this.keys.set(account.pubkey.toString(), market); 32 | } 33 | 34 | logger.debug({}, `Cached ${this.keys.size} markets`); 35 | } 36 | 37 | public save(marketId: string, keys: MinimalMarketLayoutV3) { 38 | if (!this.keys.has(marketId)) { 39 | logger.trace({}, `Caching new market: ${marketId}`); 40 | this.keys.set(marketId, keys); 41 | } 42 | } 43 | 44 | public async get(marketId: string): Promise { 45 | if (this.keys.has(marketId)) { 46 | return this.keys.get(marketId)!; 47 | } 48 | 49 | logger.trace({}, `Fetching new market keys for ${marketId}`); 50 | const market = await this.fetch(marketId); 51 | this.keys.set(marketId, market); 52 | return market; 53 | } 54 | 55 | private fetch(marketId: string): Promise { 56 | return getMinimalMarketV3(this.connection, new PublicKey(marketId), this.connection.commitment); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /transactions/warp-transaction-executor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BlockhashWithExpiryBlockHeight, 3 | Keypair, 4 | PublicKey, 5 | SystemProgram, 6 | TransactionMessage, 7 | VersionedTransaction, 8 | } from '@solana/web3.js'; 9 | import { TransactionExecutor } from './transaction-executor.interface'; 10 | import { logger } from '../helpers'; 11 | import axios, { AxiosError } from 'axios'; 12 | import bs58 from 'bs58'; 13 | import { Currency, CurrencyAmount } from '@raydium-io/raydium-sdk'; 14 | 15 | export class WarpTransactionExecutor implements TransactionExecutor { 16 | private readonly warpFeeWallet = new PublicKey('WARPzUMPnycu9eeCZ95rcAUxorqpBqHndfV3ZP5FSyS'); 17 | 18 | constructor(private readonly warpFee: string) {} 19 | 20 | public async executeAndConfirm( 21 | transaction: VersionedTransaction, 22 | payer: Keypair, 23 | latestBlockhash: BlockhashWithExpiryBlockHeight, 24 | ): Promise<{ confirmed: boolean; signature?: string; error?: string }> { 25 | logger.debug('Executing transaction...'); 26 | 27 | try { 28 | const fee = new CurrencyAmount(Currency.SOL, this.warpFee, false).raw.toNumber(); 29 | const warpFeeMessage = new TransactionMessage({ 30 | payerKey: payer.publicKey, 31 | recentBlockhash: latestBlockhash.blockhash, 32 | instructions: [ 33 | SystemProgram.transfer({ 34 | fromPubkey: payer.publicKey, 35 | toPubkey: this.warpFeeWallet, 36 | lamports: fee, 37 | }), 38 | ], 39 | }).compileToV0Message(); 40 | 41 | const warpFeeTx = new VersionedTransaction(warpFeeMessage); 42 | warpFeeTx.sign([payer]); 43 | 44 | const response = await axios.post<{ confirmed: boolean; signature: string; error?: string }>( 45 | 'https://tx.warp.id/transaction/execute', 46 | { 47 | transactions: [bs58.encode(warpFeeTx.serialize()), bs58.encode(transaction.serialize())], 48 | latestBlockhash, 49 | }, 50 | { 51 | timeout: 100000, 52 | }, 53 | ); 54 | 55 | return response.data; 56 | } catch (error) { 57 | if (error instanceof AxiosError) { 58 | logger.trace({ error: error.response?.data }, 'Failed to execute warp transaction'); 59 | } 60 | } 61 | 62 | return { confirmed: false }; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /cache/whitelist.cache.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | import { logger, WHITELIST_REFRESH_INTERVAL } from '../helpers'; 4 | import { getPdaMetadataKey } from '@raydium-io/raydium-sdk'; 5 | import { getMetadataAccountDataSerializer, MetadataAccountData, MetadataAccountDataArgs } from '@metaplex-foundation/mpl-token-metadata'; 6 | import { Serializer } from '@metaplex-foundation/umi/serializers'; 7 | 8 | export class WhitelistCache { 9 | private whitelist: string[] = []; 10 | private fileLocation = path.join(__dirname, '../storage/whitelist.txt'); 11 | 12 | constructor() { 13 | setInterval(() => this.loadWhitelist(), WHITELIST_REFRESH_INTERVAL); 14 | } 15 | 16 | public init() { 17 | this.loadWhitelist(); 18 | } 19 | 20 | public whitelistIsEmpty(){ 21 | return this.whitelist.length == 0; 22 | } 23 | 24 | public async isInList(connection, poolKeys): Promise { 25 | try { 26 | 27 | if (this.whitelistIsEmpty()) { 28 | return false; 29 | } 30 | 31 | let metadataSerializer: Serializer = getMetadataAccountDataSerializer(); 32 | 33 | const metadataPDA = getPdaMetadataKey(poolKeys.baseMint); 34 | const metadataAccount = await connection.getAccountInfo(metadataPDA.publicKey, connection.commitment); 35 | 36 | if (!metadataAccount?.data) { 37 | return false; 38 | } 39 | 40 | const deserialize = metadataSerializer.deserialize(metadataAccount.data); 41 | 42 | if (this.whitelist.includes(deserialize[0].updateAuthority.toString())) { 43 | logger.trace({ mint: poolKeys.baseMint }, `Whitelist -> ${deserialize[0].updateAuthority.toString()} is whitelisted!`); 44 | return true; 45 | } 46 | 47 | return false; 48 | 49 | } catch (e) { 50 | logger.error({ mint: poolKeys.baseMint }, `Whitelist -> Failed to check whitelist`); 51 | return false; 52 | } 53 | } 54 | 55 | private loadWhitelist() { 56 | logger.trace(`Refreshing whitelist...`); 57 | 58 | const count = this.whitelist.length; 59 | const data = fs.readFileSync(this.fileLocation, 'utf-8'); 60 | this.whitelist = data 61 | .split('\n') 62 | .map((a) => a.trim()) 63 | .filter((a) => a); 64 | 65 | if (this.whitelist.length != count) { 66 | logger.info(`Loaded whitelist list: ${this.whitelist.length}`); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /filters/renounced.filter.ts: -------------------------------------------------------------------------------- 1 | import { Filter, FilterResult } from './pool-filters'; 2 | import { MintLayout } from '@solana/spl-token'; 3 | import { Connection } from '@solana/web3.js'; 4 | import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; 5 | import { logger } from '../helpers'; 6 | 7 | export class RenouncedFreezeFilter implements Filter { 8 | private readonly errorMessage: string[] = []; 9 | private cachedResult: FilterResult | undefined = undefined; 10 | 11 | constructor( 12 | private readonly connection: Connection, 13 | private readonly checkRenounced: boolean, 14 | private readonly checkFreezable: boolean, 15 | ) { 16 | if (this.checkRenounced) { 17 | this.errorMessage.push('mint'); 18 | } 19 | 20 | if (this.checkFreezable) { 21 | this.errorMessage.push('freeze'); 22 | } 23 | } 24 | 25 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 26 | if (this.cachedResult) { 27 | return this.cachedResult; 28 | } 29 | 30 | try { 31 | const accountInfo = await this.connection.getAccountInfo(poolKeys.baseMint, this.connection.commitment); 32 | if (!accountInfo?.data) { 33 | return { ok: false, message: 'RenouncedFreeze -> Failed to fetch account data' }; 34 | } 35 | 36 | const deserialize = MintLayout.decode(accountInfo.data); 37 | const renounced = !this.checkRenounced || deserialize.mintAuthorityOption === 0; 38 | const freezable = !this.checkFreezable || deserialize.freezeAuthorityOption !== 0; 39 | const ok = renounced && !freezable; 40 | const message: string[] = []; 41 | 42 | if (!renounced) { 43 | message.push('mint'); 44 | } 45 | 46 | if (freezable) { 47 | message.push('freeze'); 48 | } 49 | 50 | const result = { 51 | ok: ok, 52 | message: ok ? undefined : `RenouncedFreeze -> Creator can ${message.join(' and ')} tokens`, 53 | }; 54 | 55 | if (result.ok) { 56 | this.cachedResult = result; 57 | } 58 | 59 | return result; 60 | } catch (e) { 61 | logger.error( 62 | { mint: poolKeys.baseMint }, 63 | `RenouncedFreeze -> Failed to check if creator can ${this.errorMessage.join(' and ')} tokens`, 64 | ); 65 | } 66 | 67 | return { 68 | ok: false, 69 | message: `RenouncedFreeze -> Failed to check if creator can ${this.errorMessage.join(' and ')} tokens`, 70 | }; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | 125 | # PNPM 126 | pnpm-lock.yaml 127 | 128 | # yarn v2 129 | .yarn/cache 130 | .yarn/unplugged 131 | .yarn/build-state.yml 132 | .yarn/install-state.gz 133 | .pnp.* 134 | 135 | # JetBrains 136 | .idea 137 | 138 | # Visual Studio Code 139 | *.code-workspace 140 | -------------------------------------------------------------------------------- /filters/mutable.filter.ts: -------------------------------------------------------------------------------- 1 | import { Filter, FilterResult } from './pool-filters'; 2 | import { Connection } from '@solana/web3.js'; 3 | import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; 4 | import { getPdaMetadataKey } from '@raydium-io/raydium-sdk'; 5 | import { MetadataAccountData, MetadataAccountDataArgs } from '@metaplex-foundation/mpl-token-metadata'; 6 | import { Serializer } from '@metaplex-foundation/umi/serializers'; 7 | import { logger } from '../helpers'; 8 | 9 | export class MutableFilter implements Filter { 10 | private readonly errorMessage: string[] = []; 11 | 12 | constructor( 13 | private readonly connection: Connection, 14 | private readonly metadataSerializer: Serializer, 15 | private readonly checkMutable: boolean, 16 | private readonly checkSocials: boolean, 17 | ) { 18 | if (this.checkMutable) { 19 | this.errorMessage.push('mutable'); 20 | } 21 | 22 | if (this.checkSocials) { 23 | this.errorMessage.push('socials'); 24 | } 25 | } 26 | 27 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 28 | try { 29 | const metadataPDA = getPdaMetadataKey(poolKeys.baseMint); 30 | const metadataAccount = await this.connection.getAccountInfo(metadataPDA.publicKey, this.connection.commitment); 31 | 32 | if (!metadataAccount?.data) { 33 | return { ok: false, message: 'Mutable -> Failed to fetch account data' }; 34 | } 35 | 36 | const deserialize = this.metadataSerializer.deserialize(metadataAccount.data); 37 | const mutable = !this.checkMutable || deserialize[0].isMutable; 38 | const hasSocials = !this.checkSocials || (await this.hasSocials(deserialize[0])); 39 | const ok = (!this.checkMutable || mutable) && (!this.checkSocials || hasSocials); 40 | 41 | const message: string[] = []; 42 | 43 | if (this.checkMutable && mutable) { 44 | message.push('metadata can be changed'); 45 | } 46 | 47 | if (this.checkSocials && !hasSocials) { 48 | message.push('has no socials'); 49 | } 50 | 51 | return { ok: ok, message: ok ? undefined : `MutableSocials -> Token ${message.join(' and ')}` }; 52 | 53 | } catch (e) { 54 | // I comment this part momentarily as you can get a certificates error from the hostname. 55 | // The solution would be to set "rejectUnauthorized: false" 56 | // logger.error({ mint: poolKeys.baseMint, error: e }, `MutableSocials -> Failed to check ${this.errorMessage.join(' and ')}`); 57 | } 58 | 59 | return { 60 | ok: false, 61 | message: `MutableSocials -> Failed to check ${this.errorMessage.join(' and ')}`, 62 | }; 63 | } 64 | 65 | private async hasSocials(metadata: MetadataAccountData) { 66 | const response = await fetch(metadata.uri); 67 | const data = await response.json(); 68 | return Object.values(data?.extensions ?? {}).filter((value: any) => value).length > 0; 69 | } 70 | } -------------------------------------------------------------------------------- /filters/pool-filters.ts: -------------------------------------------------------------------------------- 1 | import { Connection } from '@solana/web3.js'; 2 | import { LiquidityPoolKeysV4, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 3 | import { getMetadataAccountDataSerializer } from '@metaplex-foundation/mpl-token-metadata'; 4 | import { BurnFilter } from './burn.filter'; 5 | import { MutableFilter } from './mutable.filter'; 6 | import { RenouncedFreezeFilter } from './renounced.filter'; 7 | import { PoolSizeFilter } from './pool-size.filter'; 8 | import { 9 | CHECK_IF_BURNED, 10 | CHECK_IF_FREEZABLE, 11 | CHECK_IF_MINT_IS_RENOUNCED, 12 | CHECK_IF_MUTABLE, 13 | CHECK_IF_SOCIALS, 14 | CHECK_TOKEN_DISTRIBUTION, 15 | CHECK_HOLDERS, 16 | logger } from '../helpers'; 17 | import { HoldersCountFilter, TopHolderDistributionFilter } from './holders'; 18 | import { BlacklistFilter } from './blacklist.filter'; 19 | import { BlacklistCache } from '../cache'; 20 | 21 | export interface Filter { 22 | execute(poolKeysV4: LiquidityPoolKeysV4): Promise; 23 | } 24 | 25 | export interface FilterResult { 26 | ok: boolean; 27 | message?: string; 28 | } 29 | 30 | export interface PoolFilterArgs { 31 | minPoolSize: TokenAmount; 32 | maxPoolSize: TokenAmount; 33 | quoteToken: Token; 34 | } 35 | 36 | export class PoolFilters { 37 | private readonly filters: Filter[] = []; 38 | 39 | constructor( 40 | readonly connection: Connection, 41 | readonly args: PoolFilterArgs, 42 | readonly blacklistCache: BlacklistCache 43 | ) { 44 | 45 | if(CHECK_HOLDERS){ 46 | this.filters.push(new HoldersCountFilter(connection)); 47 | } 48 | 49 | if(CHECK_TOKEN_DISTRIBUTION){ 50 | this.filters.push(new TopHolderDistributionFilter(connection)); 51 | } 52 | 53 | if (CHECK_IF_BURNED) { 54 | this.filters.push(new BurnFilter(connection)); 55 | } 56 | 57 | if (CHECK_IF_MINT_IS_RENOUNCED || CHECK_IF_FREEZABLE) { 58 | this.filters.push(new RenouncedFreezeFilter(connection, CHECK_IF_MINT_IS_RENOUNCED, CHECK_IF_FREEZABLE)); 59 | } 60 | 61 | if (CHECK_IF_MUTABLE || CHECK_IF_SOCIALS) { 62 | this.filters.push(new MutableFilter(connection, getMetadataAccountDataSerializer(), CHECK_IF_MUTABLE, CHECK_IF_SOCIALS)); 63 | } 64 | 65 | // not optional 66 | this.filters.push(new BlacklistFilter(connection, blacklistCache)); 67 | 68 | if (!args.minPoolSize.isZero() || !args.maxPoolSize.isZero()) { 69 | this.filters.push(new PoolSizeFilter(connection, args.quoteToken, args.minPoolSize, args.maxPoolSize)); 70 | } 71 | } 72 | 73 | public async execute(poolKeys: LiquidityPoolKeysV4): Promise { 74 | if (this.filters.length === 0) { 75 | return true; 76 | } 77 | 78 | const result = await Promise.all(this.filters.map((f) => f.execute(poolKeys))); 79 | const pass = result.every((r) => r.ok); 80 | 81 | if (pass) { 82 | return true; 83 | } 84 | 85 | for (const filterResult of result.filter((r) => !r.ok)) { 86 | logger.trace(filterResult.message); 87 | } 88 | 89 | return false; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /listeners/listeners.ts: -------------------------------------------------------------------------------- 1 | import { LIQUIDITY_STATE_LAYOUT_V4, MAINNET_PROGRAM_ID, MARKET_STATE_LAYOUT_V3, Token } from '@raydium-io/raydium-sdk'; 2 | import bs58 from 'bs58'; 3 | import { Connection, PublicKey } from '@solana/web3.js'; 4 | import { TOKEN_PROGRAM_ID } from '@solana/spl-token'; 5 | import { EventEmitter } from 'events'; 6 | 7 | export class Listeners extends EventEmitter { 8 | private subscriptions: number[] = []; 9 | 10 | constructor(private readonly connection: Connection) { 11 | super(); 12 | } 13 | 14 | public async start(config: { 15 | walletPublicKey: PublicKey; 16 | quoteToken: Token; 17 | autoSell: boolean; 18 | cacheNewMarkets: boolean; 19 | }) { 20 | if (config.cacheNewMarkets) { 21 | const openBookSubscription = await this.subscribeToOpenBookMarkets(config); 22 | this.subscriptions.push(openBookSubscription); 23 | } 24 | 25 | const raydiumSubscription = await this.subscribeToRaydiumPools(config); 26 | this.subscriptions.push(raydiumSubscription); 27 | 28 | if (config.autoSell) { 29 | const walletSubscription = await this.subscribeToWalletChanges(config); 30 | this.subscriptions.push(walletSubscription); 31 | } 32 | } 33 | 34 | private async subscribeToOpenBookMarkets(config: { quoteToken: Token }) { 35 | return this.connection.onProgramAccountChange( 36 | MAINNET_PROGRAM_ID.OPENBOOK_MARKET, 37 | async (updatedAccountInfo) => { 38 | this.emit('market', updatedAccountInfo); 39 | }, 40 | this.connection.commitment, 41 | [ 42 | { dataSize: MARKET_STATE_LAYOUT_V3.span }, 43 | { 44 | memcmp: { 45 | offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'), 46 | bytes: config.quoteToken.mint.toBase58(), 47 | }, 48 | }, 49 | ], 50 | ); 51 | } 52 | 53 | private async subscribeToRaydiumPools(config: { quoteToken: Token }) { 54 | return this.connection.onProgramAccountChange( 55 | MAINNET_PROGRAM_ID.AmmV4, 56 | async (updatedAccountInfo) => { 57 | this.emit('pool', updatedAccountInfo); 58 | }, 59 | this.connection.commitment, 60 | [ 61 | { dataSize: LIQUIDITY_STATE_LAYOUT_V4.span }, 62 | { 63 | memcmp: { 64 | offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'), 65 | bytes: config.quoteToken.mint.toBase58(), 66 | }, 67 | }, 68 | { 69 | memcmp: { 70 | offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'), 71 | bytes: MAINNET_PROGRAM_ID.OPENBOOK_MARKET.toBase58(), 72 | }, 73 | }, 74 | { 75 | memcmp: { 76 | offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('status'), 77 | bytes: bs58.encode([6, 0, 0, 0, 0, 0, 0, 0]), 78 | }, 79 | }, 80 | ], 81 | ); 82 | } 83 | 84 | private async subscribeToWalletChanges(config: { walletPublicKey: PublicKey }) { 85 | return this.connection.onProgramAccountChange( 86 | TOKEN_PROGRAM_ID, 87 | async (updatedAccountInfo) => { 88 | this.emit('wallet', updatedAccountInfo); 89 | }, 90 | this.connection.commitment, 91 | [ 92 | { 93 | dataSize: 165, 94 | }, 95 | { 96 | memcmp: { 97 | offset: 32, 98 | bytes: config.walletPublicKey.toBase58(), 99 | }, 100 | }, 101 | ], 102 | ); 103 | } 104 | 105 | public async stop() { 106 | for (let i = this.subscriptions.length; i >= 0; --i) { 107 | const subscription = this.subscriptions[i]; 108 | await this.connection.removeAccountChangeListener(subscription); 109 | this.subscriptions.splice(i, 1); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /cache/technical-analysis.cache.ts: -------------------------------------------------------------------------------- 1 | import { Liquidity, LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; 2 | import { COMMITMENT_LEVEL, RPC_ENDPOINT, logger } from '../helpers'; 3 | import { Connection } from '@solana/web3.js'; 4 | 5 | export class TechnicalAnalysisCache_Entity { 6 | constructor(process, poolKeys, prices) { 7 | this.process = process; 8 | this.poolKeys = poolKeys; 9 | this.prices = prices; 10 | 11 | this.done = false; 12 | this.extendExpiryTime(); 13 | } 14 | 15 | extendExpiryTime(){ 16 | this.expiryTime = new Date(new Date().getTime() + 5 * 60 * 1000); //5 mins 17 | } 18 | 19 | process: NodeJS.Timeout; 20 | expiryTime: Date; 21 | poolKeys: LiquidityPoolKeysV4; 22 | done: boolean; 23 | prices: { 24 | value: number, 25 | date: Date 26 | }[]; 27 | } 28 | 29 | export class TechnicalAnalysisCache { 30 | private readonly data: Map = new Map(); 31 | 32 | constructor() { 33 | setInterval(() => { 34 | this.data.forEach((cached, key) => { 35 | if(cached.done || cached.expiryTime < new Date()) { 36 | logger.trace(`Technical analysis watcher for mint: ${key} expired`); 37 | clearInterval(cached.process); 38 | this.data.delete(key); 39 | } 40 | }); 41 | }, 30 * 1000); 42 | } 43 | 44 | 45 | public addNew(mint: string, poolKeys: LiquidityPoolKeysV4) { 46 | let connection = new Connection(RPC_ENDPOINT, { 47 | commitment: COMMITMENT_LEVEL 48 | }); 49 | 50 | if (this.data.has(mint)) { 51 | return; //already exists 52 | } 53 | 54 | logger.trace(`Adding new technical analysis watcher for mint: ${mint}`); 55 | 56 | let process = this.startWatcher(connection, mint); 57 | this.set(mint, new TechnicalAnalysisCache_Entity(process, poolKeys, [])); 58 | } 59 | 60 | public getPrices(mint: string): number[] { 61 | if (!this.data.has(mint)) { 62 | return null; 63 | } 64 | 65 | let cached = this.data.get(mint); 66 | cached.extendExpiryTime(); 67 | this.set(mint, cached); 68 | return cached.prices.sort((a, b) => a.date.getTime() - b.date.getTime()).map(p => p.value); 69 | } 70 | 71 | public async markAsDone(mint: string) { 72 | const cached = this.data.get(mint); 73 | if (cached) { 74 | 75 | logger.trace(`Marking technical analysis watcher for mint: ${mint} as done`); 76 | cached.done = true; 77 | this.set(mint, cached); 78 | } 79 | } 80 | 81 | private set(mint: string, entity: TechnicalAnalysisCache_Entity) { 82 | // nu afdrug 83 | this.data.set(mint, entity); 84 | } 85 | 86 | private startWatcher(connection: Connection, mint: string): NodeJS.Timeout { 87 | return setInterval(async () => { 88 | try { 89 | 90 | if (!this.data.has(mint)) { 91 | return; //doesnt exist 92 | } 93 | 94 | let currentTime = new Date(); 95 | let cached = this.data.get(mint); 96 | 97 | if (cached.done) { 98 | clearInterval(cached.process); 99 | this.data.delete(mint); 100 | return; 101 | } 102 | 103 | let poolInfo = await Liquidity.fetchInfo({ 104 | connection: connection, 105 | poolKeys: cached.poolKeys 106 | }); 107 | 108 | let tokenPriceBN = Liquidity.getRate(poolInfo); 109 | 110 | if (cached.prices.length === 0 || parseFloat(tokenPriceBN.toFixed(16)) !== cached.prices[cached.prices.length - 1].value) { 111 | cached.prices.push({ value: parseFloat(tokenPriceBN.toFixed(16)), date: currentTime }); 112 | } 113 | 114 | this.set(mint, cached); 115 | } catch (e) { 116 | logger.error({ error: e }, `Technical analysis watcher for mint: ${mint} failed`); 117 | } 118 | }, 500); 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /messaging.ts: -------------------------------------------------------------------------------- 1 | import { Telegraf } from "telegraf"; 2 | import { InlineKeyboardMarkup, Message } from "telegraf/typings/core/types/typegram"; 3 | import { BotConfig } from "./bot"; 4 | 5 | export class Messaging { 6 | private readonly tg_bot: Telegraf; 7 | 8 | constructor(readonly config: BotConfig) { 9 | 10 | if (this.config.useTelegram) { 11 | this.tg_bot = new Telegraf(this.config.telegramBotToken); 12 | this.setupBot(); 13 | this.tg_bot.launch(); 14 | } 15 | } 16 | 17 | private setupBot() { 18 | this.tg_bot.on("message", async (ctx) => { 19 | 20 | if (!this.checkChatId(ctx)) { 21 | return; 22 | } 23 | 24 | if (ctx.text?.toLowerCase().includes("/status")) { 25 | ctx.reply("Working", { parse_mode: "HTML" }); 26 | } 27 | 28 | if (ctx.text?.toLowerCase().includes("/config")) { 29 | ctx.reply(this.objectToText(this.config, ["wallet", "telegramBotToken", "telegramChatId"]), { parse_mode: "HTML" }); 30 | } 31 | 32 | if (ctx.text?.toLowerCase().includes("/help")) { 33 | let kb: InlineKeyboardMarkup = { 34 | inline_keyboard: [ 35 | [ 36 | { text: 'status', switch_inline_query_current_chat: `/status` }, 37 | { text: 'config', switch_inline_query_current_chat: `/config` }, 38 | { text: 'logs', switch_inline_query_current_chat: `/logs` } 39 | ] 40 | ] 41 | }; 42 | 43 | ctx.reply("Available commands", { parse_mode: "HTML", reply_markup: kb }); 44 | } 45 | 46 | //unstable 47 | // if(ctx.text?.toLowerCase().includes("/logs")){ 48 | // const linesOfLog = 150; 49 | // const logFilePath = "./logs/activity.log"; 50 | // fs.readFile(logFilePath, 'utf8', (err, data) => { 51 | // if (err) { 52 | // ctx.reply(`Error reading log file: ${err.message}`, { parse_mode: "HTML" }); 53 | // } else { 54 | // const lines = data.trim().split(/\r?\n/); 55 | // const lastLines = lines.slice(Math.max(lines.length - linesOfLog, 0)).join('\n'); 56 | // const message = `${lastLines}`; 57 | // const chunks = message.match(/[\s\S]{1,4084}/g) || []; 58 | // chunks.forEach((chunk) => { 59 | // ctx.reply(`${chunk}`, { parse_mode: "HTML" }); 60 | // }); 61 | // } 62 | // }); 63 | // } 64 | }); 65 | } 66 | 67 | private checkChatId(ctx: any): boolean { 68 | if (ctx.chat?.id !== this.config.telegramChatId) { 69 | ctx.reply("fuck off"); 70 | return false; 71 | } 72 | return true; 73 | } 74 | 75 | private objectToText(obj: object, excludeKeys: string[]): string { 76 | let result = ''; 77 | for (const key in obj) { 78 | if (obj.hasOwnProperty(key) && !excludeKeys.includes(key)) { 79 | let value = obj[key]; 80 | if (typeof value === 'object' && value !== null) { 81 | continue; 82 | } 83 | result += `${key}: ${value}\n`; 84 | } 85 | } 86 | return result; 87 | } 88 | 89 | public async sendTelegramMessage(message: string, mint: string, messageId?: number): Promise { 90 | if(!this.config.useTelegram){ 91 | return null; 92 | } 93 | 94 | try { 95 | let kb: InlineKeyboardMarkup = { 96 | inline_keyboard: [ 97 | [ 98 | { text: '🍔Dexscreener', url: `https://dexscreener.com/solana/${mint}?maker=${this.config.wallet.publicKey}` }, 99 | { text: 'Rugcheck🔍', url: `https://rugcheck.xyz/tokens/${mint}` } 100 | ] 101 | ] 102 | }; 103 | 104 | if (messageId) { 105 | this.tg_bot.telegram.editMessageText(this.config.telegramChatId, messageId, undefined, message, { 106 | parse_mode: "HTML", reply_markup: kb 107 | }); 108 | return undefined; 109 | 110 | } else { 111 | return await this.tg_bot.telegram.sendMessage(this.config.telegramChatId, message, { 112 | parse_mode: "HTML", reply_markup: kb 113 | }); 114 | } 115 | 116 | } 117 | catch (e) { 118 | return undefined; 119 | } 120 | } 121 | } -------------------------------------------------------------------------------- /transactions/jito-rpc-transaction-executor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BlockhashWithExpiryBlockHeight, 3 | Keypair, 4 | PublicKey, 5 | SystemProgram, 6 | Connection, 7 | TransactionMessage, 8 | VersionedTransaction, 9 | } from '@solana/web3.js'; 10 | import { TransactionExecutor } from './transaction-executor.interface'; 11 | import { logger } from '../helpers'; 12 | import axios, { AxiosError } from 'axios'; 13 | import bs58 from 'bs58'; 14 | import { Currency, CurrencyAmount } from '@raydium-io/raydium-sdk'; 15 | 16 | export class JitoTransactionExecutor implements TransactionExecutor { 17 | // https://jito-labs.gitbook.io/mev/searcher-resources/json-rpc-api-reference/bundles/gettipaccounts 18 | private jitpTipAccounts = [ 19 | 'Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghXLvLkY', 20 | 'DttWaMuVvTiduZRnguLF7jNxTgiMBZ1hyAumKUiL2KRL', 21 | '96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5', 22 | '3AVi9Tg9Uo68tJfuvoKvqKNWKkC5wPdSSdeBnizKZ6jT', 23 | 'HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe', 24 | 'ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt6iGPaS49', 25 | 'ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt', 26 | 'DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh', 27 | ]; 28 | 29 | private JitoFeeWallet: PublicKey; 30 | 31 | constructor( 32 | private readonly jitoFee: string, 33 | private readonly connection: Connection, 34 | ) { 35 | this.JitoFeeWallet = this.getRandomValidatorKey(); 36 | } 37 | 38 | private getRandomValidatorKey(): PublicKey { 39 | const randomValidator = this.jitpTipAccounts[Math.floor(Math.random() * this.jitpTipAccounts.length)]; 40 | return new PublicKey(randomValidator); 41 | } 42 | 43 | public async executeAndConfirm( 44 | transaction: VersionedTransaction, 45 | payer: Keypair, 46 | latestBlockhash: BlockhashWithExpiryBlockHeight, 47 | ): Promise<{ confirmed: boolean; signature?: string; error?: string }> { 48 | logger.debug('Starting Jito transaction execution...'); 49 | this.JitoFeeWallet = this.getRandomValidatorKey(); // Update wallet key each execution 50 | logger.trace(`Selected Jito fee wallet: ${this.JitoFeeWallet.toBase58()}`); 51 | 52 | try { 53 | const fee = new CurrencyAmount(Currency.SOL, this.jitoFee, false).raw.toNumber(); 54 | logger.trace(`Calculated fee: ${fee} lamports`); 55 | 56 | const jitTipTxFeeMessage = new TransactionMessage({ 57 | payerKey: payer.publicKey, 58 | recentBlockhash: latestBlockhash.blockhash, 59 | instructions: [ 60 | SystemProgram.transfer({ 61 | fromPubkey: payer.publicKey, 62 | toPubkey: this.JitoFeeWallet, 63 | lamports: fee, 64 | }), 65 | ], 66 | }).compileToV0Message(); 67 | 68 | const jitoFeeTx = new VersionedTransaction(jitTipTxFeeMessage); 69 | jitoFeeTx.sign([payer]); 70 | 71 | const jitoTxsignature = bs58.encode(jitoFeeTx.signatures[0]); 72 | 73 | // Serialize the transactions once here 74 | const serializedjitoFeeTx = bs58.encode(jitoFeeTx.serialize()); 75 | const serializedTransaction = bs58.encode(transaction.serialize()); 76 | const serializedTransactions = [serializedjitoFeeTx, serializedTransaction]; 77 | 78 | // https://jito-labs.gitbook.io/mev/searcher-resources/json-rpc-api-reference/url 79 | const endpoints = [ 80 | 'https://mainnet.block-engine.jito.wtf/api/v1/bundles', 81 | 'https://amsterdam.mainnet.block-engine.jito.wtf/api/v1/bundles', 82 | 'https://frankfurt.mainnet.block-engine.jito.wtf/api/v1/bundles', 83 | 'https://ny.mainnet.block-engine.jito.wtf/api/v1/bundles', 84 | 'https://tokyo.mainnet.block-engine.jito.wtf/api/v1/bundles', 85 | ]; 86 | 87 | const requests = endpoints.map((url) => 88 | axios.post(url, { 89 | jsonrpc: '2.0', 90 | id: 1, 91 | method: 'sendBundle', 92 | params: [serializedTransactions], 93 | }), 94 | ); 95 | 96 | logger.trace('Sending transactions to endpoints...'); 97 | const results = await Promise.all(requests.map((p) => p.catch((e) => e))); 98 | 99 | const successfulResults = results.filter((result) => !(result instanceof Error)); 100 | 101 | if (successfulResults.length > 0) { 102 | logger.trace(`At least one successful response`); 103 | logger.debug(`Confirming jito transaction...`); 104 | return await this.confirm(jitoTxsignature, latestBlockhash); 105 | } else { 106 | logger.debug(`No successful responses received for jito`); 107 | } 108 | 109 | return { confirmed: false }; 110 | } catch (error) { 111 | if (error instanceof AxiosError) { 112 | logger.trace({ error: error.response?.data }, 'Failed to execute jito transaction'); 113 | } 114 | logger.error('Error during transaction execution', error); 115 | return { confirmed: false }; 116 | } 117 | } 118 | 119 | private async confirm(signature: string, latestBlockhash: BlockhashWithExpiryBlockHeight) { 120 | const confirmation = await this.connection.confirmTransaction( 121 | { 122 | signature, 123 | lastValidBlockHeight: latestBlockhash.lastValidBlockHeight, 124 | blockhash: latestBlockhash.blockhash, 125 | }, 126 | this.connection.commitment, 127 | ); 128 | 129 | return { confirmed: !confirmation.value.err, signature }; 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /helpers/constants.ts: -------------------------------------------------------------------------------- 1 | import { Logger } from 'pino'; 2 | import dotenv from 'dotenv'; 3 | import { Commitment } from '@solana/web3.js'; 4 | import { logger } from './logger'; 5 | 6 | dotenv.config(); 7 | 8 | const retrieveEnvVariable = (variableName: string, logger: Logger) => { 9 | const variable = process.env[variableName] || ''; 10 | if (!variable) { 11 | logger.error(`${variableName} is not set`); 12 | process.exit(1); 13 | } 14 | return variable; 15 | }; 16 | 17 | // Wallet 18 | export const PRIVATE_KEY = retrieveEnvVariable('PRIVATE_KEY', logger); 19 | 20 | // Connection 21 | export const NETWORK = 'mainnet-beta'; 22 | export const COMMITMENT_LEVEL: Commitment = retrieveEnvVariable('COMMITMENT_LEVEL', logger) as Commitment; 23 | export const RPC_ENDPOINT = retrieveEnvVariable('RPC_ENDPOINT', logger); 24 | export const RPC_WEBSOCKET_ENDPOINT = retrieveEnvVariable('RPC_WEBSOCKET_ENDPOINT', logger); 25 | 26 | // Bot 27 | export const LOG_LEVEL = retrieveEnvVariable('LOG_LEVEL', logger); 28 | export const MAX_TOKENS_AT_THE_TIME = Number(retrieveEnvVariable('MAX_TOKENS_AT_THE_TIME', logger)); 29 | export const COMPUTE_UNIT_LIMIT = Number(retrieveEnvVariable('COMPUTE_UNIT_LIMIT', logger)); 30 | export const COMPUTE_UNIT_PRICE = Number(retrieveEnvVariable('COMPUTE_UNIT_PRICE', logger)); 31 | export const PRE_LOAD_EXISTING_MARKETS = retrieveEnvVariable('PRE_LOAD_EXISTING_MARKETS', logger) === 'true'; 32 | export const CACHE_NEW_MARKETS = retrieveEnvVariable('CACHE_NEW_MARKETS', logger) === 'true'; 33 | export const TRANSACTION_EXECUTOR = retrieveEnvVariable('TRANSACTION_EXECUTOR', logger); 34 | export const CUSTOM_FEE = retrieveEnvVariable('CUSTOM_FEE', logger); 35 | export const MAX_LAG = Number(retrieveEnvVariable('MAX_LAG', logger)); 36 | export const USE_TA = retrieveEnvVariable('USE_TA', logger) === 'true'; 37 | export const USE_TELEGRAM = retrieveEnvVariable('USE_TELEGRAM', logger) === 'true'; 38 | 39 | // Buy 40 | export const AUTO_BUY_DELAY = Number(retrieveEnvVariable('AUTO_BUY_DELAY', logger)); 41 | export const QUOTE_MINT = retrieveEnvVariable('QUOTE_MINT', logger); 42 | export const QUOTE_AMOUNT = retrieveEnvVariable('QUOTE_AMOUNT', logger); 43 | export const MAX_BUY_RETRIES = Number(retrieveEnvVariable('MAX_BUY_RETRIES', logger)); 44 | export const BUY_SLIPPAGE = Number(retrieveEnvVariable('BUY_SLIPPAGE', logger)); 45 | 46 | export const BUY_SIGNAL_TIME_TO_WAIT = Number(retrieveEnvVariable('BUY_SIGNAL_TIME_TO_WAIT', logger)); 47 | export const BUY_SIGNAL_PRICE_INTERVAL = Number(retrieveEnvVariable('BUY_SIGNAL_PRICE_INTERVAL', logger)); 48 | export const BUY_SIGNAL_FRACTION_TIME_TO_WAIT = Number(retrieveEnvVariable('BUY_SIGNAL_FRACTION_TIME_TO_WAIT', logger)); 49 | export const BUY_SIGNAL_LOW_VOLUME_THRESHOLD = Number(retrieveEnvVariable('BUY_SIGNAL_LOW_VOLUME_THRESHOLD', logger)); 50 | 51 | // Sell 52 | export const AUTO_SELL = retrieveEnvVariable('AUTO_SELL', logger) === 'true'; 53 | export const AUTO_SELL_DELAY = Number(retrieveEnvVariable('AUTO_SELL_DELAY', logger)); 54 | export const MAX_SELL_RETRIES = Number(retrieveEnvVariable('MAX_SELL_RETRIES', logger)); 55 | export const TAKE_PROFIT = Number(retrieveEnvVariable('TAKE_PROFIT', logger)); 56 | export const STOP_LOSS = Number(retrieveEnvVariable('STOP_LOSS', logger)); 57 | export const TRAILING_STOP_LOSS = retrieveEnvVariable('TRAILING_STOP_LOSS', logger) === 'true'; 58 | export const PRICE_CHECK_INTERVAL = Number(retrieveEnvVariable('PRICE_CHECK_INTERVAL', logger)); 59 | export const PRICE_CHECK_DURATION = Number(retrieveEnvVariable('PRICE_CHECK_DURATION', logger)); 60 | export const SELL_SLIPPAGE = Number(retrieveEnvVariable('SELL_SLIPPAGE', logger)); 61 | export const SKIP_SELLING_IF_LOST_MORE_THAN = Number(retrieveEnvVariable('SKIP_SELLING_IF_LOST_MORE_THAN', logger)); 62 | export const AUTO_SELL_WITHOUT_SELL_SIGNAL = retrieveEnvVariable('AUTO_SELL_WITHOUT_SELL_SIGNAL', logger) === 'true'; 63 | export const KEEP_5_PERCENT_FOR_MOONSHOTS = retrieveEnvVariable('KEEP_5_PERCENT_FOR_MOONSHOTS', logger) === 'true'; 64 | 65 | 66 | // Filters 67 | export const FILTER_CHECK_INTERVAL = Number(retrieveEnvVariable('FILTER_CHECK_INTERVAL', logger)); 68 | export const FILTER_CHECK_DURATION = Number(retrieveEnvVariable('FILTER_CHECK_DURATION', logger)); 69 | export const CONSECUTIVE_FILTER_MATCHES = Number(retrieveEnvVariable('CONSECUTIVE_FILTER_MATCHES', logger)); 70 | export const CHECK_IF_MUTABLE = retrieveEnvVariable('CHECK_IF_MUTABLE', logger) === 'true'; 71 | export const CHECK_IF_SOCIALS = retrieveEnvVariable('CHECK_IF_SOCIALS', logger) === 'true'; 72 | export const CHECK_IF_MINT_IS_RENOUNCED = retrieveEnvVariable('CHECK_IF_MINT_IS_RENOUNCED', logger) === 'true'; 73 | export const CHECK_IF_FREEZABLE = retrieveEnvVariable('CHECK_IF_FREEZABLE', logger) === 'true'; 74 | export const CHECK_IF_BURNED = retrieveEnvVariable('CHECK_IF_BURNED', logger) === 'true'; 75 | export const MIN_POOL_SIZE = retrieveEnvVariable('MIN_POOL_SIZE', logger); 76 | export const MAX_POOL_SIZE = retrieveEnvVariable('MAX_POOL_SIZE', logger); 77 | export const USE_SNIPE_LIST = retrieveEnvVariable('USE_SNIPE_LIST', logger) === 'true'; 78 | export const SNIPE_LIST_REFRESH_INTERVAL = Number(retrieveEnvVariable('SNIPE_LIST_REFRESH_INTERVAL', logger)); 79 | export const BLACKLIST_REFRESH_INTERVAL = Number(retrieveEnvVariable('BLACKLIST_REFRESH_INTERVAL', logger)); 80 | export const WHITELIST_REFRESH_INTERVAL = Number(retrieveEnvVariable('WHITELIST_REFRESH_INTERVAL', logger)); 81 | 82 | //Holders filters 83 | export const CHECK_TOKEN_DISTRIBUTION = retrieveEnvVariable('CHECK_TOKEN_DISTRIBUTION', logger)=== 'true'; 84 | export const TOP_HOLDER_MAX_PERCENTAGE = Number(retrieveEnvVariable('TOP_HOLDER_MAX_PERCENTAGE', logger)); 85 | export const CHECK_ABNORMAL_DISTRIBUTION = retrieveEnvVariable('CHECK_ABNORMAL_DISTRIBUTION', logger) === 'true'; 86 | export const ABNORMAL_HOLDER_NR = Number(retrieveEnvVariable('ABNORMAL_HOLDER_NR', logger)); 87 | export const CHECK_HOLDERS = retrieveEnvVariable('CHECK_HOLDERS', logger) === 'true'; 88 | export const TOP_10_PERCENTAGE_CHECK = retrieveEnvVariable('TOP_10_PERCENTAGE_CHECK', logger) === 'true'; 89 | export const TOP_10_MAX_PERCENTAGE = Number (retrieveEnvVariable('TOP_10_MAX_PERCENTAGE', logger)); 90 | export const HOLDER_MIN_AMOUNT = Number (retrieveEnvVariable('HOLDER_MIN_AMOUNT', logger)); 91 | 92 | //Telegram config 93 | export const TELEGRAM_BOT_TOKEN = retrieveEnvVariable('TELEGRAM_BOT_TOKEN', logger); 94 | export const TELEGRAM_CHAT_ID = Number (retrieveEnvVariable('TELEGRAM_CHAT_ID', logger)); 95 | 96 | //Technical analysis 97 | export const MACD_SHORT_PERIOD = Number (retrieveEnvVariable('MACD_SHORT_PERIOD', logger)); 98 | export const MACD_LONG_PERIOD = Number (retrieveEnvVariable('MACD_LONG_PERIOD', logger)); 99 | export const MACD_SIGNAL_PERIOD = Number (retrieveEnvVariable('MACD_SIGNAL_PERIOD', logger)); 100 | 101 | export const RSI_PERIOD = Number (retrieveEnvVariable('RSI_PERIOD', logger)); 102 | -------------------------------------------------------------------------------- /technicalAnalysis.ts: -------------------------------------------------------------------------------- 1 | import { BotConfig } from "./bot"; 2 | 3 | export class TechnicalAnalysis { 4 | constructor(public botConfig: BotConfig) { } 5 | 6 | public calculateEMAs = (prices: number[]): { EMA_3: number, EMA_18: number, prevEMA_3: number } => { 7 | const shortPeriod = 3; 8 | const longPeriod = 18; 9 | 10 | if (prices.length < longPeriod - 1) { 11 | return { EMA_3: null, EMA_18: null, prevEMA_3: null }; 12 | } 13 | 14 | const shortMultiplier = 2 / (shortPeriod + 1); 15 | const longMultiplier = 2 / (longPeriod + 1); 16 | 17 | let shortEMA = prices.slice(0, shortPeriod).reduce((acc, val) => acc + val, 0) / shortPeriod; 18 | let longEMA = prices.slice(0, longPeriod).reduce((acc, val) => acc + val, 0) / longPeriod; 19 | 20 | let prevEMA = shortEMA; 21 | 22 | prices.forEach(price => { 23 | prevEMA = shortEMA; 24 | shortEMA = (price - shortEMA) * shortMultiplier + shortEMA; 25 | longEMA = (price - longEMA) * longMultiplier + longEMA; 26 | }); 27 | 28 | return { 29 | EMA_3: shortEMA, 30 | EMA_18: longEMA, 31 | prevEMA_3: prevEMA 32 | }; 33 | } 34 | 35 | public calculateMACDv2 = ( 36 | prices: number[], 37 | _shortPeriod : number = null, 38 | _longPeriod: number = null, 39 | _signalPeriod: number = null 40 | ): { macd: number, signal: number } => { 41 | const shortPeriod = _shortPeriod ?? this.botConfig.MACDShortPeriod; 42 | const longPeriod = _longPeriod ?? this.botConfig.MACDLongPeriod; 43 | const signalPeriod = _signalPeriod ?? this.botConfig.MACDSignalPeriod; 44 | 45 | if (prices.length < longPeriod + signalPeriod - 1) { 46 | return { macd: null, signal: null }; 47 | } 48 | 49 | const shortMultiplier = 2 / (shortPeriod + 1); 50 | const longMultiplier = 2 / (longPeriod + 1); 51 | 52 | let shortEMA = prices.slice(0, shortPeriod).reduce((acc, val) => acc + val, 0) / shortPeriod; 53 | let longEMA = prices.slice(0, longPeriod).reduce((acc, val) => acc + val, 0) / longPeriod; 54 | 55 | const macdLine: number[] = []; 56 | for (let i = longPeriod; i < prices.length; i++) { 57 | shortEMA = (prices[i] - shortEMA) * shortMultiplier + shortEMA; 58 | longEMA = (prices[i] - longEMA) * longMultiplier + longEMA; 59 | 60 | const macdValue = shortEMA - longEMA; 61 | macdLine.push(macdValue); 62 | } 63 | 64 | let sum = 0; 65 | for (let i = 0; i < signalPeriod; i++) { 66 | sum += macdLine[i]; 67 | } 68 | let signalEMA = sum / signalPeriod; 69 | const signal: number[] = [signalEMA]; 70 | 71 | const signalMultiplier = 2 / (signalPeriod + 1); 72 | for (let i = signalPeriod; i < macdLine.length; i++) { 73 | signalEMA = (macdLine[i] - signalEMA) * signalMultiplier + signalEMA; 74 | signal.push(signalEMA); 75 | } 76 | 77 | return { 78 | macd: macdLine[macdLine.length - 1], 79 | signal: signal[signal.length - 1] 80 | }; 81 | } 82 | 83 | 84 | public calculateRSIv2 = (prices: number[]): number => { 85 | const period = this.botConfig.RSIPeriod; 86 | const delta: number[] = []; 87 | let gainSum = 0; 88 | let lossSum = 0; 89 | 90 | for (let i = 1; i < prices.length; i++) { 91 | delta.push(prices[i] - prices[i - 1]); 92 | } 93 | 94 | for (let i = 0; i < period; i++) { 95 | if (delta[i] > 0) { 96 | gainSum += delta[i]; 97 | } else { 98 | lossSum += Math.abs(delta[i]); 99 | } 100 | } 101 | 102 | const initialAvgGain = gainSum / period; 103 | const initialAvgLoss = lossSum / period; 104 | 105 | let prevAvgGain = initialAvgGain; 106 | let prevAvgLoss = initialAvgLoss; 107 | 108 | let cRSI = 0; 109 | 110 | for (let i = period; i < prices.length; i++) { 111 | const gain = delta[i] > 0 ? delta[i] : 0; 112 | const loss = delta[i] < 0 ? Math.abs(delta[i]) : 0; 113 | 114 | const avgGain = ((prevAvgGain * (period - 1)) + gain) / period; 115 | const avgLoss = ((prevAvgLoss * (period - 1)) + loss) / period; 116 | 117 | const RS = avgGain / avgLoss; 118 | cRSI = 100 - (100 / (1 + RS)); 119 | 120 | prevAvgGain = avgGain; 121 | prevAvgLoss = avgLoss; 122 | } 123 | 124 | return cRSI; 125 | } 126 | 127 | public calculateRSIv3 = (prices: number[], _period: number = null): { RSI: number, RSI_EMA_11: number, RSI_prevEMA_11: number } => { 128 | const period = _period ?? this.botConfig.RSIPeriod; 129 | const emaPeriod = 11; 130 | const delta: number[] = []; 131 | const rsiValues: number[] = []; 132 | let gainSum = 0; 133 | let lossSum = 0; 134 | 135 | for (let i = 1; i < prices.length; i++) { 136 | delta.push(prices[i] - prices[i - 1]); 137 | } 138 | 139 | for (let i = 0; i < period; i++) { 140 | if (delta[i] > 0) { 141 | gainSum += delta[i]; 142 | } else { 143 | lossSum += Math.abs(delta[i]); 144 | } 145 | } 146 | 147 | const initialAvgGain = gainSum / period; 148 | const initialAvgLoss = lossSum / period; 149 | 150 | let prevAvgGain = initialAvgGain; 151 | let prevAvgLoss = initialAvgLoss; 152 | 153 | let cRSI = 0; 154 | 155 | for (let i = period; i < prices.length; i++) { 156 | const gain = delta[i] > 0 ? delta[i] : 0; 157 | const loss = delta[i] < 0 ? Math.abs(delta[i]) : 0; 158 | 159 | const avgGain = ((prevAvgGain * (period - 1)) + gain) / period; 160 | const avgLoss = ((prevAvgLoss * (period - 1)) + loss) / period; 161 | 162 | const RS = avgGain / avgLoss; 163 | cRSI = 100 - (100 / (1 + RS)); 164 | 165 | prevAvgGain = avgGain; 166 | prevAvgLoss = avgLoss; 167 | 168 | rsiValues.push(cRSI); 169 | } 170 | 171 | if (rsiValues.length < emaPeriod) { 172 | return { RSI: cRSI, RSI_EMA_11: NaN, RSI_prevEMA_11: NaN }; 173 | } 174 | 175 | const emaMultiplier = 2 / (emaPeriod + 1); 176 | let ema_11 = rsiValues.slice(0, emaPeriod).reduce((acc, val) => acc + val, 0) / emaPeriod; 177 | let prevEMA_11 = ema_11; 178 | 179 | for (let i = emaPeriod; i < rsiValues.length; i++) { 180 | prevEMA_11 = ema_11; 181 | ema_11 = (rsiValues[i] - ema_11) * emaMultiplier + ema_11; 182 | } 183 | 184 | return { RSI: cRSI, RSI_EMA_11: ema_11, RSI_prevEMA_11: prevEMA_11 }; 185 | } 186 | 187 | 188 | } -------------------------------------------------------------------------------- /filters/holders.ts: -------------------------------------------------------------------------------- 1 | import { Connection, PublicKey, AccountInfo } from '@solana/web3.js'; 2 | import { LiquidityPoolKeysV4 } from '@raydium-io/raydium-sdk'; 3 | import { Filter, FilterResult } from './pool-filters'; 4 | import { TOKEN_PROGRAM_ID, MintLayout } from '@solana/spl-token'; 5 | import { logger, HOLDER_MIN_AMOUNT, TOP_HOLDER_MAX_PERCENTAGE, ABNORMAL_HOLDER_NR, TOP_10_MAX_PERCENTAGE, CHECK_ABNORMAL_DISTRIBUTION, TOP_10_PERCENTAGE_CHECK } from '../helpers'; 6 | 7 | export class HoldersCountFilter implements Filter { 8 | constructor(private readonly connection: Connection) { } 9 | 10 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 11 | const baseThisCase = poolKeys.baseMint.toBase58(); 12 | const accounts = await this.connection.getProgramAccounts( 13 | TOKEN_PROGRAM_ID, 14 | { 15 | dataSlice: { offset: 0, length: 0 }, // No need to fetch data if not inspecting it 16 | filters: [ 17 | { dataSize: 165 }, // Size of a SPL Token account 18 | { 19 | memcmp: { 20 | offset: 0, // Mint address is at the start of the SPL Token account data 21 | bytes: poolKeys.baseMint.toBase58(), 22 | }, 23 | }, 24 | ], 25 | } 26 | ); 27 | const holderCount = accounts.length; 28 | logger.trace(`Holders count : ${holderCount}`); 29 | const isSuspicious = holderCount < HOLDER_MIN_AMOUNT; // Example condition 30 | 31 | return { 32 | ok: !isSuspicious, 33 | message: isSuspicious ? `Too few holders ${holderCount} ` : `Sufficient number of holders. ${holderCount}`, 34 | }; 35 | } 36 | } 37 | 38 | 39 | 40 | interface HolderInfo { 41 | address: PublicKey; 42 | uiAmount: number; 43 | owner: PublicKey; 44 | lamports: number; 45 | } 46 | 47 | export class TopHolderDistributionFilter implements Filter { 48 | constructor(private readonly connection: Connection) { } 49 | 50 | async execute(poolKeys: LiquidityPoolKeysV4): Promise { 51 | try { 52 | 53 | // Fetch the total supply of the token from its mint account 54 | const mintAccountInfo = await this.connection.getAccountInfo(poolKeys.baseMint); 55 | let totalSupply = 0; 56 | if (mintAccountInfo && mintAccountInfo.data.length === MintLayout.span) { 57 | const mintData = MintLayout.decode(mintAccountInfo.data); 58 | totalSupply = Number(mintData.supply); // Adjust based on your needs (handle big numbers appropriately) 59 | } 60 | const largestAccountsResponse = await this.connection.getTokenLargestAccounts(poolKeys.baseMint); 61 | const addresses = largestAccountsResponse.value.map(account => new PublicKey(account.address)); 62 | 63 | // Fetch additional account details for each of the largest accounts 64 | const accountInfos = await this.connection.getMultipleAccountsInfo(addresses, { commitment: 'confirmed' }); 65 | 66 | const largestAccounts = accountInfos.map((info, index) => ({ 67 | address: addresses[index], 68 | uiAmount: largestAccountsResponse.value[index].uiAmount ?? 0, 69 | owner: info ? new PublicKey(info.data.slice(32, 64)) : new PublicKey('11111111111111111111111111111111'), // Use a default or null-like public key 70 | lamports: info ? info.lamports : 0 71 | })); 72 | 73 | const distributionResult = await this.checkTokenDistribution(largestAccounts); 74 | let message = `Total Supply: ${totalSupply}, \nTop holder percentages: ${distributionResult.percentages.join(' | ')}`; 75 | 76 | if (distributionResult.isTopHolderExcessive) { 77 | message += `.\nWarning: Top holder exceeds threshold, has: ${distributionResult.percentages[0]}.`; 78 | } 79 | 80 | if (TOP_10_PERCENTAGE_CHECK && distributionResult.isTopTenPercentageExcessive) { 81 | message += `\nWarning: Top ten holders collectively exceed threshold of ${TOP_10_MAX_PERCENTAGE}% with ${distributionResult.topTenPercentage.toFixed(2)}%.`; 82 | } 83 | 84 | if (distributionResult.isTopHoldersPoor) { 85 | message += `.\nWarning: Top holders are poor, total net worth: ${distributionResult.topHoldersTotalSol.toFixed(3)}.`; 86 | } 87 | 88 | if (distributionResult.topWalletIsNotPool) { 89 | message += `.\nWarning: Top wallet is not the pool wallet.`; 90 | } 91 | 92 | const distributionOk = !distributionResult.isTopHolderExcessive && 93 | !distributionResult.isTopHoldersPoor && !distributionResult.topWalletIsNotPool && 94 | (!TOP_10_PERCENTAGE_CHECK || !distributionResult.isTopTenPercentageExcessive); 95 | 96 | if (CHECK_ABNORMAL_DISTRIBUTION) { 97 | const abnormalDistribution = this.checkForAbnormalDistribution(largestAccounts); 98 | message += abnormalDistribution ? "\nAbnormal distribution detected!" : "\nDistribution looks normal."; 99 | return { 100 | ok: distributionOk && !abnormalDistribution, 101 | message: message 102 | }; 103 | } else { 104 | return { 105 | ok: distributionOk, 106 | message: message + ". Abnormal distribution check is disabled." 107 | }; 108 | } 109 | } catch (error) { 110 | logger.error(`Failed to execute TopHolderDistributionFilter: ${error}`); 111 | return { ok: false, message: 'Failed to check token distribution.' }; 112 | } 113 | } 114 | 115 | private async checkTokenDistribution(accounts: HolderInfo[]): Promise<{ 116 | percentages: string[], 117 | totalSupply: number, 118 | topTenPercentage: number, 119 | isTopTenPercentageExcessive: boolean, 120 | isTopHolderExcessive: boolean, 121 | isTopHoldersPoor: boolean, 122 | topHoldersTotalSol: number, 123 | topWalletIsNotPool: boolean 124 | }> { 125 | 126 | const totalSupply = accounts.reduce((sum, account) => sum + account.uiAmount, 0); 127 | const excludeAddress = new PublicKey("5Q544fKrFoe6tsEbD7S8EmxGTJYAKtTVhAW5Q5pge4j1"); 128 | 129 | const topWalletIsNotPool = accounts.findIndex(account => account.owner.equals(excludeAddress)) != 0; 130 | 131 | const filteredAccounts = accounts.filter(account => !account.owner.equals(excludeAddress)); 132 | 133 | const percentages = filteredAccounts.slice(0, 10).map(account => ((account.uiAmount / totalSupply) * 100).toFixed(2) + '%'); 134 | const percentagesRaw = filteredAccounts.slice(0, 10).map(account => (account.uiAmount / totalSupply) * 100); 135 | const isTopHolderExcessive = parseFloat(percentages[0]) > TOP_HOLDER_MAX_PERCENTAGE; 136 | const topTenPercentage = percentagesRaw.reduce((sum, current) => sum + current, 0); 137 | const isTopTenPercentageExcessive = topTenPercentage > TOP_10_MAX_PERCENTAGE; 138 | 139 | const ownerAddresses = filteredAccounts.map(x => x.owner); 140 | const ownerAccounts = await this.connection.getMultipleAccountsInfo(ownerAddresses, { commitment: 'confirmed' }); 141 | 142 | const lessThanThresholdAccounts = ownerAccounts.filter(account => account && account.lamports < 1000000000).length; 143 | const isTopHoldersPoor = lessThanThresholdAccounts > (ownerAccounts.length / 2); 144 | const topHoldersTotalSol = ownerAccounts.filter(x => x).reduce((sum, account) => sum + (account.lamports / 1000000000), 0); 145 | 146 | 147 | 148 | return { 149 | percentages, 150 | totalSupply, 151 | topTenPercentage, 152 | isTopTenPercentageExcessive, 153 | isTopHolderExcessive, 154 | isTopHoldersPoor, 155 | topHoldersTotalSol, 156 | topWalletIsNotPool 157 | }; 158 | } 159 | 160 | private checkForAbnormalDistribution(accounts: HolderInfo[]): boolean { 161 | const amountsMap = new Map(); 162 | accounts.forEach(account => { 163 | amountsMap.set(account.uiAmount, (amountsMap.get(account.uiAmount) || 0) + 1); 164 | }); 165 | 166 | return Array.from(amountsMap.values()).some(count => count >= ABNORMAL_HOLDER_NR); 167 | } 168 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Solana Trading Bot (Beta) 2 | 3 | The Solana Trading Bot is a software tool designed to automate the buying and selling of tokens on the Solana blockchain. 4 | It is configured to execute trades based on predefined parameters and strategies set by the user. 5 | 6 | The bot can monitor market conditions in real-time, such as pool burn, mint renounced and other factors, and it will execute trades when these conditions are fulfilled. 7 | 8 | ## Setup 9 | 10 | To run the script you need to: 11 | 12 | - Create a new empty Solana wallet 13 | - Transfer some SOL to it. 14 | - Convert some SOL to USDC or WSOL. 15 | - You need USDC or WSOL depending on the configuration set below. 16 | - Configure the script by updating `.env.copy` file (remove the .copy from the file name when done). 17 | - Check [Configuration](#configuration) section bellow 18 | - Install dependencies by typing: `npm install` 19 | - Run the script by typing: `npm run start` in terminal 20 | 21 | You should see the following output: 22 | ![output](readme/output.png) 23 | 24 | ### Configuration 25 | 26 | #### Wallet 27 | 28 | - `PRIVATE_KEY` - Your wallet's private key. 29 | 30 | #### Connection 31 | 32 | - `RPC_ENDPOINT` - HTTPS RPC endpoint for interacting with the Solana network. 33 | - `RPC_WEBSOCKET_ENDPOINT` - WebSocket RPC endpoint for real-time updates from the Solana network. 34 | - `COMMITMENT_LEVEL`- The commitment level of transactions (e.g., "finalized" for the highest level of security). 35 | 36 | #### Bot 37 | 38 | - `LOG_LEVEL` - Set logging level, e.g., `info`, `debug`, `trace`, etc. 39 | - `MAX_TOKENS_AT_THE_TIME` - Set to `1` to process buying one token at a time. 40 | - `COMPUTE_UNIT_LIMIT` - Compute limit used to calculate fees. 41 | - `COMPUTE_UNIT_PRICE` - Compute price used to calculate fees. 42 | - `PRE_LOAD_EXISTING_MARKETS` - Bot will load all existing markets in memory on start. 43 | - This option should not be used with public RPC. 44 | - `CACHE_NEW_MARKETS` - Set to `true` to cache new markets. 45 | - This option should not be used with public RPC. 46 | - `TRANSACTION_EXECUTOR` - Set to `warp` to use warp infrastructure for executing transactions, or set it to jito to use JSON-RPC jito executer 47 | - For more details checkout [warp](#warp-transactions-beta) section 48 | - `CUSTOM_FEE` - If using warp or jito executors this value will be used for transaction fees instead of `COMPUTE_UNIT_LIMIT` and `COMPUTE_UNIT_LIMIT` 49 | - Minimum value is 0.0001 SOL, but we recommend using 0.006 SOL or above 50 | - On top of this fee, minimal solana network fee will be applied 51 | - `MAX_LAG` - Ignore tokens that PoolOpenTime is longer than now + `MAX_LAG` seconds 52 | - `USE_TA` - Use technical analysis for entries and exits (VERY HARD ON RPC's) 53 | - `USE_TELEGRAM` - Use telegram bot for notifications 54 | 55 | #### Buy 56 | 57 | - `QUOTE_MINT` - Which pools to snipe, USDC or WSOL. 58 | - `QUOTE_AMOUNT` - Amount used to buy each new token. 59 | - `AUTO_BUY_DELAY` - Delay in milliseconds before buying a token. 60 | - `MAX_BUY_RETRIES` - Maximum number of retries for buying a token. 61 | - `BUY_SLIPPAGE` - Slippage % 62 | - `BUY_SIGNAL_TIME_TO_WAIT` - Time to wait for buy signal in milliseconds 63 | - `BUY_SIGNAL_PRICE_INTERVAL` - Time between price checks for indicators 64 | - `BUY_SIGNAL_FRACTION_TIME_TO_WAIT` - % fraction how long to wait for indicator population of total time 65 | - `BUY_SIGNAL_LOW_VOLUME_THRESHOLD` - amount of different prices to collect before considered too low of a volume in relation to indicator population timer 66 | 67 | #### Sell 68 | 69 | - `AUTO_SELL` - Set to `true` to enable automatic selling of tokens. 70 | - If you want to manually sell bought tokens, disable this option. 71 | - `MAX_SELL_RETRIES` - Maximum number of retries for selling a token. 72 | - `AUTO_SELL_DELAY` - Delay in milliseconds before auto-selling a token. 73 | - `PRICE_CHECK_INTERVAL` - Interval in milliseconds for checking the take profit and stop loss conditions. 74 | - Set to zero to disable take profit and stop loss. 75 | - `PRICE_CHECK_DURATION` - Time in milliseconds to wait for stop loss/take profit conditions. 76 | - If you don't reach profit or loss bot will auto sell after this time. 77 | - Set to zero to disable take profit and stop loss. 78 | - `TAKE_PROFIT` - Percentage profit at which to take profit. 79 | - Take profit is calculated based on quote mint. 80 | - `STOP_LOSS` - Percentage loss at which to stop the loss. 81 | - Stop loss is calculated based on quote mint. 82 | - `TRAILING_STOP_LOSS` - Set to `true` to use trailing stop loss. 83 | - `SKIP_SELLING_IF_LOST_MORE_THAN` - If token loses more than X% of value, bot will not try to sell 84 | - This config is useful if you find yourself in a situation when rugpull happen, and you failed to sell. In this case there is a big loss of value, and sometimes it's more beneficial to keep the token, instead of selling it for almost nothing. 85 | - `SELL_SLIPPAGE` - Slippage %. 86 | - `AUTO_SELL_WITHOUT_SELL_SIGNAL` - Set `false` to keep holding tokens in case didn't find sell signal 87 | - `KEEP_5_PERCENT_FOR_MOONSHOTS` - Keep 5% of token. WARNING: consider token account rent expenses and TAKE_PROFIT and STOP_LOSS is skewed by small amount. 88 | 89 | #### Snipe list 90 | 91 | - `USE_SNIPE_LIST` - Set to `true` to enable buying only tokens listed in `snipe-list.txt`. 92 | - Pool must not exist before the bot starts. 93 | - If token can be traded before bot starts nothing will happen. Bot will not buy the token. 94 | - `SNIPE_LIST_REFRESH_INTERVAL` - Interval in milliseconds to refresh the snipe list. 95 | - You can update snipe list while bot is running. It will pickup the new changes each time it does refresh. 96 | 97 | Note: When using snipe list filters below will be disabled. 98 | 99 | #### Filters 100 | 101 | - `FILTER_CHECK_INTERVAL` - Interval in milliseconds for checking if pool match the filters. 102 | - Set to zero to disable filters. 103 | - `FILTER_CHECK_DURATION` - Time in milliseconds to wait for pool to match the filters. 104 | - If pool doesn't match the filter buy will not happen. 105 | - Set to zero to disable filters. 106 | - `CONSECUTIVE_FILTER_MATCHES` - How many times in a row pool needs to match the filters. 107 | - This is useful because when pool is burned (and rugged), other filters may not report the same behavior. eg. pool size may still have old value 108 | - `CHECK_IF_MUTABLE` - Set to `true` to buy tokens only if their metadata are not mutable. 109 | - `CHECK_IF_SOCIALS` - Set to `true` to buy tokens only if they have at least 1 social. 110 | - `CHECK_IF_MINT_IS_RENOUNCED` - Set to `true` to buy tokens only if their mint is renounced. 111 | - `CHECK_IF_FREEZABLE` - Set to `true` to buy tokens only if they are not freezable. 112 | - `CHECK_IF_BURNED` - Set to `true` to buy tokens only if their liquidity pool is burned. 113 | - `MIN_POOL_SIZE` - Bot will buy only if the pool size is greater than or equal the specified amount. 114 | - Set `0` to disable. 115 | - `MAX_POOL_SIZE` - Bot will buy only if the pool size is less than or equal the specified amount. 116 | - Set `0` to disable. 117 | - `BLACKLIST_REFRESH_INTERVAL` - Interval in milliseconds to refresh the blacklist. 118 | - Blacklist checks update authority metadata of token, for "creator" wallets. 119 | - `WHITELIST_REFRESH_INTERVAL` - Interval in milliseconds to refresh the whitelist 120 | - Whitelist checks update authority metadata of token, for "creator" wallets. 121 | 122 | #### Holders 123 | 124 | - Check out .env.copy for variables. I took it from some dude on discord and it works great! Hah 125 | - Top holders are poor means: 1 SOL in lamports in more than 50% of wallets of top holders. 126 | - Pool wallet is not top wallet in holders means: Usually when tokens are sooo young, raydium must be top wallet, otherwise it's generally preminted. 127 | 128 | #### Technical analysis 129 | - `MACD_SHORT_PERIOD` - default 12 130 | - `MACD_LONG_PERIOD` - default 26 131 | - `MACD_SIGNAL_PERIOD` - default 9 132 | 133 | - `RSI_PERIOD` - default 14 134 | 135 | ## Warp transactions (beta) 136 | 137 | In case you experience a lot of failed transactions or transaction performance is too slow, you can try using `warp` for executing transactions. 138 | Warp is hosted service that executes transactions using integrations with third party providers. 139 | 140 | Using warp for transactions supports the team behind this project. 141 | 142 | ### Security 143 | 144 | When using warp, transaction is sent to the hosted service. 145 | **Payload that is being sent will NOT contain your wallet private key**. Fee transaction is signed on your machine. 146 | Each request is processed by hosted service and sent to third party provider. 147 | **We don't store your transactions, nor we store your private key.** 148 | 149 | Note: Warp transactions are disabled by default. 150 | 151 | ### Fees 152 | 153 | When using warp for transactions, fee is distributed between developers of warp and third party providers. 154 | In case TX fails, no fee will be taken from your account. 155 | 156 | ## Common issues 157 | 158 | If you have an error which is not listed here, please create a new issue in this repository. 159 | To collect more information on an issue, please change `LOG_LEVEL` to `debug`. 160 | 161 | ### Unsupported RPC node 162 | 163 | - If you see following error in your log file: 164 | `Error: 410 Gone: {"jsonrpc":"2.0","error":{"code": 410, "message":"The RPC call or parameters have been disabled."}, "id": "986f3599-b2b7-47c4-b951-074c19842bad" }` 165 | it means your RPC node doesn't support methods needed to execute script. 166 | - FIX: Change your RPC node. You can use Helius or Quicknode. 167 | 168 | ### No token account 169 | 170 | - If you see following error in your log file: 171 | `Error: No SOL token account found in wallet: ` 172 | it means that wallet you provided doesn't have USDC/WSOL token account. 173 | - FIX: Go to dex and swap some SOL to USDC/WSOL. For example when you swap sol to wsol you should see it in wallet as shown below: 174 | 175 | ![wsol](readme/wsol.png) 176 | 177 | ## Contact 178 | 179 | [![](https://img.shields.io/discord/1201826085655023616?color=5865F2&logo=Discord&style=flat-square)](https://discord.gg/xYUETCA2aP) 180 | 181 | - If you want to leave a tip, send to original creator, i'm just a fork :) 182 | 183 | - If you need custom features or assistance, feel free to contact the admin team on discord for dedicated support. 184 | 185 | ## Disclaimer 186 | 187 | The Solana Trading Bot is provided as is, for learning purposes. 188 | Trading cryptocurrencies and tokens involves risk, and past performance is not indicative of future results. 189 | The use of this bot is at your own risk, and we are not responsible for any losses incurred while using the bot. 190 | -------------------------------------------------------------------------------- /tradeSignals.ts: -------------------------------------------------------------------------------- 1 | import { Liquidity, LiquidityPoolKeysV4, Percent, TokenAmount } from "@raydium-io/raydium-sdk"; 2 | import { logger, sleep } from "./helpers"; 3 | import { Connection } from "@solana/web3.js"; 4 | import { BotConfig } from "./bot"; 5 | import { TechnicalAnalysis } from "./technicalAnalysis"; 6 | import BN from "bn.js"; 7 | import { Messaging } from "./messaging"; 8 | import { TechnicalAnalysisCache } from "./cache/technical-analysis.cache"; 9 | 10 | export class TradeSignals { 11 | 12 | private readonly TA: TechnicalAnalysis; 13 | private readonly stopLoss = new Map(); 14 | 15 | constructor( 16 | private readonly connection: Connection, 17 | readonly config: BotConfig, 18 | private readonly messaging: Messaging, 19 | private readonly technicalAnalysisCache: TechnicalAnalysisCache 20 | ) { 21 | this.TA = new TechnicalAnalysis(config); 22 | } 23 | 24 | public async waitForBuySignal(poolKeys: LiquidityPoolKeysV4) { 25 | 26 | if(!this.config.useTechnicalAnalysis){ 27 | return true; 28 | } 29 | 30 | this.technicalAnalysisCache.addNew(poolKeys.baseMint.toString(), poolKeys); 31 | 32 | logger.trace({ mint: poolKeys.baseMint.toString() }, `Waiting for buy signal`); 33 | 34 | const totalTimeToCheck = this.config.buySignalTimeToWait; 35 | const interval = this.config.buySignalPriceInterval; 36 | const maxSignalWaitTime = totalTimeToCheck * (this.config.buySignalFractionPercentageTimeToWait / 100) 37 | 38 | //used strategy 39 | let strategy = 1; 40 | 41 | let startTime = Date.now(); 42 | let timesChecked = 0; 43 | 44 | let previousRSI = null; 45 | 46 | do { 47 | try { 48 | 49 | let prices = this.technicalAnalysisCache.getPrices(poolKeys.baseMint.toString()); 50 | 51 | if(prices == null){ 52 | continue; 53 | } 54 | 55 | if (strategy == 1) { 56 | let currentRSI = this.TA.calculateRSIv2(prices); 57 | let macd = this.TA.calculateMACDv2(prices); 58 | 59 | if (previousRSI !== currentRSI) { 60 | logger.trace({ 61 | mint: poolKeys.baseMint.toString() 62 | }, `(${timesChecked}) Waiting for buy signal: RSI: ${currentRSI.toFixed(3)}, MACD: ${macd.macd}, Signal: ${macd.signal}`); 63 | previousRSI = currentRSI; 64 | } 65 | 66 | if (((Date.now() - startTime) > maxSignalWaitTime) && prices.length < this.config.buySignalLowVolumeThreshold) { 67 | logger.trace(`Not enough volume for signal after ${maxSignalWaitTime / 1000} seconds, skipping buy signal`); 68 | return false; 69 | } 70 | 71 | if (((Date.now() - startTime) > maxSignalWaitTime) && currentRSI == 0 && !macd.macd) { 72 | logger.trace(`Not enough data for signal after ${maxSignalWaitTime / 1000} seconds, skipping buy signal`); 73 | return false; 74 | } 75 | 76 | if (currentRSI > 0 && currentRSI < 30 && macd.macd && macd.signal && macd.macd > macd.signal) { 77 | logger.trace("RSI is less than 30, macd + signal = long, sending buy signal"); 78 | return true; 79 | } 80 | } 81 | 82 | if (strategy == 2) { 83 | let { RSI, RSI_EMA_11, RSI_prevEMA_11 } = this.TA.calculateRSIv3(prices, 14); 84 | let macd = this.TA.calculateMACDv2(prices, 8, 15, 6); 85 | let { EMA_3, EMA_18, prevEMA_3 } = this.TA.calculateEMAs(prices); 86 | 87 | let isMacdAboveSignal = macd.macd > macd.signal; 88 | let isEmaLAboveTokenPrice = EMA_18 > prices[prices.length - 1]; 89 | let isEmaSAbovePrevEmaS = EMA_3 > prevEMA_3; 90 | 91 | if (previousRSI !== RSI) { 92 | logger.trace({ 93 | mint: poolKeys.baseMint.toString() 94 | }, `(${timesChecked}) Waiting for buy signal: RSI: ${RSI.toFixed(3)}, RSI_EMA_11: ${RSI_EMA_11.toFixed(3)}, RSI_EMA_11 > RSI_EMA_11[-1]: ${RSI_prevEMA_11 < RSI_EMA_11}, macd>signal: ${isMacdAboveSignal}, priceema_3[-1]: ${isEmaSAbovePrevEmaS}`); 95 | previousRSI = RSI; 96 | } 97 | 98 | if (((Date.now() - startTime) > maxSignalWaitTime) && prices.length < this.config.buySignalLowVolumeThreshold) { 99 | logger.trace(`Not enough volume for signal after ${maxSignalWaitTime / 1000} seconds, skipping buy signal`); 100 | return false; 101 | } 102 | 103 | if (((Date.now() - startTime) > maxSignalWaitTime) && RSI == 0 && !macd.macd) { 104 | logger.trace(`Not enough data for signal after ${maxSignalWaitTime / 1000} seconds, skipping buy signal`); 105 | return false; 106 | } 107 | 108 | if (RSI > 0 && RSI < 50 && RSI_EMA_11 < 30 && RSI_prevEMA_11 < RSI_EMA_11 && macd.macd && macd.signal && macd.macd > macd.signal && EMA_18 > prices[prices.length - 1] && EMA_3 > prevEMA_3) { 109 | logger.trace("RSI is less than 30, macd + signal = long, and EMAs going mad, sending buy signal"); 110 | return true; 111 | } 112 | } 113 | 114 | } catch (e) { 115 | logger.trace({ mint: poolKeys.baseMint.toString(), e }, `Failed to check token price`); 116 | continue; 117 | } finally { 118 | timesChecked++; 119 | await sleep(interval); 120 | } 121 | } while ((Date.now() - startTime) < totalTimeToCheck); 122 | 123 | return false; 124 | } 125 | 126 | 127 | public async waitForSellSignal(amountIn: TokenAmount, poolKeys: LiquidityPoolKeysV4) { 128 | this.technicalAnalysisCache.markAsDone(poolKeys.baseMint.toString()); 129 | 130 | if (this.config.priceCheckDuration === 0 || this.config.priceCheckInterval === 0) { 131 | return true; 132 | } 133 | 134 | const timesToCheck = this.config.priceCheckDuration / this.config.priceCheckInterval; 135 | const profitFraction = this.config.quoteAmount.mul(this.config.takeProfit).numerator.div(new BN(100)); 136 | const profitAmount = new TokenAmount(this.config.quoteToken, profitFraction, true); 137 | const takeProfit = this.config.quoteAmount.add(profitAmount); 138 | let stopLoss: TokenAmount; 139 | 140 | if (!this.stopLoss.get(poolKeys.baseMint.toString())) { 141 | const lossFraction = this.config.quoteAmount.mul(this.config.stopLoss).numerator.div(new BN(100)); 142 | const lossAmount = new TokenAmount(this.config.quoteToken, lossFraction, true); 143 | stopLoss = this.config.quoteAmount.subtract(lossAmount); 144 | 145 | this.stopLoss.set(poolKeys.baseMint.toString(), stopLoss); 146 | } else { 147 | stopLoss = this.stopLoss.get(poolKeys.baseMint.toString())!; 148 | } 149 | 150 | const slippage = new Percent(this.config.sellSlippage, 100); 151 | let timesChecked = 0; 152 | //let telegram_status_message_id: number | undefined = undefined; 153 | 154 | do { 155 | try { 156 | const poolInfo = await Liquidity.fetchInfo({ 157 | connection: this.connection, 158 | poolKeys, 159 | }); 160 | 161 | const amountOut = Liquidity.computeAmountOut({ 162 | poolKeys, 163 | poolInfo, 164 | amountIn: amountIn, 165 | currencyOut: this.config.quoteToken, 166 | slippage, 167 | }).amountOut as TokenAmount; 168 | 169 | if (this.config.trailingStopLoss) { 170 | const trailingLossFraction = amountOut.mul(this.config.stopLoss).numerator.div(new BN(100)); 171 | const trailingLossAmount = new TokenAmount(this.config.quoteToken, trailingLossFraction, true); 172 | const trailingStopLoss = amountOut.subtract(trailingLossAmount); 173 | 174 | if (trailingStopLoss.gt(stopLoss)) { 175 | logger.trace( 176 | { mint: poolKeys.baseMint.toString() }, 177 | `Updating trailing stop loss from ${stopLoss.toFixed()} to ${trailingStopLoss.toFixed()}`, 178 | ); 179 | this.stopLoss.set(poolKeys.baseMint.toString(), trailingStopLoss); 180 | stopLoss = trailingStopLoss; 181 | } 182 | } 183 | 184 | if (this.config.skipSellingIfLostMoreThan > 0) { 185 | const stopSellingFraction = this.config.quoteAmount 186 | .mul(100 - this.config.skipSellingIfLostMoreThan) 187 | .numerator.div(new BN(100)); 188 | 189 | const stopSellingAmount = new TokenAmount(this.config.quoteToken, stopSellingFraction, true); 190 | 191 | if (amountOut.lt(stopSellingAmount)) { 192 | logger.info( 193 | { mint: poolKeys.baseMint.toString() }, 194 | `Token dropped more than ${this.config.skipSellingIfLostMoreThan}%, sell stopped. Initial: ${this.config.quoteAmount.toFixed()} | Current: ${amountOut.toFixed()}`, 195 | ); 196 | 197 | await this.messaging.sendTelegramMessage(`🚨RUG RUG RUG🚨\n\nMint ${poolKeys.baseMint.toString()}\nToken dropped more than ${this.config.skipSellingIfLostMoreThan}%, sell stopped\nInitial: ${this.config.quoteAmount.toFixed()}\nCurrent: ${amountOut.toFixed()}`, poolKeys.baseMint.toString()) 198 | 199 | this.stopLoss.delete(poolKeys.baseMint.toString()); 200 | return false; 201 | } 202 | } 203 | 204 | logger.debug( 205 | { mint: poolKeys.baseMint.toString() }, 206 | `${timesChecked}/${timesToCheck} Take profit: ${takeProfit.toFixed()} | Stop loss: ${stopLoss.toFixed()} | Current: ${amountOut.toFixed()}`, 207 | ); 208 | 209 | if (amountOut.lt(stopLoss)) { 210 | this.stopLoss.delete(poolKeys.baseMint.toString()); 211 | return true; 212 | } 213 | 214 | if (amountOut.gt(takeProfit)) { 215 | this.stopLoss.delete(poolKeys.baseMint.toString()); 216 | return true; 217 | } 218 | 219 | await sleep(this.config.priceCheckInterval); 220 | } catch (e) { 221 | logger.trace({ mint: poolKeys.baseMint.toString(), e }, `Failed to check token price`); 222 | } finally { 223 | timesChecked++; 224 | } 225 | } while (timesChecked < timesToCheck); 226 | 227 | 228 | if (this.config.autoSellWithoutSellSignal) { 229 | return true; 230 | } else { 231 | await this.messaging.sendTelegramMessage(`🚫NO SELL🚫\n\nMint ${poolKeys.baseMint.toString()}\nTime ran out, sell stopped, you're a bagholder now`, poolKeys.baseMint.toString()) 232 | return false; 233 | } 234 | } 235 | } -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | import { MarketCache, PoolCache } from './cache'; 2 | import { Listeners } from './listeners'; 3 | import { Connection, KeyedAccountInfo, Keypair } from '@solana/web3.js'; 4 | import { LIQUIDITY_STATE_LAYOUT_V4, MARKET_STATE_LAYOUT_V3, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 5 | import { AccountLayout, getAssociatedTokenAddressSync } from '@solana/spl-token'; 6 | import { Bot, BotConfig } from './bot'; 7 | import { DefaultTransactionExecutor, TransactionExecutor } from './transactions'; 8 | import { 9 | getToken, 10 | getWallet, 11 | logger, 12 | COMMITMENT_LEVEL, 13 | RPC_ENDPOINT, 14 | RPC_WEBSOCKET_ENDPOINT, 15 | PRE_LOAD_EXISTING_MARKETS, 16 | LOG_LEVEL, 17 | QUOTE_MINT, 18 | MAX_POOL_SIZE, 19 | MIN_POOL_SIZE, 20 | QUOTE_AMOUNT, 21 | PRIVATE_KEY, 22 | USE_SNIPE_LIST, 23 | AUTO_SELL_DELAY, 24 | MAX_SELL_RETRIES, 25 | AUTO_SELL, 26 | MAX_BUY_RETRIES, 27 | AUTO_BUY_DELAY, 28 | COMPUTE_UNIT_LIMIT, 29 | COMPUTE_UNIT_PRICE, 30 | CACHE_NEW_MARKETS, 31 | TAKE_PROFIT, 32 | STOP_LOSS, 33 | BUY_SLIPPAGE, 34 | SELL_SLIPPAGE, 35 | PRICE_CHECK_DURATION, 36 | PRICE_CHECK_INTERVAL, 37 | SNIPE_LIST_REFRESH_INTERVAL, 38 | TRANSACTION_EXECUTOR, 39 | CUSTOM_FEE, 40 | FILTER_CHECK_INTERVAL, 41 | FILTER_CHECK_DURATION, 42 | CONSECUTIVE_FILTER_MATCHES, 43 | MAX_TOKENS_AT_THE_TIME, 44 | CHECK_IF_MINT_IS_RENOUNCED, 45 | CHECK_IF_FREEZABLE, 46 | CHECK_IF_BURNED, 47 | CHECK_IF_MUTABLE, 48 | CHECK_IF_SOCIALS, 49 | TRAILING_STOP_LOSS, 50 | SKIP_SELLING_IF_LOST_MORE_THAN, 51 | MAX_LAG, 52 | CHECK_HOLDERS, 53 | CHECK_ABNORMAL_DISTRIBUTION, 54 | CHECK_TOKEN_DISTRIBUTION, 55 | TELEGRAM_CHAT_ID, 56 | BLACKLIST_REFRESH_INTERVAL, 57 | MACD_SHORT_PERIOD, 58 | MACD_LONG_PERIOD, 59 | MACD_SIGNAL_PERIOD, 60 | RSI_PERIOD, 61 | TELEGRAM_BOT_TOKEN, 62 | AUTO_SELL_WITHOUT_SELL_SIGNAL, 63 | BUY_SIGNAL_TIME_TO_WAIT, 64 | BUY_SIGNAL_PRICE_INTERVAL, 65 | BUY_SIGNAL_FRACTION_TIME_TO_WAIT, 66 | BUY_SIGNAL_LOW_VOLUME_THRESHOLD, 67 | USE_TELEGRAM, 68 | USE_TA 69 | } from './helpers'; 70 | import { WarpTransactionExecutor } from './transactions/warp-transaction-executor'; 71 | import { JitoTransactionExecutor } from './transactions/jito-rpc-transaction-executor'; 72 | import { TechnicalAnalysisCache } from './cache/technical-analysis.cache'; 73 | 74 | const connection = new Connection(RPC_ENDPOINT, { 75 | wsEndpoint: RPC_WEBSOCKET_ENDPOINT, 76 | commitment: COMMITMENT_LEVEL, 77 | }); 78 | 79 | function printDetails(wallet: Keypair, quoteToken: Token, bot: Bot) { 80 | logger.info(` 81 | .. :-===++++- 82 | .-==+++++++- =+++++++++- 83 | ..:::--===+=.=: .+++++++++++:=+++++++++: 84 | .==+++++++++++++++=:+++: .+++++++++++.=++++++++-. 85 | .-+++++++++++++++=:=++++- .+++++++++=:.=+++++-::-. 86 | -:+++++++++++++=:+++++++- .++++++++-:- =+++++=-: 87 | -:++++++=++++=:++++=++++= .++++++++++- =+++++: 88 | -:++++-:=++=:++++=:-+++++:+++++====--:::::::. 89 | ::=+-:::==:=+++=::-:--::::::::::---------::. 90 | ::-: .::::::::. --------:::.. 91 | :- .:.-:::. 92 | 93 | WARP DRIVE ACTIVATED 🚀🐟 94 | Made with ❤️ by humans. 95 | `); 96 | 97 | const botConfig = bot.config; 98 | 99 | logger.info('------- CONFIGURATION START -------'); 100 | logger.info(`Wallet: ${wallet.publicKey.toString()}`); 101 | 102 | logger.info('- Bot -'); 103 | logger.info(`Using transaction executor: ${TRANSACTION_EXECUTOR}`); 104 | 105 | if (bot.isWarp || bot.isJito) { 106 | logger.info(`${TRANSACTION_EXECUTOR} fee: ${CUSTOM_FEE}`); 107 | } else { 108 | logger.info(`Compute Unit limit: ${botConfig.unitLimit}`); 109 | logger.info(`Compute Unit price (micro lamports): ${botConfig.unitPrice}`); 110 | } 111 | 112 | logger.info(`Max tokens at the time: ${botConfig.maxTokensAtTheTime}`); 113 | logger.info(`Pre load existing markets: ${PRE_LOAD_EXISTING_MARKETS}`); 114 | logger.info(`Cache new markets: ${CACHE_NEW_MARKETS}`); 115 | logger.info(`Log level: ${LOG_LEVEL}`); 116 | logger.info(`Max lag: ${MAX_LAG}`); 117 | 118 | logger.info('- Buy -'); 119 | logger.info(`Buy amount: ${botConfig.quoteAmount.toFixed()} ${botConfig.quoteToken.name}`); 120 | logger.info(`Auto buy delay: ${botConfig.autoBuyDelay} ms`); 121 | logger.info(`Max buy retries: ${botConfig.maxBuyRetries}`); 122 | logger.info(`Buy amount (${quoteToken.symbol}): ${botConfig.quoteAmount.toFixed()}`); 123 | logger.info(`Buy slippage: ${botConfig.buySlippage}%`); 124 | 125 | logger.info('- Sell -'); 126 | logger.info(`Auto sell: ${AUTO_SELL}`); 127 | logger.info(`Auto sell delay: ${botConfig.autoSellDelay} ms`); 128 | logger.info(`Max sell retries: ${botConfig.maxSellRetries}`); 129 | logger.info(`Sell slippage: ${botConfig.sellSlippage}%`); 130 | logger.info(`Price check interval: ${botConfig.priceCheckInterval} ms`); 131 | logger.info(`Price check duration: ${botConfig.priceCheckDuration} ms`); 132 | logger.info(`Take profit: ${botConfig.takeProfit}%`); 133 | logger.info(`Stop loss: ${botConfig.stopLoss}%`); 134 | logger.info(`Trailing stop loss: ${botConfig.trailingStopLoss}`); 135 | logger.info(`Skip selling if lost more than: ${botConfig.skipSellingIfLostMoreThan}%`); 136 | 137 | logger.info('- Snipe list -'); 138 | logger.info(`Snipe list: ${botConfig.useSnipeList}`); 139 | logger.info(`Snipe list refresh interval: ${SNIPE_LIST_REFRESH_INTERVAL} ms`); 140 | 141 | if (botConfig.useSnipeList) { 142 | logger.info('- Filters -'); 143 | logger.info(`Filters are disabled when snipe list is on`); 144 | } else { 145 | logger.info('- Filters -'); 146 | logger.info(`Filter check interval: ${botConfig.filterCheckInterval} ms`); 147 | logger.info(`Filter check duration: ${botConfig.filterCheckDuration} ms`); 148 | logger.info(`Consecutive filter matches: ${botConfig.consecutiveMatchCount}`); 149 | logger.info(`Check renounced: ${CHECK_IF_MINT_IS_RENOUNCED}`); 150 | logger.info(`Check freezable: ${CHECK_IF_FREEZABLE}`); 151 | logger.info(`Check burned: ${CHECK_IF_BURNED}`); 152 | logger.info(`Check mutable: ${CHECK_IF_MUTABLE}`); 153 | logger.info(`Check socials: ${CHECK_IF_SOCIALS}`); 154 | logger.info(`Min pool size: ${botConfig.minPoolSize.toFixed()}`); 155 | logger.info(`Max pool size: ${botConfig.maxPoolSize.toFixed()}`); 156 | } 157 | 158 | logger.info(`Check Holders: ${botConfig.checkHolders}`); 159 | logger.info(`Check Token Distribution: ${botConfig.checkTokenDistribution}`); 160 | logger.info(`Check Abnormal Distribution: ${botConfig.checkAbnormalDistribution}`); 161 | logger.info(`Blacklist refresh interval: ${BLACKLIST_REFRESH_INTERVAL}`); 162 | 163 | logger.info(`Buy signal MACD: ${MACD_SHORT_PERIOD}/${MACD_LONG_PERIOD}/${MACD_SIGNAL_PERIOD}`); 164 | logger.info(`Buy signal RSI: ${RSI_PERIOD}`); 165 | 166 | logger.info('------- CONFIGURATION END -------'); 167 | 168 | logger.info('Bot is running! Press CTRL + C to stop it.'); 169 | } 170 | 171 | const runListener = async () => { 172 | logger.level = LOG_LEVEL; 173 | logger.info('Bot is starting...'); 174 | 175 | const marketCache = new MarketCache(connection); 176 | const poolCache = new PoolCache(); 177 | const technicalAnalysisCache = new TechnicalAnalysisCache(); 178 | 179 | let txExecutor: TransactionExecutor; 180 | 181 | switch (TRANSACTION_EXECUTOR) { 182 | case 'warp': { 183 | txExecutor = new WarpTransactionExecutor(CUSTOM_FEE); 184 | break; 185 | } 186 | case 'jito': { 187 | txExecutor = new JitoTransactionExecutor(CUSTOM_FEE, connection); 188 | break; 189 | } 190 | default: { 191 | txExecutor = new DefaultTransactionExecutor(connection); 192 | break; 193 | } 194 | } 195 | 196 | const wallet = getWallet(PRIVATE_KEY.trim()); 197 | const quoteToken = getToken(QUOTE_MINT); 198 | const botConfig = { 199 | wallet, 200 | quoteAta: getAssociatedTokenAddressSync(quoteToken.mint, wallet.publicKey), 201 | minPoolSize: new TokenAmount(quoteToken, MIN_POOL_SIZE, false), 202 | maxPoolSize: new TokenAmount(quoteToken, MAX_POOL_SIZE, false), 203 | quoteToken, 204 | quoteAmount: new TokenAmount(quoteToken, QUOTE_AMOUNT, false), 205 | maxTokensAtTheTime: MAX_TOKENS_AT_THE_TIME, 206 | useSnipeList: USE_SNIPE_LIST, 207 | autoSell: AUTO_SELL, 208 | autoSellDelay: AUTO_SELL_DELAY, 209 | maxSellRetries: MAX_SELL_RETRIES, 210 | autoBuyDelay: AUTO_BUY_DELAY, 211 | maxBuyRetries: MAX_BUY_RETRIES, 212 | unitLimit: COMPUTE_UNIT_LIMIT, 213 | unitPrice: COMPUTE_UNIT_PRICE, 214 | takeProfit: TAKE_PROFIT, 215 | stopLoss: STOP_LOSS, 216 | trailingStopLoss: TRAILING_STOP_LOSS, 217 | skipSellingIfLostMoreThan: SKIP_SELLING_IF_LOST_MORE_THAN, 218 | buySlippage: BUY_SLIPPAGE, 219 | sellSlippage: SELL_SLIPPAGE, 220 | priceCheckInterval: PRICE_CHECK_INTERVAL, 221 | priceCheckDuration: PRICE_CHECK_DURATION, 222 | filterCheckInterval: FILTER_CHECK_INTERVAL, 223 | filterCheckDuration: FILTER_CHECK_DURATION, 224 | consecutiveMatchCount: CONSECUTIVE_FILTER_MATCHES, 225 | checkHolders:CHECK_HOLDERS, 226 | checkTokenDistribution:CHECK_TOKEN_DISTRIBUTION, 227 | checkAbnormalDistribution:CHECK_ABNORMAL_DISTRIBUTION, 228 | telegramChatId:TELEGRAM_CHAT_ID, 229 | telegramBotToken: TELEGRAM_BOT_TOKEN, 230 | blacklistRefreshInterval: BLACKLIST_REFRESH_INTERVAL, 231 | MACDLongPeriod: MACD_LONG_PERIOD, 232 | MACDShortPeriod: MACD_SHORT_PERIOD, 233 | MACDSignalPeriod: MACD_SIGNAL_PERIOD, 234 | RSIPeriod: RSI_PERIOD, 235 | autoSellWithoutSellSignal: AUTO_SELL_WITHOUT_SELL_SIGNAL, 236 | buySignalTimeToWait: BUY_SIGNAL_TIME_TO_WAIT, 237 | buySignalPriceInterval: BUY_SIGNAL_PRICE_INTERVAL, 238 | buySignalFractionPercentageTimeToWait: BUY_SIGNAL_FRACTION_TIME_TO_WAIT, 239 | buySignalLowVolumeThreshold: BUY_SIGNAL_LOW_VOLUME_THRESHOLD, 240 | useTelegram: USE_TELEGRAM, 241 | useTechnicalAnalysis: USE_TA 242 | }; 243 | 244 | const bot = new Bot(connection, marketCache, poolCache, txExecutor, technicalAnalysisCache, botConfig); 245 | const valid = await bot.validate(); 246 | 247 | if (!valid) { 248 | logger.info('Bot is exiting...'); 249 | process.exit(1); 250 | } 251 | 252 | if (PRE_LOAD_EXISTING_MARKETS) { 253 | await marketCache.init({ quoteToken }); 254 | } 255 | 256 | const runTimestamp = Math.floor(new Date().getTime() / 1000); 257 | const listeners = new Listeners(connection); 258 | await listeners.start({ 259 | walletPublicKey: wallet.publicKey, 260 | quoteToken, 261 | autoSell: AUTO_SELL, 262 | cacheNewMarkets: CACHE_NEW_MARKETS, 263 | }); 264 | 265 | listeners.on('market', (updatedAccountInfo: KeyedAccountInfo) => { 266 | const marketState = MARKET_STATE_LAYOUT_V3.decode(updatedAccountInfo.accountInfo.data); 267 | marketCache.save(updatedAccountInfo.accountId.toString(), marketState); 268 | }); 269 | 270 | listeners.on('pool', async (updatedAccountInfo: KeyedAccountInfo) => { 271 | const poolState = LIQUIDITY_STATE_LAYOUT_V4.decode(updatedAccountInfo.accountInfo.data); 272 | const poolOpenTime = parseInt(poolState.poolOpenTime.toString()); 273 | const exists = await poolCache.get(poolState.baseMint.toString()); 274 | 275 | let currentTimestamp = Math.floor(new Date().getTime() / 1000); 276 | let lag = currentTimestamp - poolOpenTime; 277 | 278 | if (!exists && poolOpenTime > runTimestamp) { 279 | poolCache.save(updatedAccountInfo.accountId.toString(), poolState); 280 | 281 | if(MAX_LAG != 0 && lag > MAX_LAG){ 282 | logger.trace(`Lag too high: ${lag} sec`); 283 | return; 284 | } else { 285 | logger.trace(`Lag: ${lag} sec`); 286 | await bot.buy(updatedAccountInfo.accountId, poolState, lag); 287 | } 288 | } 289 | }); 290 | 291 | listeners.on('wallet', async (updatedAccountInfo: KeyedAccountInfo) => { 292 | const accountData = AccountLayout.decode(updatedAccountInfo.accountInfo.data); 293 | 294 | if (accountData.mint.equals(quoteToken.mint)) { 295 | return; 296 | } 297 | 298 | await bot.sell(updatedAccountInfo.accountId, accountData); 299 | }); 300 | 301 | printDetails(wallet, quoteToken, bot); 302 | }; 303 | 304 | runListener(); 305 | 306 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "commonjs", /* Specify what module code is generated. */ 29 | // "rootDir": "./", /* Specify the root folder within your source files. */ 30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ 39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ 40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ 41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ 42 | "resolveJsonModule": true, /* Enable importing .json files. */ 43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ 44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 45 | 46 | /* JavaScript Support */ 47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 50 | 51 | /* Emit */ 52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 58 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 59 | // "removeComments": true, /* Disable emitting comments. */ 60 | // "noEmit": true, /* Disable emitting files from a compilation. */ 61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 68 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 75 | 76 | /* Interop Constraints */ 77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ 79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ 81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 83 | 84 | /* Type Checking */ 85 | "strict": false, /* Enable all strict type-checking options. */ 86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 104 | 105 | /* Completeness */ 106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /bot.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ComputeBudgetProgram, 3 | Connection, 4 | Keypair, 5 | PublicKey, 6 | TransactionMessage, 7 | VersionedTransaction, 8 | } from '@solana/web3.js'; 9 | import { 10 | createAssociatedTokenAccountIdempotentInstruction, 11 | createCloseAccountInstruction, 12 | getAccount, 13 | getAssociatedTokenAddress, 14 | RawAccount, 15 | TOKEN_PROGRAM_ID, 16 | } from '@solana/spl-token'; 17 | import { Liquidity, LiquidityPoolKeysV4, LiquidityStateV4, Percent, Token, TokenAmount } from '@raydium-io/raydium-sdk'; 18 | import { MarketCache, PoolCache, SnipeListCache } from './cache'; 19 | import { PoolFilters } from './filters'; 20 | import { TransactionExecutor } from './transactions'; 21 | import { createPoolKeys, KEEP_5_PERCENT_FOR_MOONSHOTS, logger, NETWORK, sleep } from './helpers'; 22 | import { Semaphore } from 'async-mutex'; 23 | import { WarpTransactionExecutor } from './transactions/warp-transaction-executor'; 24 | import { JitoTransactionExecutor } from './transactions/jito-rpc-transaction-executor'; 25 | import { BlacklistCache } from './cache/blacklist.cache'; 26 | import { TradeSignals } from './tradeSignals'; 27 | import { Messaging } from './messaging'; 28 | import { WhitelistCache } from './cache/whitelist.cache'; 29 | import { TechnicalAnalysisCache } from './cache/technical-analysis.cache'; 30 | 31 | export interface BotConfig { 32 | wallet: Keypair; 33 | minPoolSize: TokenAmount; 34 | maxPoolSize: TokenAmount; 35 | quoteToken: Token; 36 | quoteAmount: TokenAmount; 37 | quoteAta: PublicKey; 38 | maxTokensAtTheTime: number; 39 | useSnipeList: boolean; 40 | autoSell: boolean; 41 | autoBuyDelay: number; 42 | autoSellDelay: number; 43 | maxBuyRetries: number; 44 | maxSellRetries: number; 45 | unitLimit: number; 46 | unitPrice: number; 47 | takeProfit: number; 48 | stopLoss: number; 49 | trailingStopLoss: boolean; 50 | skipSellingIfLostMoreThan: number; 51 | buySlippage: number; 52 | sellSlippage: number; 53 | priceCheckInterval: number; 54 | priceCheckDuration: number; 55 | filterCheckInterval: number; 56 | filterCheckDuration: number; 57 | consecutiveMatchCount: number; 58 | checkHolders: boolean; 59 | checkTokenDistribution: boolean; 60 | checkAbnormalDistribution: boolean; 61 | telegramChatId: number; 62 | telegramBotToken: string, 63 | blacklistRefreshInterval: number, 64 | MACDLongPeriod: number, 65 | MACDShortPeriod: number, 66 | MACDSignalPeriod: number, 67 | RSIPeriod: number, 68 | autoSellWithoutSellSignal: boolean, 69 | buySignalTimeToWait: number, 70 | buySignalPriceInterval: number, 71 | buySignalFractionPercentageTimeToWait: number, 72 | buySignalLowVolumeThreshold: number, 73 | useTechnicalAnalysis: boolean, 74 | useTelegram: boolean 75 | } 76 | 77 | export class Bot { 78 | private readonly snipeListCache?: SnipeListCache; 79 | private readonly blacklistCache?: BlacklistCache; 80 | private readonly whitelistCache?: WhitelistCache; 81 | 82 | private readonly semaphore: Semaphore; 83 | private sellExecutionCount = 0; 84 | public readonly isWarp: boolean = false; 85 | public readonly isJito: boolean = false; 86 | private readonly tradeSignals: TradeSignals; 87 | private readonly messaging: Messaging; 88 | 89 | constructor( 90 | private readonly connection: Connection, 91 | private readonly marketStorage: MarketCache, 92 | private readonly poolStorage: PoolCache, 93 | private readonly txExecutor: TransactionExecutor, 94 | private readonly technicalAnalysisCache: TechnicalAnalysisCache, 95 | readonly config: BotConfig, 96 | ) { 97 | this.isWarp = txExecutor instanceof WarpTransactionExecutor; 98 | this.isJito = txExecutor instanceof JitoTransactionExecutor; 99 | 100 | this.semaphore = new Semaphore(config.maxTokensAtTheTime); 101 | 102 | this.messaging = new Messaging(config); 103 | 104 | this.tradeSignals = new TradeSignals(connection, config, this.messaging, technicalAnalysisCache); 105 | 106 | this.whitelistCache = new WhitelistCache(); 107 | this.whitelistCache.init(); 108 | 109 | this.blacklistCache = new BlacklistCache(); 110 | this.blacklistCache.init(); 111 | 112 | if (this.config.useSnipeList) { 113 | this.snipeListCache = new SnipeListCache(); 114 | this.snipeListCache.init(); 115 | } 116 | } 117 | 118 | async validate() { 119 | try { 120 | await getAccount(this.connection, this.config.quoteAta, this.connection.commitment); 121 | } catch (error) { 122 | logger.error( 123 | `${this.config.quoteToken.symbol} token account not found in wallet: ${this.config.wallet.publicKey.toString()}`, 124 | ); 125 | return false; 126 | } 127 | 128 | return true; 129 | } 130 | 131 | public async whitelistSnipe(accountId: PublicKey, poolState: LiquidityStateV4): Promise { 132 | if (this.whitelistCache.whitelistIsEmpty()) { 133 | return false; 134 | } 135 | 136 | const [market] = await Promise.all([ 137 | this.marketStorage.get(poolState.marketId.toString()), 138 | getAssociatedTokenAddress(poolState.baseMint, this.config.wallet.publicKey), 139 | ]); 140 | const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(accountId, poolState, market); 141 | 142 | //updateAuthority is whitelisted 143 | return await this.whitelistCache.isInList(this.connection, poolKeys); 144 | } 145 | 146 | public async buy(accountId: PublicKey, poolState: LiquidityStateV4, lag: number = 0) { 147 | logger.trace({ mint: poolState.baseMint }, `Processing new pool...`); 148 | 149 | const whitelistSnipe = await this.whitelistSnipe(accountId, poolState); 150 | 151 | if (this.config.useSnipeList && !this.snipeListCache?.isInList(poolState.baseMint.toString())) { 152 | logger.debug({ mint: poolState.baseMint.toString() }, `Skipping buy because token is not in a snipe list`); 153 | return; 154 | } 155 | 156 | if (!whitelistSnipe) { 157 | if (this.config.autoBuyDelay > 0) { 158 | logger.debug({ mint: poolState.baseMint }, `Waiting for ${this.config.autoBuyDelay} ms before buy`); // - (lag * 1000) 159 | await sleep(this.config.autoBuyDelay); // - (lag * 1000) 160 | } 161 | } 162 | 163 | 164 | 165 | const numberOfActionsBeingProcessed = 166 | this.config.maxTokensAtTheTime - this.semaphore.getValue() + this.sellExecutionCount; 167 | if (this.semaphore.isLocked() || numberOfActionsBeingProcessed >= this.config.maxTokensAtTheTime) { 168 | logger.debug( 169 | { mint: poolState.baseMint.toString() }, 170 | `Skipping buy because max tokens to process at the same time is ${this.config.maxTokensAtTheTime} and currently ${numberOfActionsBeingProcessed} tokens is being processed`, 171 | ); 172 | return; 173 | } 174 | 175 | await this.semaphore.acquire(); 176 | 177 | try { 178 | const [market, mintAta] = await Promise.all([ 179 | this.marketStorage.get(poolState.marketId.toString()), 180 | getAssociatedTokenAddress(poolState.baseMint, this.config.wallet.publicKey), 181 | ]); 182 | const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(accountId, poolState, market); 183 | 184 | if (!whitelistSnipe) { 185 | if (!this.config.useSnipeList) { 186 | 187 | const match = await this.filterMatch(poolKeys); 188 | 189 | if (!match) { 190 | logger.trace({ mint: poolKeys.baseMint.toString() }, `Skipping buy because pool doesn't match filters`); 191 | return; 192 | } 193 | } 194 | 195 | let buySignal = await this.tradeSignals.waitForBuySignal(poolKeys); 196 | 197 | if (!buySignal) { 198 | await this.messaging.sendTelegramMessage(`😭Skipping buy signal😭\n\nMint ${poolKeys.baseMint.toString()}`, poolState.baseMint.toString()) 199 | 200 | logger.trace({ mint: poolKeys.baseMint.toString() }, `Skipping buy because buy signal not received`); 201 | return; 202 | } 203 | } 204 | 205 | const startTime = Date.now(); 206 | for (let i = 0; i < this.config.maxBuyRetries; i++) { 207 | try { 208 | 209 | if ((Date.now() - startTime) > 10000) { 210 | logger.info(`Not buying mint ${poolState.baseMint.toString()}, max buy 10 sec timer exceeded!`); 211 | return; 212 | } 213 | 214 | logger.info( 215 | { mint: poolState.baseMint.toString() }, 216 | `Send buy transaction attempt: ${i + 1}/${this.config.maxBuyRetries}`, 217 | ); 218 | const tokenOut = new Token(TOKEN_PROGRAM_ID, poolKeys.baseMint, poolKeys.baseDecimals); 219 | const result = await this.swap( 220 | poolKeys, 221 | this.config.quoteAta, 222 | mintAta, 223 | this.config.quoteToken, 224 | tokenOut, 225 | this.config.quoteAmount, 226 | this.config.buySlippage, 227 | this.config.wallet, 228 | 'buy', 229 | ); 230 | 231 | if (result.confirmed) { 232 | logger.info( 233 | { 234 | mint: poolState.baseMint.toString(), 235 | signature: result.signature, 236 | url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`, 237 | }, 238 | `Confirmed buy tx`, 239 | ); 240 | 241 | await this.messaging.sendTelegramMessage(`💚Confirmed buy💚\n\nMint ${poolKeys.baseMint.toString()}\nSignature ${result.signature}`, poolState.baseMint.toString()) 242 | 243 | break; 244 | } 245 | 246 | logger.info( 247 | { 248 | mint: poolState.baseMint.toString(), 249 | signature: result.signature, 250 | error: result.error, 251 | }, 252 | `Error confirming buy tx`, 253 | ); 254 | } catch (error) { 255 | logger.debug({ mint: poolState.baseMint.toString(), error }, `Error confirming buy transaction`); 256 | } 257 | } 258 | } catch (error) { 259 | logger.error({ mint: poolState.baseMint.toString(), error }, `Failed to buy token`); 260 | } finally { 261 | this.semaphore.release(); 262 | } 263 | } 264 | 265 | public async sell(accountId: PublicKey, rawAccount: RawAccount) { 266 | this.sellExecutionCount++; 267 | 268 | try { 269 | const poolData = await this.poolStorage.get(rawAccount.mint.toString()); 270 | 271 | if (poolData && poolData.sold) { 272 | return; 273 | } 274 | 275 | logger.trace({ mint: rawAccount.mint }, `Processing new token...`); 276 | 277 | if (!poolData) { 278 | logger.trace({ mint: rawAccount.mint.toString() }, `Token pool data is not found, can't sell`); 279 | return; 280 | } 281 | 282 | 283 | let moonshotConditionAmount = KEEP_5_PERCENT_FOR_MOONSHOTS ? (rawAccount.amount * BigInt(95)) / BigInt(100) : rawAccount.amount; 284 | 285 | const tokenIn = new Token(TOKEN_PROGRAM_ID, poolData.state.baseMint, poolData.state.baseDecimal.toNumber()); 286 | const tokenAmountIn = new TokenAmount(tokenIn, moonshotConditionAmount, true); 287 | 288 | if (tokenAmountIn.isZero()) { 289 | logger.info({ mint: rawAccount.mint.toString() }, `Empty balance, can't sell`); 290 | return; 291 | } 292 | 293 | if (this.config.autoSellDelay > 0) { 294 | logger.debug({ mint: rawAccount.mint }, `Waiting for ${this.config.autoSellDelay} ms before sell`); 295 | await sleep(this.config.autoSellDelay); 296 | } 297 | 298 | const market = await this.marketStorage.get(poolData.state.marketId.toString()); 299 | const poolKeys: LiquidityPoolKeysV4 = createPoolKeys(new PublicKey(poolData.id), poolData.state, market); 300 | 301 | for (let i = 0; i < this.config.maxSellRetries; i++) { 302 | try { 303 | if (i < 1) { // Only check for sell signal on first attempt, not on retries 304 | const shouldSell = await this.tradeSignals.waitForSellSignal(tokenAmountIn, poolKeys); 305 | 306 | if (!shouldSell) { 307 | return; 308 | } 309 | } 310 | 311 | if (KEEP_5_PERCENT_FOR_MOONSHOTS) { //only if you aim for the moon 312 | this.poolStorage.markAsSold(rawAccount.mint.toString()); 313 | } 314 | 315 | logger.info( 316 | { mint: rawAccount.mint }, 317 | `Send sell transaction attempt: ${i + 1}/${this.config.maxSellRetries}`, 318 | ); 319 | 320 | const result = await this.swap( 321 | poolKeys, 322 | accountId, 323 | this.config.quoteAta, 324 | tokenIn, 325 | this.config.quoteToken, 326 | tokenAmountIn, 327 | this.config.sellSlippage, 328 | this.config.wallet, 329 | 'sell', 330 | ); 331 | 332 | if (result.confirmed) { 333 | 334 | try { 335 | this.connection.getParsedTransaction(result.signature, { commitment: "confirmed", maxSupportedTransactionVersion: 0 }) 336 | .then(async (parsedConfirmedTransaction) => { 337 | if (parsedConfirmedTransaction) { 338 | let preTokenBalances = parsedConfirmedTransaction.meta.preTokenBalances; 339 | let postTokenBalances = parsedConfirmedTransaction.meta.postTokenBalances; 340 | 341 | // Filter for WSOL mint and your public key 342 | let pre = preTokenBalances 343 | .filter(x => x.mint === this.config.quoteToken.mint.toString() && x.owner === this.config.wallet.publicKey.toString()) 344 | .map(x => x.uiTokenAmount.uiAmount) 345 | .reduce((a, b) => a + b, 0); // Sum the pre values 346 | 347 | let post = postTokenBalances 348 | .filter(x => x.mint === this.config.quoteToken.mint.toString() && x.owner === this.config.wallet.publicKey.toString()) 349 | .map(x => x.uiTokenAmount.uiAmount) 350 | .reduce((a, b) => a + b, 0); // Sum the post values 351 | 352 | let quoteAmountNumber = parseFloat(this.config.quoteAmount.toFixed()); 353 | let profitOrLoss = (post - pre) - quoteAmountNumber; 354 | let percentageChange = (profitOrLoss / quoteAmountNumber) * 100 355 | 356 | await this.messaging.sendTelegramMessage(`⭕Confirmed sale at ${(post - pre).toFixed(5)}⭕\n\n${profitOrLoss < 0 ? "🔴Loss " : "🟢Profit "}${profitOrLoss.toFixed(5)} ${this.config.quoteToken.symbol} (${(percentageChange).toFixed(2)}%)\n\nRetries ${i + 1}/${this.config.maxSellRetries}`, rawAccount.mint.toString()); 357 | } 358 | }) 359 | .catch((error) => { 360 | console.log('Error fetching transaction details:', error); 361 | }); 362 | 363 | 364 | } catch (error) { 365 | console.log("Error calculating profit", error); 366 | } 367 | logger.info( 368 | { 369 | dex: `https://dexscreener.com/solana/${rawAccount.mint.toString()}?maker=${this.config.wallet.publicKey}`, 370 | mint: rawAccount.mint.toString(), 371 | signature: result.signature, 372 | url: `https://solscan.io/tx/${result.signature}?cluster=${NETWORK}`, 373 | }, 374 | `Confirmed sell tx`, 375 | ); 376 | break; 377 | } 378 | 379 | logger.info( 380 | { 381 | mint: rawAccount.mint.toString(), 382 | signature: result.signature, 383 | error: result.error, 384 | }, 385 | `Error confirming sell tx`, 386 | ); 387 | } catch (error) { 388 | logger.debug({ mint: rawAccount.mint.toString(), error }, `Error confirming sell transaction`); 389 | } 390 | } 391 | } catch (error) { 392 | logger.error({ mint: rawAccount.mint.toString(), error }, `Failed to sell token`); 393 | } finally { 394 | this.sellExecutionCount--; 395 | } 396 | } 397 | 398 | // noinspection JSUnusedLocalSymbols 399 | private async swap( 400 | poolKeys: LiquidityPoolKeysV4, 401 | ataIn: PublicKey, 402 | ataOut: PublicKey, 403 | tokenIn: Token, 404 | tokenOut: Token, 405 | amountIn: TokenAmount, 406 | slippage: number, 407 | wallet: Keypair, 408 | direction: 'buy' | 'sell', 409 | ) { 410 | const slippagePercent = new Percent(slippage, 100); 411 | const poolInfo = await Liquidity.fetchInfo({ 412 | connection: this.connection, 413 | poolKeys, 414 | }); 415 | 416 | const computedAmountOut = Liquidity.computeAmountOut({ 417 | poolKeys, 418 | poolInfo, 419 | amountIn, 420 | currencyOut: tokenOut, 421 | slippage: slippagePercent, 422 | }); 423 | 424 | const latestBlockhash = await this.connection.getLatestBlockhash(); 425 | const { innerTransaction } = Liquidity.makeSwapFixedInInstruction( 426 | { 427 | poolKeys: poolKeys, 428 | userKeys: { 429 | tokenAccountIn: ataIn, 430 | tokenAccountOut: ataOut, 431 | owner: wallet.publicKey, 432 | }, 433 | amountIn: amountIn.raw, 434 | minAmountOut: computedAmountOut.minAmountOut.raw, 435 | }, 436 | poolKeys.version, 437 | ); 438 | 439 | const messageV0 = new TransactionMessage({ 440 | payerKey: wallet.publicKey, 441 | recentBlockhash: latestBlockhash.blockhash, 442 | instructions: [ 443 | ...(this.isWarp || this.isJito 444 | ? [] 445 | : [ 446 | ComputeBudgetProgram.setComputeUnitPrice({ microLamports: this.config.unitPrice }), 447 | ComputeBudgetProgram.setComputeUnitLimit({ units: this.config.unitLimit }), 448 | ]), 449 | ...(direction === 'buy' 450 | ? [ 451 | createAssociatedTokenAccountIdempotentInstruction( 452 | wallet.publicKey, 453 | ataOut, 454 | wallet.publicKey, 455 | tokenOut.mint, 456 | ), 457 | ] 458 | : []), 459 | ...innerTransaction.instructions, 460 | // Close the account if we are selling and not keeping 5% for moonshots 461 | ...((direction === 'sell' && !KEEP_5_PERCENT_FOR_MOONSHOTS) ? [createCloseAccountInstruction(ataIn, wallet.publicKey, wallet.publicKey)] : []), 462 | ], 463 | }).compileToV0Message(); 464 | 465 | const transaction = new VersionedTransaction(messageV0); 466 | transaction.sign([wallet, ...innerTransaction.signers]); 467 | 468 | return this.txExecutor.executeAndConfirm(transaction, wallet, latestBlockhash); 469 | } 470 | 471 | private async filterMatch(poolKeys: LiquidityPoolKeysV4) { 472 | if (this.config.filterCheckInterval === 0 || this.config.filterCheckDuration === 0) { 473 | return true; 474 | } 475 | 476 | const filters = new PoolFilters(this.connection, { 477 | quoteToken: this.config.quoteToken, 478 | minPoolSize: this.config.minPoolSize, 479 | maxPoolSize: this.config.maxPoolSize, 480 | }, this.blacklistCache); 481 | 482 | const timesToCheck = this.config.filterCheckDuration / this.config.filterCheckInterval; 483 | let timesChecked = 0; 484 | let matchCount = 0; 485 | 486 | do { 487 | try { 488 | const shouldBuy = await filters.execute(poolKeys); 489 | 490 | if (shouldBuy) { 491 | matchCount++; 492 | 493 | if (this.config.consecutiveMatchCount <= matchCount) { 494 | logger.debug( 495 | { mint: poolKeys.baseMint.toString() }, 496 | `Filter match ${matchCount}/${this.config.consecutiveMatchCount}`, 497 | ); 498 | return true; 499 | } 500 | } else { 501 | matchCount = 0; 502 | } 503 | 504 | if (this.config.filterCheckInterval > 1) { 505 | logger.trace({ mint: poolKeys.baseMint.toString() }, `${timesChecked + 1}/${timesToCheck} Filter didn't match, waiting for ${this.config.filterCheckInterval / 1000} sec.`); 506 | } 507 | await sleep(this.config.filterCheckInterval); 508 | } finally { 509 | timesChecked++; 510 | } 511 | } while (timesChecked < timesToCheck); 512 | 513 | return false; 514 | } 515 | } -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . --------------------------------------------------------------------------------